mysql

package
v3.0.0-rc.3+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2018 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Overview

Package mysql is a library to support MySQL binary protocol, both client and server sides. It also supports binlog event parsing.

Index

Constants

View Source
const (
	// MysqlNativePassword uses a salt and transmits a hash on the wire.
	MysqlNativePassword = "mysql_native_password"

	// MysqlClearPassword transmits the password in the clear.
	MysqlClearPassword = "mysql_clear_password"

	// MysqlDialog uses the dialog plugin on the client side.
	// It transmits data in the clear.
	MysqlDialog = "dialog"
)

Supported auth forms.

View Source
const (
	// CapabilityClientLongPassword is CLIENT_LONG_PASSWORD.
	// New more secure passwords. Assumed to be set since 4.1.1.
	// We do not check this anywhere.
	CapabilityClientLongPassword = 1

	// CapabilityClientFoundRows is CLIENT_FOUND_ROWS.
	CapabilityClientFoundRows = 1 << 1

	// CapabilityClientLongFlag is CLIENT_LONG_FLAG.
	// Longer flags in Protocol::ColumnDefinition320.
	// Set it everywhere, not used, as we use Protocol::ColumnDefinition41.
	CapabilityClientLongFlag = 1 << 2

	// CapabilityClientConnectWithDB is CLIENT_CONNECT_WITH_DB.
	// One can specify db on connect.
	CapabilityClientConnectWithDB = 1 << 3

	// CapabilityClientProtocol41 is CLIENT_PROTOCOL_41.
	// New 4.1 protocol. Enforced everywhere.
	CapabilityClientProtocol41 = 1 << 9

	// CapabilityClientSSL is CLIENT_SSL.
	// Switch to SSL after handshake.
	CapabilityClientSSL = 1 << 11

	// CapabilityClientTransactions is CLIENT_TRANSACTIONS.
	// Can send status flags in EOF_Packet.
	// This flag is optional in 3.23, but always set by the server since 4.0.
	// We just do it all the time.
	CapabilityClientTransactions = 1 << 13

	// CapabilityClientSecureConnection is CLIENT_SECURE_CONNECTION.
	// New 4.1 authentication. Always set, expected, never checked.
	CapabilityClientSecureConnection = 1 << 15

	// CapabilityClientMultiStatements is CLIENT_MULTI_STATEMENTS
	// Can handle multiple statements per COM_QUERY and COM_STMT_PREPARE.
	CapabilityClientMultiStatements = 1 << 16

	// CapabilityClientMultiResults is CLIENT_MULTI_RESULTS
	// Can send multiple resultsets for COM_QUERY.
	CapabilityClientMultiResults = 1 << 17

	// CapabilityClientPluginAuth is CLIENT_PLUGIN_AUTH.
	// Client supports plugin authentication.
	CapabilityClientPluginAuth = 1 << 19

	// CapabilityClientConnAttr is CLIENT_CONNECT_ATTRS
	// Permits connection attributes in Protocol::HandshakeResponse41.
	CapabilityClientConnAttr = 1 << 20

	// CapabilityClientPluginAuthLenencClientData is CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA
	CapabilityClientPluginAuthLenencClientData = 1 << 21

	// CapabilityClientDeprecateEOF is CLIENT_DEPRECATE_EOF
	// Expects an OK (instead of EOF) after the resultset rows of a Text Resultset.
	CapabilityClientDeprecateEOF = 1 << 24
)

Capability flags. Originally found in include/mysql/mysql_com.h

View Source
const (
	// ComQuit is COM_QUIT.
	ComQuit = 0x01

	// ComInitDB is COM_INIT_DB.
	ComInitDB = 0x02

	// ComQuery is COM_QUERY.
	ComQuery = 0x03

	// ComPing is COM_PING.
	ComPing = 0x0e

	// ComBinlogDump is COM_BINLOG_DUMP.
	ComBinlogDump = 0x12

	// ComSetOption is COM_SET_OPTION
	ComSetOption = 0x1b

	// ComBinlogDumpGTID is COM_BINLOG_DUMP_GTID.
	ComBinlogDumpGTID = 0x1e

	// OKPacket is the header of the OK packet.
	OKPacket = 0x00

	// EOFPacket is the header of the EOF packet.
	EOFPacket = 0xfe

	// AuthSwitchRequestPacket is used to switch auth method.
	AuthSwitchRequestPacket = 0xfe

	// ErrPacket is the header of the error packet.
	ErrPacket = 0xff

	// NullValue is the encoded value of NULL.
	NullValue = 0xfb
)

Packet types. Originally found in include/mysql/mysql_com.h

View Source
const (
	// CRUnknownError is CR_UNKNOWN_ERROR
	CRUnknownError = 2000

	// CRConnectionError is CR_CONNECTION_ERROR
	// This is returned if a connection via a Unix socket fails.
	CRConnectionError = 2002

	// CRConnHostError is CR_CONN_HOST_ERROR
	// This is returned if a connection via a TCP socket fails.
	CRConnHostError = 2003

	// CRServerGone is CR_SERVER_GONE_ERROR.
	// This is returned if the client tries to send a command but it fails.
	CRServerGone = 2006

	// CRVersionError is CR_VERSION_ERROR
	// This is returned if the server versions don't match what we support.
	CRVersionError = 2007

	// CRServerHandshakeErr is CR_SERVER_HANDSHAKE_ERR
	CRServerHandshakeErr = 2012

	// CRServerLost is CR_SERVER_LOST.
	// Used when:
	// - the client cannot write an initial auth packet.
	// - the client cannot read an initial auth packet.
	// - the client cannot read a response from the server.
	CRServerLost = 2013

	// CRCommandsOutOfSync is CR_COMMANDS_OUT_OF_SYNC
	// Sent when the streaming calls are not done in the right order.
	CRCommandsOutOfSync = 2014

	// CRNamedPipeStateError is CR_NAMEDPIPESETSTATE_ERROR.
	// This is the highest possible number for a connection error.
	CRNamedPipeStateError = 2018

	// CRCantReadCharset is CR_CANT_READ_CHARSET
	CRCantReadCharset = 2019

	// CRSSLConnectionError is CR_SSL_CONNECTION_ERROR
	CRSSLConnectionError = 2026

	// CRMalformedPacket is CR_MALFORMED_PACKET
	CRMalformedPacket = 2027
)

Error codes for client-side errors. Originally found in include/mysql/errmsg.h and https://dev.mysql.com/doc/refman/5.7/en/error-messages-client.html

