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;
49 * @param string $server
51 * @param string $password
52 * @param string $dbName
53 * @throws Exception|DBConnectionError
56 function open( $server, $user, $password, $dbName ) {
57 global $wgAllDBsAreLocalhost, $wgSQLMode;
58 wfProfileIn( __METHOD__
);
60 # Debugging hack -- fake cluster
61 if ( $wgAllDBsAreLocalhost ) {
62 $realServer = 'localhost';
64 $realServer = $server;
67 $this->mServer
= $server;
69 $this->mPassword
= $password;
70 $this->mDBname
= $dbName;
72 wfProfileIn( "dbconnect-$server" );
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 wfProfileOut( "dbconnect-$server" );
83 wfProfileOut( __METHOD__
);
84 $this->restoreErrorHandler();
87 $error = $this->restoreErrorHandler();
89 wfProfileOut( "dbconnect-$server" );
91 # Always log connection errors
92 if ( !$this->mConn
) {
94 $error = $this->lastError();
96 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
97 wfDebug( "DB connection error\n" .
98 "Server: $server, User: $user, Password: " .
99 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
101 wfProfileOut( __METHOD__
);
103 $this->reportConnectionError( $error );
106 if ( $dbName != '' ) {
107 wfSuppressWarnings();
108 $success = $this->selectDB( $dbName );
111 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
112 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
113 "from client host " . wfHostname() . "\n" );
115 wfProfileOut( __METHOD__
);
117 $this->reportConnectionError( "Error selecting database $dbName" );
121 // Tell the server what we're communicating with
122 if ( !$this->connectInitCharset() ) {
123 $this->reportConnectionError( "Error setting character set" );
126 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
127 if ( is_string( $wgSQLMode ) ) {
128 $mode = $this->addQuotes( $wgSQLMode );
129 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
130 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
132 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
133 wfProfileOut( __METHOD__
);
134 $this->reportConnectionError( "Error setting sql_mode to $mode" );
138 $this->mOpened
= true;
139 wfProfileOut( __METHOD__
);
145 * Set the character set information right after connection
148 protected function connectInitCharset() {
152 // Tell the server we're communicating with it in UTF-8.
153 // This may engage various charset conversions.
154 return $this->mysqlSetCharset( 'utf8' );
156 return $this->mysqlSetCharset( 'binary' );
161 * Open a connection to a MySQL server
163 * @param string $realServer
164 * @return mixed Raw connection
165 * @throws DBConnectionError
167 abstract protected function mysqlConnect( $realServer );
170 * Set the character set of the MySQL link
172 * @param string $charset
175 abstract protected function mysqlSetCharset( $charset );
178 * @param ResultWrapper|resource $res
179 * @throws DBUnexpectedError
181 function freeResult( $res ) {
182 if ( $res instanceof ResultWrapper
) {
185 wfSuppressWarnings();
186 $ok = $this->mysqlFreeResult( $res );
189 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
196 * @param resource $res Raw result
199 abstract protected function mysqlFreeResult( $res );
202 * @param ResultWrapper|resource $res
203 * @return stdClass|bool
204 * @throws DBUnexpectedError
206 function fetchObject( $res ) {
207 if ( $res instanceof ResultWrapper
) {
210 wfSuppressWarnings();
211 $row = $this->mysqlFetchObject( $res );
214 $errno = $this->lastErrno();
215 // Unfortunately, mysql_fetch_object does not reset the last errno.
216 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
217 // these are the only errors mysql_fetch_object can cause.
218 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
219 if ( $errno == 2000 ||
$errno == 2013 ) {
220 throw new DBUnexpectedError(
222 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
230 * Fetch a result row as an object
232 * @param resource $res Raw result
235 abstract protected function mysqlFetchObject( $res );
238 * @param ResultWrapper|resource $res
240 * @throws DBUnexpectedError
242 function fetchRow( $res ) {
243 if ( $res instanceof ResultWrapper
) {
246 wfSuppressWarnings();
247 $row = $this->mysqlFetchArray( $res );
250 $errno = $this->lastErrno();
251 // Unfortunately, mysql_fetch_array does not reset the last errno.
252 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
253 // these are the only errors mysql_fetch_array can cause.
254 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
255 if ( $errno == 2000 ||
$errno == 2013 ) {
256 throw new DBUnexpectedError(
258 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
266 * Fetch a result row as an associative and numeric array
268 * @param resource $res Raw result
271 abstract protected function mysqlFetchArray( $res );
274 * @throws DBUnexpectedError
275 * @param ResultWrapper|resource $res
278 function numRows( $res ) {
279 if ( $res instanceof ResultWrapper
) {
282 wfSuppressWarnings();
283 $n = $this->mysqlNumRows( $res );
286 // Unfortunately, mysql_num_rows does not reset the last errno.
287 // We are not checking for any errors here, since
288 // these are no errors mysql_num_rows can cause.
289 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
290 // See https://bugzilla.wikimedia.org/42430
295 * Get number of rows in result
297 * @param resource $res Raw result
300 abstract protected function mysqlNumRows( $res );
303 * @param ResultWrapper|resource $res
306 function numFields( $res ) {
307 if ( $res instanceof ResultWrapper
) {
311 return $this->mysqlNumFields( $res );
315 * Get number of fields in result
317 * @param resource $res Raw result
320 abstract protected function mysqlNumFields( $res );
323 * @param ResultWrapper|resource $res
327 function fieldName( $res, $n ) {
328 if ( $res instanceof ResultWrapper
) {
332 return $this->mysqlFieldName( $res, $n );
336 * Get the name of the specified field in a result
338 * @param ResultWrapper|resource $res
342 abstract protected function mysqlFieldName( $res, $n );
345 * mysql_field_type() wrapper
346 * @param ResultWrapper|resource $res
350 public function fieldType( $res, $n ) {
351 if ( $res instanceof ResultWrapper
) {
355 return $this->mysqlFieldType( $res, $n );
359 * Get the type of the specified field in a result
361 * @param ResultWrapper|resource $res
365 abstract protected function mysqlFieldType( $res, $n );
368 * @param ResultWrapper|resource $res
372 function dataSeek( $res, $row ) {
373 if ( $res instanceof ResultWrapper
) {
377 return $this->mysqlDataSeek( $res, $row );
381 * Move internal result pointer
383 * @param ResultWrapper|resource $res
387 abstract protected function mysqlDataSeek( $res, $row );
392 function lastError() {
393 if ( $this->mConn
) {
394 # Even if it's non-zero, it can still be invalid
395 wfSuppressWarnings();
396 $error = $this->mysqlError( $this->mConn
);
398 $error = $this->mysqlError();
402 $error = $this->mysqlError();
405 $error .= ' (' . $this->mServer
. ')';
412 * Returns the text of the error message from previous MySQL operation
414 * @param resource $conn Raw connection
417 abstract protected function mysqlError( $conn = null );
420 * @param string $table
421 * @param array $uniqueIndexes
423 * @param string $fname
424 * @return ResultWrapper
426 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
427 return $this->nativeReplace( $table, $rows, $fname );
431 * Estimate rows in dataset
432 * Returns estimated count, based on EXPLAIN output
433 * Takes same arguments as Database::select()
435 * @param string|array $table
436 * @param string|array $vars
437 * @param string|array $conds
438 * @param string $fname
439 * @param string|array $options
442 public function estimateRowCount( $table, $vars = '*', $conds = '',
443 $fname = __METHOD__
, $options = array()
445 $options['EXPLAIN'] = true;
446 $res = $this->select( $table, $vars, $conds, $fname, $options );
447 if ( $res === false ) {
450 if ( !$this->numRows( $res ) ) {
455 foreach ( $res as $plan ) {
456 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
463 * @param string $table
464 * @param string $field
465 * @return bool|MySQLField
467 function fieldInfo( $table, $field ) {
468 $table = $this->tableName( $table );
469 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
473 $n = $this->mysqlNumFields( $res->result
);
474 for ( $i = 0; $i < $n; $i++
) {
475 $meta = $this->mysqlFetchField( $res->result
, $i );
476 if ( $field == $meta->name
) {
477 return new MySQLField( $meta );
485 * Get column information from a result
487 * @param resource $res Raw result
491 abstract protected function mysqlFetchField( $res, $n );
494 * Get information about an index into an object
495 * Returns false if the index does not exist
497 * @param string $table
498 * @param string $index
499 * @param string $fname
500 * @return bool|array|null False or null on failure
502 function indexInfo( $table, $index, $fname = __METHOD__
) {
503 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
504 # SHOW INDEX should work for 3.x and up:
505 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
506 $table = $this->tableName( $table );
507 $index = $this->indexName( $index );
509 $sql = 'SHOW INDEX FROM ' . $table;
510 $res = $this->query( $sql, $fname );
518 foreach ( $res as $row ) {
519 if ( $row->Key_name
== $index ) {
524 return empty( $result ) ?
false : $result;
531 function strencode( $s ) {
532 $sQuoted = $this->mysqlRealEscapeString( $s );
534 if ( $sQuoted === false ) {
536 $sQuoted = $this->mysqlRealEscapeString( $s );
543 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
548 public function addIdentifierQuotes( $s ) {
549 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
550 // Remove NUL bytes and escape backticks by doubling
551 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
555 * @param string $name
558 public function isQuotedIdentifier( $name ) {
559 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
566 $ping = $this->mysqlPing();
571 $this->closeConnection();
572 $this->mOpened
= false;
573 $this->mConn
= false;
574 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
580 * Ping a server connection or reconnect if there is no connection
584 abstract protected function mysqlPing();
587 * Set lag time in seconds for a fake slave
591 public function setFakeSlaveLag( $lag ) {
592 $this->mFakeSlaveLag
= $lag;
596 * Make this connection a fake master
598 * @param bool $enabled
600 public function setFakeMaster( $enabled = true ) {
601 $this->mFakeMaster
= $enabled;
607 * This will do a SHOW SLAVE STATUS
612 if ( !is_null( $this->mFakeSlaveLag
) ) {
613 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
615 return $this->mFakeSlaveLag
;
618 return $this->getLagFromSlaveStatus();
624 function getLagFromSlaveStatus() {
625 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
629 $row = $res->fetchObject();
633 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
636 return intval( $row->Seconds_Behind_Master
);
641 * @deprecated in 1.19, use getLagFromSlaveStatus
645 function getLagFromProcesslist() {
646 wfDeprecated( __METHOD__
, '1.19' );
647 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
651 # Find slave SQL thread
652 foreach ( $res as $row ) {
653 /* This should work for most situations - when default db
654 * for thread is not specified, it had no events executed,
655 * and therefore it doesn't know yet how lagged it is.
657 * Relay log I/O thread does not select databases.
659 if ( $row->User
== 'system user' &&
660 $row->State
!= 'Waiting for master to send event' &&
661 $row->State
!= 'Connecting to master' &&
662 $row->State
!= 'Queueing master event to the relay log' &&
663 $row->State
!= 'Waiting for master update' &&
664 $row->State
!= 'Requesting binlog dump' &&
665 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
666 $row->State
!= 'Reconnecting after a failed master event read' &&
667 $row->State
!= 'Registering slave on master'
669 # This is it, return the time (except -ve)
670 if ( $row->Time
> 0x7fffffff ) {
682 * Wait for the slave to catch up to a given master position.
683 * @todo Return values for this and base class are rubbish
685 * @param DBMasterPos|MySQLMasterPos $pos
686 * @param int $timeout The maximum number of seconds to wait for synchronisation
687 * @return int Zero if the slave was past that position already,
688 * greater than zero if we waited for some period of time, less than
689 * zero if we timed out.
691 function masterPosWait( DBMasterPos
$pos, $timeout ) {
692 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
693 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
696 wfProfileIn( __METHOD__
);
697 # Commit any open transactions
698 $this->commit( __METHOD__
, 'flush' );
700 if ( !is_null( $this->mFakeSlaveLag
) ) {
701 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
703 if ( $wait > $timeout * 1e6
) {
704 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
705 wfProfileOut( __METHOD__
);
708 } elseif ( $wait > 0 ) {
709 wfDebug( "Fake slave waiting $wait us\n" );
711 wfProfileOut( __METHOD__
);
715 wfDebug( "Fake slave up to date ($wait us)\n" );
716 wfProfileOut( __METHOD__
);
722 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
723 $encFile = $this->addQuotes( $pos->file
);
724 $encPos = intval( $pos->pos
);
725 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
726 $res = $this->doQuery( $sql );
729 if ( $res && $row = $this->fetchRow( $res ) ) {
730 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
731 if ( ctype_digit( $status ) ) { // success
732 $this->lastKnownSlavePos
= $pos;
736 wfProfileOut( __METHOD__
);
742 * Get the position of the master from SHOW SLAVE STATUS
744 * @return MySQLMasterPos|bool
746 function getSlavePos() {
747 if ( !is_null( $this->mFakeSlaveLag
) ) {
748 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
749 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
754 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
755 $row = $this->fetchObject( $res );
758 $pos = isset( $row->Exec_master_log_pos
)
759 ?
$row->Exec_master_log_pos
760 : $row->Exec_Master_Log_Pos
;
762 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
769 * Get the position of the master from SHOW MASTER STATUS
771 * @return MySQLMasterPos|bool
773 function getMasterPos() {
774 if ( $this->mFakeMaster
) {
775 return new MySQLMasterPos( 'fake', microtime( true ) );
778 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
779 $row = $this->fetchObject( $res );
782 return new MySQLMasterPos( $row->File
, $row->Position
);
789 * @param string $index
792 function useIndexClause( $index ) {
793 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
799 function lowPriorityOption() {
800 return 'LOW_PRIORITY';
806 public function getSoftwareLink() {
807 $version = $this->getServerVersion();
808 if ( strpos( $version, 'MariaDB' ) !== false ) {
809 return '[{{int:version-db-mariadb-url}} MariaDB]';
810 } elseif ( strpos( $version, 'percona' ) !== false ) {
811 return '[{{int:version-db-percona-url}} Percona Server]';
813 return '[{{int:version-db-mysql-url}} MySQL]';
818 * @param array $options
820 public function setSessionOptions( array $options ) {
821 if ( isset( $options['connTimeout'] ) ) {
822 $timeout = (int)$options['connTimeout'];
823 $this->query( "SET net_read_timeout=$timeout" );
824 $this->query( "SET net_write_timeout=$timeout" );
830 * @param string $newLine
833 public function streamStatementEnd( &$sql, &$newLine ) {
834 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
835 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
836 $this->delimiter
= $m[1];
840 return parent
::streamStatementEnd( $sql, $newLine );
844 * Check to see if a named lock is available. This is non-blocking.
846 * @param string $lockName name of lock to poll
847 * @param string $method name of method calling us
851 public function lockIsFree( $lockName, $method ) {
852 $lockName = $this->addQuotes( $lockName );
853 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
854 $row = $this->fetchObject( $result );
856 return ( $row->lockstatus
== 1 );
860 * @param string $lockName
861 * @param string $method
862 * @param int $timeout
865 public function lock( $lockName, $method, $timeout = 5 ) {
866 $lockName = $this->addQuotes( $lockName );
867 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
868 $row = $this->fetchObject( $result );
870 if ( $row->lockstatus
== 1 ) {
873 wfDebug( __METHOD__
. " failed to acquire lock\n" );
881 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
882 * @param string $lockName
883 * @param string $method
886 public function unlock( $lockName, $method ) {
887 $lockName = $this->addQuotes( $lockName );
888 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
889 $row = $this->fetchObject( $result );
891 return ( $row->lockstatus
== 1 );
896 * @param array $write
897 * @param string $method
898 * @param bool $lowPriority
901 public function lockTables( $read, $write, $method, $lowPriority = true ) {
904 foreach ( $write as $table ) {
905 $tbl = $this->tableName( $table ) .
906 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
910 foreach ( $read as $table ) {
911 $items[] = $this->tableName( $table ) . ' READ';
913 $sql = "LOCK TABLES " . implode( ',', $items );
914 $this->query( $sql, $method );
920 * @param string $method
923 public function unlockTables( $method ) {
924 $this->query( "UNLOCK TABLES", $method );
930 * Get search engine class. All subclasses of this
931 * need to implement this if they wish to use searching.
935 public function getSearchEngine() {
936 return 'SearchMySQL';
941 * @return mixed null|bool|ResultWrapper
943 public function setBigSelects( $value = true ) {
944 if ( $value === 'default' ) {
945 if ( $this->mDefaultBigSelects
=== null ) {
946 # Function hasn't been called before so it must already be set to the default
949 $value = $this->mDefaultBigSelects
;
951 } elseif ( $this->mDefaultBigSelects
=== null ) {
952 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
954 $encValue = $value ?
'1' : '0';
955 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
959 * DELETE where the condition is a join. MySql uses multi-table deletes.
960 * @param $delTable string
961 * @param $joinTable string
962 * @param $delVar string
963 * @param $joinVar string
964 * @param $conds array|string
965 * @param bool|string $fname bool
966 * @throws DBUnexpectedError
967 * @return bool|ResultWrapper
969 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
971 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
974 $delTable = $this->tableName( $delTable );
975 $joinTable = $this->tableName( $joinTable );
976 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
978 if ( $conds != '*' ) {
979 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
982 return $this->query( $sql, $fname );
986 * @param string $table
988 * @param array $uniqueIndexes
990 * @param string $fname
993 public function upsert( $table, array $rows, array $uniqueIndexes,
994 array $set, $fname = __METHOD__
996 if ( !count( $rows ) ) {
997 return true; // nothing to do
999 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
1001 $table = $this->tableName( $table );
1002 $columns = array_keys( $rows[0] );
1004 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
1005 $rowTuples = array();
1006 foreach ( $rows as $row ) {
1007 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
1009 $sql .= implode( ',', $rowTuples );
1010 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
1012 return (bool)$this->query( $sql, $fname );
1016 * Determines how long the server has been up
1020 function getServerUptime() {
1021 $vars = $this->getMysqlStatus( 'Uptime' );
1023 return (int)$vars['Uptime'];
1027 * Determines if the last failure was due to a deadlock
1031 function wasDeadlock() {
1032 return $this->lastErrno() == 1213;
1036 * Determines if the last failure was due to a lock timeout
1040 function wasLockTimeout() {
1041 return $this->lastErrno() == 1205;
1045 * Determines if the last query error was something that should be dealt
1046 * with by pinging the connection and reissuing the query
1050 function wasErrorReissuable() {
1051 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
1055 * Determines if the last failure was due to the database being read-only.
1059 function wasReadOnlyError() {
1060 return $this->lastErrno() == 1223 ||
1061 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1065 * @param string $oldName
1066 * @param string $newName
1067 * @param bool $temporary
1068 * @param string $fname
1071 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1072 $tmp = $temporary ?
'TEMPORARY ' : '';
1073 $newName = $this->addIdentifierQuotes( $newName );
1074 $oldName = $this->addIdentifierQuotes( $oldName );
1075 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1077 return $this->query( $query, $fname );
1081 * List all tables on the database
1083 * @param string $prefix Only show tables with this prefix, e.g. mw_
1084 * @param string $fname Calling function name
1087 function listTables( $prefix = null, $fname = __METHOD__
) {
1088 $result = $this->query( "SHOW TABLES", $fname );
1090 $endArray = array();
1092 foreach ( $result as $table ) {
1093 $vars = get_object_vars( $table );
1094 $table = array_pop( $vars );
1096 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1097 $endArray[] = $table;
1106 * @param $fName string
1107 * @return bool|ResultWrapper
1109 public function dropTable( $tableName, $fName = __METHOD__
) {
1110 if ( !$this->tableExists( $tableName, $fName ) ) {
1114 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1120 protected function getDefaultSchemaVars() {
1121 $vars = parent
::getDefaultSchemaVars();
1122 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1123 $vars['wgDBTableOptions'] = str_replace(
1126 $vars['wgDBTableOptions']
1133 * Get status information from SHOW STATUS in an associative array
1135 * @param string $which
1138 function getMysqlStatus( $which = "%" ) {
1139 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1142 foreach ( $res as $row ) {
1143 $status[$row->Variable_name
] = $row->Value
;
1150 * Lists VIEWs in the database
1152 * @param string $prefix Only show VIEWs with this prefix, eg.
1153 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1154 * @param string $fname Name of calling function
1158 public function listViews( $prefix = null, $fname = __METHOD__
) {
1160 if ( !isset( $this->allViews
) ) {
1162 // The name of the column containing the name of the VIEW
1163 $propertyName = 'Tables_in_' . $this->mDBname
;
1165 // Query for the VIEWS
1166 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1167 $this->allViews
= array();
1168 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1169 array_push( $this->allViews
, $row[$propertyName] );
1173 if ( is_null( $prefix ) ||
$prefix === '' ) {
1174 return $this->allViews
;
1177 $filteredViews = array();
1178 foreach ( $this->allViews
as $viewName ) {
1179 // Does the name of this VIEW start with the table-prefix?
1180 if ( strpos( $viewName, $prefix ) === 0 ) {
1181 array_push( $filteredViews, $viewName );
1185 return $filteredViews;
1189 * Differentiates between a TABLE and a VIEW.
1191 * @param string $name Name of the TABLE/VIEW to test
1192 * @param string $prefix
1196 public function isView( $name, $prefix = null ) {
1197 return in_array( $name, $this->listViews( $prefix ) );
1205 class MySQLField
implements Field
{
1206 private $name, $tablename, $default, $max_length, $nullable,
1207 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1209 function __construct( $info ) {
1210 $this->name
= $info->name
;
1211 $this->tablename
= $info->table
;
1212 $this->default = $info->def
;
1213 $this->max_length
= $info->max_length
;
1214 $this->nullable
= !$info->not_null
;
1215 $this->is_pk
= $info->primary_key
;
1216 $this->is_unique
= $info->unique_key
;
1217 $this->is_multiple
= $info->multiple_key
;
1218 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1219 $this->type
= $info->type
;
1220 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1233 function tableName() {
1234 return $this->tableName
;
1247 function isNullable() {
1248 return $this->nullable
;
1251 function defaultValue() {
1252 return $this->default;
1259 return $this->is_key
;
1265 function isMultipleKey() {
1266 return $this->is_multiple
;
1269 function isBinary() {
1270 return $this->binary
;
1274 class MySQLMasterPos
implements DBMasterPos
{
1278 /** @var int timestamp */
1281 function __construct( $file, $pos ) {
1282 $this->file
= $file;
1286 function __toString() {
1287 // e.g db1034-bin.000976/843431247
1288 return "{$this->file}/{$this->pos}";
1292 * @return array|false (int, int)
1294 protected function getCoordinates() {
1296 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1297 return array( (int)$m[1], (int)$m[2] );
1303 function hasReached( MySQLMasterPos
$pos ) {
1304 $thisPos = $this->getCoordinates();
1305 $thatPos = $pos->getCoordinates();
1307 return ( $thisPos && $thatPos && $thisPos >= $thatPos );