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;
61 wfProfileIn( __METHOD__
);
63 # Debugging hack -- fake cluster
64 if ( $wgAllDBsAreLocalhost ) {
65 $realServer = 'localhost';
67 $realServer = $server;
70 $this->mServer
= $server;
72 $this->mPassword
= $password;
73 $this->mDBname
= $dbName;
75 wfProfileIn( "dbconnect-$server" );
77 # The kernel's default SYN retransmission period is far too slow for us,
78 # so we use a short timeout plus a manual retry. Retrying means that a small
79 # but finite rate of SYN packet loss won't cause user-visible errors.
81 $this->installErrorHandler();
83 $this->mConn
= $this->mysqlConnect( $realServer );
84 } catch ( Exception
$ex ) {
85 wfProfileOut( "dbconnect-$server" );
86 wfProfileOut( __METHOD__
);
87 $this->restoreErrorHandler();
90 $error = $this->restoreErrorHandler();
92 wfProfileOut( "dbconnect-$server" );
94 # Always log connection errors
95 if ( !$this->mConn
) {
97 $error = $this->lastError();
100 "Error connecting to {db_server}: {error}",
101 $this->getLogContext( array(
102 'method' => __METHOD__
,
106 wfDebug( "DB connection error\n" .
107 "Server: $server, User: $user, Password: " .
108 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
110 wfProfileOut( __METHOD__
);
112 $this->reportConnectionError( $error );
115 if ( $dbName != '' ) {
116 wfSuppressWarnings();
117 $success = $this->selectDB( $dbName );
121 "Error selecting database {db_name} on server {db_server}",
122 $this->getLogContext( array(
123 'method' => __METHOD__
,
126 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
127 "from client host " . wfHostname() . "\n" );
129 wfProfileOut( __METHOD__
);
131 $this->reportConnectionError( "Error selecting database $dbName" );
135 // Tell the server what we're communicating with
136 if ( !$this->connectInitCharset() ) {
137 $this->reportConnectionError( "Error setting character set" );
140 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
141 if ( is_string( $wgSQLMode ) ) {
142 $mode = $this->addQuotes( $wgSQLMode );
143 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
144 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
147 "Error setting sql_mode to $mode on server {db_server}",
148 $this->getLogContext( array(
149 'method' => __METHOD__
,
152 wfProfileOut( __METHOD__
);
153 $this->reportConnectionError( "Error setting sql_mode to $mode" );
157 $this->mOpened
= true;
158 wfProfileOut( __METHOD__
);
164 * Set the character set information right after connection
167 protected function connectInitCharset() {
171 // Tell the server we're communicating with it in UTF-8.
172 // This may engage various charset conversions.
173 return $this->mysqlSetCharset( 'utf8' );
175 return $this->mysqlSetCharset( 'binary' );
180 * Open a connection to a MySQL server
182 * @param string $realServer
183 * @return mixed Raw connection
184 * @throws DBConnectionError
186 abstract protected function mysqlConnect( $realServer );
189 * Set the character set of the MySQL link
191 * @param string $charset
194 abstract protected function mysqlSetCharset( $charset );
197 * @param ResultWrapper|resource $res
198 * @throws DBUnexpectedError
200 function freeResult( $res ) {
201 if ( $res instanceof ResultWrapper
) {
204 wfSuppressWarnings();
205 $ok = $this->mysqlFreeResult( $res );
208 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
215 * @param resource $res Raw result
218 abstract protected function mysqlFreeResult( $res );
221 * @param ResultWrapper|resource $res
222 * @return stdClass|bool
223 * @throws DBUnexpectedError
225 function fetchObject( $res ) {
226 if ( $res instanceof ResultWrapper
) {
229 wfSuppressWarnings();
230 $row = $this->mysqlFetchObject( $res );
233 $errno = $this->lastErrno();
234 // Unfortunately, mysql_fetch_object does not reset the last errno.
235 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
236 // these are the only errors mysql_fetch_object can cause.
237 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
238 if ( $errno == 2000 ||
$errno == 2013 ) {
239 throw new DBUnexpectedError(
241 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
249 * Fetch a result row as an object
251 * @param resource $res Raw result
254 abstract protected function mysqlFetchObject( $res );
257 * @param ResultWrapper|resource $res
259 * @throws DBUnexpectedError
261 function fetchRow( $res ) {
262 if ( $res instanceof ResultWrapper
) {
265 wfSuppressWarnings();
266 $row = $this->mysqlFetchArray( $res );
269 $errno = $this->lastErrno();
270 // Unfortunately, mysql_fetch_array does not reset the last errno.
271 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
272 // these are the only errors mysql_fetch_array can cause.
273 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
274 if ( $errno == 2000 ||
$errno == 2013 ) {
275 throw new DBUnexpectedError(
277 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
285 * Fetch a result row as an associative and numeric array
287 * @param resource $res Raw result
290 abstract protected function mysqlFetchArray( $res );
293 * @throws DBUnexpectedError
294 * @param ResultWrapper|resource $res
297 function numRows( $res ) {
298 if ( $res instanceof ResultWrapper
) {
301 wfSuppressWarnings();
302 $n = $this->mysqlNumRows( $res );
305 // Unfortunately, mysql_num_rows does not reset the last errno.
306 // We are not checking for any errors here, since
307 // these are no errors mysql_num_rows can cause.
308 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
309 // See https://bugzilla.wikimedia.org/42430
314 * Get number of rows in result
316 * @param resource $res Raw result
319 abstract protected function mysqlNumRows( $res );
322 * @param ResultWrapper|resource $res
325 function numFields( $res ) {
326 if ( $res instanceof ResultWrapper
) {
330 return $this->mysqlNumFields( $res );
334 * Get number of fields in result
336 * @param resource $res Raw result
339 abstract protected function mysqlNumFields( $res );
342 * @param ResultWrapper|resource $res
346 function fieldName( $res, $n ) {
347 if ( $res instanceof ResultWrapper
) {
351 return $this->mysqlFieldName( $res, $n );
355 * Get the name of the specified field in a result
357 * @param ResultWrapper|resource $res
361 abstract protected function mysqlFieldName( $res, $n );
364 * mysql_field_type() wrapper
365 * @param ResultWrapper|resource $res
369 public function fieldType( $res, $n ) {
370 if ( $res instanceof ResultWrapper
) {
374 return $this->mysqlFieldType( $res, $n );
378 * Get the type of the specified field in a result
380 * @param ResultWrapper|resource $res
384 abstract protected function mysqlFieldType( $res, $n );
387 * @param ResultWrapper|resource $res
391 function dataSeek( $res, $row ) {
392 if ( $res instanceof ResultWrapper
) {
396 return $this->mysqlDataSeek( $res, $row );
400 * Move internal result pointer
402 * @param ResultWrapper|resource $res
406 abstract protected function mysqlDataSeek( $res, $row );
411 function lastError() {
412 if ( $this->mConn
) {
413 # Even if it's non-zero, it can still be invalid
414 wfSuppressWarnings();
415 $error = $this->mysqlError( $this->mConn
);
417 $error = $this->mysqlError();
421 $error = $this->mysqlError();
424 $error .= ' (' . $this->mServer
. ')';
431 * Returns the text of the error message from previous MySQL operation
433 * @param resource $conn Raw connection
436 abstract protected function mysqlError( $conn = null );
439 * @param string $table
440 * @param array $uniqueIndexes
442 * @param string $fname
443 * @return ResultWrapper
445 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
446 return $this->nativeReplace( $table, $rows, $fname );
450 * Estimate rows in dataset
451 * Returns estimated count, based on EXPLAIN output
452 * Takes same arguments as Database::select()
454 * @param string|array $table
455 * @param string|array $vars
456 * @param string|array $conds
457 * @param string $fname
458 * @param string|array $options
461 public function estimateRowCount( $table, $vars = '*', $conds = '',
462 $fname = __METHOD__
, $options = array()
464 $options['EXPLAIN'] = true;
465 $res = $this->select( $table, $vars, $conds, $fname, $options );
466 if ( $res === false ) {
469 if ( !$this->numRows( $res ) ) {
474 foreach ( $res as $plan ) {
475 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
482 * @param string $table
483 * @param string $field
484 * @return bool|MySQLField
486 function fieldInfo( $table, $field ) {
487 $table = $this->tableName( $table );
488 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
492 $n = $this->mysqlNumFields( $res->result
);
493 for ( $i = 0; $i < $n; $i++
) {
494 $meta = $this->mysqlFetchField( $res->result
, $i );
495 if ( $field == $meta->name
) {
496 return new MySQLField( $meta );
504 * Get column information from a result
506 * @param resource $res Raw result
510 abstract protected function mysqlFetchField( $res, $n );
513 * Get information about an index into an object
514 * Returns false if the index does not exist
516 * @param string $table
517 * @param string $index
518 * @param string $fname
519 * @return bool|array|null False or null on failure
521 function indexInfo( $table, $index, $fname = __METHOD__
) {
522 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
523 # SHOW INDEX should work for 3.x and up:
524 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
525 $table = $this->tableName( $table );
526 $index = $this->indexName( $index );
528 $sql = 'SHOW INDEX FROM ' . $table;
529 $res = $this->query( $sql, $fname );
537 foreach ( $res as $row ) {
538 if ( $row->Key_name
== $index ) {
543 return empty( $result ) ?
false : $result;
550 function strencode( $s ) {
551 $sQuoted = $this->mysqlRealEscapeString( $s );
553 if ( $sQuoted === false ) {
555 $sQuoted = $this->mysqlRealEscapeString( $s );
562 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
567 public function addIdentifierQuotes( $s ) {
568 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
569 // Remove NUL bytes and escape backticks by doubling
570 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
574 * @param string $name
577 public function isQuotedIdentifier( $name ) {
578 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
585 $ping = $this->mysqlPing();
590 $this->closeConnection();
591 $this->mOpened
= false;
592 $this->mConn
= false;
593 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
599 * Ping a server connection or reconnect if there is no connection
603 abstract protected function mysqlPing();
606 * Set lag time in seconds for a fake slave
610 public function setFakeSlaveLag( $lag ) {
611 $this->mFakeSlaveLag
= $lag;
615 * Make this connection a fake master
617 * @param bool $enabled
619 public function setFakeMaster( $enabled = true ) {
620 $this->mFakeMaster
= $enabled;
626 * This will do a SHOW SLAVE STATUS
631 if ( !is_null( $this->mFakeSlaveLag
) ) {
632 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
634 return $this->mFakeSlaveLag
;
637 return $this->getLagFromSlaveStatus();
643 function getLagFromSlaveStatus() {
644 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
648 $row = $res->fetchObject();
652 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
655 return intval( $row->Seconds_Behind_Master
);
660 * Wait for the slave to catch up to a given master position.
661 * @todo Return values for this and base class are rubbish
663 * @param DBMasterPos|MySQLMasterPos $pos
664 * @param int $timeout The maximum number of seconds to wait for synchronisation
665 * @return int Zero if the slave was past that position already,
666 * greater than zero if we waited for some period of time, less than
667 * zero if we timed out.
669 function masterPosWait( DBMasterPos
$pos, $timeout ) {
670 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
671 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
674 wfProfileIn( __METHOD__
);
675 # Commit any open transactions
676 $this->commit( __METHOD__
, 'flush' );
678 if ( !is_null( $this->mFakeSlaveLag
) ) {
679 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
681 if ( $wait > $timeout * 1e6
) {
682 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
683 wfProfileOut( __METHOD__
);
686 } elseif ( $wait > 0 ) {
687 wfDebug( "Fake slave waiting $wait us\n" );
689 wfProfileOut( __METHOD__
);
693 wfDebug( "Fake slave up to date ($wait us)\n" );
694 wfProfileOut( __METHOD__
);
700 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
701 $encFile = $this->addQuotes( $pos->file
);
702 $encPos = intval( $pos->pos
);
703 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
704 $res = $this->doQuery( $sql );
707 if ( $res && $row = $this->fetchRow( $res ) ) {
708 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
709 if ( ctype_digit( $status ) ) { // success
710 $this->lastKnownSlavePos
= $pos;
714 wfProfileOut( __METHOD__
);
720 * Get the position of the master from SHOW SLAVE STATUS
722 * @return MySQLMasterPos|bool
724 function getSlavePos() {
725 if ( !is_null( $this->mFakeSlaveLag
) ) {
726 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
727 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
732 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
733 $row = $this->fetchObject( $res );
736 $pos = isset( $row->Exec_master_log_pos
)
737 ?
$row->Exec_master_log_pos
738 : $row->Exec_Master_Log_Pos
;
740 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
747 * Get the position of the master from SHOW MASTER STATUS
749 * @return MySQLMasterPos|bool
751 function getMasterPos() {
752 if ( $this->mFakeMaster
) {
753 return new MySQLMasterPos( 'fake', microtime( true ) );
756 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
757 $row = $this->fetchObject( $res );
760 return new MySQLMasterPos( $row->File
, $row->Position
);
767 * @param string $index
770 function useIndexClause( $index ) {
771 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
777 function lowPriorityOption() {
778 return 'LOW_PRIORITY';
784 public function getSoftwareLink() {
785 // MariaDB includes its name in its version string; this is how MariaDB's version of
786 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
787 // in libmysql/libmysql.c).
788 $version = $this->getServerVersion();
789 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
790 return '[{{int:version-db-mariadb-url}} MariaDB]';
793 // Percona Server's version suffix is not very distinctive, and @@version_comment
794 // doesn't give the necessary info for source builds, so assume the server is MySQL.
795 // (Even Percona's version of mysql doesn't try to make the distinction.)
796 return '[{{int:version-db-mysql-url}} MySQL]';
802 public function getServerVersion() {
803 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
804 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
805 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
806 if ( $this->serverVersion
=== null ) {
807 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
809 return $this->serverVersion
;
813 * @param array $options
815 public function setSessionOptions( array $options ) {
816 if ( isset( $options['connTimeout'] ) ) {
817 $timeout = (int)$options['connTimeout'];
818 $this->query( "SET net_read_timeout=$timeout" );
819 $this->query( "SET net_write_timeout=$timeout" );
825 * @param string $newLine
828 public function streamStatementEnd( &$sql, &$newLine ) {
829 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
830 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
831 $this->delimiter
= $m[1];
835 return parent
::streamStatementEnd( $sql, $newLine );
839 * Check to see if a named lock is available. This is non-blocking.
841 * @param string $lockName Name of lock to poll
842 * @param string $method Name of method calling us
846 public function lockIsFree( $lockName, $method ) {
847 $lockName = $this->addQuotes( $lockName );
848 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
849 $row = $this->fetchObject( $result );
851 return ( $row->lockstatus
== 1 );
855 * @param string $lockName
856 * @param string $method
857 * @param int $timeout
860 public function lock( $lockName, $method, $timeout = 5 ) {
861 $lockName = $this->addQuotes( $lockName );
862 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
863 $row = $this->fetchObject( $result );
865 if ( $row->lockstatus
== 1 ) {
868 wfDebug( __METHOD__
. " failed to acquire lock\n" );
876 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
877 * @param string $lockName
878 * @param string $method
881 public function unlock( $lockName, $method ) {
882 $lockName = $this->addQuotes( $lockName );
883 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
884 $row = $this->fetchObject( $result );
886 return ( $row->lockstatus
== 1 );
891 * @param array $write
892 * @param string $method
893 * @param bool $lowPriority
896 public function lockTables( $read, $write, $method, $lowPriority = true ) {
899 foreach ( $write as $table ) {
900 $tbl = $this->tableName( $table ) .
901 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
905 foreach ( $read as $table ) {
906 $items[] = $this->tableName( $table ) . ' READ';
908 $sql = "LOCK TABLES " . implode( ',', $items );
909 $this->query( $sql, $method );
915 * @param string $method
918 public function unlockTables( $method ) {
919 $this->query( "UNLOCK TABLES", $method );
925 * Get search engine class. All subclasses of this
926 * need to implement this if they wish to use searching.
930 public function getSearchEngine() {
931 return 'SearchMySQL';
937 public function setBigSelects( $value = true ) {
938 if ( $value === 'default' ) {
939 if ( $this->mDefaultBigSelects
=== null ) {
940 # Function hasn't been called before so it must already be set to the default
943 $value = $this->mDefaultBigSelects
;
945 } elseif ( $this->mDefaultBigSelects
=== null ) {
946 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
948 $encValue = $value ?
'1' : '0';
949 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
953 * DELETE where the condition is a join. MySql uses multi-table deletes.
954 * @param string $delTable
955 * @param string $joinTable
956 * @param string $delVar
957 * @param string $joinVar
958 * @param array|string $conds
959 * @param bool|string $fname
960 * @throws DBUnexpectedError
961 * @return bool|ResultWrapper
963 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
965 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
968 $delTable = $this->tableName( $delTable );
969 $joinTable = $this->tableName( $joinTable );
970 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
972 if ( $conds != '*' ) {
973 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
976 return $this->query( $sql, $fname );
980 * @param string $table
982 * @param array $uniqueIndexes
984 * @param string $fname
987 public function upsert( $table, array $rows, array $uniqueIndexes,
988 array $set, $fname = __METHOD__
990 if ( !count( $rows ) ) {
991 return true; // nothing to do
994 if ( !is_array( reset( $rows ) ) ) {
995 $rows = array( $rows );
998 $table = $this->tableName( $table );
999 $columns = array_keys( $rows[0] );
1001 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1002 $rowTuples = array();
1003 foreach ( $rows as $row ) {
1004 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1006 $sql .= implode( ',', $rowTuples );
1007 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
1009 return (bool)$this->query( $sql, $fname );
1013 * Determines how long the server has been up
1017 function getServerUptime() {
1018 $vars = $this->getMysqlStatus( 'Uptime' );
1020 return (int)$vars['Uptime'];
1024 * Determines if the last failure was due to a deadlock
1028 function wasDeadlock() {
1029 return $this->lastErrno() == 1213;
1033 * Determines if the last failure was due to a lock timeout
1037 function wasLockTimeout() {
1038 return $this->lastErrno() == 1205;
1042 * Determines if the last query error was something that should be dealt
1043 * with by pinging the connection and reissuing the query
1047 function wasErrorReissuable() {
1048 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1052 * Determines if the last failure was due to the database being read-only.
1056 function wasReadOnlyError() {
1057 return $this->lastErrno() == 1223 ||
1058 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1062 * @param string $oldName
1063 * @param string $newName
1064 * @param bool $temporary
1065 * @param string $fname
1068 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1069 $tmp = $temporary ?
'TEMPORARY ' : '';
1070 $newName = $this->addIdentifierQuotes( $newName );
1071 $oldName = $this->addIdentifierQuotes( $oldName );
1072 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1074 return $this->query( $query, $fname );
1078 * List all tables on the database
1080 * @param string $prefix Only show tables with this prefix, e.g. mw_
1081 * @param string $fname Calling function name
1084 function listTables( $prefix = null, $fname = __METHOD__
) {
1085 $result = $this->query( "SHOW TABLES", $fname );
1087 $endArray = array();
1089 foreach ( $result as $table ) {
1090 $vars = get_object_vars( $table );
1091 $table = array_pop( $vars );
1093 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1094 $endArray[] = $table;
1102 * @param string $tableName
1103 * @param string $fName
1104 * @return bool|ResultWrapper
1106 public function dropTable( $tableName, $fName = __METHOD__
) {
1107 if ( !$this->tableExists( $tableName, $fName ) ) {
1111 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1117 protected function getDefaultSchemaVars() {
1118 $vars = parent
::getDefaultSchemaVars();
1119 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1120 $vars['wgDBTableOptions'] = str_replace(
1123 $vars['wgDBTableOptions']
1130 * Get status information from SHOW STATUS in an associative array
1132 * @param string $which
1135 function getMysqlStatus( $which = "%" ) {
1136 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1139 foreach ( $res as $row ) {
1140 $status[$row->Variable_name
] = $row->Value
;
1147 * Lists VIEWs in the database
1149 * @param string $prefix Only show VIEWs with this prefix, eg.
1150 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1151 * @param string $fname Name of calling function
1155 public function listViews( $prefix = null, $fname = __METHOD__
) {
1157 if ( !isset( $this->allViews
) ) {
1159 // The name of the column containing the name of the VIEW
1160 $propertyName = 'Tables_in_' . $this->mDBname
;
1162 // Query for the VIEWS
1163 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1164 $this->allViews
= array();
1165 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1166 array_push( $this->allViews
, $row[$propertyName] );
1170 if ( is_null( $prefix ) ||
$prefix === '' ) {
1171 return $this->allViews
;
1174 $filteredViews = array();
1175 foreach ( $this->allViews
as $viewName ) {
1176 // Does the name of this VIEW start with the table-prefix?
1177 if ( strpos( $viewName, $prefix ) === 0 ) {
1178 array_push( $filteredViews, $viewName );
1182 return $filteredViews;
1186 * Differentiates between a TABLE and a VIEW.
1188 * @param string $name Name of the TABLE/VIEW to test
1189 * @param string $prefix
1193 public function isView( $name, $prefix = null ) {
1194 return in_array( $name, $this->listViews( $prefix ) );
1202 class MySQLField
implements Field
{
1203 private $name, $tablename, $default, $max_length, $nullable,
1204 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1206 function __construct( $info ) {
1207 $this->name
= $info->name
;
1208 $this->tablename
= $info->table
;
1209 $this->default = $info->def
;
1210 $this->max_length
= $info->max_length
;
1211 $this->nullable
= !$info->not_null
;
1212 $this->is_pk
= $info->primary_key
;
1213 $this->is_unique
= $info->unique_key
;
1214 $this->is_multiple
= $info->multiple_key
;
1215 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1216 $this->type
= $info->type
;
1217 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1230 function tableName() {
1231 return $this->tableName
;
1244 function isNullable() {
1245 return $this->nullable
;
1248 function defaultValue() {
1249 return $this->default;
1256 return $this->is_key
;
1262 function isMultipleKey() {
1263 return $this->is_multiple
;
1266 function isBinary() {
1267 return $this->binary
;
1271 class MySQLMasterPos
implements DBMasterPos
{
1275 /** @var int Timestamp */
1278 function __construct( $file, $pos ) {
1279 $this->file
= $file;
1283 function __toString() {
1284 // e.g db1034-bin.000976/843431247
1285 return "{$this->file}/{$this->pos}";
1289 * @return array|bool (int, int)
1291 protected function getCoordinates() {
1293 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1294 return array( (int)$m[1], (int)$m[2] );
1300 function hasReached( MySQLMasterPos
$pos ) {
1301 $thisPos = $this->getCoordinates();
1302 $thatPos = $pos->getCoordinates();
1304 return ( $thisPos && $thatPos && $thisPos >= $thatPos );