View Source
const (
	// unknown
	ERUnknownError = 1105

	// unimplemented
	ERNotSupportedYet = 1235

	// resource exhausted
	ERDiskFull               = 1021
	EROutOfMemory            = 1037
	EROutOfSortMemory        = 1038
	ERConCount               = 1040
	EROutOfResources         = 1041
	ERRecordFileFull         = 1114
	ERHostIsBlocked          = 1129
	ERCantCreateThread       = 1135
	ERTooManyDelayedThreads  = 1151
	ERNetPacketTooLarge      = 1153
	ERTooManyUserConnections = 1203
	ERLockTableFull          = 1206
	ERUserLimitReached       = 1226

	// deadline exceeded
	ERLockWaitTimeout = 1205

	// unavailable
	ERServerShutdown = 1053

	// not found
	ERFormNotFound          = 1029
	ERKeyNotFound           = 1032
	ERBadFieldError         = 1054
	ERNoSuchThread          = 1094
	ERUnknownTable          = 1109
	ERCantFindUDF           = 1122
	ERNonExistingGrant      = 1141
	ERNoSuchTable           = 1146
	ERNonExistingTableGrant = 1147
	ERKeyDoesNotExist       = 1176

	// permissions
	ERDBAccessDenied            = 1044
	ERAccessDeniedError         = 1045
	ERKillDenied                = 1095
	ERNoPermissionToCreateUsers = 1211
	ERSpecifiedAccessDenied     = 1227

	// failed precondition
	ERNoDb                          = 1046
	ERNoSuchIndex                   = 1082
	ERCantDropFieldOrKey            = 1091
	ERTableNotLockedForWrite        = 1099
	ERTableNotLocked                = 1100
	ERTooBigSelect                  = 1104
	ERNotAllowedCommand             = 1148
	ERTooLongString                 = 1162
	ERDelayedInsertTableLocked      = 1165
	ERDupUnique                     = 1169
	ERRequiresPrimaryKey            = 1173
	ERCantDoThisDuringAnTransaction = 1179
	ERReadOnlyTransaction           = 1207
	ERCannotAddForeign              = 1215
	ERNoReferencedRow               = 1216
	ERRowIsReferenced               = 1217
	ERCantUpdateWithReadLock        = 1223
	ERNoDefault                     = 1230
	EROperandColumns                = 1241
	ERSubqueryNo1Row                = 1242
	ERNonUpdateableTable            = 1288
	ERFeatureDisabled               = 1289
	EROptionPreventsStatement       = 1290
	ERDuplicatedValueInType         = 1291
	ERRowIsReferenced2              = 1451
	ErNoReferencedRow2              = 1452

	// already exists
	ERTableExists = 1050
	ERDupEntry    = 1062
	ERFileExists  = 1086
	ERUDFExists   = 1125

	// aborted
	ERGotSignal          = 1078
	ERForcingClose       = 1080
	ERAbortingConnection = 1152
	ERLockDeadlock       = 1213

	// invalid arg
	ERUnknownComError              = 1047
	ERBadNullError                 = 1048
	ERBadDb                        = 1049
	ERBadTable                     = 1051
	ERNonUniq                      = 1052
	ERWrongFieldWithGroup          = 1055
	ERWrongGroupField              = 1056
	ERWrongSumSelect               = 1057
	ERWrongValueCount              = 1058
	ERTooLongIdent                 = 1059
	ERDupFieldName                 = 1060
	ERDupKeyName                   = 1061
	ERWrongFieldSpec               = 1063
	ERParseError                   = 1064
	EREmptyQuery                   = 1065
	ERNonUniqTable                 = 1066
	ERInvalidDefault               = 1067
	ERMultiplePriKey               = 1068
	ERTooManyKeys                  = 1069
	ERTooManyKeyParts              = 1070
	ERTooLongKey                   = 1071
	ERKeyColumnDoesNotExist        = 1072
	ERBlobUsedAsKey                = 1073
	ERTooBigFieldLength            = 1074
	ERWrongAutoKey                 = 1075
	ERWrongFieldTerminators        = 1083
	ERBlobsAndNoTerminated         = 1084
	ERTextFileNotReadable          = 1085
	ERWrongSubKey                  = 1089
	ERCantRemoveAllFields          = 1090
	ERUpdateTableUsed              = 1093
	ERNoTablesUsed                 = 1096
	ERTooBigSet                    = 1097
	ERBlobCantHaveDefault          = 1101
	ERWrongDbName                  = 1102
	ERWrongTableName               = 1103
	ERUnknownProcedure             = 1106
	ERWrongParamCountToProcedure   = 1107
	ERWrongParametersToProcedure   = 1108
	ERFieldSpecifiedTwice          = 1110
	ERInvalidGroupFuncUse          = 1111
	ERTableMustHaveColumns         = 1113
	ERUnknownCharacterSet          = 1115
	ERTooManyTables                = 1116
	ERTooManyFields                = 1117
	ERTooBigRowSize                = 1118
	ERWrongOuterJoin               = 1120
	ERNullColumnInIndex            = 1121
	ERFunctionNotDefined           = 1128
	ERWrongValueCountOnRow         = 1136
	ERInvalidUseOfNull             = 1138
	ERRegexpError                  = 1139
	ERMixOfGroupFuncAndFields      = 1140
	ERIllegalGrantForTable         = 1144
	ERSyntaxError                  = 1149
	ERWrongColumnName              = 1166
	ERWrongKeyColumn               = 1167
	ERBlobKeyWithoutLength         = 1170
	ERPrimaryCantHaveNull          = 1171
	ERTooManyRows                  = 1172
	ERUnknownSystemVariable        = 1193
	ERSetConstantsOnly             = 1204
	ERWrongArguments               = 1210
	ERWrongUsage                   = 1221
	ERWrongNumberOfColumnsInSelect = 1222
	ERDupArgument                  = 1225
	ERLocalVariable                = 1228
	ERGlobalVariable               = 1229
	ERWrongValueForVar             = 1231
	ERWrongTypeForVar              = 1232
	ERVarCantBeRead                = 1233
	ERCantUseOptionHere            = 1234
	ERIncorrectGlobalLocalVar      = 1238
	ERWrongFKDef                   = 1239
	ERKeyRefDoNotMatchTableRef     = 1240
	ERCyclicReference              = 1245
	ERCollationCharsetMismatch     = 1253
	ERCantAggregate2Collations     = 1267
	ERCantAggregate3Collations     = 1270
	ERCantAggregateNCollations     = 1271
	ERVariableIsNotStruct          = 1272
	ERUnknownCollation             = 1273
	ERWrongNameForIndex            = 1280
	ERWrongNameForCatalog          = 1281
	ERBadFTColumn                  = 1283
	ERTruncatedWrongValue          = 1292
	ERTooMuchAutoTimestampCols     = 1293
	ERInvalidOnUpdate              = 1294
	ERUnknownTimeZone              = 1298
	ERInvalidCharacterString       = 1300
	ERIllegalReference             = 1247
	ERDerivedMustHaveAlias         = 1248
	ERTableNameNotAllowedHere      = 1250
	ERQueryInterrupted             = 1317
	ERTruncatedWrongValueForField  = 1366
	ERDataTooLong                  = 1406
	ERDataOutOfRange               = 1690
)

Error codes for server-side errors. Originally found in include/mysql/mysqld_error.h and https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html The below are in sorted order by value, grouped by vterror code they should be bucketed into. See above reference for more information on each code.

View Source
const (
	// SSUnknownSqlstate is ER_SIGNAL_EXCEPTION in
	// include/mysql/sql_state.h, but:
	// const char *unknown_sqlstate= "HY000"
	// in client.c. So using that one.
	SSUnknownSQLState = "HY000"

	// SSUnknownComError is ER_UNKNOWN_COM_ERROR
	SSUnknownComError = "08S01"

	// SSHandshakeError is ER_HANDSHAKE_ERROR
	SSHandshakeError = "08S01"

	// SSServerShutdown is ER_SERVER_SHUTDOWN
	SSServerShutdown = "08S01"

	// SSDataTooLong is ER_DATA_TOO_LONG
	SSDataTooLong = "22001"

	// SSDataOutOfRange is ER_DATA_OUT_OF_RANGE
	SSDataOutOfRange = "22003"

	// SSBadNullError is ER_BAD_NULL_ERROR
	SSBadNullError = "23000"

	// SSBadFieldError is ER_BAD_FIELD_ERROR
	SSBadFieldError = "42S22"

	// SSDupKey is ER_DUP_KEY
	SSDupKey = "23000"

	// SSCantDoThisDuringAnTransaction is
	// ER_CANT_DO_THIS_DURING_AN_TRANSACTION
	SSCantDoThisDuringAnTransaction = "25000"

	// SSAccessDeniedError is ER_ACCESS_DENIED_ERROR
	SSAccessDeniedError = "28000"

	// SSLockDeadlock is ER_LOCK_DEADLOCK
	SSLockDeadlock = "40001"
)

Sql states for errors. Originally found in include/mysql/sql_state.h

View Source
const (
	// ServerStatusAutocommit is SERVER_STATUS_AUTOCOMMIT.
	ServerStatusAutocommit = 0x0002

	// ServerMoreResultsExists is SERVER_MORE_RESULTS_EXISTS
	ServerMoreResultsExists = 0x0008
)

Status flags. They are returned by the server in a few cases. Originally found in include/mysql/mysql_com.h See http://dev.mysql.com/doc/internals/en/status-flags.html

View Source
const (
	// CharacterSetUtf8 is for UTF8. We use this by default.
	CharacterSetUtf8 = 33

	// CharacterSetBinary is for binary. Use by integer fields for instance.
	CharacterSetBinary = 63
)

A few interesting character set values. See http://dev.mysql.com/doc/internals/en/character-set.html#packet-Protocol::CharacterSet

View Source
const (
	// TypeDecimal is MYSQL_TYPE_DECIMAL. It is deprecated.
	TypeDecimal = 0

	// TypeTiny is MYSQL_TYPE_TINY
	TypeTiny = 1

	// TypeShort is MYSQL_TYPE_SHORT
	TypeShort = 2

	// TypeLong is MYSQL_TYPE_LONG
	TypeLong = 3

	// TypeFloat is MYSQL_TYPE_FLOAT
	TypeFloat = 4

	// TypeDouble is MYSQL_TYPE_DOUBLE
	TypeDouble = 5

	// TypeNull is MYSQL_TYPE_NULL
	TypeNull = 6

	// TypeTimestamp is MYSQL_TYPE_TIMESTAMP
	TypeTimestamp = 7

	// TypeLongLong is MYSQL_TYPE_LONGLONG
	TypeLongLong = 8

	// TypeInt24 is MYSQL_TYPE_INT24
	TypeInt24 = 9

	// TypeDate is MYSQL_TYPE_DATE
	TypeDate = 10

	// TypeTime is MYSQL_TYPE_TIME
	TypeTime = 11

	// TypeDateTime is MYSQL_TYPE_DATETIME
	TypeDateTime = 12

	// TypeYear is MYSQL_TYPE_YEAR
	TypeYear = 13

	// TypeNewDate is MYSQL_TYPE_NEWDATE
	TypeNewDate = 14

	// TypeVarchar is MYSQL_TYPE_VARCHAR
	TypeVarchar = 15

	// TypeBit is MYSQL_TYPE_BIT
	TypeBit = 16

	// TypeTimestamp2 is MYSQL_TYPE_TIMESTAMP2
	TypeTimestamp2 = 17

	// TypeDateTime2 is MYSQL_TYPE_DATETIME2
	TypeDateTime2 = 18

	// TypeTime2 is MYSQL_TYPE_TIME2
	TypeTime2 = 19

	// TypeJSON is MYSQL_TYPE_JSON
	TypeJSON = 245

	// TypeNewDecimal is MYSQL_TYPE_NEWDECIMAL
	TypeNewDecimal = 246

	// TypeEnum is MYSQL_TYPE_ENUM
	TypeEnum = 247

	// TypeSet is MYSQL_TYPE_SET
	TypeSet = 248

	// TypeTinyBlob is MYSQL_TYPE_TINY_BLOB
	TypeTinyBlob = 249

	// TypeMediumBlob is MYSQL_TYPE_MEDIUM_BLOB
	TypeMediumBlob = 250

	// TypeLongBlob is MYSQL_TYPE_LONG_BLOB
	TypeLongBlob = 251

	// TypeBlob is MYSQL_TYPE_BLOB
	TypeBlob = 252

	// TypeVarString is MYSQL_TYPE_VAR_STRING
	TypeVarString = 253

	// TypeString is MYSQL_TYPE_STRING
	TypeString = 254

	// TypeGeometry is MYSQL_TYPE_GEOMETRY
	TypeGeometry = 255
)

This is the data type for a field. Values taken from include/mysql/mysql_com.h

View Source
const (
	// IntVarInvalidInt is INVALID_INT_EVENT
	IntVarInvalidInt = 0

	// IntVarLastInsertID is LAST_INSERT_ID_EVENT
	IntVarLastInsertID = 1

	// IntVarInsertID is INSERT_ID_EVENT
	IntVarInsertID = 2
)

Constants for the type of an INTVAR_EVENT.

