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;
37 protected $mFakeSlaveLag = null;
39 protected $mFakeMaster = false;
41 /** @var string|null */
42 private $serverVersion = null;
52 * @param string $server
54 * @param string $password
55 * @param string $dbName
56 * @throws Exception|DBConnectionError
59 function open( $server, $user, $password, $dbName ) {
60 global $wgAllDBsAreLocalhost, $wgSQLMode;
62 # Debugging hack -- fake cluster
63 if ( $wgAllDBsAreLocalhost ) {
64 $realServer = 'localhost';
66 $realServer = $server;
69 $this->mServer
= $server;
71 $this->mPassword
= $password;
72 $this->mDBname
= $dbName;
75 # The kernel's default SYN retransmission period is far too slow for us,
76 # so we use a short timeout plus a manual retry. Retrying means that a small
77 # but finite rate of SYN packet loss won't cause user-visible errors.
79 $this->installErrorHandler();
81 $this->mConn
= $this->mysqlConnect( $realServer );
82 } catch ( Exception
$ex ) {
83 $this->restoreErrorHandler();
86 $error = $this->restoreErrorHandler();
89 # Always log connection errors
90 if ( !$this->mConn
) {
92 $error = $this->lastError();
95 "Error connecting to {db_server}: {error}",
96 $this->getLogContext( array(
97 'method' => __METHOD__
,
101 wfDebug( "DB connection error\n" .
102 "Server: $server, User: $user, Password: " .
103 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
106 $this->reportConnectionError( $error );
109 if ( $dbName != '' ) {
110 wfSuppressWarnings();
111 $success = $this->selectDB( $dbName );
115 "Error selecting database {db_name} on server {db_server}",
116 $this->getLogContext( array(
117 'method' => __METHOD__
,
120 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
121 "from client host " . wfHostname() . "\n" );
124 $this->reportConnectionError( "Error selecting database $dbName" );
128 // Tell the server what we're communicating with
129 if ( !$this->connectInitCharset() ) {
130 $this->reportConnectionError( "Error setting character set" );
133 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
134 if ( is_string( $wgSQLMode ) ) {
135 $mode = $this->addQuotes( $wgSQLMode );
136 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
137 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
140 "Error setting sql_mode to $mode on server {db_server}",
141 $this->getLogContext( array(
142 'method' => __METHOD__
,
145 $this->reportConnectionError( "Error setting sql_mode to $mode" );
149 $this->mOpened
= true;
155 * Set the character set information right after connection
158 protected function connectInitCharset() {
162 // Tell the server we're communicating with it in UTF-8.
163 // This may engage various charset conversions.
164 return $this->mysqlSetCharset( 'utf8' );
166 return $this->mysqlSetCharset( 'binary' );
171 * Open a connection to a MySQL server
173 * @param string $realServer
174 * @return mixed Raw connection
175 * @throws DBConnectionError
177 abstract protected function mysqlConnect( $realServer );
180 * Set the character set of the MySQL link
182 * @param string $charset
185 abstract protected function mysqlSetCharset( $charset );
188 * @param ResultWrapper|resource $res
189 * @throws DBUnexpectedError
191 function freeResult( $res ) {
192 if ( $res instanceof ResultWrapper
) {
195 wfSuppressWarnings();
196 $ok = $this->mysqlFreeResult( $res );
199 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
206 * @param resource $res Raw result
209 abstract protected function mysqlFreeResult( $res );
212 * @param ResultWrapper|resource $res
213 * @return stdClass|bool
214 * @throws DBUnexpectedError
216 function fetchObject( $res ) {
217 if ( $res instanceof ResultWrapper
) {
220 wfSuppressWarnings();
221 $row = $this->mysqlFetchObject( $res );
224 $errno = $this->lastErrno();
225 // Unfortunately, mysql_fetch_object does not reset the last errno.
226 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
227 // these are the only errors mysql_fetch_object can cause.
228 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
229 if ( $errno == 2000 ||
$errno == 2013 ) {
230 throw new DBUnexpectedError(
232 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
240 * Fetch a result row as an object
242 * @param resource $res Raw result
245 abstract protected function mysqlFetchObject( $res );
248 * @param ResultWrapper|resource $res
250 * @throws DBUnexpectedError
252 function fetchRow( $res ) {
253 if ( $res instanceof ResultWrapper
) {
256 wfSuppressWarnings();
257 $row = $this->mysqlFetchArray( $res );
260 $errno = $this->lastErrno();
261 // Unfortunately, mysql_fetch_array does not reset the last errno.
262 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
263 // these are the only errors mysql_fetch_array can cause.
264 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
265 if ( $errno == 2000 ||
$errno == 2013 ) {
266 throw new DBUnexpectedError(
268 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
276 * Fetch a result row as an associative and numeric array
278 * @param resource $res Raw result
281 abstract protected function mysqlFetchArray( $res );
284 * @throws DBUnexpectedError
285 * @param ResultWrapper|resource $res
288 function numRows( $res ) {
289 if ( $res instanceof ResultWrapper
) {
292 wfSuppressWarnings();
293 $n = $this->mysqlNumRows( $res );
296 // Unfortunately, mysql_num_rows does not reset the last errno.
297 // We are not checking for any errors here, since
298 // these are no errors mysql_num_rows can cause.
299 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
300 // See https://bugzilla.wikimedia.org/42430
305 * Get number of rows in result
307 * @param resource $res Raw result
310 abstract protected function mysqlNumRows( $res );
313 * @param ResultWrapper|resource $res
316 function numFields( $res ) {
317 if ( $res instanceof ResultWrapper
) {
321 return $this->mysqlNumFields( $res );
325 * Get number of fields in result
327 * @param resource $res Raw result
330 abstract protected function mysqlNumFields( $res );
333 * @param ResultWrapper|resource $res
337 function fieldName( $res, $n ) {
338 if ( $res instanceof ResultWrapper
) {
342 return $this->mysqlFieldName( $res, $n );
346 * Get the name of the specified field in a result
348 * @param ResultWrapper|resource $res
352 abstract protected function mysqlFieldName( $res, $n );
355 * mysql_field_type() wrapper
356 * @param ResultWrapper|resource $res
360 public function fieldType( $res, $n ) {
361 if ( $res instanceof ResultWrapper
) {
365 return $this->mysqlFieldType( $res, $n );
369 * Get the type of the specified field in a result
371 * @param ResultWrapper|resource $res
375 abstract protected function mysqlFieldType( $res, $n );
378 * @param ResultWrapper|resource $res
382 function dataSeek( $res, $row ) {
383 if ( $res instanceof ResultWrapper
) {
387 return $this->mysqlDataSeek( $res, $row );
391 * Move internal result pointer
393 * @param ResultWrapper|resource $res
397 abstract protected function mysqlDataSeek( $res, $row );
402 function lastError() {
403 if ( $this->mConn
) {
404 # Even if it's non-zero, it can still be invalid
405 wfSuppressWarnings();
406 $error = $this->mysqlError( $this->mConn
);
408 $error = $this->mysqlError();
412 $error = $this->mysqlError();
415 $error .= ' (' . $this->mServer
. ')';
422 * Returns the text of the error message from previous MySQL operation
424 * @param resource $conn Raw connection
427 abstract protected function mysqlError( $conn = null );
430 * @param string $table
431 * @param array $uniqueIndexes
433 * @param string $fname
434 * @return ResultWrapper
436 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
437 return $this->nativeReplace( $table, $rows, $fname );
441 * Estimate rows in dataset
442 * Returns estimated count, based on EXPLAIN output
443 * Takes same arguments as Database::select()
445 * @param string|array $table
446 * @param string|array $vars
447 * @param string|array $conds
448 * @param string $fname
449 * @param string|array $options
452 public function estimateRowCount( $table, $vars = '*', $conds = '',
453 $fname = __METHOD__
, $options = array()
455 $options['EXPLAIN'] = true;
456 $res = $this->select( $table, $vars, $conds, $fname, $options );
457 if ( $res === false ) {
460 if ( !$this->numRows( $res ) ) {
465 foreach ( $res as $plan ) {
466 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
473 * @param string $table
474 * @param string $field
475 * @return bool|MySQLField
477 function fieldInfo( $table, $field ) {
478 $table = $this->tableName( $table );
479 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
483 $n = $this->mysqlNumFields( $res->result
);
484 for ( $i = 0; $i < $n; $i++
) {
485 $meta = $this->mysqlFetchField( $res->result
, $i );
486 if ( $field == $meta->name
) {
487 return new MySQLField( $meta );
495 * Get column information from a result
497 * @param resource $res Raw result
501 abstract protected function mysqlFetchField( $res, $n );
504 * Get information about an index into an object
505 * Returns false if the index does not exist
507 * @param string $table
508 * @param string $index
509 * @param string $fname
510 * @return bool|array|null False or null on failure
512 function indexInfo( $table, $index, $fname = __METHOD__
) {
513 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
514 # SHOW INDEX should work for 3.x and up:
515 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
516 $table = $this->tableName( $table );
517 $index = $this->indexName( $index );
519 $sql = 'SHOW INDEX FROM ' . $table;
520 $res = $this->query( $sql, $fname );
528 foreach ( $res as $row ) {
529 if ( $row->Key_name
== $index ) {
534 return empty( $result ) ?
false : $result;
541 function strencode( $s ) {
542 $sQuoted = $this->mysqlRealEscapeString( $s );
544 if ( $sQuoted === false ) {
546 $sQuoted = $this->mysqlRealEscapeString( $s );
553 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
558 public function addIdentifierQuotes( $s ) {
559 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
560 // Remove NUL bytes and escape backticks by doubling
561 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
565 * @param string $name
568 public function isQuotedIdentifier( $name ) {
569 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
576 $ping = $this->mysqlPing();
581 $this->closeConnection();
582 $this->mOpened
= false;
583 $this->mConn
= false;
584 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
590 * Ping a server connection or reconnect if there is no connection
594 abstract protected function mysqlPing();
597 * Set lag time in seconds for a fake slave
601 public function setFakeSlaveLag( $lag ) {
602 $this->mFakeSlaveLag
= $lag;
606 * Make this connection a fake master
608 * @param bool $enabled
610 public function setFakeMaster( $enabled = true ) {
611 $this->mFakeMaster
= $enabled;
617 * This will do a SHOW SLAVE STATUS
622 if ( !is_null( $this->mFakeSlaveLag
) ) {
623 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
625 return $this->mFakeSlaveLag
;
628 return $this->getLagFromSlaveStatus();
634 function getLagFromSlaveStatus() {
635 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
639 $row = $res->fetchObject();
643 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
646 return intval( $row->Seconds_Behind_Master
);
651 * Wait for the slave to catch up to a given master position.
652 * @todo Return values for this and base class are rubbish
654 * @param DBMasterPos|MySQLMasterPos $pos
655 * @param int $timeout The maximum number of seconds to wait for synchronisation
656 * @return int Zero if the slave was past that position already,
657 * greater than zero if we waited for some period of time, less than
658 * zero if we timed out.
660 function masterPosWait( DBMasterPos
$pos, $timeout ) {
661 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
662 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
665 # Commit any open transactions
666 $this->commit( __METHOD__
, 'flush' );
668 if ( !is_null( $this->mFakeSlaveLag
) ) {
669 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
671 if ( $wait > $timeout * 1e6
) {
672 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
675 } elseif ( $wait > 0 ) {
676 wfDebug( "Fake slave waiting $wait us\n" );
681 wfDebug( "Fake slave up to date ($wait us)\n" );
687 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
688 $encFile = $this->addQuotes( $pos->file
);
689 $encPos = intval( $pos->pos
);
690 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
691 $res = $this->doQuery( $sql );
694 if ( $res && $row = $this->fetchRow( $res ) ) {
695 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
696 if ( ctype_digit( $status ) ) { // success
697 $this->lastKnownSlavePos
= $pos;
706 * Get the position of the master from SHOW SLAVE STATUS
708 * @return MySQLMasterPos|bool
710 function getSlavePos() {
711 if ( !is_null( $this->mFakeSlaveLag
) ) {
712 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
713 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
718 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
719 $row = $this->fetchObject( $res );
722 $pos = isset( $row->Exec_master_log_pos
)
723 ?
$row->Exec_master_log_pos
724 : $row->Exec_Master_Log_Pos
;
726 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
733 * Get the position of the master from SHOW MASTER STATUS
735 * @return MySQLMasterPos|bool
737 function getMasterPos() {
738 if ( $this->mFakeMaster
) {
739 return new MySQLMasterPos( 'fake', microtime( true ) );
742 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
743 $row = $this->fetchObject( $res );
746 return new MySQLMasterPos( $row->File
, $row->Position
);
753 * @param string $index
756 function useIndexClause( $index ) {
757 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
763 function lowPriorityOption() {
764 return 'LOW_PRIORITY';
770 public function getSoftwareLink() {
771 // MariaDB includes its name in its version string; this is how MariaDB's version of
772 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
773 // in libmysql/libmysql.c).
774 $version = $this->getServerVersion();
775 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
776 return '[{{int:version-db-mariadb-url}} MariaDB]';
779 // Percona Server's version suffix is not very distinctive, and @@version_comment
780 // doesn't give the necessary info for source builds, so assume the server is MySQL.
781 // (Even Percona's version of mysql doesn't try to make the distinction.)
782 return '[{{int:version-db-mysql-url}} MySQL]';
788 public function getServerVersion() {
789 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
790 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
791 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
792 if ( $this->serverVersion
=== null ) {
793 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
795 return $this->serverVersion
;
799 * @param array $options
801 public function setSessionOptions( array $options ) {
802 if ( isset( $options['connTimeout'] ) ) {
803 $timeout = (int)$options['connTimeout'];
804 $this->query( "SET net_read_timeout=$timeout" );
805 $this->query( "SET net_write_timeout=$timeout" );
811 * @param string $newLine
814 public function streamStatementEnd( &$sql, &$newLine ) {
815 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
816 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
817 $this->delimiter
= $m[1];
821 return parent
::streamStatementEnd( $sql, $newLine );
825 * Check to see if a named lock is available. This is non-blocking.
827 * @param string $lockName Name of lock to poll
828 * @param string $method Name of method calling us
832 public function lockIsFree( $lockName, $method ) {
833 $lockName = $this->addQuotes( $lockName );
834 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
835 $row = $this->fetchObject( $result );
837 return ( $row->lockstatus
== 1 );
841 * @param string $lockName
842 * @param string $method
843 * @param int $timeout
846 public function lock( $lockName, $method, $timeout = 5 ) {
847 $lockName = $this->addQuotes( $lockName );
848 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
849 $row = $this->fetchObject( $result );
851 if ( $row->lockstatus
== 1 ) {
854 wfDebug( __METHOD__
. " failed to acquire lock\n" );
862 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
863 * @param string $lockName
864 * @param string $method
867 public function unlock( $lockName, $method ) {
868 $lockName = $this->addQuotes( $lockName );
869 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
870 $row = $this->fetchObject( $result );
872 return ( $row->lockstatus
== 1 );
877 * @param array $write
878 * @param string $method
879 * @param bool $lowPriority
882 public function lockTables( $read, $write, $method, $lowPriority = true ) {
885 foreach ( $write as $table ) {
886 $tbl = $this->tableName( $table ) .
887 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
891 foreach ( $read as $table ) {
892 $items[] = $this->tableName( $table ) . ' READ';
894 $sql = "LOCK TABLES " . implode( ',', $items );
895 $this->query( $sql, $method );
901 * @param string $method
904 public function unlockTables( $method ) {
905 $this->query( "UNLOCK TABLES", $method );
911 * Get search engine class. All subclasses of this
912 * need to implement this if they wish to use searching.
916 public function getSearchEngine() {
917 return 'SearchMySQL';
923 public function setBigSelects( $value = true ) {
924 if ( $value === 'default' ) {
925 if ( $this->mDefaultBigSelects
=== null ) {
926 # Function hasn't been called before so it must already be set to the default
929 $value = $this->mDefaultBigSelects
;
931 } elseif ( $this->mDefaultBigSelects
=== null ) {
932 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
934 $encValue = $value ?
'1' : '0';
935 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
939 * DELETE where the condition is a join. MySql uses multi-table deletes.
940 * @param string $delTable
941 * @param string $joinTable
942 * @param string $delVar
943 * @param string $joinVar
944 * @param array|string $conds
945 * @param bool|string $fname
946 * @throws DBUnexpectedError
947 * @return bool|ResultWrapper
949 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
951 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
954 $delTable = $this->tableName( $delTable );
955 $joinTable = $this->tableName( $joinTable );
956 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
958 if ( $conds != '*' ) {
959 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
962 return $this->query( $sql, $fname );
966 * @param string $table
968 * @param array $uniqueIndexes
970 * @param string $fname
973 public function upsert( $table, array $rows, array $uniqueIndexes,
974 array $set, $fname = __METHOD__
976 if ( !count( $rows ) ) {
977 return true; // nothing to do
980 if ( !is_array( reset( $rows ) ) ) {
981 $rows = array( $rows );
984 $table = $this->tableName( $table );
985 $columns = array_keys( $rows[0] );
987 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
988 $rowTuples = array();
989 foreach ( $rows as $row ) {
990 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
992 $sql .= implode( ',', $rowTuples );
993 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
995 return (bool)$this->query( $sql, $fname );
999 * Determines how long the server has been up
1003 function getServerUptime() {
1004 $vars = $this->getMysqlStatus( 'Uptime' );
1006 return (int)$vars['Uptime'];
1010 * Determines if the last failure was due to a deadlock
1014 function wasDeadlock() {
1015 return $this->lastErrno() == 1213;
1019 * Determines if the last failure was due to a lock timeout
1023 function wasLockTimeout() {
1024 return $this->lastErrno() == 1205;
1028 * Determines if the last query error was something that should be dealt
1029 * with by pinging the connection and reissuing the query
1033 function wasErrorReissuable() {
1034 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1038 * Determines if the last failure was due to the database being read-only.
1042 function wasReadOnlyError() {
1043 return $this->lastErrno() == 1223 ||
1044 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1048 * @param string $oldName
1049 * @param string $newName
1050 * @param bool $temporary
1051 * @param string $fname
1054 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1055 $tmp = $temporary ?
'TEMPORARY ' : '';
1056 $newName = $this->addIdentifierQuotes( $newName );
1057 $oldName = $this->addIdentifierQuotes( $oldName );
1058 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1060 return $this->query( $query, $fname );
1064 * List all tables on the database
1066 * @param string $prefix Only show tables with this prefix, e.g. mw_
1067 * @param string $fname Calling function name
1070 function listTables( $prefix = null, $fname = __METHOD__
) {
1071 $result = $this->query( "SHOW TABLES", $fname );
1073 $endArray = array();
1075 foreach ( $result as $table ) {
1076 $vars = get_object_vars( $table );
1077 $table = array_pop( $vars );
1079 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1080 $endArray[] = $table;
1088 * @param string $tableName
1089 * @param string $fName
1090 * @return bool|ResultWrapper
1092 public function dropTable( $tableName, $fName = __METHOD__
) {
1093 if ( !$this->tableExists( $tableName, $fName ) ) {
1097 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1103 protected function getDefaultSchemaVars() {
1104 $vars = parent
::getDefaultSchemaVars();
1105 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1106 $vars['wgDBTableOptions'] = str_replace(
1109 $vars['wgDBTableOptions']
1116 * Get status information from SHOW STATUS in an associative array
1118 * @param string $which
1121 function getMysqlStatus( $which = "%" ) {
1122 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1125 foreach ( $res as $row ) {
1126 $status[$row->Variable_name
] = $row->Value
;
1133 * Lists VIEWs in the database
1135 * @param string $prefix Only show VIEWs with this prefix, eg.
1136 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1137 * @param string $fname Name of calling function
1141 public function listViews( $prefix = null, $fname = __METHOD__
) {
1143 if ( !isset( $this->allViews
) ) {
1145 // The name of the column containing the name of the VIEW
1146 $propertyName = 'Tables_in_' . $this->mDBname
;
1148 // Query for the VIEWS
1149 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1150 $this->allViews
= array();
1151 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1152 array_push( $this->allViews
, $row[$propertyName] );
1156 if ( is_null( $prefix ) ||
$prefix === '' ) {
1157 return $this->allViews
;
1160 $filteredViews = array();
1161 foreach ( $this->allViews
as $viewName ) {
1162 // Does the name of this VIEW start with the table-prefix?
1163 if ( strpos( $viewName, $prefix ) === 0 ) {
1164 array_push( $filteredViews, $viewName );
1168 return $filteredViews;
1172 * Differentiates between a TABLE and a VIEW.
1174 * @param string $name Name of the TABLE/VIEW to test
1175 * @param string $prefix
1179 public function isView( $name, $prefix = null ) {
1180 return in_array( $name, $this->listViews( $prefix ) );
1188 class MySQLField
implements Field
{
1189 private $name, $tablename, $default, $max_length, $nullable,
1190 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1192 function __construct( $info ) {
1193 $this->name
= $info->name
;
1194 $this->tablename
= $info->table
;
1195 $this->default = $info->def
;
1196 $this->max_length
= $info->max_length
;
1197 $this->nullable
= !$info->not_null
;
1198 $this->is_pk
= $info->primary_key
;
1199 $this->is_unique
= $info->unique_key
;
1200 $this->is_multiple
= $info->multiple_key
;
1201 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1202 $this->type
= $info->type
;
1203 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1216 function tableName() {
1217 return $this->tableName
;
1230 function isNullable() {
1231 return $this->nullable
;
1234 function defaultValue() {
1235 return $this->default;
1242 return $this->is_key
;
1248 function isMultipleKey() {
1249 return $this->is_multiple
;
1252 function isBinary() {
1253 return $this->binary
;
1257 class MySQLMasterPos
implements DBMasterPos
{
1260 /** @var int Position */
1262 /** @var float UNIX timestamp */
1263 public $asOfTime = 0.0;
1265 function __construct( $file, $pos ) {
1266 $this->file
= $file;
1268 $this->asOfTime
= microtime( true );
1271 function __toString() {
1272 // e.g db1034-bin.000976/843431247
1273 return "{$this->file}/{$this->pos}";
1277 * @return array|bool (int, int)
1279 protected function getCoordinates() {
1281 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1282 return array( (int)$m[1], (int)$m[2] );
1288 function hasReached( MySQLMasterPos
$pos ) {
1289 $thisPos = $this->getCoordinates();
1290 $thatPos = $pos->getCoordinates();
1292 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1295 function asOfTime() {
1296 return $this->asOfTime
;