Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / db / DatabaseMysql.php
blobca5a2b4cbf48102c92d7345b5da2398d67c4c74a
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
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.
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.
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
20 * @file
21 * @ingroup Database
24 /**
25 * Database abstraction object for mySQL
26 * Inherit all methods and properties of Database::Database()
28 * @ingroup Database
29 * @see Database
31 class DatabaseMysql extends DatabaseBase {
33 /**
34 * @return string
36 function getType() {
37 return 'mysql';
40 /**
41 * @param $sql string
42 * @return resource
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 );
50 return $ret;
53 /**
54 * @param $server string
55 * @param $user string
56 * @param $password string
57 * @param $dbName string
58 * @return bool
59 * @throws DBConnectionError
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
63 wfProfileIn( __METHOD__ );
65 # Load mysql.so if we don't have it
66 wfDl( 'mysql' );
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 wfProfileOut( __METHOD__ );
72 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
75 # Debugging hack -- fake cluster
76 if ( $wgAllDBsAreLocalhost ) {
77 $realServer = 'localhost';
78 } else {
79 $realServer = $server;
81 $this->close();
82 $this->mServer = $server;
83 $this->mUser = $user;
84 $this->mPassword = $password;
85 $this->mDBname = $dbName;
87 $connFlags = 0;
88 if ( $this->mFlags & DBO_SSL ) {
89 $connFlags |= MYSQL_CLIENT_SSL;
91 if ( $this->mFlags & DBO_COMPRESS ) {
92 $connFlags |= MYSQL_CLIENT_COMPRESS;
95 wfProfileIn( "dbconnect-$server" );
97 # The kernel's default SYN retransmission period is far too slow for us,
98 # so we use a short timeout plus a manual retry. Retrying means that a small
99 # but finite rate of SYN packet loss won't cause user-visible errors.
100 $this->mConn = false;
101 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
102 $numAttempts = 2;
103 } else {
104 $numAttempts = 1;
106 $this->installErrorHandler();
107 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
108 if ( $i > 1 ) {
109 usleep( 1000 );
111 if ( $this->mFlags & DBO_PERSISTENT ) {
112 $this->mConn = mysql_pconnect( $realServer, $user, $password, $connFlags );
113 } else {
114 # Create a new connection...
115 $this->mConn = mysql_connect( $realServer, $user, $password, true, $connFlags );
117 #if ( $this->mConn === false ) {
118 #$iplus = $i + 1;
119 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
122 $error = $this->restoreErrorHandler();
124 wfProfileOut( "dbconnect-$server" );
126 # Always log connection errors
127 if ( !$this->mConn ) {
128 if ( !$error ) {
129 $error = $this->lastError();
131 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
132 wfDebug( "DB connection error\n" .
133 "Server: $server, User: $user, Password: " .
134 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
136 wfProfileOut( __METHOD__ );
137 return $this->reportConnectionError( $error );
140 if ( $dbName != '' ) {
141 wfSuppressWarnings();
142 $success = mysql_select_db( $dbName, $this->mConn );
143 wfRestoreWarnings();
144 if ( !$success ) {
145 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
146 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
147 "from client host " . wfHostname() . "\n" );
149 wfProfileOut( __METHOD__ );
150 return $this->reportConnectionError( "Error selecting database $dbName" );
154 // Tell the server we're communicating with it in UTF-8.
155 // This may engage various charset conversions.
156 if ( $wgDBmysql5 ) {
157 $this->query( 'SET NAMES utf8', __METHOD__ );
158 } else {
159 $this->query( 'SET NAMES binary', __METHOD__ );
161 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
162 if ( is_string( $wgSQLMode ) ) {
163 $mode = $this->addQuotes( $wgSQLMode );
164 $this->query( "SET sql_mode = $mode", __METHOD__ );
167 $this->mOpened = true;
168 wfProfileOut( __METHOD__ );
169 return true;
173 * @return bool
175 protected function closeConnection() {
176 return mysql_close( $this->mConn );
180 * @param $res ResultWrapper
181 * @throws DBUnexpectedError
183 function freeResult( $res ) {
184 if ( $res instanceof ResultWrapper ) {
185 $res = $res->result;
187 wfSuppressWarnings();
188 $ok = mysql_free_result( $res );
189 wfRestoreWarnings();
190 if ( !$ok ) {
191 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
196 * @param $res ResultWrapper
197 * @return object|bool
198 * @throws DBUnexpectedError
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper ) {
202 $res = $res->result;
204 wfSuppressWarnings();
205 $row = mysql_fetch_object( $res );
206 wfRestoreWarnings();
208 $errno = $this->lastErrno();
209 // Unfortunately, mysql_fetch_object does not reset the last errno.
210 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
211 // these are the only errors mysql_fetch_object can cause.
212 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
213 if ( $errno == 2000 || $errno == 2013 ) {
214 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
216 return $row;
220 * @param $res ResultWrapper
221 * @return array|bool
222 * @throws DBUnexpectedError
224 function fetchRow( $res ) {
225 if ( $res instanceof ResultWrapper ) {
226 $res = $res->result;
228 wfSuppressWarnings();
229 $row = mysql_fetch_array( $res );
230 wfRestoreWarnings();
232 $errno = $this->lastErrno();
233 // Unfortunately, mysql_fetch_array does not reset the last errno.
234 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
235 // these are the only errors mysql_fetch_object can cause.
236 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
237 if ( $errno == 2000 || $errno == 2013 ) {
238 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
240 return $row;
244 * @throws DBUnexpectedError
245 * @param $res ResultWrapper
246 * @return int
248 function numRows( $res ) {
249 if ( $res instanceof ResultWrapper ) {
250 $res = $res->result;
252 wfSuppressWarnings();
253 $n = mysql_num_rows( $res );
254 wfRestoreWarnings();
255 // Unfortunately, mysql_num_rows does not reset the last errno.
256 // We are not checking for any errors here, since
257 // these are no errors mysql_num_rows can cause.
258 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
259 // See https://bugzilla.wikimedia.org/42430
260 return $n;
264 * @param $res ResultWrapper
265 * @return int
267 function numFields( $res ) {
268 if ( $res instanceof ResultWrapper ) {
269 $res = $res->result;
271 return mysql_num_fields( $res );
275 * @param $res ResultWrapper
276 * @param $n string
277 * @return string
279 function fieldName( $res, $n ) {
280 if ( $res instanceof ResultWrapper ) {
281 $res = $res->result;
283 return mysql_field_name( $res, $n );
287 * @return int
289 function insertId() {
290 return mysql_insert_id( $this->mConn );
294 * @param $res ResultWrapper
295 * @param $row
296 * @return bool
298 function dataSeek( $res, $row ) {
299 if ( $res instanceof ResultWrapper ) {
300 $res = $res->result;
302 return mysql_data_seek( $res, $row );
306 * @return int
308 function lastErrno() {
309 if ( $this->mConn ) {
310 return mysql_errno( $this->mConn );
311 } else {
312 return mysql_errno();
317 * @return string
319 function lastError() {
320 if ( $this->mConn ) {
321 # Even if it's non-zero, it can still be invalid
322 wfSuppressWarnings();
323 $error = mysql_error( $this->mConn );
324 if ( !$error ) {
325 $error = mysql_error();
327 wfRestoreWarnings();
328 } else {
329 $error = mysql_error();
331 if ( $error ) {
332 $error .= ' (' . $this->mServer . ')';
334 return $error;
338 * @return int
340 function affectedRows() {
341 return mysql_affected_rows( $this->mConn );
345 * @param $table string
346 * @param $uniqueIndexes
347 * @param $rows array
348 * @param $fname string
349 * @return ResultWrapper
351 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
352 return $this->nativeReplace( $table, $rows, $fname );
356 * Estimate rows in dataset
357 * Returns estimated count, based on EXPLAIN output
358 * Takes same arguments as Database::select()
360 * @param $table string|array
361 * @param $vars string|array
362 * @param $conds string|array
363 * @param $fname string
364 * @param $options string|array
365 * @return int
367 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
368 $options['EXPLAIN'] = true;
369 $res = $this->select( $table, $vars, $conds, $fname, $options );
370 if ( $res === false ) {
371 return false;
373 if ( !$this->numRows( $res ) ) {
374 return 0;
377 $rows = 1;
378 foreach ( $res as $plan ) {
379 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
381 return $rows;
385 * @param $table string
386 * @param $field string
387 * @return bool|MySQLField
389 function fieldInfo( $table, $field ) {
390 $table = $this->tableName( $table );
391 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
392 if ( !$res ) {
393 return false;
395 $n = mysql_num_fields( $res->result );
396 for ( $i = 0; $i < $n; $i++ ) {
397 $meta = mysql_fetch_field( $res->result, $i );
398 if ( $field == $meta->name ) {
399 return new MySQLField( $meta );
402 return false;
406 * Get information about an index into an object
407 * Returns false if the index does not exist
409 * @param $table string
410 * @param $index string
411 * @param $fname string
412 * @return bool|array|null False or null on failure
414 function indexInfo( $table, $index, $fname = __METHOD__ ) {
415 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
416 # SHOW INDEX should work for 3.x and up:
417 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
418 $table = $this->tableName( $table );
419 $index = $this->indexName( $index );
421 $sql = 'SHOW INDEX FROM ' . $table;
422 $res = $this->query( $sql, $fname );
424 if ( !$res ) {
425 return null;
428 $result = array();
430 foreach ( $res as $row ) {
431 if ( $row->Key_name == $index ) {
432 $result[] = $row;
435 return empty( $result ) ? false : $result;
439 * @param $db
440 * @return bool
442 function selectDB( $db ) {
443 $this->mDBname = $db;
444 return mysql_select_db( $db, $this->mConn );
448 * @param $s string
450 * @return string
452 function strencode( $s ) {
453 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
455 if ( $sQuoted === false ) {
456 $this->ping();
457 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
459 return $sQuoted;
463 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
465 * @param $s string
467 * @return string
469 public function addIdentifierQuotes( $s ) {
470 return "`" . $this->strencode( $s ) . "`";
474 * @param $name string
475 * @return bool
477 public function isQuotedIdentifier( $name ) {
478 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
482 * @return bool
484 function ping() {
485 $ping = mysql_ping( $this->mConn );
486 if ( $ping ) {
487 return true;
490 mysql_close( $this->mConn );
491 $this->mOpened = false;
492 $this->mConn = false;
493 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
494 return true;
498 * Returns slave lag.
500 * This will do a SHOW SLAVE STATUS
502 * @return int
504 function getLag() {
505 if ( !is_null( $this->mFakeSlaveLag ) ) {
506 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
507 return $this->mFakeSlaveLag;
510 return $this->getLagFromSlaveStatus();
514 * @return bool|int
516 function getLagFromSlaveStatus() {
517 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
518 if ( !$res ) {
519 return false;
521 $row = $res->fetchObject();
522 if ( !$row ) {
523 return false;
525 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
526 return false;
527 } else {
528 return intval( $row->Seconds_Behind_Master );
533 * @deprecated in 1.19, use getLagFromSlaveStatus
535 * @return bool|int
537 function getLagFromProcesslist() {
538 wfDeprecated( __METHOD__, '1.19' );
539 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
540 if ( !$res ) {
541 return false;
543 # Find slave SQL thread
544 foreach ( $res as $row ) {
545 /* This should work for most situations - when default db
546 * for thread is not specified, it had no events executed,
547 * and therefore it doesn't know yet how lagged it is.
549 * Relay log I/O thread does not select databases.
551 if ( $row->User == 'system user' &&
552 $row->State != 'Waiting for master to send event' &&
553 $row->State != 'Connecting to master' &&
554 $row->State != 'Queueing master event to the relay log' &&
555 $row->State != 'Waiting for master update' &&
556 $row->State != 'Requesting binlog dump' &&
557 $row->State != 'Waiting to reconnect after a failed master event read' &&
558 $row->State != 'Reconnecting after a failed master event read' &&
559 $row->State != 'Registering slave on master'
561 # This is it, return the time (except -ve)
562 if ( $row->Time > 0x7fffffff ) {
563 return false;
564 } else {
565 return $row->Time;
569 return false;
573 * Wait for the slave to catch up to a given master position.
575 * @param $pos DBMasterPos object
576 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
577 * @return bool|string
579 function masterPosWait( DBMasterPos $pos, $timeout ) {
580 $fname = __METHOD__;
581 wfProfileIn( $fname );
583 # Commit any open transactions
584 if ( $this->mTrxLevel ) {
585 $this->commit( $fname );
588 if ( !is_null( $this->mFakeSlaveLag ) ) {
589 $status = parent::masterPosWait( $pos, $timeout );
590 wfProfileOut( $fname );
591 return $status;
594 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
595 $encFile = $this->addQuotes( $pos->file );
596 $encPos = intval( $pos->pos );
597 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
598 $res = $this->doQuery( $sql );
600 if ( $res && $row = $this->fetchRow( $res ) ) {
601 wfProfileOut( $fname );
602 return $row[0];
604 wfProfileOut( $fname );
605 return false;
609 * Get the position of the master from SHOW SLAVE STATUS
611 * @return MySQLMasterPos|bool
613 function getSlavePos() {
614 if ( !is_null( $this->mFakeSlaveLag ) ) {
615 return parent::getSlavePos();
618 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
619 $row = $this->fetchObject( $res );
621 if ( $row ) {
622 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
623 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
624 } else {
625 return false;
630 * Get the position of the master from SHOW MASTER STATUS
632 * @return MySQLMasterPos|bool
634 function getMasterPos() {
635 if ( $this->mFakeMaster ) {
636 return parent::getMasterPos();
639 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
640 $row = $this->fetchObject( $res );
642 if ( $row ) {
643 return new MySQLMasterPos( $row->File, $row->Position );
644 } else {
645 return false;
650 * @return string
652 function getServerVersion() {
653 return mysql_get_server_info( $this->mConn );
657 * @param $index
658 * @return string
660 function useIndexClause( $index ) {
661 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
665 * @return string
667 function lowPriorityOption() {
668 return 'LOW_PRIORITY';
672 * @return string
674 public function getSoftwareLink() {
675 return '[http://www.mysql.com/ MySQL]';
679 * @param $options array
681 public function setSessionOptions( array $options ) {
682 if ( isset( $options['connTimeout'] ) ) {
683 $timeout = (int)$options['connTimeout'];
684 $this->query( "SET net_read_timeout=$timeout" );
685 $this->query( "SET net_write_timeout=$timeout" );
689 public function streamStatementEnd( &$sql, &$newLine ) {
690 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
691 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
692 $this->delimiter = $m[1];
693 $newLine = '';
695 return parent::streamStatementEnd( $sql, $newLine );
699 * Check to see if a named lock is available. This is non-blocking.
701 * @param string $lockName name of lock to poll
702 * @param string $method name of method calling us
703 * @return Boolean
704 * @since 1.20
706 public function lockIsFree( $lockName, $method ) {
707 $lockName = $this->addQuotes( $lockName );
708 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
709 $row = $this->fetchObject( $result );
710 return ( $row->lockstatus == 1 );
714 * @param $lockName string
715 * @param $method string
716 * @param $timeout int
717 * @return bool
719 public function lock( $lockName, $method, $timeout = 5 ) {
720 $lockName = $this->addQuotes( $lockName );
721 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
722 $row = $this->fetchObject( $result );
724 if ( $row->lockstatus == 1 ) {
725 return true;
726 } else {
727 wfDebug( __METHOD__ . " failed to acquire lock\n" );
728 return false;
733 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
734 * @param $lockName string
735 * @param $method string
736 * @return bool
738 public function unlock( $lockName, $method ) {
739 $lockName = $this->addQuotes( $lockName );
740 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
741 $row = $this->fetchObject( $result );
742 return ( $row->lockstatus == 1 );
746 * @param $read array
747 * @param $write array
748 * @param $method string
749 * @param $lowPriority bool
750 * @return bool
752 public function lockTables( $read, $write, $method, $lowPriority = true ) {
753 $items = array();
755 foreach ( $write as $table ) {
756 $tbl = $this->tableName( $table ) .
757 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
758 ' WRITE';
759 $items[] = $tbl;
761 foreach ( $read as $table ) {
762 $items[] = $this->tableName( $table ) . ' READ';
764 $sql = "LOCK TABLES " . implode( ',', $items );
765 $this->query( $sql, $method );
766 return true;
770 * @param $method string
771 * @return bool
773 public function unlockTables( $method ) {
774 $this->query( "UNLOCK TABLES", $method );
775 return true;
779 * Get search engine class. All subclasses of this
780 * need to implement this if they wish to use searching.
782 * @return String
784 public function getSearchEngine() {
785 return 'SearchMySQL';
789 * @param bool $value
790 * @return mixed
792 public function setBigSelects( $value = true ) {
793 if ( $value === 'default' ) {
794 if ( $this->mDefaultBigSelects === null ) {
795 # Function hasn't been called before so it must already be set to the default
796 return;
797 } else {
798 $value = $this->mDefaultBigSelects;
800 } elseif ( $this->mDefaultBigSelects === null ) {
801 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
803 $encValue = $value ? '1' : '0';
804 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
808 * DELETE where the condition is a join. MySql uses multi-table deletes.
809 * @param $delTable string
810 * @param $joinTable string
811 * @param $delVar string
812 * @param $joinVar string
813 * @param $conds array|string
814 * @param bool|string $fname bool
815 * @throws DBUnexpectedError
816 * @return bool|ResultWrapper
818 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__ ) {
819 if ( !$conds ) {
820 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
823 $delTable = $this->tableName( $delTable );
824 $joinTable = $this->tableName( $joinTable );
825 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
827 if ( $conds != '*' ) {
828 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
831 return $this->query( $sql, $fname );
835 * Determines how long the server has been up
837 * @return int
839 function getServerUptime() {
840 $vars = $this->getMysqlStatus( 'Uptime' );
841 return (int)$vars['Uptime'];
845 * Determines if the last failure was due to a deadlock
847 * @return bool
849 function wasDeadlock() {
850 return $this->lastErrno() == 1213;
854 * Determines if the last failure was due to a lock timeout
856 * @return bool
858 function wasLockTimeout() {
859 return $this->lastErrno() == 1205;
863 * Determines if the last query error was something that should be dealt
864 * with by pinging the connection and reissuing the query
866 * @return bool
868 function wasErrorReissuable() {
869 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
873 * Determines if the last failure was due to the database being read-only.
875 * @return bool
877 function wasReadOnlyError() {
878 return $this->lastErrno() == 1223 ||
879 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
883 * @param $oldName
884 * @param $newName
885 * @param $temporary bool
886 * @param $fname string
888 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
889 $tmp = $temporary ? 'TEMPORARY ' : '';
890 $newName = $this->addIdentifierQuotes( $newName );
891 $oldName = $this->addIdentifierQuotes( $oldName );
892 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
893 $this->query( $query, $fname );
897 * List all tables on the database
899 * @param string $prefix Only show tables with this prefix, e.g. mw_
900 * @param string $fname calling function name
901 * @return array
903 function listTables( $prefix = null, $fname = __METHOD__ ) {
904 $result = $this->query( "SHOW TABLES", $fname );
906 $endArray = array();
908 foreach ( $result as $table ) {
909 $vars = get_object_vars( $table );
910 $table = array_pop( $vars );
912 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
913 $endArray[] = $table;
917 return $endArray;
921 * @param $tableName
922 * @param $fName string
923 * @return bool|ResultWrapper
925 public function dropTable( $tableName, $fName = __METHOD__ ) {
926 if ( !$this->tableExists( $tableName, $fName ) ) {
927 return false;
929 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
933 * @return array
935 protected function getDefaultSchemaVars() {
936 $vars = parent::getDefaultSchemaVars();
937 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
938 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
939 return $vars;
943 * Get status information from SHOW STATUS in an associative array
945 * @param $which string
946 * @return array
948 function getMysqlStatus( $which = "%" ) {
949 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
950 $status = array();
952 foreach ( $res as $row ) {
953 $status[$row->Variable_name] = $row->Value;
956 return $status;
962 * Utility class.
963 * @ingroup Database
965 class MySQLField implements Field {
966 private $name, $tablename, $default, $max_length, $nullable,
967 $is_pk, $is_unique, $is_multiple, $is_key, $type;
969 function __construct( $info ) {
970 $this->name = $info->name;
971 $this->tablename = $info->table;
972 $this->default = $info->def;
973 $this->max_length = $info->max_length;
974 $this->nullable = !$info->not_null;
975 $this->is_pk = $info->primary_key;
976 $this->is_unique = $info->unique_key;
977 $this->is_multiple = $info->multiple_key;
978 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
979 $this->type = $info->type;
983 * @return string
985 function name() {
986 return $this->name;
990 * @return string
992 function tableName() {
993 return $this->tableName;
997 * @return string
999 function type() {
1000 return $this->type;
1004 * @return bool
1006 function isNullable() {
1007 return $this->nullable;
1010 function defaultValue() {
1011 return $this->default;
1015 * @return bool
1017 function isKey() {
1018 return $this->is_key;
1022 * @return bool
1024 function isMultipleKey() {
1025 return $this->is_multiple;
1029 class MySQLMasterPos implements DBMasterPos {
1030 var $file, $pos;
1032 function __construct( $file, $pos ) {
1033 $this->file = $file;
1034 $this->pos = $pos;
1037 function __toString() {
1038 return "{$this->file}/{$this->pos}";