View Source
const (
	// BinlogChecksumAlgOff indicates that checksums are supported but off.
	BinlogChecksumAlgOff = 0

	// BinlogChecksumAlgCRC32 indicates that CRC32 checksums are used.
	BinlogChecksumAlgCRC32 = 1

	// BinlogChecksumAlgUndef indicates that checksums are not supported.
	BinlogChecksumAlgUndef = 255
)

Constants about the type of checksum in a packet. These constants are common between MariaDB 10.0 and MySQL 5.6.

View Source
const (
	// QFlags2Code is Q_FLAGS2_CODE
	QFlags2Code = 0

	// QSQLModeCode is Q_SQL_MODE_CODE
	QSQLModeCode = 1

	// QCatalog is Q_CATALOG
	QCatalog = 2

	// QAutoIncrement is Q_AUTO_INCREMENT
	QAutoIncrement = 3

	// QCharsetCode is Q_CHARSET_CODE
	QCharsetCode = 4

	// QTimeZoneCode is Q_TIME_ZONE_CODE
	QTimeZoneCode = 5

	// QCatalogNZCode is Q_CATALOG_NZ_CODE
	QCatalogNZCode = 6
)

These constants describe the type of status variables in q Query packet.

View Source
const BaseShowTables = "" /* 203-byte string literal not displayed */

BaseShowTables is the base query used in further methods.

View Source
const (
	// DefaultServerVersion is the default server version we're sending to the client.
	// Can be changed.
	DefaultServerVersion = "5.5.10-Vitess"
)
View Source
const (
	// ERVitessMaxRowsExceeded is when a user tries to select more rows than the max rows as enforced by vitess.
	ERVitessMaxRowsExceeded = 10001
)

Error codes return in SQLErrors generated by vitess. These error codes are in a high range to avoid conflicting with mysql error codes below.

View Source
const (
	// MaxPacketSize is the maximum payload length of a packet
	// the server supports.
	MaxPacketSize = (1 << 24) - 1
)
View Source
const (
	// MaximumPositionSize is the maximum size of a
	// replication position. It is used as the maximum column size in the _vt.reparent_journal and
	// other related tables. A row has a maximum size of 65535 bytes. So
	// we want to stay under that. We use VARBINARY so the
	// character set doesn't matter, we only store ascii
	// characters anyway.
	MaximumPositionSize = 64000
)

Variables

View Source
var BaseShowTablesFields = []*querypb.Field{
	{
		Name:         "table_name",
		Type:         querypb.Type_VARCHAR,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "TABLE_NAME",
		ColumnLength: 192,
		Charset:      CharacterSetUtf8,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "table_type",
		Type:         querypb.Type_VARCHAR,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "TABLE_TYPE",
		ColumnLength: 192,
		Charset:      CharacterSetUtf8,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "unix_timestamp(create_time)",
		Type:         querypb.Type_INT64,
		ColumnLength: 11,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_BINARY_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "table_comment",
		Type:         querypb.Type_VARCHAR,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "TABLE_COMMENT",
		ColumnLength: 6144,
		Charset:      CharacterSetUtf8,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "table_rows",
		Type:         querypb.Type_UINT64,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "TABLE_ROWS",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_UNSIGNED_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "data_length",
		Type:         querypb.Type_UINT64,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "DATA_LENGTH",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_UNSIGNED_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "index_length",
		Type:         querypb.Type_UINT64,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "INDEX_LENGTH",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_UNSIGNED_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "data_free",
		Type:         querypb.Type_UINT64,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "DATA_FREE",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_UNSIGNED_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "max_data_length",
		Type:         querypb.Type_UINT64,
		Table:        "tables",
		OrgTable:     "TABLES",
		Database:     "information_schema",
		OrgName:      "MAX_DATA_LENGTH",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_UNSIGNED_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
}

BaseShowTablesFields contains the fields returned by a BaseShowTables or a BaseShowTablesForTable command. They are validated by the testBaseShowTables test.

View Source
var CharacterSetMap = map[string]uint8{
	"big5":     1,
	"dec8":     3,
	"cp850":    4,
	"hp8":      6,
	"koi8r":    7,
	"latin1":   8,
	"latin2":   9,
	"swe7":     10,
	"ascii":    11,
	"ujis":     12,
	"sjis":     13,
	"hebrew":   16,
	"tis620":   18,
	"euckr":    19,
	"koi8u":    22,
	"gb2312":   24,
	"greek":    25,
	"cp1250":   26,
	"gbk":      28,
	"latin5":   30,
	"armscii8": 32,
	"utf8":     CharacterSetUtf8,
	"ucs2":     35,
	"cp866":    36,
	"keybcs2":  37,
	"macce":    38,
	"macroman": 39,
	"cp852":    40,
	"latin7":   41,
	"utf8mb4":  45,
	"cp1251":   51,
	"utf16":    54,
	"utf16le":  56,
	"cp1256":   57,
	"cp1257":   59,
	"utf32":    60,
	"binary":   CharacterSetBinary,
	"geostd8":  92,
	"cp932":    95,
	"eucjpms":  97,
}

CharacterSetMap maps the charset name (used in ConnParams) to the integer value. Interesting ones have their own constant above.

View Source
var DescribeTableFields = []*querypb.Field{
	{
		Name:         "Field",
		Type:         querypb.Type_VARCHAR,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "COLUMN_NAME",
		ColumnLength: 192,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Type",
		Type:         querypb.Type_TEXT,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "COLUMN_TYPE",
		ColumnLength: 589815,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG | querypb.MySqlFlag_BLOB_FLAG),
	},
	{
		Name:         "Null",
		Type:         querypb.Type_VARCHAR,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "IS_NULLABLE",
		ColumnLength: 9,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Key",
		Type:         querypb.Type_VARCHAR,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "COLUMN_KEY",
		ColumnLength: 9,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Default",
		Type:         querypb.Type_TEXT,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "COLUMN_DEFAULT",
		ColumnLength: 589815,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_BLOB_FLAG),
	},
	{
		Name:         "Extra",
		Type:         querypb.Type_VARCHAR,
		Table:        "COLUMNS",
		OrgTable:     "COLUMNS",
		Database:     "information_schema",
		OrgName:      "EXTRA",
		ColumnLength: 90,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
}

DescribeTableFields contains the fields returned by a 'describe <table>' command. They are validated by the testDescribeTable test.

View Source
var (
	// ErrNotSlave means there is no slave status.
	// Returned by ShowSlaveStatus().
	ErrNotSlave = errors.New("no slave status")
)
View Source
var (
	// IntVarNames maps a InVar type to the variable name it represents.
	IntVarNames = map[byte]string{
		IntVarLastInsertID: "LAST_INSERT_ID",
		IntVarInsertID:     "INSERT_ID",
	}
)

Name of the variable represented by an IntVar.

