mysql

package
v0.10.5 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2022 License: Apache-2.0 Imports: 53 Imported by: 56

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"

	// CachingSha2Password uses a salt and transmits a SHA256 hash on the wire.
	CachingSha2Password = "caching_sha2_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

	// CLIENT_SESSION_TRACK 1 << 23
	// Can set ServerSessionStateChanged in the Status Flags
	// and send session-state change data after a OK packet.
	// Not yet supported.
	CapabilityClientSessionTrack = 1 << 23

	// 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 (
	// a transaction is active
	ServerStatusInTrans   uint16 = 0x0001
	NoServerStatusInTrans uint16 = 0xFFFE

	// auto-commit is enabled
	ServerStatusAutocommit   uint16 = 0x0002
	NoServerStatusAutocommit uint16 = 0xFFFD

	ServerMoreResultsExists     uint16 = 0x0008
	ServerStatusNoGoodIndexUsed uint16 = 0x0010
	ServerStatusNoIndexUsed     uint16 = 0x0020
	// Used by Binary Protocol Resultset to signal that COM_STMT_FETCH must be used to fetch the row-data.
	ServerStatusCursorExists       uint16 = 0x0040
	ServerStatusLastRowSent        uint16 = 0x0080
	ServerStatusDbDropped          uint16 = 0x0100
	ServerStatusNoBackslashEscapes uint16 = 0x0200
	ServerStatusMetadataChanged    uint16 = 0x0400
	ServerQueryWasSlow             uint16 = 0x0800
	ServerPsOutParams              uint16 = 0x1000
	// in a read-only transaction
	ServerStatusInTransReadonly uint16 = 0x2000
	// connection state information has changed
	ServerSessionStateChanged uint16 = 0x4000
)

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 (
	// one or more system variables changed.
	SessionTrackSystemVariables uint8 = 0x00
	// schema changed.
	SessionTrackSchema uint8 = 0x01
	// "track state change" changed.
	SessionTrackStateChange uint8 = 0x02
	// "track GTIDs" changed.
	SessionTrackGtids uint8 = 0x03
)

State Change Information

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

	// ComPrepare is COM_PREPARE.
	ComPrepare = 0x16

	// ComStmtExecute is COM_STMT_EXECUTE.
	ComStmtExecute = 0x17

	// ComStmtSendLongData is COM_STMT_SEND_LONG_DATA
	ComStmtSendLongData = 0x18

	// ComStmtClose is COM_STMT_CLOSE.
	ComStmtClose = 0x19

	// ComStmtReset is COM_STMT_RESET
	ComStmtReset = 0x1a

	//ComStmtFetch is COM_STMT_FETCH
	ComStmtFetch = 0x1c

	// ComSetOption is COM_SET_OPTION
	ComSetOption = 0x1b

	// ComResetConnection is COM_RESET_CONNECTION
	ComResetConnection = 0x1f

	// 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

	// 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 (
	// AuthMoreDataPacket is sent when server requires more data to authenticate
	AuthMoreDataPacket = 0x01

	// CachingSha2FastAuth is sent before OKPacket when server authenticates using cache
	CachingSha2FastAuth = 0x03

	// CachingSha2FullAuth is sent when server requests un-scrambled password to authenticate
	CachingSha2FullAuth = 0x04

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

