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;
36 /** @var string|null */
37 private $serverVersion = null;
47 * @param string $server
49 * @param string $password
50 * @param string $dbName
51 * @throws Exception|DBConnectionError
54 function open( $server, $user, $password, $dbName ) {
55 global $wgAllDBsAreLocalhost, $wgSQLMode;
57 # Close/unset connection handle
60 # Debugging hack -- fake cluster
61 $realServer = $wgAllDBsAreLocalhost ?
'localhost' : $server;
62 $this->mServer
= $server;
64 $this->mPassword
= $password;
65 $this->mDBname
= $dbName;
67 $this->installErrorHandler();
69 $this->mConn
= $this->mysqlConnect( $realServer );
70 } catch ( Exception
$ex ) {
71 $this->restoreErrorHandler();
74 $error = $this->restoreErrorHandler();
76 # Always log connection errors
77 if ( !$this->mConn
) {
79 $error = $this->lastError();
82 "Error connecting to {db_server}: {error}",
83 $this->getLogContext( array(
84 'method' => __METHOD__
,
88 wfDebug( "DB connection error\n" .
89 "Server: $server, User: $user, Password: " .
90 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
92 $this->reportConnectionError( $error );
95 if ( $dbName != '' ) {
96 MediaWiki\
suppressWarnings();
97 $success = $this->selectDB( $dbName );
98 MediaWiki\restoreWarnings
();
101 "Error selecting database {db_name} on server {db_server}",
102 $this->getLogContext( array(
103 'method' => __METHOD__
,
106 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
107 "from client host " . wfHostname() . "\n" );
109 $this->reportConnectionError( "Error selecting database $dbName" );
113 // Tell the server what we're communicating with
114 if ( !$this->connectInitCharset() ) {
115 $this->reportConnectionError( "Error setting character set" );
118 // Abstract over any insane MySQL defaults
119 $set = array( 'group_concat_max_len = 262144' );
120 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
121 if ( is_string( $wgSQLMode ) ) {
122 $set[] = 'sql_mode = ' . $this->addQuotes( $wgSQLMode );
124 // Set any custom settings defined by site config
125 // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
126 foreach ( $this->mSessionVars
as $var => $val ) {
127 // Escape strings but not numbers to avoid MySQL complaining
128 if ( !is_int( $val ) && !is_float( $val ) ) {
129 $val = $this->addQuotes( $val );
131 $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
135 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
136 $success = $this->doQuery( 'SET ' . implode( ', ', $set ) );
139 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)',
140 $this->getLogContext( array(
141 'method' => __METHOD__
,
144 $this->reportConnectionError(
145 'Error setting MySQL variables on server {db_server} (check $wgSQLMode)' );
149 $this->mOpened
= true;
155 * Set the character set information right after connection
158 protected function connectInitCharset() {
162 // Tell the server we're communicating with it in UTF-8.
163 // This may engage various charset conversions.
164 return $this->mysqlSetCharset( 'utf8' );
166 return $this->mysqlSetCharset( 'binary' );
171 * Open a connection to a MySQL server
173 * @param string $realServer
174 * @return mixed Raw connection
175 * @throws DBConnectionError
177 abstract protected function mysqlConnect( $realServer );
180 * Set the character set of the MySQL link
182 * @param string $charset
185 abstract protected function mysqlSetCharset( $charset );
188 * @param ResultWrapper|resource $res
189 * @throws DBUnexpectedError
191 function freeResult( $res ) {
192 if ( $res instanceof ResultWrapper
) {
195 MediaWiki\
suppressWarnings();
196 $ok = $this->mysqlFreeResult( $res );
197 MediaWiki\restoreWarnings
();
199 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
206 * @param resource $res Raw result
209 abstract protected function mysqlFreeResult( $res );
212 * @param ResultWrapper|resource $res
213 * @return stdClass|bool
214 * @throws DBUnexpectedError
216 function fetchObject( $res ) {
217 if ( $res instanceof ResultWrapper
) {
220 MediaWiki\
suppressWarnings();
221 $row = $this->mysqlFetchObject( $res );
222 MediaWiki\restoreWarnings
();
224 $errno = $this->lastErrno();
225 // Unfortunately, mysql_fetch_object does not reset the last errno.
226 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
227 // these are the only errors mysql_fetch_object can cause.
228 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
229 if ( $errno == 2000 ||
$errno == 2013 ) {
230 throw new DBUnexpectedError(
232 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
240 * Fetch a result row as an object
242 * @param resource $res Raw result
245 abstract protected function mysqlFetchObject( $res );
248 * @param ResultWrapper|resource $res
250 * @throws DBUnexpectedError
252 function fetchRow( $res ) {
253 if ( $res instanceof ResultWrapper
) {
256 MediaWiki\
suppressWarnings();
257 $row = $this->mysqlFetchArray( $res );
258 MediaWiki\restoreWarnings
();
260 $errno = $this->lastErrno();
261 // Unfortunately, mysql_fetch_array does not reset the last errno.
262 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
263 // these are the only errors mysql_fetch_array can cause.
264 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
265 if ( $errno == 2000 ||
$errno == 2013 ) {
266 throw new DBUnexpectedError(
268 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
276 * Fetch a result row as an associative and numeric array
278 * @param resource $res Raw result
281 abstract protected function mysqlFetchArray( $res );
284 * @throws DBUnexpectedError
285 * @param ResultWrapper|resource $res
288 function numRows( $res ) {
289 if ( $res instanceof ResultWrapper
) {
292 MediaWiki\
suppressWarnings();
293 $n = $this->mysqlNumRows( $res );
294 MediaWiki\restoreWarnings
();
296 // Unfortunately, mysql_num_rows does not reset the last errno.
297 // We are not checking for any errors here, since
298 // these are no errors mysql_num_rows can cause.
299 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
300 // See https://phabricator.wikimedia.org/T44430
305 * Get number of rows in result
307 * @param resource $res Raw result
310 abstract protected function mysqlNumRows( $res );
313 * @param ResultWrapper|resource $res
316 function numFields( $res ) {
317 if ( $res instanceof ResultWrapper
) {
321 return $this->mysqlNumFields( $res );
325 * Get number of fields in result
327 * @param resource $res Raw result
330 abstract protected function mysqlNumFields( $res );
333 * @param ResultWrapper|resource $res
337 function fieldName( $res, $n ) {
338 if ( $res instanceof ResultWrapper
) {
342 return $this->mysqlFieldName( $res, $n );
346 * Get the name of the specified field in a result
348 * @param ResultWrapper|resource $res
352 abstract protected function mysqlFieldName( $res, $n );
355 * mysql_field_type() wrapper
356 * @param ResultWrapper|resource $res
360 public function fieldType( $res, $n ) {
361 if ( $res instanceof ResultWrapper
) {
365 return $this->mysqlFieldType( $res, $n );
369 * Get the type of the specified field in a result
371 * @param ResultWrapper|resource $res
375 abstract protected function mysqlFieldType( $res, $n );
378 * @param ResultWrapper|resource $res
382 function dataSeek( $res, $row ) {
383 if ( $res instanceof ResultWrapper
) {
387 return $this->mysqlDataSeek( $res, $row );
391 * Move internal result pointer
393 * @param ResultWrapper|resource $res
397 abstract protected function mysqlDataSeek( $res, $row );
402 function lastError() {
403 if ( $this->mConn
) {
404 # Even if it's non-zero, it can still be invalid
405 MediaWiki\
suppressWarnings();
406 $error = $this->mysqlError( $this->mConn
);
408 $error = $this->mysqlError();
410 MediaWiki\restoreWarnings
();
412 $error = $this->mysqlError();
415 $error .= ' (' . $this->mServer
. ')';
422 * Returns the text of the error message from previous MySQL operation
424 * @param resource $conn Raw connection
427 abstract protected function mysqlError( $conn = null );
430 * @param string $table
431 * @param array $uniqueIndexes
433 * @param string $fname
434 * @return ResultWrapper
436 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
437 return $this->nativeReplace( $table, $rows, $fname );
441 * Estimate rows in dataset
442 * Returns estimated count, based on EXPLAIN output
443 * Takes same arguments as Database::select()
445 * @param string|array $table
446 * @param string|array $vars
447 * @param string|array $conds
448 * @param string $fname
449 * @param string|array $options
452 public function estimateRowCount( $table, $vars = '*', $conds = '',
453 $fname = __METHOD__
, $options = array()
455 $options['EXPLAIN'] = true;
456 $res = $this->select( $table, $vars, $conds, $fname, $options );
457 if ( $res === false ) {
460 if ( !$this->numRows( $res ) ) {
465 foreach ( $res as $plan ) {
466 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
473 * @param string $table
474 * @param string $field
475 * @return bool|MySQLField
477 function fieldInfo( $table, $field ) {
478 $table = $this->tableName( $table );
479 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
483 $n = $this->mysqlNumFields( $res->result
);
484 for ( $i = 0; $i < $n; $i++
) {
485 $meta = $this->mysqlFetchField( $res->result
, $i );
486 if ( $field == $meta->name
) {
487 return new MySQLField( $meta );
495 * Get column information from a result
497 * @param resource $res Raw result
501 abstract protected function mysqlFetchField( $res, $n );
504 * Get information about an index into an object
505 * Returns false if the index does not exist
507 * @param string $table
508 * @param string $index
509 * @param string $fname
510 * @return bool|array|null False or null on failure
512 function indexInfo( $table, $index, $fname = __METHOD__
) {
513 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
514 # SHOW INDEX should work for 3.x and up:
515 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
516 $table = $this->tableName( $table );
517 $index = $this->indexName( $index );
519 $sql = 'SHOW INDEX FROM ' . $table;
520 $res = $this->query( $sql, $fname );
528 foreach ( $res as $row ) {
529 if ( $row->Key_name
== $index ) {
534 return empty( $result ) ?
false : $result;
541 function strencode( $s ) {
542 $sQuoted = $this->mysqlRealEscapeString( $s );
544 if ( $sQuoted === false ) {
546 $sQuoted = $this->mysqlRealEscapeString( $s );
553 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
558 public function addIdentifierQuotes( $s ) {
559 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
560 // Remove NUL bytes and escape backticks by doubling
561 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
565 * @param string $name
568 public function isQuotedIdentifier( $name ) {
569 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
576 $ping = $this->mysqlPing();
578 // Connection was good or lost but reconnected...
579 // @note: mysqlnd (php 5.6+) does not support this (PHP bug 52561)
583 // Try a full disconnect/reconnect cycle if ping() failed
584 $this->closeConnection();
585 $this->mOpened
= false;
586 $this->mConn
= false;
587 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
593 * Ping a server connection or reconnect if there is no connection
597 abstract protected function mysqlPing();
602 * This will do a SHOW SLAVE STATUS
607 return $this->getLagFromSlaveStatus();
613 function getLagFromSlaveStatus() {
614 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
618 $row = $res->fetchObject();
622 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
625 return intval( $row->Seconds_Behind_Master
);
630 * Wait for the slave to catch up to a given master position.
631 * @todo Return values for this and base class are rubbish
633 * @param DBMasterPos|MySQLMasterPos $pos
634 * @param int $timeout The maximum number of seconds to wait for synchronisation
635 * @return int Zero if the slave was past that position already,
636 * greater than zero if we waited for some period of time, less than
637 * zero if we timed out.
639 function masterPosWait( DBMasterPos
$pos, $timeout ) {
640 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
641 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
644 # Commit any open transactions
645 $this->commit( __METHOD__
, 'flush' );
647 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
648 $encFile = $this->addQuotes( $pos->file
);
649 $encPos = intval( $pos->pos
);
650 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
651 $res = $this->doQuery( $sql );
654 if ( $res && $row = $this->fetchRow( $res ) ) {
655 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
656 if ( ctype_digit( $status ) ) { // success
657 $this->lastKnownSlavePos
= $pos;
665 * Get the position of the master from SHOW SLAVE STATUS
667 * @return MySQLMasterPos|bool
669 function getSlavePos() {
670 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
671 $row = $this->fetchObject( $res );
674 $pos = isset( $row->Exec_master_log_pos
)
675 ?
$row->Exec_master_log_pos
676 : $row->Exec_Master_Log_Pos
;
678 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
685 * Get the position of the master from SHOW MASTER STATUS
687 * @return MySQLMasterPos|bool
689 function getMasterPos() {
690 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
691 $row = $this->fetchObject( $res );
694 return new MySQLMasterPos( $row->File
, $row->Position
);
701 * @param string $index
704 function useIndexClause( $index ) {
705 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
711 function lowPriorityOption() {
712 return 'LOW_PRIORITY';
718 public function getSoftwareLink() {
719 // MariaDB includes its name in its version string; this is how MariaDB's version of
720 // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
721 // in libmysql/libmysql.c).
722 $version = $this->getServerVersion();
723 if ( strpos( $version, 'MariaDB' ) !== false ||
strpos( $version, '-maria-' ) !== false ) {
724 return '[{{int:version-db-mariadb-url}} MariaDB]';
727 // Percona Server's version suffix is not very distinctive, and @@version_comment
728 // doesn't give the necessary info for source builds, so assume the server is MySQL.
729 // (Even Percona's version of mysql doesn't try to make the distinction.)
730 return '[{{int:version-db-mysql-url}} MySQL]';
736 public function getServerVersion() {
737 // Not using mysql_get_server_info() or similar for consistency: in the handshake,
738 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
739 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
740 if ( $this->serverVersion
=== null ) {
741 $this->serverVersion
= $this->selectField( '', 'VERSION()', '', __METHOD__
);
743 return $this->serverVersion
;
747 * @param array $options
749 public function setSessionOptions( array $options ) {
750 if ( isset( $options['connTimeout'] ) ) {
751 $timeout = (int)$options['connTimeout'];
752 $this->query( "SET net_read_timeout=$timeout" );
753 $this->query( "SET net_write_timeout=$timeout" );
759 * @param string $newLine
762 public function streamStatementEnd( &$sql, &$newLine ) {
763 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
764 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
765 $this->delimiter
= $m[1];
769 return parent
::streamStatementEnd( $sql, $newLine );
773 * Check to see if a named lock is available. This is non-blocking.
775 * @param string $lockName Name of lock to poll
776 * @param string $method Name of method calling us
780 public function lockIsFree( $lockName, $method ) {
781 $lockName = $this->addQuotes( $lockName );
782 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
783 $row = $this->fetchObject( $result );
785 return ( $row->lockstatus
== 1 );
789 * @param string $lockName
790 * @param string $method
791 * @param int $timeout
794 public function lock( $lockName, $method, $timeout = 5 ) {
795 $lockName = $this->addQuotes( $lockName );
796 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
797 $row = $this->fetchObject( $result );
799 if ( $row->lockstatus
== 1 ) {
802 wfDebug( __METHOD__
. " failed to acquire lock\n" );
810 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
811 * @param string $lockName
812 * @param string $method
815 public function unlock( $lockName, $method ) {
816 $lockName = $this->addQuotes( $lockName );
817 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
818 $row = $this->fetchObject( $result );
820 return ( $row->lockstatus
== 1 );
823 public function namedLocksEnqueue() {
829 * @param array $write
830 * @param string $method
831 * @param bool $lowPriority
834 public function lockTables( $read, $write, $method, $lowPriority = true ) {
837 foreach ( $write as $table ) {
838 $tbl = $this->tableName( $table ) .
839 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
843 foreach ( $read as $table ) {
844 $items[] = $this->tableName( $table ) . ' READ';
846 $sql = "LOCK TABLES " . implode( ',', $items );
847 $this->query( $sql, $method );
853 * @param string $method
856 public function unlockTables( $method ) {
857 $this->query( "UNLOCK TABLES", $method );
863 * Get search engine class. All subclasses of this
864 * need to implement this if they wish to use searching.
868 public function getSearchEngine() {
869 return 'SearchMySQL';
875 public function setBigSelects( $value = true ) {
876 if ( $value === 'default' ) {
877 if ( $this->mDefaultBigSelects
=== null ) {
878 # Function hasn't been called before so it must already be set to the default
881 $value = $this->mDefaultBigSelects
;
883 } elseif ( $this->mDefaultBigSelects
=== null ) {
884 $this->mDefaultBigSelects
=
885 (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__
);
887 $encValue = $value ?
'1' : '0';
888 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
892 * DELETE where the condition is a join. MySql uses multi-table deletes.
893 * @param string $delTable
894 * @param string $joinTable
895 * @param string $delVar
896 * @param string $joinVar
897 * @param array|string $conds
898 * @param bool|string $fname
899 * @throws DBUnexpectedError
900 * @return bool|ResultWrapper
902 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
904 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
907 $delTable = $this->tableName( $delTable );
908 $joinTable = $this->tableName( $joinTable );
909 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
911 if ( $conds != '*' ) {
912 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
915 return $this->query( $sql, $fname );
919 * @param string $table
921 * @param array $uniqueIndexes
923 * @param string $fname
926 public function upsert( $table, array $rows, array $uniqueIndexes,
927 array $set, $fname = __METHOD__
929 if ( !count( $rows ) ) {
930 return true; // nothing to do
933 if ( !is_array( reset( $rows ) ) ) {
934 $rows = array( $rows );
937 $table = $this->tableName( $table );
938 $columns = array_keys( $rows[0] );
940 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
941 $rowTuples = array();
942 foreach ( $rows as $row ) {
943 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
945 $sql .= implode( ',', $rowTuples );
946 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
948 return (bool)$this->query( $sql, $fname );
952 * Determines how long the server has been up
956 function getServerUptime() {
957 $vars = $this->getMysqlStatus( 'Uptime' );
959 return (int)$vars['Uptime'];
963 * Determines if the last failure was due to a deadlock
967 function wasDeadlock() {
968 return $this->lastErrno() == 1213;
972 * Determines if the last failure was due to a lock timeout
976 function wasLockTimeout() {
977 return $this->lastErrno() == 1205;
981 * Determines if the last query error was something that should be dealt
982 * with by pinging the connection and reissuing the query
986 function wasErrorReissuable() {
987 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
991 * Determines if the last failure was due to the database being read-only.
995 function wasReadOnlyError() {
996 return $this->lastErrno() == 1223 ||
997 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
1000 function wasConnectionError( $errno ) {
1001 return $errno == 2013 ||
$errno == 2006;
1005 * Get the underlying binding handle, mConn
1007 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
1008 * This catches broken callers than catch and ignore disconnection exceptions.
1009 * Unlike checking isOpen(), this is safe to call inside of open().
1011 * @return resource|object
1012 * @throws DBUnexpectedError
1015 protected function getBindingHandle() {
1016 if ( !$this->mConn
) {
1017 throw new DBUnexpectedError(
1019 'DB connection was already closed or the connection dropped.'
1023 return $this->mConn
;
1027 * @param string $oldName
1028 * @param string $newName
1029 * @param bool $temporary
1030 * @param string $fname
1033 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
1034 $tmp = $temporary ?
'TEMPORARY ' : '';
1035 $newName = $this->addIdentifierQuotes( $newName );
1036 $oldName = $this->addIdentifierQuotes( $oldName );
1037 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
1039 return $this->query( $query, $fname );
1043 * List all tables on the database
1045 * @param string $prefix Only show tables with this prefix, e.g. mw_
1046 * @param string $fname Calling function name
1049 function listTables( $prefix = null, $fname = __METHOD__
) {
1050 $result = $this->query( "SHOW TABLES", $fname );
1052 $endArray = array();
1054 foreach ( $result as $table ) {
1055 $vars = get_object_vars( $table );
1056 $table = array_pop( $vars );
1058 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1059 $endArray[] = $table;
1067 * @param string $tableName
1068 * @param string $fName
1069 * @return bool|ResultWrapper
1071 public function dropTable( $tableName, $fName = __METHOD__
) {
1072 if ( !$this->tableExists( $tableName, $fName ) ) {
1076 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1082 protected function getDefaultSchemaVars() {
1083 $vars = parent
::getDefaultSchemaVars();
1084 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1085 $vars['wgDBTableOptions'] = str_replace(
1088 $vars['wgDBTableOptions']
1095 * Get status information from SHOW STATUS in an associative array
1097 * @param string $which
1100 function getMysqlStatus( $which = "%" ) {
1101 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1104 foreach ( $res as $row ) {
1105 $status[$row->Variable_name
] = $row->Value
;
1112 * Lists VIEWs in the database
1114 * @param string $prefix Only show VIEWs with this prefix, eg.
1115 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1116 * @param string $fname Name of calling function
1120 public function listViews( $prefix = null, $fname = __METHOD__
) {
1122 if ( !isset( $this->allViews
) ) {
1124 // The name of the column containing the name of the VIEW
1125 $propertyName = 'Tables_in_' . $this->mDBname
;
1127 // Query for the VIEWS
1128 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1129 $this->allViews
= array();
1130 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1131 array_push( $this->allViews
, $row[$propertyName] );
1135 if ( is_null( $prefix ) ||
$prefix === '' ) {
1136 return $this->allViews
;
1139 $filteredViews = array();
1140 foreach ( $this->allViews
as $viewName ) {
1141 // Does the name of this VIEW start with the table-prefix?
1142 if ( strpos( $viewName, $prefix ) === 0 ) {
1143 array_push( $filteredViews, $viewName );
1147 return $filteredViews;
1151 * Differentiates between a TABLE and a VIEW.
1153 * @param string $name Name of the TABLE/VIEW to test
1154 * @param string $prefix
1158 public function isView( $name, $prefix = null ) {
1159 return in_array( $name, $this->listViews( $prefix ) );
1167 class MySQLField
implements Field
{
1168 private $name, $tablename, $default, $max_length, $nullable,
1169 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary,
1170 $is_numeric, $is_blob, $is_unsigned, $is_zerofill;
1172 function __construct( $info ) {
1173 $this->name
= $info->name
;
1174 $this->tablename
= $info->table
;
1175 $this->default = $info->def
;
1176 $this->max_length
= $info->max_length
;
1177 $this->nullable
= !$info->not_null
;
1178 $this->is_pk
= $info->primary_key
;
1179 $this->is_unique
= $info->unique_key
;
1180 $this->is_multiple
= $info->multiple_key
;
1181 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1182 $this->type
= $info->type
;
1183 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1184 $this->is_numeric
= isset( $info->numeric ) ?
$info->numeric : false;
1185 $this->is_blob
= isset( $info->blob
) ?
$info->blob
: false;
1186 $this->is_unsigned
= isset( $info->unsigned
) ?
$info->unsigned
: false;
1187 $this->is_zerofill
= isset( $info->zerofill
) ?
$info->zerofill
: false;
1200 function tableName() {
1201 return $this->tableName
;
1214 function isNullable() {
1215 return $this->nullable
;
1218 function defaultValue() {
1219 return $this->default;
1226 return $this->is_key
;
1232 function isMultipleKey() {
1233 return $this->is_multiple
;
1239 function isBinary() {
1240 return $this->binary
;
1246 function isNumeric() {
1247 return $this->is_numeric
;
1254 return $this->is_blob
;
1260 function isUnsigned() {
1261 return $this->is_unsigned
;
1267 function isZerofill() {
1268 return $this->is_zerofill
;
1272 class MySQLMasterPos
implements DBMasterPos
{
1275 /** @var int Position */
1277 /** @var float UNIX timestamp */
1278 public $asOfTime = 0.0;
1280 function __construct( $file, $pos ) {
1281 $this->file
= $file;
1283 $this->asOfTime
= microtime( true );
1286 function __toString() {
1287 // e.g db1034-bin.000976/843431247
1288 return "{$this->file}/{$this->pos}";
1292 * @return array|bool (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 );
1310 function asOfTime() {
1311 return $this->asOfTime
;