View Source
var ShowIndexFromTableFields = []*querypb.Field{
	{
		Name:         "Table",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "TABLE_NAME",
		ColumnLength: 192,
		Charset:      CharacterSetUtf8,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Non_unique",
		Type:         querypb.Type_INT64,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "NON_UNIQUE",
		ColumnLength: 1,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "Key_name",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "INDEX_NAME",
		ColumnLength: 192,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Seq_in_index",
		Type:         querypb.Type_INT64,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "SEQ_IN_INDEX",
		ColumnLength: 2,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG | querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "Column_name",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "COLUMN_NAME",
		ColumnLength: 192,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Collation",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "COLLATION",
		ColumnLength: 3,
		Charset:      33,
	},
	{
		Name:         "Cardinality",
		Type:         querypb.Type_INT64,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "CARDINALITY",
		ColumnLength: 21,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "Sub_part",
		Type:         querypb.Type_INT64,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "SUB_PART",
		ColumnLength: 3,
		Charset:      CharacterSetBinary,
		Flags:        uint32(querypb.MySqlFlag_NUM_FLAG),
	},
	{
		Name:         "Packed",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "PACKED",
		ColumnLength: 30,
		Charset:      33,
	},
	{
		Name:         "Null",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "NULLABLE",
		ColumnLength: 9,
		Charset:      33,
		Flags:        1,
	},
	{
		Name:         "Index_type",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "INDEX_TYPE",
		ColumnLength: 48,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
	{
		Name:         "Comment",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "COMMENT",
		ColumnLength: 48,
		Charset:      33,
	},
	{
		Name:         "Index_comment",
		Type:         querypb.Type_VARCHAR,
		Table:        "STATISTICS",
		OrgTable:     "STATISTICS",
		Database:     "information_schema",
		OrgName:      "INDEX_COMMENT",
		ColumnLength: 3072,
		Charset:      33,
		Flags:        uint32(querypb.MySqlFlag_NOT_NULL_FLAG),
	},
}

ShowIndexFromTableFields contains the fields returned by a 'show index from <table>' command. They are validated by the testShowIndexFromTable test.

View Source
var ZeroTimestamp = []byte("0000-00-00 00:00:00")

ZeroTimestamp is the special value 0 for a timestamp.

Functions

func AuthServerNegotiateClearOrDialog

func AuthServerNegotiateClearOrDialog(c *Conn, method string) (string, error)

AuthServerNegotiateClearOrDialog will finish a negotiation based on the method type for the connection. Only supports MysqlClearPassword and MysqlDialog.

func AuthServerReadPacketString

func AuthServerReadPacketString(c *Conn) (string, error)

AuthServerReadPacketString is a helper method to read a packet as a null terminated string. It is used by the mysql_clear_password and dialog plugins.

func BaseShowTablesForTable

func BaseShowTablesForTable(table string) string

BaseShowTablesForTable specializes BaseShowTables for a single table.

func BaseShowTablesRow

func BaseShowTablesRow(tableName string, isView bool, comment string) []sqltypes.Value

BaseShowTablesRow returns the fields from a BaseShowTables or BaseShowTablesForTable command.

func CellValue

func CellValue(data []byte, pos int, typ byte, metadata uint16, styp querypb.Type) (sqltypes.Value, int, error)

CellValue returns the data for a cell as a sqltypes.Value, and how many bytes it takes. It only uses the querypb.Type value for the signed flag.

func DescribeTableRow

func DescribeTableRow(name string, typ string, null bool, key string, def string) []sqltypes.Value

DescribeTableRow returns a row for a 'describe table' command. 'name' is the name of the field. 'type' is the type of the field. Something like:

'int(11)' for 'int'
'int(10) unsigned' for 'int unsigned'
'bigint(20)' for 'bigint'
'bigint(20) unsigned' for 'bigint unsigned'
'varchar(128)'

'null' is true if the field can be NULL. 'key' is either:

  • 'PRI' if part of the primary key. If not:
  • 'UNI' if part of a unique index. If not:
  • 'MUL' if part of a non-unique index. If not:
  • empty if part of no key / index.

'def' is the default value for the field. Empty if NULL default.

func EncodeGTID

func EncodeGTID(gtid GTID) string

EncodeGTID returns a string that contains both the flavor and value of the GTID, so that the correct parser can be selected when that string is passed to DecodeGTID.

func EncodePosition

func EncodePosition(rp Position) string

EncodePosition returns a string that contains both the flavor and value of the Position, so that the correct parser can be selected when that string is passed to DecodePosition.

func ExecuteFetchMap

func ExecuteFetchMap(conn *Conn, query string) (map[string]string, error)

ExecuteFetchMap returns a map from column names to cell data for a query that should return exactly 1 row.

func GetCharset

func GetCharset(conn *Conn) (*binlogdatapb.Charset, error)

GetCharset returns the current numerical values of the per-session character set variables.

func InitAuthServerStatic

func InitAuthServerStatic()

InitAuthServerStatic Handles initializing the AuthServerStatic if necessary.

func IsConnErr

func IsConnErr(err error) bool

IsConnErr returns true if the error is a connection error.

func IsNum

func IsNum(typ uint8) bool

IsNum returns true if a MySQL type is a numeric value. It is the same as IS_NUM defined in mysql.h.

FIXME(alainjobart) This needs to use the constants in replication/constants.go, so we are using numerical values here.

func NewSQLErrorFromError

func NewSQLErrorFromError(err error) error

NewSQLErrorFromError returns a *SQLError from the provided error. If it's not the right type, it still tries to get it from a regexp.

func NewSalt

func NewSalt() ([]byte, error)

NewSalt returns a 20 character salt.

func ParseErrorPacket

func ParseErrorPacket(data []byte) error

ParseErrorPacket parses the error packet and returns a SQLError.

func RegisterAuthServerImpl

func RegisterAuthServerImpl(name string, authServer AuthServer)

RegisterAuthServerImpl registers an implementations of AuthServer.

func RegisterAuthServerStaticFromParams

func RegisterAuthServerStaticFromParams(file, str string)

RegisterAuthServerStaticFromParams creates and registers a new AuthServerStatic, loaded for a JSON file or string. If file is set, it uses file. Otherwise, load the string. It log.Exits out in case of error.

func ScramblePassword

func ScramblePassword(salt, password []byte) []byte

ScramblePassword computes the hash of the password using 4.1+ method.

func SetCharset

func SetCharset(conn *Conn, cs *binlogdatapb.Charset) error

SetCharset changes the per-session character set variables.

func ShowIndexFromTableRow

func ShowIndexFromTableRow(table string, unique bool, keyName string, seqInIndex int, columnName string, nullable bool) []sqltypes.Value

ShowIndexFromTableRow returns the fields from a 'show index from table' command. 'table' is the table name. 'unique' is true for unique indexes, false for non-unique indexes. 'keyName' is 'PRIMARY' for PKs, otherwise the name of the index. 'seqInIndex' is starting at 1 for first key in index. 'columnName' is the name of the column this index applies to. 'nullable' is true if this column can be null.

func SlaveStatusToProto

func SlaveStatusToProto(s SlaveStatus) *replicationdatapb.Status

SlaveStatusToProto translates a Status to proto3.

Types

type AuthServer

type AuthServer interface {
	// AuthMethod returns the authentication method to use for the
	// given user. If this returns MysqlNativePassword
	// (mysql_native_password), then ValidateHash() will be
	// called, and no further roundtrip with the client is
	// expected. If anything else is returned, Negotiate()
	// will be called on the connection, and the AuthServer
	// needs to handle the packets.
	AuthMethod(user string) (string, error)

	// Salt returns the salt to use for a connection.
	// It should be 20 bytes of data.
	// Most implementations should just use mysql.NewSalt().
	// (this is meant to support a plugin that would use an
	// existing MySQL server as the source of auth, and just forward
	// the salt generated by that server).
	// Do not return zero bytes, as a known salt can be the source
	// of a crypto attack.
	Salt() ([]byte, error)

	// ValidateHash validates the data sent by the client matches
	// what the server computes.  It also returns the user data.
	ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error)

	// Negotiate is called if AuthMethod returns anything else
	// than MysqlNativePassword. It is handed the connection after the
	// AuthSwitchRequest packet is sent.
	// - If the negotiation fails, it should just return an error
	// (should be a SQLError if possible).
	// The framework is responsible for writing the Error packet
	// and closing the connection in that case.
	// - If the negotiation works, it should return the Getter,
	// and no error. The framework is responsible for writing the
	// OK packet.
	Negotiate(c *Conn, user string, remoteAddr net.Addr) (Getter, error)
}

AuthServer is the interface that servers must implement to validate users and passwords. It has two modes:

1. using salt the way MySQL native auth does it. In that case, the password is not sent in the clear, but the salt is used to hash the password both on the client and server side, and the result is sent and compared.

2. sending the user / password in the clear (using MySQL Cleartext method). The server then gets access to both user and password, and can authenticate using any method. If SSL is not used, it means the password is sent in the clear. That may not be suitable for some use cases.

func GetAuthServer

func GetAuthServer(name string) AuthServer

GetAuthServer returns an AuthServer by name, or log.Exitf.

type AuthServerNone

type AuthServerNone struct{}

AuthServerNone takes all comers. It's meant to be used for testing and prototyping. With this config, you can connect to a local vtgate using the following command line: 'mysql -P port -h ::'. It only uses MysqlNativePassword method.

func (*AuthServerNone) AuthMethod

func (a *AuthServerNone) AuthMethod(user string) (string, error)

AuthMethod is part of the AuthServer interface. We always return MysqlNativePassword.

func (*AuthServerNone) Negotiate

func (a *AuthServerNone) Negotiate(c *Conn, user string, remotAddr net.Addr) (Getter, error)

Negotiate is part of the AuthServer interface. It will never be called.

func (*AuthServerNone) Salt

func (a *AuthServerNone) Salt() ([]byte, error)

Salt makes salt

func (*AuthServerNone) ValidateHash

func (a *AuthServerNone) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error)

ValidateHash validates hash

type AuthServerStatic

type AuthServerStatic struct {
	// Method can be set to:
	// - MysqlNativePassword
	// - MysqlClearPassword
	// - MysqlDialog
	// It defaults to MysqlNativePassword.
	Method string

	// Entries contains the users, passwords and user data.
	Entries map[string][]*AuthServerStaticEntry
	// contains filtered or unexported fields
}

AuthServerStatic implements AuthServer using a static configuration.

func NewAuthServerStatic

func NewAuthServerStatic() *AuthServerStatic

NewAuthServerStatic returns a new empty AuthServerStatic.

func (*AuthServerStatic) AuthMethod

func (a *AuthServerStatic) AuthMethod(user string) (string, error)

AuthMethod is part of the AuthServer interface.

func (*AuthServerStatic) Negotiate

func (a *AuthServerStatic) Negotiate(c *Conn, user string, remoteAddr net.Addr) (Getter, error)

Negotiate is part of the AuthServer interface. It will be called if Method is anything else than MysqlNativePassword. We only recognize MysqlClearPassword and MysqlDialog here.

func (*AuthServerStatic) Salt

func (a *AuthServerStatic) Salt() ([]byte, error)

Salt is part of the AuthServer interface.

func (*AuthServerStatic) ValidateHash

func (a *AuthServerStatic) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error)

ValidateHash is part of the AuthServer interface.

type AuthServerStaticEntry

type AuthServerStaticEntry struct {
	// MysqlNativePassword is generated by password hashing methods in MySQL.
	// These changes are illustrated by changes in the result from the PASSWORD() function
	// that computes password hash values and in the structure of the user table where passwords are stored.
	// mysql> SELECT PASSWORD('mypass');
	// +-------------------------------------------+
	// | PASSWORD('mypass')                        |
	// +-------------------------------------------+
	// | *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
	// +-------------------------------------------+
	// MysqlNativePassword's format looks like "*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4", it store a hashing value.
	// Use MysqlNativePassword in auth config, maybe more secure. After all, it is cryptographic storage.
	MysqlNativePassword string
	Password            string
	UserData            string
	SourceHost          string
}

AuthServerStaticEntry stores the values for a given user.

type BinlogEvent

