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
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
32 abstract class DatabaseMysqlBase
extends DatabaseBase
{
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
44 * @param string $server
46 * @param string $password
47 * @param string $dbName
48 * @throws Exception|DBConnectionError
51 function open( $server, $user, $password, $dbName ) {
52 global $wgAllDBsAreLocalhost, $wgSQLMode;
53 wfProfileIn( __METHOD__
);
55 # Debugging hack -- fake cluster
56 if ( $wgAllDBsAreLocalhost ) {
57 $realServer = 'localhost';
59 $realServer = $server;
62 $this->mServer
= $server;
64 $this->mPassword
= $password;
65 $this->mDBname
= $dbName;
67 wfProfileIn( "dbconnect-$server" );
69 # The kernel's default SYN retransmission period is far too slow for us,
70 # so we use a short timeout plus a manual retry. Retrying means that a small
71 # but finite rate of SYN packet loss won't cause user-visible errors.
73 $this->installErrorHandler();
75 $this->mConn
= $this->mysqlConnect( $realServer );
76 } catch ( Exception
$ex ) {
77 wfProfileOut( "dbconnect-$server" );
78 wfProfileOut( __METHOD__
);
79 $this->restoreErrorHandler();
82 $error = $this->restoreErrorHandler();
84 wfProfileOut( "dbconnect-$server" );
86 # Always log connection errors
87 if ( !$this->mConn
) {
89 $error = $this->lastError();
91 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
92 wfDebug( "DB connection error\n" .
93 "Server: $server, User: $user, Password: " .
94 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
96 wfProfileOut( __METHOD__
);
98 $this->reportConnectionError( $error );
101 if ( $dbName != '' ) {
102 wfSuppressWarnings();
103 $success = $this->selectDB( $dbName );
106 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
107 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
108 "from client host " . wfHostname() . "\n" );
110 wfProfileOut( __METHOD__
);
112 $this->reportConnectionError( "Error selecting database $dbName" );
116 // Tell the server what we're communicating with
117 if ( !$this->connectInitCharset() ) {
118 $this->reportConnectionError( "Error setting character set" );
121 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
122 if ( is_string( $wgSQLMode ) ) {
123 $mode = $this->addQuotes( $wgSQLMode );
124 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
125 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
127 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
128 wfProfileOut( __METHOD__
);
129 $this->reportConnectionError( "Error setting sql_mode to $mode" );
133 $this->mOpened
= true;
134 wfProfileOut( __METHOD__
);
140 * Set the character set information right after connection
143 protected function connectInitCharset() {
147 // Tell the server we're communicating with it in UTF-8.
148 // This may engage various charset conversions.
149 return $this->mysqlSetCharset( 'utf8' );
151 return $this->mysqlSetCharset( 'binary' );
156 * Open a connection to a MySQL server
158 * @param string $realServer
159 * @return mixed Raw connection
160 * @throws DBConnectionError
162 abstract protected function mysqlConnect( $realServer );
165 * Set the character set of the MySQL link
167 * @param string $charset
170 abstract protected function mysqlSetCharset( $charset );
173 * @param ResultWrapper|resource $res
174 * @throws DBUnexpectedError
176 function freeResult( $res ) {
177 if ( $res instanceof ResultWrapper
) {
180 wfSuppressWarnings();
181 $ok = $this->mysqlFreeResult( $res );
184 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
191 * @param resource $res Raw result
194 abstract protected function mysqlFreeResult( $res );
197 * @param ResultWrapper|resource $res
198 * @return stdClass|bool
199 * @throws DBUnexpectedError
201 function fetchObject( $res ) {
202 if ( $res instanceof ResultWrapper
) {
205 wfSuppressWarnings();
206 $row = $this->mysqlFetchObject( $res );
209 $errno = $this->lastErrno();
210 // Unfortunately, mysql_fetch_object does not reset the last errno.
211 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
212 // these are the only errors mysql_fetch_object can cause.
213 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
214 if ( $errno == 2000 ||
$errno == 2013 ) {
215 throw new DBUnexpectedError(
217 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
225 * Fetch a result row as an object
227 * @param resource $res Raw result
230 abstract protected function mysqlFetchObject( $res );
233 * @param ResultWrapper|resource $res
235 * @throws DBUnexpectedError
237 function fetchRow( $res ) {
238 if ( $res instanceof ResultWrapper
) {
241 wfSuppressWarnings();
242 $row = $this->mysqlFetchArray( $res );
245 $errno = $this->lastErrno();
246 // Unfortunately, mysql_fetch_array does not reset the last errno.
247 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
248 // these are the only errors mysql_fetch_array can cause.
249 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
250 if ( $errno == 2000 ||
$errno == 2013 ) {
251 throw new DBUnexpectedError(
253 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
261 * Fetch a result row as an associative and numeric array
263 * @param resource $res Raw result
266 abstract protected function mysqlFetchArray( $res );
269 * @throws DBUnexpectedError
270 * @param ResultWrapper|resource $res
273 function numRows( $res ) {
274 if ( $res instanceof ResultWrapper
) {
277 wfSuppressWarnings();
278 $n = $this->mysqlNumRows( $res );
281 // Unfortunately, mysql_num_rows does not reset the last errno.
282 // We are not checking for any errors here, since
283 // these are no errors mysql_num_rows can cause.
284 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
285 // See https://bugzilla.wikimedia.org/42430
290 * Get number of rows in result
292 * @param resource $res Raw result
295 abstract protected function mysqlNumRows( $res );
298 * @param ResultWrapper|resource $res
301 function numFields( $res ) {
302 if ( $res instanceof ResultWrapper
) {
306 return $this->mysqlNumFields( $res );
310 * Get number of fields in result
312 * @param resource $res Raw result
315 abstract protected function mysqlNumFields( $res );
318 * @param ResultWrapper|resource $res
322 function fieldName( $res, $n ) {
323 if ( $res instanceof ResultWrapper
) {
327 return $this->mysqlFieldName( $res, $n );
331 * Get the name of the specified field in a result
333 * @param ResultWrapper|resource $res
337 abstract protected function mysqlFieldName( $res, $n );
340 * mysql_field_type() wrapper
341 * @param ResultWrapper|resource $res
345 public function fieldType( $res, $n ) {
346 if ( $res instanceof ResultWrapper
) {
350 return $this->mysqlFieldType( $res, $n );
354 * Get the type of the specified field in a result
356 * @param ResultWrapper|resource $res
360 abstract protected function mysqlFieldType( $res, $n );
363 * @param ResultWrapper|resource $res
367 function dataSeek( $res, $row ) {
368 if ( $res instanceof ResultWrapper
) {
372 return $this->mysqlDataSeek( $res, $row );
376 * Move internal result pointer
378 * @param ResultWrapper|resource $res
382 abstract protected function mysqlDataSeek( $res, $row );
387 function lastError() {
388 if ( $this->mConn
) {
389 # Even if it's non-zero, it can still be invalid
390 wfSuppressWarnings();
391 $error = $this->mysqlError( $this->mConn
);
393 $error = $this->mysqlError();
397 $error = $this->mysqlError();
400 $error .= ' (' . $this->mServer
. ')';
407 * Returns the text of the error message from previous MySQL operation
409 * @param resource $conn Raw connection
412 abstract protected function mysqlError( $conn = null );
415 * @param string $table
416 * @param array $uniqueIndexes
418 * @param string $fname
419 * @return ResultWrapper
421 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
422 return $this->nativeReplace( $table, $rows, $fname );
426 * Estimate rows in dataset
427 * Returns estimated count, based on EXPLAIN output
428 * Takes same arguments as Database::select()
430 * @param string|array $table
431 * @param string|array $vars
432 * @param string|array $conds
433 * @param string $fname
434 * @param string|array $options
437 public function estimateRowCount( $table, $vars = '*', $conds = '',
438 $fname = __METHOD__
, $options = array()
440 $options['EXPLAIN'] = true;
441 $res = $this->select( $table, $vars, $conds, $fname, $options );
442 if ( $res === false ) {
445 if ( !$this->numRows( $res ) ) {
450 foreach ( $res as $plan ) {
451 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
458 * @param string $table
459 * @param string $field
460 * @return bool|MySQLField
462 function fieldInfo( $table, $field ) {
463 $table = $this->tableName( $table );
464 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
468 $n = $this->mysqlNumFields( $res->result
);
469 for ( $i = 0; $i < $n; $i++
) {
470 $meta = $this->mysqlFetchField( $res->result
, $i );
471 if ( $field == $meta->name
) {
472 return new MySQLField( $meta );
480 * Get column information from a result
482 * @param resource $res Raw result
486 abstract protected function mysqlFetchField( $res, $n );
489 * Get information about an index into an object
490 * Returns false if the index does not exist
492 * @param string $table
493 * @param string $index
494 * @param string $fname
495 * @return bool|array|null False or null on failure
497 function indexInfo( $table, $index, $fname = __METHOD__
) {
498 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
499 # SHOW INDEX should work for 3.x and up:
500 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
501 $table = $this->tableName( $table );
502 $index = $this->indexName( $index );
504 $sql = 'SHOW INDEX FROM ' . $table;
505 $res = $this->query( $sql, $fname );
513 foreach ( $res as $row ) {
514 if ( $row->Key_name
== $index ) {
519 return empty( $result ) ?
false : $result;
526 function strencode( $s ) {
527 $sQuoted = $this->mysqlRealEscapeString( $s );
529 if ( $sQuoted === false ) {
531 $sQuoted = $this->mysqlRealEscapeString( $s );
538 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
543 public function addIdentifierQuotes( $s ) {
544 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
545 // Remove NUL bytes and escape backticks by doubling
546 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
550 * @param string $name
553 public function isQuotedIdentifier( $name ) {
554 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
561 $ping = $this->mysqlPing();
566 $this->closeConnection();
567 $this->mOpened
= false;
568 $this->mConn
= false;
569 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
575 * Ping a server connection or reconnect if there is no connection
579 abstract protected function mysqlPing();
584 * This will do a SHOW SLAVE STATUS
589 if ( !is_null( $this->mFakeSlaveLag
) ) {
590 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
592 return $this->mFakeSlaveLag
;
595 return $this->getLagFromSlaveStatus();
601 function getLagFromSlaveStatus() {
602 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
606 $row = $res->fetchObject();
610 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
613 return intval( $row->Seconds_Behind_Master
);
618 * @deprecated in 1.19, use getLagFromSlaveStatus
622 function getLagFromProcesslist() {
623 wfDeprecated( __METHOD__
, '1.19' );
624 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
628 # Find slave SQL thread
629 foreach ( $res as $row ) {
630 /* This should work for most situations - when default db
631 * for thread is not specified, it had no events executed,
632 * and therefore it doesn't know yet how lagged it is.
634 * Relay log I/O thread does not select databases.
636 if ( $row->User
== 'system user' &&
637 $row->State
!= 'Waiting for master to send event' &&
638 $row->State
!= 'Connecting to master' &&
639 $row->State
!= 'Queueing master event to the relay log' &&
640 $row->State
!= 'Waiting for master update' &&
641 $row->State
!= 'Requesting binlog dump' &&
642 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
643 $row->State
!= 'Reconnecting after a failed master event read' &&
644 $row->State
!= 'Registering slave on master'
646 # This is it, return the time (except -ve)
647 if ( $row->Time
> 0x7fffffff ) {
659 * Wait for the slave to catch up to a given master position.
660 * @todo Return values for this and base class are rubbish
662 * @param DBMasterPos|MySQLMasterPos $pos
663 * @param int $timeout The maximum number of seconds to wait for synchronisation
664 * @return bool|string
666 function masterPosWait( DBMasterPos
$pos, $timeout ) {
667 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
668 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
671 wfProfileIn( __METHOD__
);
672 # Commit any open transactions
673 $this->commit( __METHOD__
, 'flush' );
675 if ( !is_null( $this->mFakeSlaveLag
) ) {
676 $status = parent
::masterPosWait( $pos, $timeout );
677 wfProfileOut( __METHOD__
);
682 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
683 $encFile = $this->addQuotes( $pos->file
);
684 $encPos = intval( $pos->getMasterPos() );
685 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
686 $res = $this->doQuery( $sql );
689 if ( $res && $row = $this->fetchRow( $res ) ) {
690 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
691 if ( ctype_digit( $status ) ) { // success
692 $this->lastKnownSlavePos
= $pos;
696 wfProfileOut( __METHOD__
);
702 * Get the position of the master from SHOW SLAVE STATUS
704 * @return MySQLMasterPos|bool
706 function getSlavePos() {
707 if ( !is_null( $this->mFakeSlaveLag
) ) {
708 return parent
::getSlavePos();
711 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
712 $row = $this->fetchObject( $res );
715 $pos = isset( $row->Exec_master_log_pos
)
716 ?
$row->Exec_master_log_pos
717 : $row->Exec_Master_Log_Pos
;
719 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
726 * Get the position of the master from SHOW MASTER STATUS
728 * @return MySQLMasterPos|bool
730 function getMasterPos() {
731 if ( $this->mFakeMaster
) {
732 return parent
::getMasterPos();
735 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
736 $row = $this->fetchObject( $res );
739 return new MySQLMasterPos( $row->File
, $row->Position
);
746 * @param string $index
749 function useIndexClause( $index ) {
750 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
756 function lowPriorityOption() {
757 return 'LOW_PRIORITY';
763 public function getSoftwareLink() {
764 return '[http://www.mysql.com/ MySQL]';
768 * @param array $options
770 public function setSessionOptions( array $options ) {
771 if ( isset( $options['connTimeout'] ) ) {
772 $timeout = (int)$options['connTimeout'];
773 $this->query( "SET net_read_timeout=$timeout" );
774 $this->query( "SET net_write_timeout=$timeout" );
780 * @param string $newLine
783 public function streamStatementEnd( &$sql, &$newLine ) {
784 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
785 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
786 $this->delimiter
= $m[1];
790 return parent
::streamStatementEnd( $sql, $newLine );
794 * Check to see if a named lock is available. This is non-blocking.
796 * @param string $lockName name of lock to poll
797 * @param string $method name of method calling us
801 public function lockIsFree( $lockName, $method ) {
802 $lockName = $this->addQuotes( $lockName );
803 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
804 $row = $this->fetchObject( $result );
806 return ( $row->lockstatus
== 1 );
810 * @param string $lockName
811 * @param string $method
812 * @param int $timeout
815 public function lock( $lockName, $method, $timeout = 5 ) {
816 $lockName = $this->addQuotes( $lockName );
817 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
818 $row = $this->fetchObject( $result );
820 if ( $row->lockstatus
== 1 ) {
823 wfDebug( __METHOD__
. " failed to acquire lock\n" );
831 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
832 * @param string $lockName
833 * @param string $method
836 public function unlock( $lockName, $method ) {
837 $lockName = $this->addQuotes( $lockName );
838 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
839 $row = $this->fetchObject( $result );
841 return ( $row->lockstatus
== 1 );
846 * @param array $write
847 * @param string $method
848 * @param bool $lowPriority
851 public function lockTables( $read, $write, $method, $lowPriority = true ) {
854 foreach ( $write as $table ) {
855 $tbl = $this->tableName( $table ) .
856 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
860 foreach ( $read as $table ) {
861 $items[] = $this->tableName( $table ) . ' READ';
863 $sql = "LOCK TABLES " . implode( ',', $items );
864 $this->query( $sql, $method );
870 * @param string $method
873 public function unlockTables( $method ) {
874 $this->query( "UNLOCK TABLES", $method );
880 * Get search engine class. All subclasses of this
881 * need to implement this if they wish to use searching.
885 public function getSearchEngine() {
886 return 'SearchMySQL';
891 * @return mixed null|bool|ResultWrapper
893 public function setBigSelects( $value = true ) {
894 if ( $value === 'default' ) {
895 if ( $this->mDefaultBigSelects
=== null ) {
896 # Function hasn't been called before so it must already be set to the default
899 $value = $this->mDefaultBigSelects
;
901 } elseif ( $this->mDefaultBigSelects
=== null ) {
902 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
904 $encValue = $value ?
'1' : '0';
905 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
909 * DELETE where the condition is a join. MySql uses multi-table deletes.
910 * @param $delTable string
911 * @param $joinTable string
912 * @param $delVar string
913 * @param $joinVar string
914 * @param $conds array|string
915 * @param bool|string $fname bool
916 * @throws DBUnexpectedError
917 * @return bool|ResultWrapper
919 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
921 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
924 $delTable = $this->tableName( $delTable );
925 $joinTable = $this->tableName( $joinTable );
926 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
928 if ( $conds != '*' ) {
929 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
932 return $this->query( $sql, $fname );
936 * @param string $table
938 * @param array $uniqueIndexes
940 * @param string $fname
943 public function upsert( $table, array $rows, array $uniqueIndexes,
944 array $set, $fname = __METHOD__
946 if ( !count( $rows ) ) {
947 return true; // nothing to do
949 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
951 $table = $this->tableName( $table );
952 $columns = array_keys( $rows[0] );
954 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
955 $rowTuples = array();
956 foreach ( $rows as $row ) {
957 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
959 $sql .= implode( ',', $rowTuples );
960 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
962 return (bool)$this->query( $sql, $fname );
966 * Determines how long the server has been up
970 function getServerUptime() {
971 $vars = $this->getMysqlStatus( 'Uptime' );
973 return (int)$vars['Uptime'];
977 * Determines if the last failure was due to a deadlock
981 function wasDeadlock() {
982 return $this->lastErrno() == 1213;
986 * Determines if the last failure was due to a lock timeout
990 function wasLockTimeout() {
991 return $this->lastErrno() == 1205;
995 * Determines if the last query error was something that should be dealt
996 * with by pinging the connection and reissuing the query
1000 function wasErrorReissuable() {
1001 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1005 * Determines if the last failure was due to the database being read-only.
1009 function wasReadOnlyError() {
1010 return $this->lastErrno() == 1223 ||
1011 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1015 * @param string $oldName
1016 * @param string $newName
1017 * @param bool $temporary
1018 * @param string $fname
1021 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1022 $tmp = $temporary ?
'TEMPORARY ' : '';
1023 $newName = $this->addIdentifierQuotes( $newName );
1024 $oldName = $this->addIdentifierQuotes( $oldName );
1025 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1027 return $this->query( $query, $fname );
1031 * List all tables on the database
1033 * @param string $prefix Only show tables with this prefix, e.g. mw_
1034 * @param string $fname Calling function name
1037 function listTables( $prefix = null, $fname = __METHOD__
) {
1038 $result = $this->query( "SHOW TABLES", $fname );
1040 $endArray = array();
1042 foreach ( $result as $table ) {
1043 $vars = get_object_vars( $table );
1044 $table = array_pop( $vars );
1046 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1047 $endArray[] = $table;
1056 * @param $fName string
1057 * @return bool|ResultWrapper
1059 public function dropTable( $tableName, $fName = __METHOD__
) {
1060 if ( !$this->tableExists( $tableName, $fName ) ) {
1064 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1070 protected function getDefaultSchemaVars() {
1071 $vars = parent
::getDefaultSchemaVars();
1072 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1073 $vars['wgDBTableOptions'] = str_replace(
1076 $vars['wgDBTableOptions']
1083 * Get status information from SHOW STATUS in an associative array
1085 * @param string $which
1088 function getMysqlStatus( $which = "%" ) {
1089 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1092 foreach ( $res as $row ) {
1093 $status[$row->Variable_name
] = $row->Value
;
1100 * Lists VIEWs in the database
1102 * @param string $prefix Only show VIEWs with this prefix, eg.
1103 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1104 * @param string $fname Name of calling function
1108 public function listViews( $prefix = null, $fname = __METHOD__
) {
1110 if ( !isset( $this->allViews
) ) {
1112 // The name of the column containing the name of the VIEW
1113 $propertyName = 'Tables_in_' . $this->mDBname
;
1115 // Query for the VIEWS
1116 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1117 $this->allViews
= array();
1118 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1119 array_push( $this->allViews
, $row[$propertyName] );
1123 if ( is_null( $prefix ) ||
$prefix === '' ) {
1124 return $this->allViews
;
1127 $filteredViews = array();
1128 foreach ( $this->allViews
as $viewName ) {
1129 // Does the name of this VIEW start with the table-prefix?
1130 if ( strpos( $viewName, $prefix ) === 0 ) {
1131 array_push( $filteredViews, $viewName );
1135 return $filteredViews;
1139 * Differentiates between a TABLE and a VIEW.
1141 * @param string $name Name of the TABLE/VIEW to test
1142 * @param string $prefix
1146 public function isView( $name, $prefix = null ) {
1147 return in_array( $name, $this->listViews( $prefix ) );
1155 class MySQLField
implements Field
{
1156 private $name, $tablename, $default, $max_length, $nullable,
1157 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1159 function __construct( $info ) {
1160 $this->name
= $info->name
;
1161 $this->tablename
= $info->table
;
1162 $this->default = $info->def
;
1163 $this->max_length
= $info->max_length
;
1164 $this->nullable
= !$info->not_null
;
1165 $this->is_pk
= $info->primary_key
;
1166 $this->is_unique
= $info->unique_key
;
1167 $this->is_multiple
= $info->multiple_key
;
1168 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1169 $this->type
= $info->type
;
1170 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1183 function tableName() {
1184 return $this->tableName
;
1197 function isNullable() {
1198 return $this->nullable
;
1201 function defaultValue() {
1202 return $this->default;
1209 return $this->is_key
;
1215 function isMultipleKey() {
1216 return $this->is_multiple
;
1219 function isBinary() {
1220 return $this->binary
;
1224 class MySQLMasterPos
implements DBMasterPos
{
1231 function __construct( $file, $pos ) {
1232 $this->file
= $file;
1236 function __toString() {
1237 // e.g db1034-bin.000976/843431247
1238 return "{$this->file}/{$this->pos}";
1242 * @return array|false (int, int)
1244 protected function getCoordinates() {
1246 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1247 return array( (int)$m[1], (int)$m[2] );
1253 function hasReached( MySQLMasterPos
$pos ) {
1254 $thisPos = $this->getCoordinates();
1255 $thatPos = $pos->getCoordinates();
1257 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1263 public function getMasterPos() {