Moar documentations
[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
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
40 * @param $user
41 * @param $password
42 * @param $dbName
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
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
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
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
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
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
252 * @param $n
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
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
322 * @param $uniqueIndexes
323 * @param $rows
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
386 * @param $index
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 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
515 if( !$res ) {
516 return false;
517 }
518 # Find slave SQL thread
519 foreach( $res as $row ) {
520 /* This should work for most situations - when default db
521 * for thread is not specified, it had no events executed,
522 * and therefore it doesn't know yet how lagged it is.
523 *
524 * Relay log I/O thread does not select databases.
525 */
526 if ( $row->User == 'system user' &&
527 $row->State != 'Waiting for master to send event' &&
528 $row->State != 'Connecting to master' &&
529 $row->State != 'Queueing master event to the relay log' &&
530 $row->State != 'Waiting for master update' &&
531 $row->State != 'Requesting binlog dump' &&
532 $row->State != 'Waiting to reconnect after a failed master event read' &&
533 $row->State != 'Reconnecting after a failed master event read' &&
534 $row->State != 'Registering slave on master'
535 ) {
536 # This is it, return the time (except -ve)
537 if ( $row->Time > 0x7fffffff ) {
538 return false;
539 } else {
540 return $row->Time;
541 }
542 }
543 }
544 return false;
545 }
546
547 /**
548 * Wait for the slave to catch up to a given master position.
549 *
550 * @param $pos DBMasterPos object
551 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
552 * @return bool|string
553 */
554 function masterPosWait( DBMasterPos $pos, $timeout ) {
555 $fname = 'DatabaseBase::masterPosWait';
556 wfProfileIn( $fname );
557
558 # Commit any open transactions
559 if ( $this->mTrxLevel ) {
560 $this->commit();
561 }
562
563 if ( !is_null( $this->mFakeSlaveLag ) ) {
564 $status = parent::masterPosWait( $pos, $timeout );
565 wfProfileOut( $fname );
566 return $status;
567 }
568
569 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
570 $encFile = $this->addQuotes( $pos->file );
571 $encPos = intval( $pos->pos );
572 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
573 $res = $this->doQuery( $sql );
574
575 if ( $res && $row = $this->fetchRow( $res ) ) {
576 wfProfileOut( $fname );
577 return $row[0];
578 } else {
579 wfProfileOut( $fname );
580 return false;
581 }
582 }
583
584 /**
585 * Get the position of the master from SHOW SLAVE STATUS
586 *
587 * @return MySQLMasterPos|false
588 */
589 function getSlavePos() {
590 if ( !is_null( $this->mFakeSlaveLag ) ) {
591 return parent::getSlavePos();
592 }
593
594 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
595 $row = $this->fetchObject( $res );
596
597 if ( $row ) {
598 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
599 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
600 } else {
601 return false;
602 }
603 }
604
605 /**
606 * Get the position of the master from SHOW MASTER STATUS
607 *
608 * @return MySQLMasterPos|false
609 */
610 function getMasterPos() {
611 if ( $this->mFakeMaster ) {
612 return parent::getMasterPos();
613 }
614
615 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
616 $row = $this->fetchObject( $res );
617
618 if ( $row ) {
619 return new MySQLMasterPos( $row->File, $row->Position );
620 } else {
621 return false;
622 }
623 }
624
625 /**
626 * @return string
627 */
628 function getServerVersion() {
629 return mysql_get_server_info( $this->mConn );
630 }
631
632 /**
633 * @param $index
634 * @return string
635 */
636 function useIndexClause( $index ) {
637 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
638 }
639
640 /**
641 * @return string
642 */
643 function lowPriorityOption() {
644 return 'LOW_PRIORITY';
645 }
646
647 /**
648 * @return string
649 */
650 public static function getSoftwareLink() {
651 return '[http://www.mysql.com/ MySQL]';
652 }
653
654 /**
655 * @return bool
656 */
657 function standardSelectDistinct() {
658 return false;
659 }
660
661 /**
662 * @param $options array
663 */
664 public function setSessionOptions( array $options ) {
665 if ( isset( $options['connTimeout'] ) ) {
666 $timeout = (int)$options['connTimeout'];
667 $this->query( "SET net_read_timeout=$timeout" );
668 $this->query( "SET net_write_timeout=$timeout" );
669 }
670 }
671
672 /**
673 * @param $lockName
674 * @param $method
675 * @param $timeout int
676 * @return bool
677 */
678 public function lock( $lockName, $method, $timeout = 5 ) {
679 $lockName = $this->addQuotes( $lockName );
680 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
681 $row = $this->fetchObject( $result );
682
683 if( $row->lockstatus == 1 ) {
684 return true;
685 } else {
686 wfDebug( __METHOD__." failed to acquire lock\n" );
687 return false;
688 }
689 }
690
691 /**
692 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
693 * @param $lockName
694 * @param $method string
695 * @return
696 */
697 public function unlock( $lockName, $method ) {
698 $lockName = $this->addQuotes( $lockName );
699 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
700 $row = $this->fetchObject( $result );
701 return $row->lockstatus;
702 }
703
704 /**
705 * @param $read
706 * @param $write
707 * @param $method
708 * @param $lowPriority bool
709 */
710 public function lockTables( $read, $write, $method, $lowPriority = true ) {
711 $items = array();
712
713 foreach( $write as $table ) {
714 $tbl = $this->tableName( $table ) .
715 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
716 ' WRITE';
717 $items[] = $tbl;
718 }
719 foreach( $read as $table ) {
720 $items[] = $this->tableName( $table ) . ' READ';
721 }
722 $sql = "LOCK TABLES " . implode( ',', $items );
723 $this->query( $sql, $method );
724 }
725
726 /**
727 * @param $method string
728 */
729 public function unlockTables( $method ) {
730 $this->query( "UNLOCK TABLES", $method );
731 }
732
733 /**
734 * Get search engine class. All subclasses of this
735 * need to implement this if they wish to use searching.
736 *
737 * @return String
738 */
739 public function getSearchEngine() {
740 return 'SearchMySQL';
741 }
742
743 /**
744 * @param bool $value
745 * @return mixed
746 */
747 public function setBigSelects( $value = true ) {
748 if ( $value === 'default' ) {
749 if ( $this->mDefaultBigSelects === null ) {
750 # Function hasn't been called before so it must already be set to the default
751 return;
752 } else {
753 $value = $this->mDefaultBigSelects;
754 }
755 } elseif ( $this->mDefaultBigSelects === null ) {
756 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
757 }
758 $encValue = $value ? '1' : '0';
759 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
760 }
761
762 /**
763 * DELETE where the condition is a join. MySql uses multi-table deletes.
764 * @param $delTable
765 * @param $joinTable
766 * @param $delVar
767 * @param $joinVar
768 * @param $conds array|string
769 * @param $fname bool
770 * @return bool|\ResultWrapper
771 */
772 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
773 if ( !$conds ) {
774 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
775 }
776
777 $delTable = $this->tableName( $delTable );
778 $joinTable = $this->tableName( $joinTable );
779 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
780
781 if ( $conds != '*' ) {
782 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
783 }
784
785 return $this->query( $sql, $fname );
786 }
787
788 /**
789 * Determines how long the server has been up
790 *
791 * @return int
792 */
793 function getServerUptime() {
794 $vars = $this->getMysqlStatus( 'Uptime' );
795 return (int)$vars['Uptime'];
796 }
797
798 /**
799 * Determines if the last failure was due to a deadlock
800 *
801 * @return bool
802 */
803 function wasDeadlock() {
804 return $this->lastErrno() == 1213;
805 }
806
807 /**
808 * Determines if the last failure was due to a lock timeout
809 *
810 * @return bool
811 */
812 function wasLockTimeout() {
813 return $this->lastErrno() == 1205;
814 }
815
816 /**
817 * Determines if the last query error was something that should be dealt
818 * with by pinging the connection and reissuing the query
819 *
820 * @return bool
821 */
822 function wasErrorReissuable() {
823 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
824 }
825
826 /**
827 * Determines if the last failure was due to the database being read-only.
828 *
829 * @return bool
830 */
831 function wasReadOnlyError() {
832 return $this->lastErrno() == 1223 ||
833 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
834 }
835
836 /**
837 * @param $oldName
838 * @param $newName
839 * @param $temporary bool
840 * @param $fname string
841 */
842 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
843 $tmp = $temporary ? 'TEMPORARY ' : '';
844 $newName = $this->addIdentifierQuotes( $newName );
845 $oldName = $this->addIdentifierQuotes( $oldName );
846 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
847 $this->query( $query, $fname );
848 }
849
850 /**
851 * List all tables on the database
852 *
853 * @param $prefix Only show tables with this prefix, e.g. mw_
854 * @param $fname String: calling function name
855 * @return array
856 */
857 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
858 $result = $this->query( "SHOW TABLES", $fname);
859
860 $endArray = array();
861
862 foreach( $result as $table ) {
863 $vars = get_object_vars($table);
864 $table = array_pop( $vars );
865
866 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
867 $endArray[] = $table;
868 }
869 }
870
871 return $endArray;
872 }
873
874 /**
875 * @param $tableName
876 * @param $fName string
877 * @return bool|ResultWrapper
878 */
879 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
880 if( !$this->tableExists( $tableName, $fName ) ) {
881 return false;
882 }
883 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
884 }
885
886 /**
887 * @return array
888 */
889 protected function getDefaultSchemaVars() {
890 $vars = parent::getDefaultSchemaVars();
891 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
892 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $GLOBALS['wgDBTableOptions'] );
893 return $vars;
894 }
895
896 /**
897 * Get status information from SHOW STATUS in an associative array
898 *
899 * @param $which string
900 * @return array
901 */
902 function getMysqlStatus( $which = "%" ) {
903 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
904 $status = array();
905
906 foreach ( $res as $row ) {
907 $status[$row->Variable_name] = $row->Value;
908 }
909
910 return $status;
911 }
912
913 }
914
915 /**
916 * Legacy support: Database == DatabaseMysql
917 *
918 * @deprecated in 1.16
919 */
920 class Database extends DatabaseMysql {}
921
922 /**
923 * Utility class.
924 * @ingroup Database
925 */
926 class MySQLField implements Field {
927 private $name, $tablename, $default, $max_length, $nullable,
928 $is_pk, $is_unique, $is_multiple, $is_key, $type;
929
930 function __construct ( $info ) {
931 $this->name = $info->name;
932 $this->tablename = $info->table;
933 $this->default = $info->def;
934 $this->max_length = $info->max_length;
935 $this->nullable = !$info->not_null;
936 $this->is_pk = $info->primary_key;
937 $this->is_unique = $info->unique_key;
938 $this->is_multiple = $info->multiple_key;
939 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
940 $this->type = $info->type;
941 }
942
943 /**
944 * @return string
945 */
946 function name() {
947 return $this->name;
948 }
949
950 /**
951 * @return string
952 */
953 function tableName() {
954 return $this->tableName;
955 }
956
957 /**
958 * @return string
959 */
960 function type() {
961 return $this->type;
962 }
963
964 /**
965 * @return bool
966 */
967 function isNullable() {
968 return $this->nullable;
969 }
970
971 function defaultValue() {
972 return $this->default;
973 }
974
975 /**
976 * @return bool
977 */
978 function isKey() {
979 return $this->is_key;
980 }
981
982 /**
983 * @return bool
984 */
985 function isMultipleKey() {
986 return $this->is_multiple;
987 }
988 }
989
990 class MySQLMasterPos implements DBMasterPos {
991 var $file, $pos;
992
993 function __construct( $file, $pos ) {
994 $this->file = $file;
995 $this->pos = $pos;
996 }
997
998 function __toString() {
999 return "{$this->file}/{$this->pos}";
1000 }
1001 }