type BinlogEvent interface {
	// IsValid returns true if the underlying data buffer contains a valid
	// event. This should be called first on any BinlogEvent, and other
	// methods should only be called if this one returns true. This ensures
	// you won't get panics due to bounds checking on the byte array.
	IsValid() bool

	// IsFormatDescription returns true if this is a
	// FORMAT_DESCRIPTION_EVENT. Do not call StripChecksum before
	// calling Format (Format returns the BinlogFormat anyway,
	// required for calling StripChecksum).
	IsFormatDescription() bool
	// IsQuery returns true if this is a QUERY_EVENT, which encompasses
	// all SQL statements.
	IsQuery() bool
	// IsXID returns true if this is an XID_EVENT, which is an alternate
	// form of COMMIT.
	IsXID() bool
	// IsGTID returns true if this is a GTID_EVENT.
	IsGTID() bool
	// IsRotate returns true if this is a ROTATE_EVENT.
	IsRotate() bool
	// IsIntVar returns true if this is an INTVAR_EVENT.
	IsIntVar() bool
	// IsRand returns true if this is a RAND_EVENT.
	IsRand() bool
	// IsPreviousGTIDs returns true if this event is a PREVIOUS_GTIDS_EVENT.
	IsPreviousGTIDs() bool

	// IsTableMapEvent returns true if this is a TABLE_MAP_EVENT.
	IsTableMap() bool
	// IsWriteRowsEvent returns true if this is a WRITE_ROWS_EVENT.
	IsWriteRows() bool
	// IsUpdateRowsEvent returns true if this is a UPDATE_ROWS_EVENT.
	IsUpdateRows() bool
	// IsDeleteRowsEvent returns true if this is a DELETE_ROWS_EVENT.
	IsDeleteRows() bool

	// Timestamp returns the timestamp from the event header.
	Timestamp() uint32

	// Format returns a BinlogFormat struct based on the event data.
	// This is only valid if IsFormatDescription() returns true.
	Format() (BinlogFormat, error)
	// GTID returns the GTID from the event, and if this event
	// also serves as a BEGIN statement.
	// This is only valid if IsGTID() returns true.
	GTID(BinlogFormat) (GTID, bool, error)
	// Query returns a Query struct representing data from a QUERY_EVENT.
	// This is only valid if IsQuery() returns true.
	Query(BinlogFormat) (Query, error)
	// IntVar returns the type and value of the variable for an INTVAR_EVENT.
	// This is only valid if IsIntVar() returns true.
	IntVar(BinlogFormat) (byte, uint64, error)
	// Rand returns the two seed values for a RAND_EVENT.
	// This is only valid if IsRand() returns true.
	Rand(BinlogFormat) (uint64, uint64, error)
	// PreviousGTIDs returns the Position from the event.
	// This is only valid if IsPreviousGTIDs() returns true.
	PreviousGTIDs(BinlogFormat) (Position, error)

	// TableID returns the table ID for a TableMap, UpdateRows,
	// WriteRows or DeleteRows event.
	TableID(BinlogFormat) uint64
	// TableMap returns a TableMap struct representing data from a
	// TABLE_MAP_EVENT.  This is only valid if IsTableMapEvent() returns
	// true.
	TableMap(BinlogFormat) (*TableMap, error)
	// Rows returns a Rows struct representing data from a
	// {WRITE,UPDATE,DELETE}_ROWS_EVENT.  This is only valid if
	// IsWriteRows(), IsUpdateRows(), or IsDeleteRows() returns
	// true.
	Rows(BinlogFormat, *TableMap) (Rows, error)

	// StripChecksum returns the checksum and a modified event with the
	// checksum stripped off, if any. If there is no checksum, it returns
	// the same event and a nil checksum.
	StripChecksum(BinlogFormat) (ev BinlogEvent, checksum []byte, err error)

	// IsPseudo is for custom implemetations of GTID.
	IsPseudo() bool
}

BinlogEvent represents a single event from a raw MySQL binlog dump stream. The implementation is provided by each supported flavor in go/vt/mysqlctl.

binlog.Streamer receives these events through a mysqlctl.SlaveConnection and processes them, grouping statements into BinlogTransactions as appropriate.

Methods that only access header fields can't fail as long as IsValid() returns true, so they have a single return value. Methods that might fail even when IsValid() is true return an error value.

Methods that require information from the initial FORMAT_DESCRIPTION_EVENT will have a BinlogFormat parameter.

A BinlogEvent should never be sent over the wire. UpdateStream service will send BinlogTransactions from these events.

func NewDeleteRowsEvent

func NewDeleteRowsEvent(f BinlogFormat, s *FakeBinlogStream, tableID uint64, rows Rows) BinlogEvent

NewDeleteRowsEvent returns an DeleteRows event. Uses v2.

func NewFormatDescriptionEvent

func NewFormatDescriptionEvent(f BinlogFormat, s *FakeBinlogStream) BinlogEvent

NewFormatDescriptionEvent creates a new FormatDescriptionEvent based on the provided BinlogFormat. It uses a mysql56BinlogEvent but could use a MariaDB one.

func NewIntVarEvent

func NewIntVarEvent(f BinlogFormat, s *FakeBinlogStream, typ byte, value uint64) BinlogEvent

NewIntVarEvent returns an IntVar event.

func NewInvalidEvent

func NewInvalidEvent() BinlogEvent

NewInvalidEvent returns an invalid event (its size is <19).

func NewInvalidFormatDescriptionEvent

func NewInvalidFormatDescriptionEvent(f BinlogFormat, s *FakeBinlogStream) BinlogEvent

NewInvalidFormatDescriptionEvent returns an invalid FormatDescriptionEvent. The binlog version is set to 3. It IsValid() though.

func NewInvalidQueryEvent

func NewInvalidQueryEvent(f BinlogFormat, s *FakeBinlogStream) BinlogEvent

NewInvalidQueryEvent returns an invalid QueryEvent. IsValid is however true. sqlPos is out of bounds.

func NewMariaDBGTIDEvent

func NewMariaDBGTIDEvent(f BinlogFormat, s *FakeBinlogStream, gtid MariadbGTID, hasBegin bool) BinlogEvent

NewMariaDBGTIDEvent returns a MariaDB specific GTID event. It ignores the Server in the gtid, instead uses the FakeBinlogStream.ServerID.

func NewMariadbBinlogEvent

func NewMariadbBinlogEvent(buf []byte) BinlogEvent

NewMariadbBinlogEvent creates a BinlogEvent instance from given byte array

func NewMysql56BinlogEvent

func NewMysql56BinlogEvent(buf []byte) BinlogEvent

NewMysql56BinlogEvent creates a BinlogEvent from given byte array

func NewQueryEvent

func NewQueryEvent(f BinlogFormat, s *FakeBinlogStream, q Query) BinlogEvent

NewQueryEvent makes up a QueryEvent based on the Query structure.

func NewRotateEvent

func NewRotateEvent(f BinlogFormat, s *FakeBinlogStream, position uint64, filename string) BinlogEvent

NewRotateEvent returns a RotateEvent. The timestmap of such an event should be zero, so we patch it in.

func NewTableMapEvent

func NewTableMapEvent(f BinlogFormat, s *FakeBinlogStream, tableID uint64, tm *TableMap) BinlogEvent

NewTableMapEvent returns a TableMap event. Only works with post_header_length=8.

func NewUpdateRowsEvent

func NewUpdateRowsEvent(f BinlogFormat, s *FakeBinlogStream, tableID uint64, rows Rows) BinlogEvent

NewUpdateRowsEvent returns an UpdateRows event. Uses v2.

func NewWriteRowsEvent

func NewWriteRowsEvent(f BinlogFormat, s *FakeBinlogStream, tableID uint64, rows Rows) BinlogEvent

NewWriteRowsEvent returns a WriteRows event. Uses v2.

func NewXIDEvent

func NewXIDEvent(f BinlogFormat, s *FakeBinlogStream) BinlogEvent

NewXIDEvent returns a XID event. We do not use the data, so keep it 0.

type BinlogFormat

type BinlogFormat struct {
	// FormatVersion is the version number of the binlog file format.
	// We only support version 4.
	FormatVersion uint16

	// ServerVersion is the name of the MySQL server version.
	// It starts with something like 5.6.33-xxxx.
	ServerVersion string

	// HeaderLength is the size in bytes of event headers other
	// than FORMAT_DESCRIPTION_EVENT. Almost always 19.
	HeaderLength byte

	// ChecksumAlgorithm is the ID number of the binlog checksum algorithm.
	// See three possible values below.
	ChecksumAlgorithm byte

	// HeaderSizes is an array of sizes of the headers for each message.
	HeaderSizes []byte
}

BinlogFormat contains relevant data from the FORMAT_DESCRIPTION_EVENT. This structure is passed to subsequent event types to let them know how to parse themselves.

func NewMariaDBBinlogFormat

func NewMariaDBBinlogFormat() BinlogFormat

NewMariaDBBinlogFormat returns a typical BinlogFormat for MariaDB 10.0.

func NewMySQL56BinlogFormat

func NewMySQL56BinlogFormat() BinlogFormat

NewMySQL56BinlogFormat returns a typical BinlogFormat for MySQL 5.6.

func (BinlogFormat) HeaderSize

func (f BinlogFormat) HeaderSize(typ byte) byte

HeaderSize returns the header size of any event type.

func (BinlogFormat) IsZero

func (f BinlogFormat) IsZero() bool

IsZero returns true if the BinlogFormat has not been initialized.

type Bitmap

type Bitmap struct {
	// contains filtered or unexported fields
}

Bitmap is used by the previous structures.

func NewServerBitmap

func NewServerBitmap(count int) Bitmap

NewServerBitmap returns a bitmap that can hold 'count' bits.

func (*Bitmap) Bit

func (b *Bitmap) Bit(index int) bool

Bit returned the value of a given bit in the Bitmap.

func (*Bitmap) BitCount

func (b *Bitmap) BitCount() int

BitCount returns how many bits are set in the bitmap. Note values that are not used may be set to 0 or 1, hence the non-efficient logic.

func (*Bitmap) Count

func (b *Bitmap) Count() int

Count returns the number of bits in this Bitmap.

func (*Bitmap) Set

func (b *Bitmap) Set(index int, value bool)

Set sets the given boolean value.

type Conn

