mysql

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2023 License: Apache-2.0 Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (
	UserMaxAllowedPacket uint32 = 1 << iota
)

Variables

This section is empty.

Functions

func AppendDateTime

func AppendDateTime(buf []byte, t time.Time) ([]byte, error)

func DeregisterServerPubKey

func DeregisterServerPubKey(name string)

DeregisterServerPubKey removes the public key registered with the given name.

func DeregisterTLSConfig

func DeregisterTLSConfig(key string)

DeregisterTLSConfig removes the tls.Config associated with key.

func Escape

func Escape(sql string) string

Escape remove exceptional character

func GetDefaultFieldLengthAndDecimal

func GetDefaultFieldLengthAndDecimal(tp mysql.FieldType) (flen int, decimal int)

GetDefaultFieldLengthAndDecimal returns the default display length (flen) and decimal length for column. Call this when no Flen assigned in ddl. or column value is calculated from an expression. For example: "select count(*) from t;", the column type is int64 and Flen in ResultField will be 21. See https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

func GetDefaultFieldLengthAndDecimalForCast

func GetDefaultFieldLengthAndDecimalForCast(tp mysql.FieldType) (flen int, decimal int)

GetDefaultFieldLengthAndDecimalForCast returns the default display length (flen) and decimal length for casted column when flen or decimal is not specified.

func IsIntegerType

func IsIntegerType(tp mysql.FieldType) bool

IsIntegerType indicate whether tp is an integer type.

func NewListener

func NewListener(conf *config.Listener) (proto.Listener, error)

func ParseErrorPacket

func ParseErrorPacket(data []byte) error

ParseErrorPacket parses the error packet and returns a SQLError.

func PutLengthEncodedInt

func PutLengthEncodedInt(n uint64) []byte

func PutLengthEncodedString

func PutLengthEncodedString(b []byte) []byte

func RandomBuf

func RandomBuf(size int) ([]byte, error)

RandomBuf return random salt, seed must be in the range of ascii

func RegisterServerPubKey

func RegisterServerPubKey(name string, pubKey *rsa.PublicKey)

RegisterServerPubKey registers a server RSA public key which can be used to send Content in a secure manner to the server without receiving the public key in a potentially insecure way from the server first. Registered keys can afterwards be used adding serverPubKey=<name> to the DSN.

Note: The provided rsa.PublicKey instance is exclusively owned by the driver after registering it and may not be modified.

Content, err := ioutil.ReadFile("mykey.pem")
if err != nil {
	log.Fatal(err)
}

block, _ := pem.Decode(Content)
if block == nil || block.Type != "PUBLIC KEY" {
	log.Fatal("failed to decode PEM block containing public key")
}

pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
	log.Fatal(err)
}

if rsaPubKey, ok := pub.(*rsa.PublicKey); ok {
	mysql.RegisterServerPubKey("mykey", rsaPubKey)
} else {
	log.Fatal("not a RSA public key")
}

func RegisterTLSConfig

func RegisterTLSConfig(key string, config *tls.Config) error

RegisterTLSConfig registers a custom tls.Config to be used with sql.Open. Use the key as a value in the DSN where tls=value.

Note: The provided tls.Config is exclusively owned by the driver after registering it.

rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("/path/ca-cert.pem")
if err != nil {
    log.Fatal(err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
    log.Fatal("Failed to append PEM.")
}
clientCert := make([]tls.Certificate, 0, 1)
certs, err := tls.LoadX509KeyPair("/path/client-cert.pem", "/path/client-key.pem")
if err != nil {
    log.Fatal(err)
}
clientCert = append(clientCert, certs)
mysql.RegisterTLSConfig("custom", &tls.Config{
    RootCAs: rootCertPool,
    Certificates: clientCert,
})
db, err := sql.Open("mysql", "user@tcp(localhost:3306)/test?tls=custom")

Types

type BackendConnection

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

func (*BackendConnection) Close

func (conn *BackendConnection) Close()

func (*BackendConnection) Connect

func (conn *BackendConnection) Connect(ctx context.Context) error

func (*BackendConnection) DBName

func (conn *BackendConnection) DBName() string

func (*BackendConnection) DrainResults

func (conn *BackendConnection) DrainResults() error

DrainResults will read all packets for a result set and ignore them.

func (*BackendConnection) ExecuteWithWarningCount

func (conn *BackendConnection) ExecuteWithWarningCount(query string, wantFields bool) (result proto.Result, err error)

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

func (*BackendConnection) ExecuteWithWarningCountIterRow

func (conn *BackendConnection) ExecuteWithWarningCountIterRow(query string) (result proto.Result, err error)

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

func (*BackendConnection) GetDatabaseConn

func (conn *BackendConnection) GetDatabaseConn() *Conn

func (*BackendConnection) PersistVariables

func (conn *BackendConnection) PersistVariables() (map[string]proto.Value, error)

PersistVariables returns the persisted variables from remote mysql.

func (*BackendConnection) Ping

func (conn *BackendConnection) Ping() error

Ping implements mysql ping command.

func (*BackendConnection) PrepareExecute

func (conn *BackendConnection) PrepareExecute(query string, data []byte) (proto.Result, error)

func (*BackendConnection) PrepareExecuteArgs

func (conn *BackendConnection) PrepareExecuteArgs(query string, args []proto.Value) (proto.Result, error)

func (*BackendConnection) PrepareQuery

func (conn *BackendConnection) PrepareQuery(query string, data []byte) (proto.Result, error)

func (*BackendConnection) PrepareQueryArgs

func (conn *BackendConnection) PrepareQueryArgs(query string, data []proto.Value) (proto.Result, error)

func (*BackendConnection) ReadColumnDefinition

func (conn *BackendConnection) ReadColumnDefinition(field *Field, index int) error

ReadColumnDefinition reads the next Column Definition packet. Returns a SQLError. https://dev.mysql.com/doc/internals/en/com-query-response.html#column-definition

func (*BackendConnection) ReadColumnDefinitionType

func (conn *BackendConnection) ReadColumnDefinitionType(field *Field, index int) error

ReadColumnDefinitionType is a faster version of ReadColumnDefinition that only fills in the Type. Returns a SQLError.

func (*BackendConnection) ReadColumnDefinitions

func (conn *BackendConnection) ReadColumnDefinitions() ([]proto.Field, error)

func (*BackendConnection) ReadQueryResult

func (conn *BackendConnection) ReadQueryResult(wantFields bool) proto.Result

ReadQueryResult gets the result from the last written query.

func (*BackendConnection) ReadQueryRow

func (conn *BackendConnection) ReadQueryRow() *RawResult

ReadQueryRow returns iterator, and the line reads the results set

func (*BackendConnection) ResetVariables

func (conn *BackendConnection) ResetVariables() error

ResetVariables resets transient variables.

func (*BackendConnection) SyncVariables

func (conn *BackendConnection) SyncVariables(vars map[string]proto.Value) error

SyncVariables sync local transient variables with upstream mysql.

The sync logic:

CLIENT ----ConnA----> ARANA ----ConnB----> MySQL

      |                      |
transient-vars          persist-vars
       \                     /
        \                   /
             >>> SYNC <<<

func (*BackendConnection) WriteComFieldList

func (conn *BackendConnection) WriteComFieldList(table string, wildcard string) error

WriteComFieldList https://dev.mysql.com/doc/internals/en/com-field-list.html

func (*BackendConnection) WriteComInitDB

func (conn *BackendConnection) WriteComInitDB(db string) error

WriteComInitDB changes the default database to use. Client -> Server. Returns SQLError(CRServerGone) if it can't.

func (*BackendConnection) WriteComQuery

func (conn *BackendConnection) WriteComQuery(query string) error

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

func (*BackendConnection) WriteComSetOption

func (conn *BackendConnection) WriteComSetOption(operation uint16) error

WriteComSetOption changes the connection's capability of executing multi statements. Returns SQLError(CRServerGone) if it can't.

type BackendStatement

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

type BinaryRow

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

func NewBinaryRow

func NewBinaryRow(fields []proto.Field, raw []byte) BinaryRow

func (BinaryRow) Fields

func (bi BinaryRow) Fields() []proto.Field

func (BinaryRow) Get

func (bi BinaryRow) Get(name string) (proto.Value, error)

func (BinaryRow) IsBinary

func (bi BinaryRow) IsBinary() bool

func (BinaryRow) Length

func (bi BinaryRow) Length() int

func (BinaryRow) Scan

func (bi BinaryRow) Scan(dest []proto.Value) error

func (BinaryRow) WriteTo

func (bi BinaryRow) WriteTo(w io.Writer) (n int64, err error)

type Config

type Config struct {
	User             string            // Username
	Passwd           string            // Password (requires User)
	Net              string            // Network type
	Addr             string            // Network address (requires Net)
	DBName           string            // Database name
	Params           map[string]string // Connection parameters
	Collation        string            // Connection collation
	Loc              *time.Location    // Location for time.Time values
	MaxAllowedPacket int               // Max packet size allowed
	ServerPubKey     string            // Server public key name

	TLSConfig string // TLS configuration name

	Timeout      time.Duration // Dial timeout
	ReadTimeout  time.Duration // I/O read timeout
	WriteTimeout time.Duration // I/O write timeout

	AllowAllFiles             bool // Allow all files to be used with LOAD DATA LOCAL INFILE
	AllowCleartextPasswords   bool // Allows the cleartext client side plugin
	AllowNativePasswords      bool // Allows the native password authentication method
	AllowOldPasswords         bool // Allows the old insecure password method
	CheckConnLiveness         bool // Check connections for liveness before using them
	ClientFoundRows           bool // Return number of matching rows instead of rows changed
	ColumnsWithAlias          bool // Prepend table alias to column names
	InterpolateParams         bool // Interpolate placeholders into query string
	MultiStatements           bool // Allow multiple statements in one query
	ParseTime                 bool // Parse time values to time.Time
	RejectReadOnly            bool // Reject read-only connections
	DisableClientDeprecateEOF bool // Disable client deprecate EOF
	// contains filtered or unexported fields
}

func NewConfig

func NewConfig() *Config

NewConfig creates a new ServerConfig and sets default values.

func ParseDSN

func ParseDSN(dsn string) (cfg *Config, err error)

ParseDSN parses the DSN string to a Config

func (*Config) Clone

func (cfg *Config) Clone() *Config

type Conn

type Conn struct {

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

	// 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
	// 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 (*Conn) CharacterSet

func (c *Conn) CharacterSet() uint8

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

func (c *Conn) DefColumnDefinition(field *Field) []byte

func (*Conn) GetNetConn

func (c *Conn) GetNetConn() net.Conn

func (*Conn) GetTLSClientCerts

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

GetTLSClientCerts gets TLS certificates.

func (*Conn) ID

func (c *Conn) ID() uint32

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

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

RemoteAddr returns the underlying socket RemoteAddr().

func (*Conn) Schema

func (c *Conn) Schema() string

func (*Conn) ServerVersion

func (c *Conn) ServerVersion() string

func (*Conn) SetSchema

func (c *Conn) SetSchema(schema string)

func (*Conn) SetTenant

func (c *Conn) SetTenant(t string)

func (*Conn) SetTransientVariables

func (c *Conn) SetTransientVariables(v map[string]proto.Value)

func (*Conn) String

func (c *Conn) String() string

Ident returns a useful identification string for error logging

func (*Conn) Tenant

func (c *Conn) Tenant() string

func (*Conn) TransientVariables

func (c *Conn) TransientVariables() map[string]proto.Value

type Connector

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

func NewConnector

func NewConnector(dsn string) (*Connector, error)

func (*Connector) NewBackendConnection

func (c *Connector) NewBackendConnection(ctx context.Context) (*BackendConnection, error)

type Field

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

func NewField

func NewField(name string, filedType mysql.FieldType) *Field

func (*Field) DatabaseName

func (mf *Field) DatabaseName() string

func (*Field) DatabaseTypeName

func (mf *Field) DatabaseTypeName() string

func (*Field) DecimalSize

func (mf *Field) DecimalSize() (int64, int64, bool)

func (*Field) FieldType

func (mf *Field) FieldType() mysql.FieldType

func (*Field) Length

func (mf *Field) Length() (length int64, ok bool)

func (*Field) Name

func (mf *Field) Name() string

func (*Field) Nullable

func (mf *Field) Nullable() (nullable, ok bool)

func (*Field) OriginName

func (mf *Field) OriginName() string

func (*Field) ScanType

func (mf *Field) ScanType() reflect.Type

func (*Field) SetName

func (mf *Field) SetName(name string)

func (*Field) SetOrgName

func (mf *Field) SetOrgName(name string)

func (*Field) TableName

func (mf *Field) TableName() string

type Listener

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

func (*Listener) Close

func (l *Listener) Close()

func (*Listener) ExecuteCommand

func (l *Listener) ExecuteCommand(c *Conn, ctx *proto.Context) error

func (*Listener) Listen

func (l *Listener) Listen()

func (*Listener) SetExecutor

func (l *Listener) SetExecutor(executor proto.Executor)

func (*Listener) ValidateHash

func (l *Listener) ValidateHash(handshake *handshakeResult) error

type RawBytes

type RawBytes []byte

type RawResult

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

func (*RawResult) Close

func (rr *RawResult) Close() error

func (*RawResult) Dataset

func (rr *RawResult) Dataset() (proto.Dataset, error)

func (*RawResult) Discard

func (rr *RawResult) Discard() (err error)

func (*RawResult) Fields

func (rr *RawResult) Fields() ([]proto.Field, error)

func (*RawResult) LastInsertId

func (rr *RawResult) LastInsertId() (uint64, error)

func (*RawResult) Next

func (rr *RawResult) Next() (row proto.Row, err error)

func (*RawResult) RowsAffected

func (rr *RawResult) RowsAffected() (uint64, error)

func (*RawResult) SetCloser

func (rr *RawResult) SetCloser(closer func() error)

func (*RawResult) Warn

func (rr *RawResult) Warn() (uint16, error)

type Scanner

type Scanner interface {
	// Scan assigns a value from a database driver.
	//
	// The src value will be of one of the following types:
	//
	//    int64
	//    float64
	//    bool
	//    []byte
	//    string
	//    time.Time
	//    nil - for NULL values
	//
	// An error should be returned if the value cannot be stored
	// without loss of information.
	//
	// Reference types such as []byte are only valid until the next call to Scan
	// and should not be retained. Their underlying memory is owned by the driver.
	// If retention is necessary, copy their values before the next call to Scan.
	Scan(src interface{}) error
}

Scanner is an interface used by Scan.

type ServerConfig

type ServerConfig struct {
	ServerVersion string `yaml:"server_version" json:"server_version"`
}

type TextRow

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

func NewTextRow

func NewTextRow(fields []proto.Field, raw []byte) TextRow

func (TextRow) Fields

func (te TextRow) Fields() []proto.Field

func (TextRow) Get

func (te TextRow) Get(name string) (proto.Value, error)

func (TextRow) IsBinary

func (te TextRow) IsBinary() bool

func (TextRow) Length

func (te TextRow) Length() int

func (TextRow) Scan

func (te TextRow) Scan(dest []proto.Value) error

func (TextRow) WriteTo

func (te TextRow) WriteTo(w io.Writer) (n int64, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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