Auth packet types

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

	// internal
	ERInternalError = 1815

	// unimplemented
	ERNotSupportedYet = 1235
	ERUnsupportedPS   = 1295

	// 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
	ERCantFindFile          = 1017
	ERFormNotFound          = 1029
	ERKeyNotFound           = 1032
	ERBadFieldError         = 1054
	ERNoSuchThread          = 1094
	ERUnknownTable          = 1109
	ERCantFindUDF           = 1122
	ERNonExistingGrant      = 1141
	ERNoSuchTable           = 1146
	ERNonExistingTableGrant = 1147
	ERKeyDoesNotExist       = 1176
	ERDbDropExists          = 1008

	// 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
	ERWarnDataOutOfRange            = 1264
	ERNonUpdateableTable            = 1288
	ERFeatureDisabled               = 1289
	EROptionPreventsStatement       = 1290
	ERDuplicatedValueInType         = 1291
	ERSPDoesNotExist                = 1305
	ERRowIsReferenced2              = 1451
	ErNoReferencedRow2              = 1452
	ErSPNotVarArg                   = 1414
	ERInnodbReadOnly                = 1874

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

	// 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
	ERLockOrActiveTransaction      = 1192
	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
	ERForbidSchemaChange           = 1450
	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"

	// SSNetError is network related error
	SSNetError = "08S01"

	// SSWrongNumberOfColumns is related to columns error
	SSWrongNumberOfColumns = "21000"

	// SSDataTooLong is ER_DATA_TOO_LONG
	SSDataTooLong = "22001"

	// SSDataOutOfRange is ER_DATA_OUT_OF_RANGE
	SSDataOutOfRange = "22003"

	// SSConstraintViolation is constraint violation
	SSConstraintViolation = "23000"

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

	// SSAccessDeniedError is ER_ACCESS_DENIED_ERROR
	SSAccessDeniedError = "28000"

	// SSNoDB is ER_NO_DB_ERROR
	SSNoDB = "3D000"

	// SSLockDeadlock is ER_LOCK_DEADLOCK
	SSLockDeadlock = "40001"

	//SSClientError is the state on client errors
	SSClientError = "42000"

	// SSBadFieldError is ER_BAD_FIELD_ERROR
	SSBadFieldError = "42S22"

	// SSUnknownTable is ER_UNKNOWN_TABLE
	SSUnknownTable = "42S02"

	// SSQueryInterrupted is ER_QUERY_INTERRUPTED;
	SSQueryInterrupted = "70100"
)

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

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 (
	// BaseShowPrimary is the base query for fetching primary key info.
	BaseShowPrimary = "" /* 169-byte string literal not displayed */
	// ShowRowsRead is the query used to find the number of rows read.
	ShowRowsRead = "show status like 'Innodb_rows_read'"
)

CapabilityFlags are client capability flag sent to mysql on connect

View Source
const CapabilityFlagsSsl = CapabilityFlags |
	CapabilityClientSSL

CapabilityFlagsSsl signals that we can handle SSL as well

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 FilePosFlavorID = "FilePos"

FilePosFlavorID is the string identifier for the filePos flavor.

View Source
const MariadbFlavorID = "MariaDB"

MariadbFlavorID is the string identifier for the MariaDB flavor.

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
)
View Source
const Mysql56FlavorID = "MySQL56"

Mysql56FlavorID is the string identifier for the Mysql56 flavor.

View Source
const TablesWithSize56 = `` /* 227-byte string literal not displayed */

TablesWithSize56 is a query to select table along with size for mysql 5.6

View Source
const TablesWithSize57 = `` /* 709-byte string literal not displayed */

TablesWithSize57 is a query to select table along with size for mysql 5.7. It's a little weird, because the JOIN predicate only works if the table and databases do not contain weird characters. As a fallback, we use the mysql 5.6 query, which is not always up to date, but works for all table/db names.

View Source
const TablesWithSize80 = `` /* 279-byte string literal not displayed */

TablesWithSize80 is a query to select table along with size for mysql 8.0

Variables