type Conn struct {

	// ConnectionID is set:
	// - at Connect() time for clients, with the value returned by
	// the server.
	// - at accept time for the server.
	ConnectionID uint32

	// Capabilities is the current set of features this connection
	// is using.  It is the features that are both supported by
	// the client and the server, and currently in use.
	// It is set during the initial handshake.
	//
	// It is only used for CapabilityClientDeprecateEOF
	// and CapabilityClientFoundRows.
	Capabilities uint32

	// CharacterSet is the character set used by the other side of the
	// connection.
	// It is set during the initial handshake.
	// See the values in constants.go.
	CharacterSet uint8

	// User is the name used by the client to connect.
	// It is set during the initial handshake.
	User string

	// UserData is custom data returned by the AuthServer module.
	// It is set during the initial handshake.
	UserData Getter

	// SchemaName is the default database name to use. It is set
	// during handshake, and by ComInitDb packets. Both client and
	// servers maintain it.
	SchemaName string

	// ServerVersion is set during Connect with the server
	// version.  It is not changed afterwards. It is unused for
	// server-side connections.
	ServerVersion string

	// StatusFlags are the status flags we will base our returned flags on.
	// This is a bit field, with values documented in constants.go.
	// An interesting value here would be ServerStatusAutocommit.
	// It is only used by the server. These flags can be changed
	// by Handler methods.
	StatusFlags uint16

	// ClientData is a place where an application can store any
	// connection-related data. Mostly used on the server side, to
	// avoid maps indexed by ConnectionID for instance.
	ClientData interface{}
	// contains filtered or unexported fields
}

Conn is a connection between a client and a server, using the MySQL binary protocol. It is built on top of an existing net.Conn, that has already been established.

Use Connect on the client side to create a connection. Use NewListener to create a server side and listen for connections.

func Connect

func Connect(ctx context.Context, params *ConnParams) (*Conn, error)

Connect creates a connection to a server. It then handles the initial handshake.

If context is canceled before the end of the process, this function will return nil, ctx.Err().

FIXME(alainjobart) once we have more of a server side, add test cases to cover all failure scenarios.

func (*Conn) Close

func (c *Conn) Close()

Close closes the connection. It can be called from a different go routine to interrupt the current connection.

func (*Conn) CloseResult

func (c *Conn) CloseResult()

CloseResult can be used to terminate a streaming query early. It just drains the remaining values.

func (*Conn) DisableBinlogPlaybackCommand

func (c *Conn) DisableBinlogPlaybackCommand() string

DisableBinlogPlaybackCommand returns a command to run to disable binlog playback.

func (*Conn) EnableBinlogPlaybackCommand

func (c *Conn) EnableBinlogPlaybackCommand() string

EnableBinlogPlaybackCommand returns a command to run to enable binlog playback.

func (*Conn) ExecuteFetch

func (c *Conn) ExecuteFetch(query string, maxrows int, wantfields bool) (result *sqltypes.Result, err error)

ExecuteFetch executes a query and returns the result. Returns a SQLError. Depending on the transport used, the error returned might be different for the same condition:

1. if the server closes the connection when no command is in flight:

1.1 unix: WriteComQuery will fail with a 'broken pipe', and we'll
    return CRServerGone(2006).

1.2 tcp: WriteComQuery will most likely work, but readComQueryResponse
    will fail, and we'll return CRServerLost(2013).

    This is because closing a TCP socket on the server side sends
    a FIN to the client (telling the client the server is done
    writing), but on most platforms doesn't send a RST.  So the
    client has no idea it can't write. So it succeeds writing data, which
    *then* triggers the server to send a RST back, received a bit
    later. By then, the client has already started waiting for
    the response, and will just return a CRServerLost(2013).
    So CRServerGone(2006) will almost never be seen with TCP.
  1. if the server closes the connection when a command is in flight, readComQueryResponse will fail, and we'll return CRServerLost(2013).

func (*Conn) ExecuteFetchMulti

func (c *Conn) ExecuteFetchMulti(query string, maxrows int, wantfields bool) (result *sqltypes.Result, more bool, err error)

ExecuteFetchMulti is for fetching multiple results from a multi-statement result. It returns an additional 'more' flag. If it is set, you must fetch the additional results using ReadQueryResult.

func (*Conn) ExecuteFetchWithWarningCount

func (c *Conn) ExecuteFetchWithWarningCount(query string, maxrows int, wantfields bool) (result *sqltypes.Result, warnings uint16, err error)

ExecuteFetchWithWarningCount is for fetching results and a warning count Note: In a future iteration this should be abolished and merged into the ExecuteFetch API.

func (*Conn) ExecuteStreamFetch

func (c *Conn) ExecuteStreamFetch(query string) (err error)

ExecuteStreamFetch starts a streaming query. Fields(), FetchNext() and CloseResult() can be called once this is successful. Returns a SQLError.

func (*Conn) FetchNext

func (c *Conn) FetchNext() ([]sqltypes.Value, error)

FetchNext returns the next result for an ongoing streaming query. It returns (nil, nil) if there is nothing more to read.

func (*Conn) Fields

func (c *Conn) Fields() ([]*querypb.Field, error)

Fields returns the fields for an ongoing streaming query.

func (*Conn) ID

func (c *Conn) ID() int64

ID returns the MySQL connection ID for this connection.

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

IsClosed returns true if this connection was ever closed by the Close() method. Note if the other side closes the connection, but Close() wasn't called, this will return false.

func (*Conn) IsMariaDB

func (c *Conn) IsMariaDB() bool

IsMariaDB returns true iff the other side of the client connection is identified as MariaDB. Most applications should not care, but this is useful in tests.

func (*Conn) MasterPosition

func (c *Conn) MasterPosition() (Position, error)

MasterPosition returns the current master replication position.

func (*Conn) Ping

func (c *Conn) Ping() error

Ping implements mysql ping command.

func (*Conn) ReadBinlogEvent

func (c *Conn) ReadBinlogEvent() (BinlogEvent, error)

ReadBinlogEvent reads the next BinlogEvent. This must be used in conjunction with SendBinlogDumpCommand.

func (*Conn) ReadPacket

func (c *Conn) ReadPacket() ([]byte, error)

ReadPacket reads a packet from the underlying connection. it is the public API version, that returns a SQLError. The memory for the packet is always allocated, and it is owned by the caller after this function returns.

func (*Conn) ReadQueryResult

func (c *Conn) ReadQueryResult(maxrows int, wantfields bool) (result *sqltypes.Result, more bool, warnings uint16, err error)

ReadQueryResult gets the result from the last written query.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the underlying socket RemoteAddr().

func (*Conn) ResetReplicationCommands

func (c *Conn) ResetReplicationCommands() []string

ResetReplicationCommands returns the commands to completely reset replication on the host.

func (*Conn) SendBinlogDumpCommand

func (c *Conn) SendBinlogDumpCommand(slaveID uint32, startPos Position) error

SendBinlogDumpCommand sends the flavor-specific version of the COM_BINLOG_DUMP command to start dumping raw binlog events over a slave connection, starting at a given GTID.

func (*Conn) SetMasterCommand

func (c *Conn) SetMasterCommand(params *ConnParams, masterHost string, masterPort int, masterConnectRetry int) string

SetMasterCommand returns the command to use the provided master as the new master (without changing any GTID position). It is guaranteed to be called with replication stopped. It should not start or stop replication.

func (*Conn) SetSlavePositionCommands

func (c *Conn) SetSlavePositionCommands(pos Position) []string

SetSlavePositionCommands returns the commands to set the replication position at which the slave will resume when it is later reparented with SetMasterCommands.

func (*Conn) ShowSlaveStatus

func (c *Conn) ShowSlaveStatus() (SlaveStatus, error)

ShowSlaveStatus executes the right SHOW SLAVE STATUS command, and returns a parse Position with other fields.

func (*Conn) StartSlaveCommand

func (c *Conn) StartSlaveCommand() string

StartSlaveCommand returns the command to start the slave.

func (*Conn) StopSlaveCommand

func (c *Conn) StopSlaveCommand() string

StopSlaveCommand returns the command to stop the slave.

func (*Conn) String

func (c *Conn) String() string

Ident returns a useful identification string for error logging

func (*Conn) WaitUntilPositionCommand

func (c *Conn) WaitUntilPositionCommand(ctx context.Context, pos Position) (string, error)

WaitUntilPositionCommand returns the SQL command to issue to wait until the given position, until the context expires. The command returns -1 if it times out. It returns NULL if GTIDs are not enabled.

func (*Conn) WriteComBinlogDump

func (c *Conn) WriteComBinlogDump(serverID uint32, binlogFilename string, binlogPos uint32, flags uint16) error

WriteComBinlogDump writes a ComBinlogDump command. See http://dev.mysql.com/doc/internals/en/com-binlog-dump.html for syntax. Returns a SQLError.

func (*Conn) WriteComBinlogDumpGTID

func (c *Conn) WriteComBinlogDumpGTID(serverID uint32, binlogFilename string, binlogPos uint64, flags uint16, gtidSet []byte) error

WriteComBinlogDumpGTID writes a ComBinlogDumpGTID command. Only works with MySQL 5.6+ (and not MariaDB). See http://dev.mysql.com/doc/internals/en/com-binlog-dump-gtid.html for syntax.

func (*Conn) WriteComQuery

func (c *Conn) WriteComQuery(query string) error

WriteComQuery writes a query for the server to execute. Client -> Server. Returns SQLError(CRServerGone) if it can't.

type ConnParams

type ConnParams struct {
	Host       string `json:"host"`
	Port       int    `json:"port"`
	Uname      string `json:"uname"`
	Pass       string `json:"pass"`
	DbName     string `json:"dbname"`
	UnixSocket string `json:"unix_socket"`
	Charset    string `json:"charset"`
	Flags      uint64 `json:"flags"`

	// The following SSL flags are only used when flags |= 2048
	// is set (CapabilityClientSSL).
	SslCa      string `json:"ssl_ca"`
	SslCaPath  string `json:"ssl_ca_path"`
	SslCert    string `json:"ssl_cert"`
	SslKey     string `json:"ssl_key"`
	ServerName string `json:"server_name"`

	// The following is only set when the deprecated "dbname" flags are
	// supplied and will be removed.
	DeprecatedDBName string

	// The following is only set to force the client to connect without
	// using CapabilityClientDeprecateEOF
	DisableClientDeprecateEOF bool
}

ConnParams contains all the parameters to use to connect to mysql.

func (*ConnParams) EnableClientFoundRows

