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();
99 wfLogDBError( "Error connecting to {$this->mServer}: $error" );
100 wfDebug( "DB connection error\n" .
101 "Server: $server, User: $user, Password: " .
102 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
104 wfProfileOut( __METHOD__
);
106 $this->reportConnectionError( $error );
109 if ( $dbName != '' ) {
110 wfSuppressWarnings();
111 $success = $this->selectDB( $dbName );
114 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}" );
115 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
116 "from client host " . wfHostname() . "\n" );
118 wfProfileOut( __METHOD__
);
120 $this->reportConnectionError( "Error selecting database $dbName" );
124 // Tell the server what we're communicating with
125 if ( !$this->connectInitCharset() ) {
126 $this->reportConnectionError( "Error setting character set" );
129 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
130 if ( is_string( $wgSQLMode ) ) {
131 $mode = $this->addQuotes( $wgSQLMode );
132 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
133 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
135 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
136 wfProfileOut( __METHOD__
);
137 $this->reportConnectionError( "Error setting sql_mode to $mode" );
141 $this->mOpened
= true;
142 wfProfileOut( __METHOD__
);
148 * Set the character set information right after connection
151 protected function connectInitCharset() {
155 // Tell the server we're communicating with it in UTF-8.
156 // This may engage various charset conversions.
157 return $this->mysqlSetCharset( 'utf8' );
159 return $this->mysqlSetCharset( 'binary' );
164 * Open a connection to a MySQL server
166 * @param string $realServer
167 * @return mixed Raw connection
168 * @throws DBConnectionError
170 abstract protected function mysqlConnect( $realServer );
173 * Set the character set of the MySQL link
175 * @param string $charset
178 abstract protected function mysqlSetCharset( $charset );
181 * @param ResultWrapper|resource $res
182 * @throws DBUnexpectedError
184 function freeResult( $res ) {
185 if ( $res instanceof ResultWrapper
) {
188 wfSuppressWarnings();
189 $ok = $this->mysqlFreeResult( $res );
192 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
199 * @param resource $res Raw result
202 abstract protected function mysqlFreeResult( $res );
205 * @param ResultWrapper|resource $res
206 * @return stdClass|bool
207 * @throws DBUnexpectedError
209 function fetchObject( $res ) {
210 if ( $res instanceof ResultWrapper
) {
213 wfSuppressWarnings();
214 $row = $this->mysqlFetchObject( $res );
217 $errno = $this->lastErrno();
218 // Unfortunately, mysql_fetch_object does not reset the last errno.
219 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
220 // these are the only errors mysql_fetch_object can cause.
221 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
222 if ( $errno == 2000 ||
$errno == 2013 ) {
223 throw new DBUnexpectedError(
225 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
233 * Fetch a result row as an object
235 * @param resource $res Raw result
238 abstract protected function mysqlFetchObject( $res );
241 * @param ResultWrapper|resource $res
243 * @throws DBUnexpectedError
245 function fetchRow( $res ) {
246 if ( $res instanceof ResultWrapper
) {
249 wfSuppressWarnings();
250 $row = $this->mysqlFetchArray( $res );
253 $errno = $this->lastErrno();
254 // Unfortunately, mysql_fetch_array does not reset the last errno.
255 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
256 // these are the only errors mysql_fetch_array can cause.
257 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
258 if ( $errno == 2000 ||
$errno == 2013 ) {
259 throw new DBUnexpectedError(
261 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
269 * Fetch a result row as an associative and numeric array
271 * @param resource $res Raw result
274 abstract protected function mysqlFetchArray( $res );
277 * @throws DBUnexpectedError
278 * @param ResultWrapper|resource $res
281 function numRows( $res ) {
282 if ( $res instanceof ResultWrapper
) {
285 wfSuppressWarnings();
286 $n = $this->mysqlNumRows( $res );
289 // Unfortunately, mysql_num_rows does not reset the last errno.
290 // We are not checking for any errors here, since
291 // these are no errors mysql_num_rows can cause.
292 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
293 // See https://bugzilla.wikimedia.org/42430
298 * Get number of rows in result
300 * @param resource $res Raw result
303 abstract protected function mysqlNumRows( $res );
306 * @param ResultWrapper|resource $res
309 function numFields( $res ) {
310 if ( $res instanceof ResultWrapper
) {
314 return $this->mysqlNumFields( $res );
318 * Get number of fields in result
320 * @param resource $res Raw result
323 abstract protected function mysqlNumFields( $res );
326 * @param ResultWrapper|resource $res
330 function fieldName( $res, $n ) {
331 if ( $res instanceof ResultWrapper
) {
335 return $this->mysqlFieldName( $res, $n );
339 * Get the name of the specified field in a result
341 * @param ResultWrapper|resource $res
345 abstract protected function mysqlFieldName( $res, $n );
348 * mysql_field_type() wrapper
349 * @param ResultWrapper|resource $res
353 public function fieldType( $res, $n ) {
354 if ( $res instanceof ResultWrapper
) {
358 return $this->mysqlFieldType( $res, $n );
362 * Get the type of the specified field in a result
364 * @param ResultWrapper|resource $res
368 abstract protected function mysqlFieldType( $res, $n );
371 * @param ResultWrapper|resource $res
375 function dataSeek( $res, $row ) {
376 if ( $res instanceof ResultWrapper
) {
380 return $this->mysqlDataSeek( $res, $row );
384 * Move internal result pointer
386 * @param ResultWrapper|resource $res
390 abstract protected function mysqlDataSeek( $res, $row );
395 function lastError() {
396 if ( $this->mConn
) {
397 # Even if it's non-zero, it can still be invalid
398 wfSuppressWarnings();
399 $error = $this->mysqlError( $this->mConn
);
401 $error = $this->mysqlError();
405 $error = $this->mysqlError();
408 $error .= ' (' . $this->mServer
. ')';
415 * Returns the text of the error message from previous MySQL operation
417 * @param resource $conn Raw connection
420 abstract protected function mysqlError( $conn = null );
423 * @param string $table
424 * @param array $uniqueIndexes
426 * @param string $fname
427 * @return ResultWrapper
429 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
430 return $this->nativeReplace( $table, $rows, $fname );
434 * Estimate rows in dataset
435 * Returns estimated count, based on EXPLAIN output
436 * Takes same arguments as Database::select()
438 * @param string|array $table
439 * @param string|array $vars
440 * @param string|array $conds
441 * @param string $fname
442 * @param string|array $options
445 public function estimateRowCount( $table, $vars = '*', $conds = '',
446 $fname = __METHOD__
, $options = array()
448 $options['EXPLAIN'] = true;
449 $res = $this->select( $table, $vars, $conds, $fname, $options );
450 if ( $res === false ) {
453 if ( !$this->numRows( $res ) ) {
458 foreach ( $res as $plan ) {
459 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
466 * @param string $table
467 * @param string $field
468 * @return bool|MySQLField
470 function fieldInfo( $table, $field ) {
471 $table = $this->tableName( $table );
472 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
476 $n = $this->mysqlNumFields( $res->result
);
477 for ( $i = 0; $i < $n; $i++
) {
478 $meta = $this->mysqlFetchField( $res->result
, $i );
479 if ( $field == $meta->name
) {
480 return new MySQLField( $meta );
488 * Get column information from a result
490 * @param resource $res Raw result
494 abstract protected function mysqlFetchField( $res, $n );
497 * Get information about an index into an object
498 * Returns false if the index does not exist
500 * @param string $table
501 * @param string $index
502 * @param string $fname
503 * @return bool|array|null False or null on failure
505 function indexInfo( $table, $index, $fname = __METHOD__
) {
506 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
507 # SHOW INDEX should work for 3.x and up:
508 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
509 $table = $this->tableName( $table );
510 $index = $this->indexName( $index );
512 $sql = 'SHOW INDEX FROM ' . $table;
513 $res = $this->query( $sql, $fname );
521 foreach ( $res as $row ) {
522 if ( $row->Key_name
== $index ) {
527 return empty( $result ) ?
false : $result;
534 function strencode( $s ) {
535 $sQuoted = $this->mysqlRealEscapeString( $s );
537 if ( $sQuoted === false ) {
539 $sQuoted = $this->mysqlRealEscapeString( $s );
546 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
551 public function addIdentifierQuotes( $s ) {
552 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
553 // Remove NUL bytes and escape backticks by doubling
554 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
558 * @param string $name
561 public function isQuotedIdentifier( $name ) {
562 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
569 $ping = $this->mysqlPing();
574 $this->closeConnection();
575 $this->mOpened
= false;
576 $this->mConn
= false;
577 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
583 * Ping a server connection or reconnect if there is no connection
587 abstract protected function mysqlPing();
590 * Set lag time in seconds for a fake slave
594 public function setFakeSlaveLag( $lag ) {
595 $this->mFakeSlaveLag
= $lag;
599 * Make this connection a fake master
601 * @param bool $enabled
603 public function setFakeMaster( $enabled = true ) {
604 $this->mFakeMaster
= $enabled;
610 * This will do a SHOW SLAVE STATUS
615 if ( !is_null( $this->mFakeSlaveLag
) ) {
616 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
618 return $this->mFakeSlaveLag
;
621 return $this->getLagFromSlaveStatus();
627 function getLagFromSlaveStatus() {
628 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
632 $row = $res->fetchObject();
636 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
639 return intval( $row->Seconds_Behind_Master
);
644 * Wait for the slave to catch up to a given master position.
645 * @todo Return values for this and base class are rubbish
647 * @param DBMasterPos|MySQLMasterPos $pos
648 * @param int $timeout The maximum number of seconds to wait for synchronisation
649 * @return int Zero if the slave was past that position already,
650 * greater than zero if we waited for some period of time, less than
651 * zero if we timed out.
653 function masterPosWait( DBMasterPos
$pos, $timeout ) {
654 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
655 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
658 wfProfileIn( __METHOD__
);
659 # Commit any open transactions
660 $this->commit( __METHOD__
, 'flush' );
662 if ( !is_null( $this->mFakeSlaveLag
) ) {
663 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
665 if ( $wait > $timeout * 1e6
) {
666 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
667 wfProfileOut( __METHOD__
);
670 } elseif ( $wait > 0 ) {
671 wfDebug( "Fake slave waiting $wait us\n" );
673 wfProfileOut( __METHOD__
);
677 wfDebug( "Fake slave up to date ($wait us)\n" );
678 wfProfileOut( __METHOD__
);
684 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
685 $encFile = $this->addQuotes( $pos->file
);
686 $encPos = intval( $pos->pos
);
687 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
688 $res = $this->doQuery( $sql );
691 if ( $res && $row = $this->fetchRow( $res ) ) {
692 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
693 if ( ctype_digit( $status ) ) { // success
694 $this->lastKnownSlavePos
= $pos;
698 wfProfileOut( __METHOD__
);
704 * Get the position of the master from SHOW SLAVE STATUS
706 * @return MySQLMasterPos|bool
708 function getSlavePos() {
709 if ( !is_null( $this->mFakeSlaveLag
) ) {
710 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
711 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
716 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
717 $row = $this->fetchObject( $res );
720 $pos = isset( $row->Exec_master_log_pos
)
721 ?
$row->Exec_master_log_pos
722 : $row->Exec_Master_Log_Pos
;
724 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
731 * Get the position of the master from SHOW MASTER STATUS
733 * @return MySQLMasterPos|bool
735 function getMasterPos() {
736 if ( $this->mFakeMaster
) {
737 return new MySQLMasterPos( 'fake', microtime( true ) );
740 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
741 $row = $this->fetchObject( $res );
744 return new MySQLMasterPos( $row->File
, $row->Position
);
751 * @param string $index
754 function useIndexClause( $index ) {
755 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
761 function lowPriorityOption() {
762 return 'LOW_PRIORITY';
768 public function getSoftwareLink() {
769 // MariaDB includes its name in its version string; this is how MariaDB's version of
770 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
771 // in libmysql/libmysql.c).
772 $version = $this->getServerVersion();
773 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
774 return '[{{int:version-db-mariadb-url}} MariaDB]';
777 // Percona Server's version suffix is not very distinctive, and @@version_comment
778 // doesn't give the necessary info for source builds, so assume the server is MySQL.
779 // (Even Percona's version of mysql doesn't try to make the distinction.)
780 return '[{{int:version-db-mysql-url}} MySQL]';
786 public function getServerVersion() {
787 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
788 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
789 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
790 if ( $this->serverVersion
=== null ) {
791 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
793 return $this->serverVersion
;
797 * @param array $options
799 public function setSessionOptions( array $options ) {
800 if ( isset( $options['connTimeout'] ) ) {
801 $timeout = (int)$options['connTimeout'];
802 $this->query( "SET net_read_timeout=$timeout" );
803 $this->query( "SET net_write_timeout=$timeout" );
809 * @param string $newLine
812 public function streamStatementEnd( &$sql, &$newLine ) {
813 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
814 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
815 $this->delimiter
= $m[1];
819 return parent
::streamStatementEnd( $sql, $newLine );
823 * Check to see if a named lock is available. This is non-blocking.
825 * @param string $lockName Name of lock to poll
826 * @param string $method Name of method calling us
830 public function lockIsFree( $lockName, $method ) {
831 $lockName = $this->addQuotes( $lockName );
832 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
833 $row = $this->fetchObject( $result );
835 return ( $row->lockstatus
== 1 );
839 * @param string $lockName
840 * @param string $method
841 * @param int $timeout
844 public function lock( $lockName, $method, $timeout = 5 ) {
845 $lockName = $this->addQuotes( $lockName );
846 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
847 $row = $this->fetchObject( $result );
849 if ( $row->lockstatus
== 1 ) {
852 wfDebug( __METHOD__
. " failed to acquire lock\n" );
860 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
861 * @param string $lockName
862 * @param string $method
865 public function unlock( $lockName, $method ) {
866 $lockName = $this->addQuotes( $lockName );
867 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
868 $row = $this->fetchObject( $result );
870 return ( $row->lockstatus
== 1 );
875 * @param array $write
876 * @param string $method
877 * @param bool $lowPriority
880 public function lockTables( $read, $write, $method, $lowPriority = true ) {
883 foreach ( $write as $table ) {
884 $tbl = $this->tableName( $table ) .
885 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
889 foreach ( $read as $table ) {
890 $items[] = $this->tableName( $table ) . ' READ';
892 $sql = "LOCK TABLES " . implode( ',', $items );
893 $this->query( $sql, $method );
899 * @param string $method
902 public function unlockTables( $method ) {
903 $this->query( "UNLOCK TABLES", $method );
909 * Get search engine class. All subclasses of this
910 * need to implement this if they wish to use searching.
914 public function getSearchEngine() {
915 return 'SearchMySQL';
921 public function setBigSelects( $value = true ) {
922 if ( $value === 'default' ) {
923 if ( $this->mDefaultBigSelects
=== null ) {
924 # Function hasn't been called before so it must already be set to the default
927 $value = $this->mDefaultBigSelects
;
929 } elseif ( $this->mDefaultBigSelects
=== null ) {
930 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
932 $encValue = $value ?
'1' : '0';
933 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
937 * DELETE where the condition is a join. MySql uses multi-table deletes.
938 * @param string $delTable
939 * @param string $joinTable
940 * @param string $delVar
941 * @param string $joinVar
942 * @param array|string $conds
943 * @param bool|string $fname
944 * @throws DBUnexpectedError
945 * @return bool|ResultWrapper
947 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
949 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
952 $delTable = $this->tableName( $delTable );
953 $joinTable = $this->tableName( $joinTable );
954 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
956 if ( $conds != '*' ) {
957 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
960 return $this->query( $sql, $fname );
964 * @param string $table
966 * @param array $uniqueIndexes
968 * @param string $fname
971 public function upsert( $table, array $rows, array $uniqueIndexes,
972 array $set, $fname = __METHOD__
974 if ( !count( $rows ) ) {
975 return true; // nothing to do
978 if ( !is_array( reset( $rows ) ) ) {
979 $rows = array( $rows );
982 $table = $this->tableName( $table );
983 $columns = array_keys( $rows[0] );
985 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
986 $rowTuples = array();
987 foreach ( $rows as $row ) {
988 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
990 $sql .= implode( ',', $rowTuples );
991 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
993 return (bool)$this->query( $sql, $fname );
997 * Determines how long the server has been up
1001 function getServerUptime() {
1002 $vars = $this->getMysqlStatus( 'Uptime' );
1004 return (int)$vars['Uptime'];
1008 * Determines if the last failure was due to a deadlock
1012 function wasDeadlock() {
1013 return $this->lastErrno() == 1213;
1017 * Determines if the last failure was due to a lock timeout
1021 function wasLockTimeout() {
1022 return $this->lastErrno() == 1205;
1026 * Determines if the last query error was something that should be dealt
1027 * with by pinging the connection and reissuing the query
1031 function wasErrorReissuable() {
1032 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1036 * Determines if the last failure was due to the database being read-only.
1040 function wasReadOnlyError() {
1041 return $this->lastErrno() == 1223 ||
1042 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1046 * @param string $oldName
1047 * @param string $newName
1048 * @param bool $temporary
1049 * @param string $fname
1052 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1053 $tmp = $temporary ?
'TEMPORARY ' : '';
1054 $newName = $this->addIdentifierQuotes( $newName );
1055 $oldName = $this->addIdentifierQuotes( $oldName );
1056 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1058 return $this->query( $query, $fname );
1062 * List all tables on the database
1064 * @param string $prefix Only show tables with this prefix, e.g. mw_
1065 * @param string $fname Calling function name
1068 function listTables( $prefix = null, $fname = __METHOD__
) {
1069 $result = $this->query( "SHOW TABLES", $fname );
1071 $endArray = array();
1073 foreach ( $result as $table ) {
1074 $vars = get_object_vars( $table );
1075 $table = array_pop( $vars );
1077 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1078 $endArray[] = $table;
1086 * @param string $tableName
1087 * @param string $fName
1088 * @return bool|ResultWrapper
1090 public function dropTable( $tableName, $fName = __METHOD__
) {
1091 if ( !$this->tableExists( $tableName, $fName ) ) {
1095 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1101 protected function getDefaultSchemaVars() {
1102 $vars = parent
::getDefaultSchemaVars();
1103 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1104 $vars['wgDBTableOptions'] = str_replace(
1107 $vars['wgDBTableOptions']
1114 * Get status information from SHOW STATUS in an associative array
1116 * @param string $which
1119 function getMysqlStatus( $which = "%" ) {
1120 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1123 foreach ( $res as $row ) {
1124 $status[$row->Variable_name
] = $row->Value
;
1131 * Lists VIEWs in the database
1133 * @param string $prefix Only show VIEWs with this prefix, eg.
1134 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1135 * @param string $fname Name of calling function
1139 public function listViews( $prefix = null, $fname = __METHOD__
) {
1141 if ( !isset( $this->allViews
) ) {
1143 // The name of the column containing the name of the VIEW
1144 $propertyName = 'Tables_in_' . $this->mDBname
;
1146 // Query for the VIEWS
1147 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1148 $this->allViews
= array();
1149 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1150 array_push( $this->allViews
, $row[$propertyName] );
1154 if ( is_null( $prefix ) ||
$prefix === '' ) {
1155 return $this->allViews
;
1158 $filteredViews = array();
1159 foreach ( $this->allViews
as $viewName ) {
1160 // Does the name of this VIEW start with the table-prefix?
1161 if ( strpos( $viewName, $prefix ) === 0 ) {
1162 array_push( $filteredViews, $viewName );
1166 return $filteredViews;
1170 * Differentiates between a TABLE and a VIEW.
1172 * @param string $name Name of the TABLE/VIEW to test
1173 * @param string $prefix
1177 public function isView( $name, $prefix = null ) {
1178 return in_array( $name, $this->listViews( $prefix ) );
1186 class MySQLField
implements Field
{
1187 private $name, $tablename, $default, $max_length, $nullable,
1188 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1190 function __construct( $info ) {
1191 $this->name
= $info->name
;
1192 $this->tablename
= $info->table
;
1193 $this->default = $info->def
;
1194 $this->max_length
= $info->max_length
;
1195 $this->nullable
= !$info->not_null
;
1196 $this->is_pk
= $info->primary_key
;
1197 $this->is_unique
= $info->unique_key
;
1198 $this->is_multiple
= $info->multiple_key
;
1199 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1200 $this->type
= $info->type
;
1201 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1214 function tableName() {
1215 return $this->tableName
;
1228 function isNullable() {
1229 return $this->nullable
;
1232 function defaultValue() {
1233 return $this->default;
1240 return $this->is_key
;
1246 function isMultipleKey() {
1247 return $this->is_multiple
;
1250 function isBinary() {
1251 return $this->binary
;
1255 class MySQLMasterPos
implements DBMasterPos
{
1259 /** @var int Timestamp */
1262 function __construct( $file, $pos ) {
1263 $this->file
= $file;
1267 function __toString() {
1268 // e.g db1034-bin.000976/843431247
1269 return "{$this->file}/{$this->pos}";
1273 * @return array|bool (int, int)
1275 protected function getCoordinates() {
1277 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1278 return array( (int)$m[1], (int)$m[2] );
1284 function hasReached( MySQLMasterPos
$pos ) {
1285 $thisPos = $this->getCoordinates();
1286 $thatPos = $pos->getCoordinates();
1288 return ( $thisPos && $thatPos && $thisPos >= $thatPos );