View Source
var (
	// ErrNotReplica means there is no replication status.
	// Returned by ShowReplicationStatus().
	ErrNotReplica = errors.New("no replication status")

	// ErrNoMasterStatus means no status was returned by ShowMasterStatus().
	ErrNoMasterStatus = errors.New("no master status")
)
View Source
var BaseShowTablesFields = []*querypb.Field{{
	Name:         "t.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:         "t.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(t.create_time)",
	Type:         querypb.Type_INT64,
	ColumnLength: 11,
	Charset:      CharacterSetBinary,
	Flags:        uint32(querypb.MySqlFlag_BINARY_FLAG | querypb.MySqlFlag_NUM_FLAG),
}, {
	Name:         "t.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:         "i.file_size",
	Type:         querypb.Type_INT64,
	ColumnLength: 11,
	Charset:      CharacterSetBinary,
	Flags:        uint32(querypb.MySqlFlag_BINARY_FLAG | querypb.MySqlFlag_NUM_FLAG),
}, {
	Name:         "i.allocated_size",
	Type:         querypb.Type_INT64,
	ColumnLength: 11,
	Charset:      CharacterSetBinary,
	Flags:        uint32(querypb.MySqlFlag_BINARY_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 (
	// 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 ShowPrimaryFields = []*querypb.Field{{
	Name: "table_name",
	Type: sqltypes.VarChar,
}, {
	Name: "column_name",
	Type: sqltypes.VarChar,
}}

ShowPrimaryFields contains the fields for a BaseShowPrimary.

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

ZeroTimestamp is the special value 0 for a timestamp.

Functions

func AllPositionsComparable

func AllPositionsComparable(positions []Position) bool

AllPositionsComparable returns true if all positions in the supplied list are comparable with one another, and false if any are non-comparable.

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 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 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 EncryptPasswordWithPublicKey added in v0.10.0

func EncryptPasswordWithPublicKey(salt []byte, password []byte, pub *rsa.PublicKey) ([]byte, error)

EncryptPasswordWithPublicKey obfuscates the password and encrypts it with server's public key as required by caching_sha2_password plugin for "full" authentication

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 FuzzHandleNextCommand added in v0.10.0

func FuzzHandleNextCommand(data []byte) int

func FuzzReadQueryResults added in v0.10.0

func FuzzReadQueryResults(data []byte) int

func FuzzTLSServer added in v0.10.0

func FuzzTLSServer(data []byte) int

func FuzzWritePacket added in v0.10.0

func FuzzWritePacket(data []byte) int

Fuzzers begin here:

func GetCharset

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

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

func InitAuthServerClientCert

func InitAuthServerClientCert()

Init is public so it can be called from plugin_auth_clientcert.go (go/cmd/vtgate)

func InitAuthServerStatic

func InitAuthServerStatic()

InitAuthServerStatic Handles initializing the AuthServerStatic if necessary.

func InitAuthServerVault added in v0.9.0

func InitAuthServerVault()

InitAuthServerVault - entrypoint for initialization of Vault AuthServer implementation

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.

func IsSchemaApplyError added in v0.8.0

func IsSchemaApplyError(err error) bool

IsSchemaApplyError returns true when given error is a MySQL error applying schema change

func IsTooManyConnectionsErr added in v0.9.0

func IsTooManyConnectionsErr(err error) bool

IsTooManyConnectionsErr returns true if the error is due to too many connections.

func MasterStatusToProto

func MasterStatusToProto(s MasterStatus) *replicationdatapb.MasterStatus

MasterStatusToProto translates a MasterStatus to proto3.

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, jsonConfig string, reloadInterval time.Duration)

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 ReplicationStatusToProto

func ReplicationStatusToProto(s ReplicationStatus) *replicationdatapb.Status

ReplicationStatusToProto translates a Status to proto3.

func ScrambleCachingSha2Password added in v0.10.0

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

ScrambleCachingSha2Password computes the hash of the password using SHA256 as required by caching_sha2_password plugin for "fast" authentication

func ScrambleMysqlNativePassword added in v0.10.0

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

ScrambleMysqlNativePassword 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 ShowPrimaryRow

func ShowPrimaryRow(tableName, colName string) []sqltypes.Value

ShowPrimaryRow returns a row for a primary key column.

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 AuthServerClientCert

type AuthServerClientCert struct {
	Method string
}

func (*AuthServerClientCert) AuthMethod

func (ascc *AuthServerClientCert) AuthMethod(user string) (string, error)

AuthMethod is part of the AuthServer interface.

func (*AuthServerClientCert) Negotiate

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

Negotiate is part of the AuthServer interface.

func (*AuthServerClientCert) Salt

func (ascc *AuthServerClientCert) Salt() ([]byte, error)

Salt is not used for this plugin.

func (*AuthServerClientCert) ValidateHash

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

ValidateHash is unimplemented.

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 {
	// contains filtered or unexported fields
}

AuthServerStatic implements AuthServer using a static configuration.

func NewAuthServerStatic

func NewAuthServerStatic(file, jsonConfig string, reloadInterval time.Duration) *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
	Groups              []string
}

AuthServerStaticEntry stores the values for a given user.

type AuthServerVault added in v0.9.0

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

AuthServerVault implements AuthServer with a config loaded from Vault.

func (*AuthServerVault) AuthMethod added in v0.9.0

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

AuthMethod is part of the AuthServer interface.

func (*AuthServerVault) Negotiate added in v0.9.0

func (a *AuthServerVault) 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 (*AuthServerVault) Salt added in v0.9.0

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

Salt is part of the AuthServer interface.

func (*AuthServerVault) ValidateHash added in v0.9.0

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

ValidateHash is part of the AuthServer interface.

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

	// IsTableMap returns true if this is a TABLE_MAP_EVENT.
	IsTableMap() bool
	// IsWriteRows returns true if this is a WRITE_ROWS_EVENT.
	IsWriteRows() bool
	// IsUpdateRows returns true if this is a UPDATE_ROWS_EVENT.
	IsUpdateRows() bool
	// IsDeleteRows 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 implementations of GTID.
	IsPseudo() bool

	// IsCompressed returns true if a compressed event is found (binlog_transaction_compression=ON)
	IsCompressed() 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.BinlogConnection 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 timestamp 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 {
	// HeaderSizes is an array of sizes of the headers for each message.
	HeaderSizes []byte

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

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

	// 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
}

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 BinlogJSON added in v0.9.0

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