func (cp *ConnParams) EnableClientFoundRows()

EnableClientFoundRows sets the flag for CLIENT_FOUND_ROWS.

func (*ConnParams) EnableSSL

func (cp *ConnParams) EnableSSL()

EnableSSL will set the right flag on the parameters.

func (*ConnParams) SslEnabled

func (cp *ConnParams) SslEnabled() bool

SslEnabled returns if SSL is enabled.

type FakeBinlogStream

type FakeBinlogStream struct {
	// ServerID is the server ID of the originating mysql-server.
	ServerID uint32

	// LogPosition is an incrementing log position.
	LogPosition uint32

	// Timestamp is a uint32 of when the events occur. It is not changed.
	Timestamp uint32
}

FakeBinlogStream is used to generate consistent BinlogEvent packets for a stream. It makes sure the ServerID and log positions are reasonable.

func NewFakeBinlogStream

func NewFakeBinlogStream() *FakeBinlogStream

NewFakeBinlogStream returns a simple FakeBinlogStream.

func (*FakeBinlogStream) Packetize

func (s *FakeBinlogStream) Packetize(f BinlogFormat, typ byte, flags uint16, data []byte) []byte

Packetize adds the binlog event header to a packet, and optionally the checksum.

type GTID

type GTID interface {
	// String returns the canonical printed form of the GTID as expected by a
	// particular flavor of MySQL.
	String() string

	// Flavor returns the key under which the corresponding GTID parser function
	// is registered in the gtidParsers map.
	Flavor() string

	// SourceServer returns the ID of the server that generated the transaction.
	SourceServer() interface{}

	// SequenceNumber returns the ID number that increases with each transaction.
	// It is only valid to compare the sequence numbers of two GTIDs if they have
	// the same domain value.
	SequenceNumber() interface{}

	// SequenceDomain returns the ID of the domain within which two sequence
	// numbers can be meaningfully compared.
	SequenceDomain() interface{}

	// GTIDSet returns a GTIDSet of the same flavor as this GTID, containing only
	// this GTID.
	GTIDSet() GTIDSet
}

GTID represents a Global Transaction ID, also known as Transaction Group ID. Each flavor of MySQL has its own format for the GTID. This interface is used along with various MysqlFlavor implementations to abstract the differences.

Types that implement GTID should use a non-pointer receiver. This ensures that comparing GTID interface values with == has the expected semantics.

func DecodeGTID

func DecodeGTID(s string) (GTID, error)

DecodeGTID converts a string in the format returned by EncodeGTID back into a GTID interface value with the correct underlying flavor.

func MustDecodeGTID

func MustDecodeGTID(s string) GTID

MustDecodeGTID calls DecodeGTID and panics on error.

func MustParseGTID

func MustParseGTID(flavor, value string) GTID

MustParseGTID calls ParseGTID and panics on error.

func ParseGTID

func ParseGTID(flavor, value string) (GTID, error)

ParseGTID calls the GTID parser for the specified flavor.

type GTIDSet

type GTIDSet interface {
	// String returns the canonical printed form of the set as expected by a
	// particular flavor of MySQL.
	String() string

	// Flavor returns the key under which the corresponding parser function is
	// registered in the transactionSetParsers map.
	Flavor() string

	// ContainsGTID returns true if the set contains the specified transaction.
	ContainsGTID(GTID) bool

	// Contains returns true if the set is a superset of another set.
	Contains(GTIDSet) bool

	// Equal returns true if the set is equal to another set.
	Equal(GTIDSet) bool

	// AddGTID returns a new GTIDSet that is expanded to contain the given GTID.
	AddGTID(GTID) GTIDSet
}

GTIDSet represents the set of transactions received or applied by a server. In some flavors, a single GTID is enough to specify the set of all transactions that came before it, but in others a more complex structure is required.

GTIDSet is wrapped by replication.Position, which is a concrete struct. When sending a GTIDSet over RPCs, encode/decode it as a string. Most code outside of this package should use replication.Position rather than GTIDSet.

type Getter

type Getter interface {
	Get() *querypb.VTGateCallerID
}

A Getter has a Get()

type Handler

type Handler interface {
	// NewConnection is called when a connection is created.
	// It is not established yet. The handler can decide to
	// set StatusFlags that will be returned by the handshake methods.
	// In particular, ServerStatusAutocommit might be set.
	NewConnection(c *Conn)

	// ConnectionClosed is called when a connection is closed.
	ConnectionClosed(c *Conn)

	// ComQuery is called when a connection receives a query.
	// Note the contents of the query slice may change after
	// the first call to callback. So the Handler should not
	// hang on to the byte slice.
	ComQuery(c *Conn, query string, callback func(*sqltypes.Result) error) error

	// WarningCount is called at the end of each query to obtain
	// the value to be returned to the client in the EOF packet.
	// Note that this will be called either in the context of the
	// ComQuery callback if the result does not contain any fields,
	// or after the last ComQuery call completes.
	WarningCount(c *Conn) uint16
}

A Handler is an interface used by Listener to send queries. The implementation of this interface may store data in the ClientData field of the Connection for its own purposes.

For a given Connection, all these methods are serialized. It means only one of these methods will be called concurrently for a given Connection. So access to the Connection ClientData does not need to be protected by a mutex.

However, each connection is using one go routine, so multiple Connection objects can call these concurrently, for different Connections.

type Listener

type Listener struct {

	// ServerVersion is the version we will advertise.
	ServerVersion string

	// TLSConfig is the server TLS config. If set, we will advertise
	// that we support SSL.
	TLSConfig *tls.Config

	// AllowClearTextWithoutTLS needs to be set for the
	// mysql_clear_password authentication method to be accepted
	// by the server when TLS is not in use.
	AllowClearTextWithoutTLS bool

	// SlowConnectWarnThreshold if non-zero specifies an amount of time
	// beyond which a warning is logged to identify the slow connection
	SlowConnectWarnThreshold time.Duration

	// RequireSecureTransport configures the server to reject connections from insecure clients
	RequireSecureTransport bool
	// contains filtered or unexported fields
}

Listener is the MySQL server protocol listener.

func NewFromListener

func NewFromListener(l net.Listener, authServer AuthServer, handler Handler, connReadTimeout time.Duration, connWriteTimeout time.Duration) (*Listener, error)

NewFromListener creares a new mysql listener from an existing net.Listener

func NewListener

func NewListener(protocol, address string, authServer AuthServer, handler Handler, connReadTimeout time.Duration, connWriteTimeout time.Duration) (*Listener, error)

NewListener creates a new Listener.

func NewListenerWithConfig

func NewListenerWithConfig(cfg ListenerConfig) (*Listener, error)

NewListenerWithConfig creates new listener using provided config. There are no default values for config, so caller should ensure its correctness.

func (*Listener) Accept

func (l *Listener) Accept()

Accept runs an accept loop until the listener is closed.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the listener address.

func (*Listener) Close

func (l *Listener) Close()

Close stops the listener, which prevents accept of any new connections. Existing connections won't be closed.

func (*Listener) Shutdown

func (l *Listener) Shutdown()

Shutdown closes listener and fails any Ping requests from existing connections. This can be used for graceful shutdown, to let clients know that they should reconnect to another server.

type ListenerConfig

type ListenerConfig struct {
	// Protocol-Address pair and Listener are mutually exclusive parameters
	Protocol           string
	Address            string
	Listener           net.Listener
	AuthServer         AuthServer
	Handler            Handler
	ConnReadTimeout    time.Duration
	ConnWriteTimeout   time.Duration
	ConnReadBufferSize int
}

ListenerConfig should be used with NewListenerWithConfig to specify listener parameters.

type MariadbGTID

type MariadbGTID struct {
	// Domain is the ID number of the domain within which sequence numbers apply.
	Domain uint32
	// Server is the ID of the server that generated the transaction.
	Server uint32
	// Sequence is the sequence number of the transaction within the domain.
	Sequence uint64
}

MariadbGTID implements GTID.

func (MariadbGTID) Flavor

func (gtid MariadbGTID) Flavor() string

Flavor implements GTID.Flavor().

func (MariadbGTID) GTIDSet

func (gtid MariadbGTID) GTIDSet() GTIDSet

GTIDSet implements GTID.GTIDSet().

func (MariadbGTID) SequenceDomain

func (gtid MariadbGTID) SequenceDomain() interface{}

SequenceDomain implements GTID.SequenceDomain().

func (MariadbGTID) SequenceNumber

func (gtid MariadbGTID) SequenceNumber() interface{}

SequenceNumber implements GTID.SequenceNumber().

func (MariadbGTID) SourceServer

func (gtid MariadbGTID) SourceServer() interface{}

SourceServer implements GTID.SourceServer().

func (MariadbGTID) String

func (gtid MariadbGTID) String() string

String implements GTID.String().

type MariadbGTIDSet

type MariadbGTIDSet []MariadbGTID

MariadbGTIDSet implements GTIDSet

func (MariadbGTIDSet) AddGTID

func (gtidSet MariadbGTIDSet) AddGTID(other GTID) GTIDSet

AddGTID implements GTIDSet.AddGTID().

func (MariadbGTIDSet) Contains

func (gtidSet MariadbGTIDSet) Contains(other GTIDSet) bool

Contains implements GTIDSet.Contains().

func (MariadbGTIDSet) ContainsGTID

func (gtidSet MariadbGTIDSet) ContainsGTID(other GTID) bool

ContainsGTID implements GTIDSet.ContainsGTID().

func (MariadbGTIDSet) Equal

func (gtidSet MariadbGTIDSet) Equal(other GTIDSet) bool

Equal implements GTIDSet.Equal().

func (MariadbGTIDSet) Flavor

func (gtidSet MariadbGTIDSet) Flavor() string

Flavor implements GTIDSet.Flavor()

func (MariadbGTIDSet) String

func (gtidSet MariadbGTIDSet) String() string

String implements GTIDSet.String()

type Mysql56GTID

