mysqlconn

package
Version: v2.1.1+incompatible Latest Latest
Warning

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

Go to latest
Published: May 22, 2017 License: BSD-3-Clause Imports: 22 Imported by: 0

Documentation

Overview

Package mysqlconn is a library to support MySQL binary protocol, both client and server sides.

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

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

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

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

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

View Source
const (
	// ERAccessDeniedError is ER_ACCESS_DENIED_ERROR
	ERAccessDeniedError = 1045

	// ERUnknownComError is ER_UNKNOWN_COM_ERROR
	ERUnknownComError = 1047

	// ERBadNullError is ER_BAD_NULL_ERROR
	ERBadNullError = 1048

	// ERServerShutdown is ER_SERVER_SHUTDOWN
	ERServerShutdown = 1053

	// ERDupEntry is ER_DUP_ENTRY
	ERDupEntry = 1062

	// ERUnknownError is ER_UNKNOWN_ERROR
	ERUnknownError = 1105

	// ERCantDoThisDuringAnTransaction is
	// ER_CANT_DO_THIS_DURING_AN_TRANSACTION
	ERCantDoThisDuringAnTransaction = 1179

	// ERLockWaitTimeout is ER_LOCK_WAIT_TIMEOUT
	ERLockWaitTimeout = 1205

	// ERLockDeadlock is ER_LOCK_DEADLOCK
	ERLockDeadlock = 1213

	// EROptionPreventsStatement is ER_OPTION_PREVENTS_STATEMENT
	EROptionPreventsStatement = 1290

	// ERDataTooLong is ER_DATA_TOO_LONG
	ERDataTooLong = 1406

	// ERDataOutOfRange is ER_DATA_OUT_OF_RANGE
	ERDataOutOfRange = 1690
)

Error codes for server-side errors. Originally found in include/mysql/mysqld_error.h

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"

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

	// 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 (
	// 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 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 (
	// MaxPacketSize is the maximum payload length of a packet
	// the server supports.
	MaxPacketSize = (1 << 24) - 1
)
View Source
const (
	// ServerStatusAutocommit is SERVER_STATUS_AUTOCOMMIT.
	ServerStatusAutocommit = 0x0002
)

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

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

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

func NewSalt() ([]byte, error)

NewSalt returns a 20 character salt.

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.Fatals out in case of error.

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.

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 mysqlconn.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) (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 sqldb.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) (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.Fatalf.

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) (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) (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
}

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) (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) (Getter, error)

ValidateHash is part of the AuthServer interface.

type AuthServerStaticEntry

type AuthServerStaticEntry struct {
	Password string
	UserData string
}

AuthServerStaticEntry stores the values for a given user.

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.
	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 *sqldb.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 is part of the sqldb.Conn interface. Just drain the remaining values.

func (*Conn) ExecuteFetch

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

ExecuteFetch is the same as sqldb.Conn.ExecuteFetch. Returns a sqldb.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.

2. if the server closes the connection when a command is in flight,

readComQueryResponse will fail, and we'll return CRServerLost(2013).

func (*Conn) ExecuteStreamFetch

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

ExecuteStreamFetch is part of the sqldb.Conn interface. Returns a sqldb.SQLError.

func (*Conn) FetchNext

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

FetchNext is part of the sqldb.Conn interface.

func (*Conn) Fields

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

Fields is part of the sqldb.Conn interface.

func (*Conn) ID

func (c *Conn) ID() int64

ID is part of the sqldb.Conn interface.

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

IsClosed is part of the sqldb.Conn interface.

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 sqldb.SQLError. The memory for the packet is always allocated, and it is owned by the caller after this function returns.

func (*Conn) RemoteAddr

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

RemoteAddr returns the underlying socket RemoteAddr().

func (*Conn) Shutdown

func (c *Conn) Shutdown()

Shutdown is part of the sqldb.Conn interface.

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 sqldb.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.

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.
	ComQuery(c *Conn, query string) (*sqltypes.Result, error)
}

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

Listener is the MySQL server protocol listener.

func NewListener

func NewListener(protocol, address string, authServer AuthServer, handler Handler) (*Listener, error)

NewListener creates a new Listener.

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, and closes all connections.

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 StaticUserData

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

StaticUserData holds the username

func (*StaticUserData) Get

Get returns the wrapped username

Directories

Path Synopsis
Package fakesqldb provides a MySQL server for tests.
Package fakesqldb provides a MySQL server for tests.
Package replication contains data structure definitions for MySQL replication related features.
Package replication contains data structure definitions for MySQL replication related features.

Jump to

Keyboard shortcuts

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