BinlogJSON contains the plugins for all json types and methods for parsing the binary json representation from the binlog

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 {

	// 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{}

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

	// User is the name used by the client to connect.
	// It is set during the initial handshake.
	User string // For server-side connections, listener points to the server object.

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

	// PrepareData is the map to use a prepared statement.
	PrepareData map[uint32]*PrepareData

	// 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

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

	// StatementID is the prepared statement ID.
	StatementID uint32

	// 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

	// 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
	// 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) BaseShowTables added in v0.10.0

func (c *Conn) BaseShowTables() string

BaseShowTables returns a query that shows tables and their sizes

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) GetTLSClientCerts

func (c *Conn) GetTLSClientCerts() []*x509.Certificate

GetTLSClientCerts gets TLS certificates.

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) MasterFilePosition

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

MasterFilePosition returns the current master's file based replication position.

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) (*sqltypes.Result, bool, uint16, 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) RestartReplicationCommands

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

RestartReplicationCommands returns the commands to stop, reset and start the replication.

func (*Conn) SemiSyncExtensionLoaded

func (c *Conn) SemiSyncExtensionLoaded() bool

SemiSyncExtensionLoaded checks if the semisync extension has been loaded. It should work for both MariaDB and MySQL.

func (*Conn) SendBinlogDumpCommand

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

SendBinlogDumpCommand sends the flavor-specific version of the COM_BINLOG_DUMP command to start dumping raw binlog events over a server 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) SetReplicationPositionCommands

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

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

func (*Conn) ShowMasterStatus

func (c *Conn) ShowMasterStatus() (MasterStatus, error)

ShowMasterStatus executes the right SHOW MASTER STATUS command, and returns a parsed executed Position, as well as file based Position.

func (*Conn) ShowReplicationStatus

func (c *Conn) ShowReplicationStatus() (ReplicationStatus, error)

ShowReplicationStatus executes the right command to fetch replication status, and returns a parsed Position with other fields.

func (*Conn) StartReplicationCommand

func (c *Conn) StartReplicationCommand() string

StartReplicationCommand returns the command to start the replication.

func (*Conn) StartReplicationUntilAfterCommand

func (c *Conn) StartReplicationUntilAfterCommand(pos Position) string

StartReplicationUntilAfterCommand returns the command to start the replication.

func (*Conn) StopIOThreadCommand

func (c *Conn) StopIOThreadCommand() string

StopIOThreadCommand returns the command to stop the replica's io thread.

func (*Conn) StopReplicationCommand

func (c *Conn) StopReplicationCommand() string

StopReplicationCommand returns the command to stop the replication.

func (*Conn) String

func (c *Conn) String() string

Ident returns a useful identification string for error logging

func (*Conn) WaitUntilFilePositionCommand

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

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

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"`
	Flavor     string `json:"flavor,omitempty"`

	// 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"`
	ConnectTimeoutMs uint64 `json:"connect_timeout_ms"`

	// 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. All implementations should return false if
	// other GTIDSet is not the right concrete type for that flavor.
	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

	// Union returns a union of the receiver GTIDSet and the supplied GTIDSet.
	Union(GTIDSet) GTIDSet

	// Union returns a union of the receiver GTIDSet and the supplied GTIDSet.
	Last() string
}

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.

func ParseFilePosGTIDSet added in v0.8.0

func ParseFilePosGTIDSet(s string) (GTIDSet, error)

ParseFilePosGTIDSet is registered as a GTIDSet parser.

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

	// ComPrepare is called when a connection receives a prepared
	// statement query.
	ComPrepare(c *Conn, query string, bindVars map[string]*querypb.BindVariable) ([]*querypb.Field, error)

	// ComStmtExecute is called when a connection receives a statement
	// execute query.
	ComStmtExecute(c *Conn, prepare *PrepareData, 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

	ComResetConnection(c *Conn)
}

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.
	// atomic value stores *tls.Config
	TLSConfig atomic.Value

	// 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 sync2.AtomicBool

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

	// RequireSecureTransport configures the server to reject connections from insecure clients
	RequireSecureTransport bool

	// PreHandleFunc is called for each incoming connection, immediately after
	// accepting a new connection. By default it's no-op. Useful for custom
	// connection inspection or TLS termination. The returned connection is
	// handled further by the MySQL handler. An non-nil error will stop
	// processing the connection by the MySQL handler.
	PreHandleFunc func(context.Context, net.Conn, uint32) (net.Conn, error)
	// 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, proxyProtocol bool) (*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 map[uint32]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) Last

