561c81197daa5bc7c0becf293f59d452167d5497
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;
74 # The kernel's default SYN retransmission period is far too slow for us,
75 # so we use a short timeout plus a manual retry. Retrying means that a small
76 # but finite rate of SYN packet loss won't cause user-visible errors.
78 $this->installErrorHandler();
80 $this->mConn
= $this->mysqlConnect( $realServer );
81 } catch ( Exception
$ex ) {
82 $this->restoreErrorHandler();
85 $error = $this->restoreErrorHandler();
87 # Always log connection errors
88 if ( !$this->mConn
) {
90 $error = $this->lastError();
93 "Error connecting to {db_server}: {error}",
94 $this->getLogContext( array(
95 'method' => __METHOD__
,
99 wfDebug( "DB connection error\n" .
100 "Server: $server, User: $user, Password: " .
101 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
103 $this->reportConnectionError( $error );
106 if ( $dbName != '' ) {
107 wfSuppressWarnings();
108 $success = $this->selectDB( $dbName );
112 "Error selecting database {db_name} on server {db_server}",
113 $this->getLogContext( array(
114 'method' => __METHOD__
,
117 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
118 "from client host " . wfHostname() . "\n" );
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 // Abstract over any insane MySQL defaults
130 $set = array( 'group_concat_max_len = 262144' );
131 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
132 if ( is_string( $wgSQLMode ) ) {
133 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
135 // Set any custom settings defined by site config
136 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
137 foreach ( $this->mSessionVars
as $var => $val ) {
138 // Escape strings but not numbers to avoid MySQL complaining
139 if ( !is_int( $val ) && !is_float( $val ) ) {
140 $val = $this->addQuotes( $val );
142 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
146 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
147 $success = $this->doQuery( 'SET ' . implode( ', ', $set ), __METHOD__
);
150 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
151 $this->getLogContext( array(
152 'method' => __METHOD__
,
155 $this->reportConnectionError(
156 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
160 $this->mOpened
= true;
166 * Set the character set information right after connection
169 protected function connectInitCharset() {
173 // Tell the server we're communicating with it in UTF-8.
174 // This may engage various charset conversions.
175 return $this->mysqlSetCharset( 'utf8' );
177 return $this->mysqlSetCharset( 'binary' );
182 * Open a connection to a MySQL server
184 * @param string $realServer
185 * @return mixed Raw connection
186 * @throws DBConnectionError
188 abstract protected function mysqlConnect( $realServer );
191 * Set the character set of the MySQL link
193 * @param string $charset
196 abstract protected function mysqlSetCharset( $charset );
199 * @param ResultWrapper|resource $res
200 * @throws DBUnexpectedError
202 function freeResult( $res ) {
203 if ( $res instanceof ResultWrapper
) {
206 wfSuppressWarnings();
207 $ok = $this->mysqlFreeResult( $res );
210 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
217 * @param resource $res Raw result
220 abstract protected function mysqlFreeResult( $res );
223 * @param ResultWrapper|resource $res
224 * @return stdClass|bool
225 * @throws DBUnexpectedError
227 function fetchObject( $res ) {
228 if ( $res instanceof ResultWrapper
) {
231 wfSuppressWarnings();
232 $row = $this->mysqlFetchObject( $res );
235 $errno = $this->lastErrno();
236 // Unfortunately, mysql_fetch_object does not reset the last errno.
237 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
238 // these are the only errors mysql_fetch_object can cause.
239 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
240 if ( $errno == 2000 ||
$errno == 2013 ) {
241 throw new DBUnexpectedError(
243 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
251 * Fetch a result row as an object
253 * @param resource $res Raw result
256 abstract protected function mysqlFetchObject( $res );
259 * @param ResultWrapper|resource $res
261 * @throws DBUnexpectedError
263 function fetchRow( $res ) {
264 if ( $res instanceof ResultWrapper
) {
267 wfSuppressWarnings();
268 $row = $this->mysqlFetchArray( $res );
271 $errno = $this->lastErrno();
272 // Unfortunately, mysql_fetch_array does not reset the last errno.
273 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
274 // these are the only errors mysql_fetch_array can cause.
275 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
276 if ( $errno == 2000 ||
$errno == 2013 ) {
277 throw new DBUnexpectedError(
279 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
287 * Fetch a result row as an associative and numeric array
289 * @param resource $res Raw result
292 abstract protected function mysqlFetchArray( $res );
295 * @throws DBUnexpectedError
296 * @param ResultWrapper|resource $res
299 function numRows( $res ) {
300 if ( $res instanceof ResultWrapper
) {
303 wfSuppressWarnings();
304 $n = $this->mysqlNumRows( $res );
307 // Unfortunately, mysql_num_rows does not reset the last errno.
308 // We are not checking for any errors here, since
309 // these are no errors mysql_num_rows can cause.
310 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
311 // See https://bugzilla.wikimedia.org/42430
316 * Get number of rows in result
318 * @param resource $res Raw result
321 abstract protected function mysqlNumRows( $res );
324 * @param ResultWrapper|resource $res
327 function numFields( $res ) {
328 if ( $res instanceof ResultWrapper
) {
332 return $this->mysqlNumFields( $res );
336 * Get number of fields in result
338 * @param resource $res Raw result
341 abstract protected function mysqlNumFields( $res );
344 * @param ResultWrapper|resource $res
348 function fieldName( $res, $n ) {
349 if ( $res instanceof ResultWrapper
) {
353 return $this->mysqlFieldName( $res, $n );
357 * Get the name of the specified field in a result
359 * @param ResultWrapper|resource $res
363 abstract protected function mysqlFieldName( $res, $n );
366 * mysql_field_type() wrapper
367 * @param ResultWrapper|resource $res
371 public function fieldType( $res, $n ) {
372 if ( $res instanceof ResultWrapper
) {
376 return $this->mysqlFieldType( $res, $n );
380 * Get the type of the specified field in a result
382 * @param ResultWrapper|resource $res
386 abstract protected function mysqlFieldType( $res, $n );
389 * @param ResultWrapper|resource $res
393 function dataSeek( $res, $row ) {
394 if ( $res instanceof ResultWrapper
) {
398 return $this->mysqlDataSeek( $res, $row );
402 * Move internal result pointer
404 * @param ResultWrapper|resource $res
408 abstract protected function mysqlDataSeek( $res, $row );
413 function lastError() {
414 if ( $this->mConn
) {
415 # Even if it's non-zero, it can still be invalid
416 wfSuppressWarnings();
417 $error = $this->mysqlError( $this->mConn
);
419 $error = $this->mysqlError();
423 $error = $this->mysqlError();
426 $error .= ' (' . $this->mServer
. ')';
433 * Returns the text of the error message from previous MySQL operation
435 * @param resource $conn Raw connection
438 abstract protected function mysqlError( $conn = null );
441 * @param string $table
442 * @param array $uniqueIndexes
444 * @param string $fname
445 * @return ResultWrapper
447 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
448 return $this->nativeReplace( $table, $rows, $fname );
452 * Estimate rows in dataset
453 * Returns estimated count, based on EXPLAIN output
454 * Takes same arguments as Database::select()
456 * @param string|array $table
457 * @param string|array $vars
458 * @param string|array $conds
459 * @param string $fname
460 * @param string|array $options
463 public function estimateRowCount( $table, $vars = '*', $conds = '',
464 $fname = __METHOD__
, $options = array()
466 $options['EXPLAIN'] = true;
467 $res = $this->select( $table, $vars, $conds, $fname, $options );
468 if ( $res === false ) {
471 if ( !$this->numRows( $res ) ) {
476 foreach ( $res as $plan ) {
477 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
484 * @param string $table
485 * @param string $field
486 * @return bool|MySQLField
488 function fieldInfo( $table, $field ) {
489 $table = $this->tableName( $table );
490 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
494 $n = $this->mysqlNumFields( $res->result
);
495 for ( $i = 0; $i < $n; $i++
) {
496 $meta = $this->mysqlFetchField( $res->result
, $i );
497 if ( $field == $meta->name
) {
498 return new MySQLField( $meta );
506 * Get column information from a result
508 * @param resource $res Raw result
512 abstract protected function mysqlFetchField( $res, $n );
515 * Get information about an index into an object
516 * Returns false if the index does not exist
518 * @param string $table
519 * @param string $index
520 * @param string $fname
521 * @return bool|array|null False or null on failure
523 function indexInfo( $table, $index, $fname = __METHOD__
) {
524 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
525 # SHOW INDEX should work for 3.x and up:
526 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
527 $table = $this->tableName( $table );
528 $index = $this->indexName( $index );
530 $sql = 'SHOW INDEX FROM ' . $table;
531 $res = $this->query( $sql, $fname );
539 foreach ( $res as $row ) {
540 if ( $row->Key_name
== $index ) {
545 return empty( $result ) ?
false : $result;
552 function strencode( $s ) {
553 $sQuoted = $this->mysqlRealEscapeString( $s );
555 if ( $sQuoted === false ) {
557 $sQuoted = $this->mysqlRealEscapeString( $s );
564 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
569 public function addIdentifierQuotes( $s ) {
570 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
571 // Remove NUL bytes and escape backticks by doubling
572 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
576 * @param string $name
579 public function isQuotedIdentifier( $name ) {
580 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
587 $ping = $this->mysqlPing();
592 $this->closeConnection();
593 $this->mOpened
= false;
594 $this->mConn
= false;
595 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
601 * Ping a server connection or reconnect if there is no connection
605 abstract protected function mysqlPing();
608 * Set lag time in seconds for a fake slave
612 public function setFakeSlaveLag( $lag ) {
613 $this->mFakeSlaveLag
= $lag;
617 * Make this connection a fake master
619 * @param bool $enabled
621 public function setFakeMaster( $enabled = true ) {
622 $this->mFakeMaster
= $enabled;
628 * This will do a SHOW SLAVE STATUS
633 if ( !is_null( $this->mFakeSlaveLag
) ) {
634 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
636 return $this->mFakeSlaveLag
;
639 return $this->getLagFromSlaveStatus();
645 function getLagFromSlaveStatus() {
646 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
650 $row = $res->fetchObject();
654 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
657 return intval( $row->Seconds_Behind_Master
);
662 * Wait for the slave to catch up to a given master position.
663 * @todo Return values for this and base class are rubbish
665 * @param DBMasterPos|MySQLMasterPos $pos
666 * @param int $timeout The maximum number of seconds to wait for synchronisation
667 * @return int Zero if the slave was past that position already,
668 * greater than zero if we waited for some period of time, less than
669 * zero if we timed out.
671 function masterPosWait( DBMasterPos
$pos, $timeout ) {
672 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
673 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
676 # Commit any open transactions
677 $this->commit( __METHOD__
, 'flush' );
679 if ( !is_null( $this->mFakeSlaveLag
) ) {
680 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
682 if ( $wait > $timeout * 1e6
) {
683 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
686 } elseif ( $wait > 0 ) {
687 wfDebug( "Fake slave waiting $wait us\n" );
692 wfDebug( "Fake slave up to date ($wait us)\n" );
698 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
699 $encFile = $this->addQuotes( $pos->file
);
700 $encPos = intval( $pos->pos
);
701 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
702 $res = $this->doQuery( $sql );
705 if ( $res && $row = $this->fetchRow( $res ) ) {
706 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
707 if ( ctype_digit( $status ) ) { // success
708 $this->lastKnownSlavePos
= $pos;
716 * Get the position of the master from SHOW SLAVE STATUS
718 * @return MySQLMasterPos|bool
720 function getSlavePos() {
721 if ( !is_null( $this->mFakeSlaveLag
) ) {
722 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
723 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
728 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
729 $row = $this->fetchObject( $res );
732 $pos = isset( $row->Exec_master_log_pos
)
733 ?
$row->Exec_master_log_pos
734 : $row->Exec_Master_Log_Pos
;
736 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
743 * Get the position of the master from SHOW MASTER STATUS
745 * @return MySQLMasterPos|bool
747 function getMasterPos() {
748 if ( $this->mFakeMaster
) {
749 return new MySQLMasterPos( 'fake', microtime( true ) );
752 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
753 $row = $this->fetchObject( $res );
756 return new MySQLMasterPos( $row->File
, $row->Position
);
763 * @param string $index
766 function useIndexClause( $index ) {
767 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
773 function lowPriorityOption() {
774 return 'LOW_PRIORITY';
780 public function getSoftwareLink() {
781 // MariaDB includes its name in its version string; this is how MariaDB's version of
782 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
783 // in libmysql/libmysql.c).
784 $version = $this->getServerVersion();
785 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
786 return '[{{int:version-db-mariadb-url}} MariaDB]';
789 // Percona Server's version suffix is not very distinctive, and @@version_comment
790 // doesn't give the necessary info for source builds, so assume the server is MySQL.
791 // (Even Percona's version of mysql doesn't try to make the distinction.)
792 return '[{{int:version-db-mysql-url}} MySQL]';
798 public function getServerVersion() {
799 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
800 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
801 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
802 if ( $this->serverVersion
=== null ) {
803 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
805 return $this->serverVersion
;
809 * @param array $options
811 public function setSessionOptions( array $options ) {
812 if ( isset( $options['connTimeout'] ) ) {
813 $timeout = (int)$options['connTimeout'];
814 $this->query( "SET net_read_timeout=$timeout" );
815 $this->query( "SET net_write_timeout=$timeout" );
821 * @param string $newLine
824 public function streamStatementEnd( &$sql, &$newLine ) {
825 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
826 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
827 $this->delimiter
= $m[1];
831 return parent
::streamStatementEnd( $sql, $newLine );
835 * Check to see if a named lock is available. This is non-blocking.
837 * @param string $lockName Name of lock to poll
838 * @param string $method Name of method calling us
842 public function lockIsFree( $lockName, $method ) {
843 $lockName = $this->addQuotes( $lockName );
844 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
845 $row = $this->fetchObject( $result );
847 return ( $row->lockstatus
== 1 );
851 * @param string $lockName
852 * @param string $method
853 * @param int $timeout
856 public function lock( $lockName, $method, $timeout = 5 ) {
857 $lockName = $this->addQuotes( $lockName );
858 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
859 $row = $this->fetchObject( $result );
861 if ( $row->lockstatus
== 1 ) {
864 wfDebug( __METHOD__
. " failed to acquire lock\n" );
872 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
873 * @param string $lockName
874 * @param string $method
877 public function unlock( $lockName, $method ) {
878 $lockName = $this->addQuotes( $lockName );
879 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
880 $row = $this->fetchObject( $result );
882 return ( $row->lockstatus
== 1 );
885 public function namedLocksEnqueue() {
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,
1205 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1207 function __construct( $info ) {
1208 $this->name
= $info->name
;
1209 $this->tablename
= $info->table
;
1210 $this->default = $info->def
;
1211 $this->max_length
= $info->max_length
;
1212 $this->nullable
= !$info->not_null
;
1213 $this->is_pk
= $info->primary_key
;
1214 $this->is_unique
= $info->unique_key
;
1215 $this->is_multiple
= $info->multiple_key
;
1216 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1217 $this->type
= $info->type
;
1218 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1219 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1220 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1221 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1222 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1235 function tableName() {
1236 return $this->tableName
;
1249 function isNullable() {
1250 return $this->nullable
;
1253 function defaultValue() {
1254 return $this->default;
1261 return $this->is_key
;
1267 function isMultipleKey() {
1268 return $this->is_multiple
;
1274 function isBinary() {
1275 return $this->binary
;
1281 function isNumeric() {
1282 return $this->is_numeric
;
1289 return $this->is_blob
;
1295 function isUnsigned() {
1296 return $this->is_unsigned
;
1302 function isZerofill() {
1303 return $this->is_zerofill
;
1307 class MySQLMasterPos
implements DBMasterPos
{
1310 /** @var int Position */
1312 /** @var float UNIX timestamp */
1313 public $asOfTime = 0.0;
1315 function __construct( $file, $pos ) {
1316 $this->file
= $file;
1318 $this->asOfTime
= microtime( true );
1321 function __toString() {
1322 // e.g db1034-bin.000976/843431247
1323 return "{$this->file}/{$this->pos}";
1327 * @return array|bool (int, int)
1329 protected function getCoordinates() {
1331 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1332 return array( (int)$m[1], (int)$m[2] );
1338 function hasReached( MySQLMasterPos
$pos ) {
1339 $thisPos = $this->getCoordinates();
1340 $thatPos = $pos->getCoordinates();
1342 return ( $thisPos && $thatPos && $thisPos >= $thatPos );
1345 function asOfTime() {
1346 return $this->asOfTime
;