type Mysql56GTID struct {
	// Server is the SID of the server that originally committed the transaction.
	Server SID
	// Sequence is the sequence number of the transaction within a given Server's
	// scope.
	Sequence int64
}

Mysql56GTID implements GTID

func (Mysql56GTID) Flavor

func (gtid Mysql56GTID) Flavor() string

Flavor implements GTID.Flavor().

func (Mysql56GTID) GTIDSet

func (gtid Mysql56GTID) GTIDSet() GTIDSet

GTIDSet implements GTID.GTIDSet().

func (Mysql56GTID) SequenceDomain

func (gtid Mysql56GTID) SequenceDomain() interface{}

SequenceDomain implements GTID.SequenceDomain().

func (Mysql56GTID) SequenceNumber

func (gtid Mysql56GTID) SequenceNumber() interface{}

SequenceNumber implements GTID.SequenceNumber().

func (Mysql56GTID) SourceServer

func (gtid Mysql56GTID) SourceServer() interface{}

SourceServer implements GTID.SourceServer().

func (Mysql56GTID) String

func (gtid Mysql56GTID) String() string

String implements GTID.String().

type Mysql56GTIDSet

type Mysql56GTIDSet map[SID][]interval

Mysql56GTIDSet implements GTIDSet for MySQL 5.6.

func NewMysql56GTIDSetFromSIDBlock

func NewMysql56GTIDSetFromSIDBlock(data []byte) (Mysql56GTIDSet, error)

NewMysql56GTIDSetFromSIDBlock builds a Mysql56GTIDSet from parsing a SID Block. This is the reverse of the SIDBlock method.

Expected format:

# bytes field
8       nSIDs

(nSIDs times)

16      SID
8       nIntervals

(nIntervals times)

8       start
8       end

func (Mysql56GTIDSet) AddGTID

func (set Mysql56GTIDSet) AddGTID(gtid GTID) GTIDSet

AddGTID implements GTIDSet.

func (Mysql56GTIDSet) Contains

func (set Mysql56GTIDSet) Contains(other GTIDSet) bool

Contains implements GTIDSet.

func (Mysql56GTIDSet) ContainsGTID

func (set Mysql56GTIDSet) ContainsGTID(gtid GTID) bool

ContainsGTID implements GTIDSet.

func (Mysql56GTIDSet) Equal

func (set Mysql56GTIDSet) Equal(other GTIDSet) bool

Equal implements GTIDSet.

func (Mysql56GTIDSet) Flavor

func (Mysql56GTIDSet) Flavor() string

Flavor implements GTIDSet.

func (Mysql56GTIDSet) SIDBlock

func (set Mysql56GTIDSet) SIDBlock() []byte

SIDBlock returns the binary encoding of a MySQL 5.6 GTID set as expected by internal commands that refer to an "SID block".

e.g. https://dev.mysql.com/doc/internals/en/com-binlog-dump-gtid.html

func (Mysql56GTIDSet) SIDs

func (set Mysql56GTIDSet) SIDs() []SID

SIDs returns a sorted list of SIDs in the set.

func (Mysql56GTIDSet) String

func (set Mysql56GTIDSet) String() string

String implements GTIDSet.

type NoneGetter

type NoneGetter struct{}

NoneGetter holds the empty string

func (*NoneGetter) Get

func (ng *NoneGetter) Get() *querypb.VTGateCallerID

Get returns the empty string

type Position

type Position struct {

	// GTIDSet is the underlying GTID set. It must not be anonymous,
	// or else Position would itself also implement the GTIDSet interface.
	GTIDSet GTIDSet
	// contains filtered or unexported fields
}

Position represents the information necessary to describe which transactions a server has seen, so that it can request a replication stream from a new master that picks up where it left off.

This must be a concrete struct because custom Unmarshalers can't be registered on an interface.

The == operator should not be used with Position, because the underlying GTIDSet might use slices, which are not comparable. Using == in those cases will result in a run-time panic.

func AppendGTID

func AppendGTID(rp Position, gtid GTID) Position

AppendGTID returns a new Position that represents the position after the given GTID is replicated.

func DecodePosition

func DecodePosition(s string) (rp Position, err error)

DecodePosition converts a string in the format returned by EncodePosition back into a Position value with the correct underlying flavor.

func MustParsePosition

func MustParsePosition(flavor, value string) Position

MustParsePosition calls ParsePosition and panics on error.

func ParsePosition

func ParsePosition(flavor, value string) (rp Position, err error)

ParsePosition calls the parser for the specified flavor.

func (Position) AtLeast

func (rp Position) AtLeast(other Position) bool

AtLeast returns true if this position is equal to or after another.

func (Position) Equal

func (rp Position) Equal(other Position) bool

Equal returns true if this position is equal to another.

func (Position) IsZero

func (rp Position) IsZero() bool

IsZero returns true if this is the zero value, Position{}.

func (Position) MarshalJSON

func (rp Position) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (Position) String

func (rp Position) String() string

String returns a string representation of the underlying GTIDSet. If the set is nil, it returns "<nil>" in the style of Sprintf("%v", nil).

func (*Position) UnmarshalJSON

func (rp *Position) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler.

type Query

type Query struct {
	Database string
	Charset  *binlogdatapb.Charset
	SQL      string
}

Query contains data from a QUERY_EVENT.

func (Query) String

func (q Query) String() string

String pretty-prints a Query.

type Row

type Row struct {
	// NullIdentifyColumns describes which of the identify columns are NULL.
	// It is only set for UPDATE and DELETE events.
	NullIdentifyColumns Bitmap

	// NullColumns describes which of the present columns are NULL.
	// It is only set for WRITE and UPDATE events.
	NullColumns Bitmap

	// Identify is the raw data for the columns used to identify a row.
	// It is only set for UPDATE and DELETE events.
	Identify []byte

	// Data is the raw data.
	// It is only set for WRITE and UPDATE events.
	Data []byte
}

Row contains data for a single Row in a Rows event.

type Rows

type Rows struct {
	// Flags has the flags from the event.
	Flags uint16

	// IdentifyColumns describes which columns are included to
	// identify the row. It is a bitmap indexed by the TableMap
	// list of columns.
	// Set for UPDATE and DELETE.
	IdentifyColumns Bitmap

	// DataColumns describes which columns are included. It is
	// a bitmap indexed by the TableMap list of columns.
	// Set for WRITE and UPDATE.
	DataColumns Bitmap

	// Rows is an array of Row in the event.
	Rows []Row
}

Rows contains data from a {WRITE,UPDATE,DELETE}_ROWS_EVENT.

func (*Rows) StringIdentifiesForTests

func (rs *Rows) StringIdentifiesForTests(tm *TableMap, rowIndex int) ([]string, error)

StringIdentifiesForTests is a helper method to return the string identify of all columns in a row in a Row. Only use it in tests, as the returned values cannot be interpreted correctly without the schema. We assume everything is unsigned in this method.

func (*Rows) StringValuesForTests

func (rs *Rows) StringValuesForTests(tm *TableMap, rowIndex int) ([]string, error)

StringValuesForTests is a helper method to return the string value of all columns in a row in a Row. Only use it in tests, as the returned values cannot be interpreted correctly without the schema. We assume everything is unsigned in this method.

type SID

type SID [16]byte

SID is the 16-byte unique ID of a MySQL 5.6 server.

func ParseSID

func ParseSID(s string) (sid SID, err error)

ParseSID parses an SID in the form used by MySQL 5.6.

func (SID) String

func (sid SID) String() string

String prints an SID in the form used by MySQL 5.6.

type SQLError

type SQLError struct {
	Num     int
	State   string
	Message string
	Query   string
}

SQLError is the error structure returned from calling a db library function

func NewSQLError

func NewSQLError(number int, sqlState string, format string, args ...interface{}) *SQLError

NewSQLError creates a new SQLError. If sqlState is left empty, it will default to "HY000" (general error).

func (*SQLError) Error

func (se *SQLError) Error() string

Error implements the error interface

func (*SQLError) Number

func (se *SQLError) Number() int

Number returns the internal MySQL error code.

func (*SQLError) SQLState

func (se *SQLError) SQLState() string

SQLState returns the SQLSTATE value.

type SlaveStatus

type SlaveStatus struct {
	Position            Position
	SlaveIORunning      bool
	SlaveSQLRunning     bool
	SecondsBehindMaster uint
	MasterHost          string
	MasterPort          int
	MasterConnectRetry  int
}

SlaveStatus holds replication information from SHOW SLAVE STATUS.

func ProtoToSlaveStatus

func ProtoToSlaveStatus(s *replicationdatapb.Status) SlaveStatus

ProtoToSlaveStatus translates a proto Status, or panics.

func (*SlaveStatus) SlaveRunning

func (s *SlaveStatus) SlaveRunning() bool

SlaveRunning returns true iff both the Slave IO and Slave SQL threads are running.

type StaticUserData

type StaticUserData struct {
	// contains filtered or unexported fields
}

StaticUserData holds the username

func (*StaticUserData) Get

Get returns the wrapped username

type TableMap

type TableMap struct {
	// Flags is the table's flags.
	Flags uint16

	// Database is the database name.
	Database string

	// Name is the name of the table.
	Name string

	// Types is an array of MySQL types for the fields.
	Types []byte

	// CanBeNull's bits are set if the column can be NULL.
	CanBeNull Bitmap

	// Metadata is an array of uint16, one per column.
	// It contains a few extra information about each column,
	// that is dependent on the type.
	// - If the metadata is not present, this is zero.
	// - If the metadata is one byte, only the lower 8 bits are used.
	// - If the metadata is two bytes, all 16 bits are used.
	Metadata []uint16
}

TableMap contains data from a TABLE_MAP_EVENT.

Directories

Path Synopsis
Package endtoend is a test-only package.
Package endtoend is a test-only package.
Package fakesqldb provides a MySQL server for tests.
Package fakesqldb provides a MySQL server for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL