xmysql

package
v0.9.8 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2023 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var CtxTimeLocation = &CtxKey{}
View Source
var DefaultConnectConfig = &ConnectConfig{
	Address:    "127.0.0.1:33060",
	Username:   "root",
	Password:   sql.NullString{String: "", Valid: true},
	Schema:     "",
	UseTLS:     false,
	AuthMethod: AuthMethodAuto,
}

DefaultConnectConfig is the default configuration used if none is provided when a Connection is instantiated.

Functions

func ContextTimeLocation

func ContextTimeLocation(ctx context.Context) *time.Location

ContextTimeLocation retrieves the time location set in context used when decoding MySQL DATETIME and TIMESTAMP to Go `time.Time`. If none is defined in context, or a none `*time.Location` was found, the default will be returned.

func IsSupportedCollation

func IsSupportedCollation[T string | uint64 | int](c T) bool

IsSupportedCollation returns whether c is a valid/supported collation. Note that MySQL Protocol X only supports the utf8mb4 character set, and consequently, only collations of utf8mb4. Argument c can be the internal MYSQL ID or MySQL name.

func SetContextTimeLocation

func SetContextTimeLocation(ctx context.Context, l *time.Location) context.Context

SetContextTimeLocation sets the time location used when decoding MySQL DATETIME and TIMESTAMP to Go `time.Time` objects. If l is nil, it is unset, and default will be used.

func UnmarshalPartial added in v0.9.4

func UnmarshalPartial(b []byte, m proto.Message) error

UnmarshalPartial parses the wire-format message in b and places the result in m. The provided message must be mutable (e.g., a non-nil pointer to a message). This is the same function as proto.Unmarshall except that AllowPartial option set to true.

Types

type AuthMethodType

type AuthMethodType string
const (
	AuthMethodPlain        AuthMethodType = "PLAIN"
	AuthMethodAuto         AuthMethodType = "AUTO"
	AuthMethodSHA256Memory AuthMethodType = "SHA256_MEMORY"
	AuthMethodMySQL41      AuthMethodType = "MYSQL41"
)

type AuthMethodTypes

type AuthMethodTypes []AuthMethodType

func (AuthMethodTypes) Has

type Collation

type Collation struct {
	ID      int    `json:"id"`
	Name    string `json:"name"`
	CharSet string `json:"charSet"`
}

type CollationID

type CollationID int

type ConnectConfig

type ConnectConfig struct {
	Address             string
	UnixSockAddr        string
	Username            string
	Password            sql.NullString
	Schema              string
	UseTLS              bool
	AuthMethod          AuthMethodType
	TLSServerCACertPath string `envVar:"PXMYSQL_CA_CERT"`
	TimeZoneName        string
}

ConnectConfig manages the configuration of a connection to a MySQL server.

func (*ConnectConfig) Clone

func (cfg *ConnectConfig) Clone() *ConnectConfig

Clone duplicates other, but leaves the password nil. The caller must save the password.

func (*ConnectConfig) SetPassword

func (cfg *ConnectConfig) SetPassword(p ...string) *ConnectConfig

SetPassword sets the password within cfg. If no password is provided, the Password-field of cfg will be the SQL NULL string (sql.NullString set as invalid). Panics when p has more than 1 element.

type Connection

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

Connection manages the information and configuration on how to connect with a MySQL Server using the X Protocol (X Plugin).

func NewConnection

func NewConnection(config *ConnectConfig) (*Connection, error)

NewConnection instantiates a new connection object. The password is not public available after the configuration has been stored.

func (*Connection) NewSession

func (cnx *Connection) NewSession(ctx context.Context) (*Session, error)

NewSession instantiates a new Session which uses cnx.

Example (Auto_notls)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/golistic/pxmysql/xmysql"
)

func main() {
	config := &xmysql.ConnectConfig{
		Address:  "127.0.0.1:53360", // see _support/pxmysql-compose/docker-compose.yml
		Username: "user_native",
	}
	config.SetPassword("pwd_user_native")

	cnx, err := xmysql.NewConnection(config)
	if err != nil {
		log.Fatal(err)
	}
	ses, err := cnx.NewSession(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("TLS:", ses.UsesTLS())
}
Output:

TLS: false
Example (Plain_withtls)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/golistic/pxmysql/xmysql"
)

func main() {
	config := &xmysql.ConnectConfig{
		Address:    "127.0.0.1:53360", // see _support/pxmysql-compose/docker-compose.yml
		AuthMethod: xmysql.AuthMethodPlain,
		UseTLS:     true,
		Username:   "user_native",
	}
	config.SetPassword("pwd_user_native")

	cnx, err := xmysql.NewConnection(config)
	if err != nil {
		log.Fatal(err)
	}
	ses, err := cnx.NewSession(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("TLS:", ses.UsesTLS())
	fmt.Println("Auth Method:", config.AuthMethod)
}
Output:

TLS: true
Auth Method: PLAIN

type CtxKey

type CtxKey struct{}

type Prepared

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

func (*Prepared) Deallocate

func (p *Prepared) Deallocate(ctx context.Context) error

Deallocate makes this prepared statement not usable any longer.

func (*Prepared) Execute

func (p *Prepared) Execute(ctx context.Context, args ...any) (*Result, error)

Execute the prepared statements replacing placeholders with args.

func (*Prepared) NumPlaceholders

func (p *Prepared) NumPlaceholders() int

NumPlaceholders returns the number of placeholder parameters.

func (*Prepared) StatementID

func (p *Prepared) StatementID() uint32

StatementID returns the statement ID.

type Result

type Result struct {
	Row             *Row
	Rows            []*Row
	Columns         []*mysqlxresultset.ColumnMetaData
	ProducedMessage string
	// contains filtered or unexported fields
}

func (*Result) FetchRow

func (rs *Result) FetchRow(ctx context.Context) error

FetchRow fetches the next row for unbuffered results and stores it in Result.Row. When no more row is available nil is returned as well as a nil error (not the mysqlerrors.ErrResultNoMore error).

func (*Result) LastInsertID

func (rs *Result) LastInsertID() uint64

func (*Result) PreparedStatementID

func (rs *Result) PreparedStatementID() uint32

func (*Result) RowsAffected

func (rs *Result) RowsAffected() uint64

func (*Result) Warnings

func (rs *Result) Warnings() []error

type Row

type Row struct {
	Values []any
}

func NewRow

func NewRow(nrColumns int) *Row

NewRow returns a new instance of Row with values slice set to a length of nrColumns.

type ServerCapabilities

type ServerCapabilities struct {
	TLS            bool
	AuthMechanisms []string
}

ServerCapabilities holds the capabilities returned by the server.

func NewServerCapabilitiesFromMessage

func NewServerCapabilitiesFromMessage(msg *serverMessage) (*ServerCapabilities, error)

NewServerCapabilitiesFromMessage instantiates a new ServerCapabilities object using a message returned by MySQL Server's X Plugin.

type Session

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

Session uses the Connection configuration to set up a session with the MySQL server through the X Plugin. When a session is instantiated the authentication start, connection is switched to TLS (if needed). All interaction with the server is through this the session.

func (*Session) AuthMethod

func (ses *Session) AuthMethod() AuthMethodType

AuthMethod returns the used authentication method, which might differ from what was configured for the connection.

func (*Session) Close

func (ses *Session) Close() error

Close closes this session. It sends the Close-message to the MySQL X Plugin for both session and connection.

func (*Session) Collation

func (ses *Session) Collation(ctx context.Context) (*Collation, error)

Collation retrieves this session's collation information.

func (*Session) CurrentSchema

func (ses *Session) CurrentSchema(ctx context.Context) (string, error)

CurrentSchema retrieves the current schema (database) of this session.

func (*Session) ExecuteStatement

func (ses *Session) ExecuteStatement(ctx context.Context, stmt string, args ...any) (*Result, error)
Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/golistic/pxmysql/null"
	"github.com/golistic/pxmysql/xmysql"
)

func main() {
	config := &xmysql.ConnectConfig{
		Address:    "127.0.0.1:53360", // see _support/pxmysql-compose/docker-compose.yml
		AuthMethod: xmysql.AuthMethodPlain,
		UseTLS:     true,
		Username:   "user_native",
	}
	config.SetPassword("pwd_user_native")

	cnx, err := xmysql.NewConnection(config)
	if err != nil {
		log.Fatal(err)
	}

	ses, err := cnx.NewSession(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	q := "SELECT ?, STR_TO_DATE('2005-03-01 07:00:01', '%Y-%m-%d %H:%i:%s')"
	res, err := ses.ExecuteStatement(context.Background(), q, "started")
	if err != nil {
		log.Fatal(err)
	}

	for _, row := range res.Rows {
		fmt.Printf("%s at %s\n", row.Values[0].(string), row.Values[1].(null.Time).Time)
	}

}
Output:

started at 2005-03-01 07:00:01 +0000 UTC

func (*Session) PrepareStatement

func (ses *Session) PrepareStatement(ctx context.Context, statement string) (*Prepared, error)

PrepareStatement prepares the statement and returns an instance of Prepared which contains the Result instance. The ID of the prepared statement can be retrieved using Result.PreparedStatementID().

func (*Session) SessionID

func (ses *Session) SessionID(ctx context.Context) (int, error)

SessionID retrieves the MySQL server connection (session) ID.

func (*Session) SetCollation

func (ses *Session) SetCollation(ctx context.Context, name string) error

func (*Session) SetCurrentSchema

func (ses *Session) SetCurrentSchema(ctx context.Context, name string) error

SetCurrentSchema sets the current schema (database) of this session.

func (*Session) SetTimeZone

func (ses *Session) SetTimeZone(ctx context.Context, name string) error

func (*Session) String

func (ses *Session) String() string

func (*Session) TimeZone

func (ses *Session) TimeZone(ctx context.Context) (*time.Location, error)

TimeZone retrieves the session's time zone as Go time.Location.

func (*Session) UsesTLS

func (ses *Session) UsesTLS() bool

UsesTLS returns whether this session uses TLS.

Jump to

Keyboard shortcuts

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