func (gtidSet MariadbGTIDSet) Last() string

Last returns the last gtid

func (MariadbGTIDSet) String

func (gtidSet MariadbGTIDSet) String() string

String implements GTIDSet.String()

func (MariadbGTIDSet) Union

func (gtidSet MariadbGTIDSet) Union(other GTIDSet) GTIDSet

Union implements GTIDSet.Union(). This is a pure method, and does not mutate the receiver.

type MasterStatus

type MasterStatus struct {
	// Position represents the master's GTID based position.
	Position Position
	// FilePosition represents the master's file based position.
	FilePosition Position
}

MasterStatus holds replication information from SHOW MASTER STATUS.

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) Difference

func (set Mysql56GTIDSet) Difference(other Mysql56GTIDSet) Mysql56GTIDSet

Difference will supply the difference between the receiver and supplied Mysql56GTIDSets, and supply the result as a Mysql56GTIDSet.

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) Last

func (set Mysql56GTIDSet) Last() string

Last returns the last gtid as string For gtidset having multiple SIDs or multiple intervals it just returns the last SID with last interval

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.

func (Mysql56GTIDSet) Union

func (set Mysql56GTIDSet) Union(other GTIDSet) GTIDSet

Union implements GTIDSet.Union().

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 PacketComStmtPrepareOK added in v0.9.0

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

PacketComStmtPrepareOK contains the COM_STMT_PREPARE_OK packet details

type PacketOK added in v0.9.0

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

PacketOK contains the ok packet details

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) Comparable

func (rp *Position) Comparable(other Position) bool

Comparable returns whether the receiver is comparable to the supplied position, based on whether one of the two positions contains the other.

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) MatchesFlavor

func (rp *Position) MatchesFlavor(flavor string) bool

MatchesFlavor will take a flavor string, and return whether the positions GTIDSet matches the supplied flavor. The caller should use the constants Mysql56FlavorID, MariadbFlavorID, or FilePosFlavorID when supplying the flavor string.

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 PrepareData

type PrepareData struct {
	ParamsType  []int32
	ColumnNames []string
	PrepareStmt string
	BindVars    map[string]*querypb.BindVariable
	StatementID uint32
	ParamsCount uint16
}

PrepareData is a buffer used for store prepare statement meta data

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 ReplicationStatus

type ReplicationStatus struct {
	Position Position
	// RelayLogPosition is the Position that the replica would be at if it
	// were to finish executing everything that's currently in its relay log.
	// However, some MySQL flavors don't expose this information,
	// in which case RelayLogPosition.IsZero() will be true.
	RelayLogPosition     Position
	FilePosition         Position
	FileRelayLogPosition Position
	MasterServerID       uint
	IOThreadRunning      bool
	SQLThreadRunning     bool
	SecondsBehindMaster  uint
	MasterHost           string
	MasterPort           int
	MasterConnectRetry   int
	MasterUUID           SID
}

ReplicationStatus holds replication information from SHOW SLAVE STATUS.

func ProtoToReplicationStatus

func ProtoToReplicationStatus(s *replicationdatapb.Status) ReplicationStatus

ProtoToReplicationStatus translates a proto Status, or panics.

func (*ReplicationStatus) FindErrantGTIDs

func (s *ReplicationStatus) FindErrantGTIDs(otherReplicaStatuses []*ReplicationStatus) (Mysql56GTIDSet, error)

FindErrantGTIDs can be used to find errant GTIDs in the receiver's relay log, by comparing it against all known replicas, provided as a list of ReplicationStatus's. This method only works if the flavor for all retrieved ReplicationStatus's is MySQL. The result is returned as a Mysql56GTIDSet, each of whose elements is a found errant GTID.

func (*ReplicationStatus) ReplicationRunning

func (s *ReplicationStatus) ReplicationRunning() bool

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

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). TODO: Should be aligned with vterrors, stack traces and wrapping

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 StaticUserData

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

StaticUserData holds the username and groups

func (*StaticUserData) Get

Get returns the wrapped username and groups

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