client

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2025 License: MIT Imports: 24 Imported by: 75

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/go-mysql-org/go-mysql/client"
	"github.com/go-mysql-org/go-mysql/mysql"
)

func main() {
	// Connect MySQL at 127.0.0.1:3306, with user root, an empty password and database test
	conn, err := client.Connect("127.0.0.1:3306", "root", "", "test")
	// Or to use SSL/TLS connection if MySQL server supports TLS
	// conn, err := client.Connect("127.0.0.1:3306", "root", "", "test", func(c *Conn) {c.UseSSL(true)})
	// Or to set your own client-side certificates for identity verification for security
	// tlsConfig := NewClientTLSConfig(caPem, certPem, keyPem, false, "your-server-name")
	// conn, err := client.Connect("127.0.0.1:3306", "root", "", "test", func(c *Conn) {c.SetTLSConfig(tlsConfig)})
	if err != nil {
		msg := fmt.Sprintf(`
This example needs a MySQL listening on 127.0.0.1:3006 with user "root" and 
empty password. Please check the connectivity using mysql client.
---
Connect to MySQL failed: %v`, err)
		panic(msg)
	}

	err = conn.Ping()
	if err != nil {
		panic(err)
	}

	// (re)create the t1 table
	r, err := conn.Execute(`DROP TABLE IF EXISTS t1`)
	if err != nil {
		panic(err)
	}
	r.Close()
	r, err = conn.Execute(`CREATE TABLE t1 (id int PRIMARY KEY, name varchar(255))`)
	if err != nil {
		panic(err)
	}
	r.Close()

	// Insert
	r, err = conn.Execute(`INSERT INTO t1(id, name) VALUES(1, "abc"),(2, "def")`)
	if err != nil {
		panic(err)
	}
	defer r.Close()

	// Get last insert id and number of affected rows
	fmt.Printf("InsertId: %d, AffectedRows: %d\n", r.InsertId, r.AffectedRows)

	// Select
	r, err = conn.Execute(`SELECT id, name FROM t1`)
	if err != nil {
		panic(err)
	}

	// Handle resultset
	v, err := r.GetInt(0, 0)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Value of Row 0, Column 0: %d\n", v)

	v, err = r.GetIntByName(0, "id")
	if err != nil {
		panic(err)
	}
	fmt.Printf("Value of Row 0, Column 'id': %d\n", v)

	// Direct access to fields
	for rownum, row := range r.Values {
		fmt.Printf("Row number %d\n", rownum)
		for colnum, val := range row {
			fmt.Printf("\tColumn number %d\n", colnum)

			ival := val.Value() // interface{}
			fmt.Printf("\t\tvalue (type: %d): %#v\n", val.Type, ival)

			if val.Type == mysql.FieldValueTypeSigned {
				fval := val.AsInt64()
				fmt.Printf("\t\tint64 value: %d\n", fval)
			}
			if val.Type == mysql.FieldValueTypeString {
				fval := val.AsString()
				fmt.Printf("\t\tstring value: %s\n", fval)
			}
		}
	}
}
Output:

InsertId: 0, AffectedRows: 2
Value of Row 0, Column 0: 1
Value of Row 0, Column 'id': 1
Row number 0
	Column number 0
		value (type: 2): 1
		int64 value: 1
	Column number 1
		value (type: 4): []byte{0x61, 0x62, 0x63}
		string value: abc
Row number 1
	Column number 0
		value (type: 2): 2
		int64 value: 2
	Column number 1
		value (type: 4): []byte{0x64, 0x65, 0x66}
		string value: def

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// MaxIdleTimeoutWithoutPing - If the connection has been idle for more than this time,
	//   then ping will be performed before use to check if it alive
	MaxIdleTimeoutWithoutPing = 10 * time.Second

	// DefaultIdleTimeout - If the connection has been idle for more than this time,
	//   we can close it (but we should remember about Pool.minAlive)
	DefaultIdleTimeout = 30 * time.Second

	// MaxNewConnectionAtOnce - If we need to create new connections,
	//   then we will create no more than this number of connections at a time.
	// This restriction will be ignored on pool initialization.
	MaxNewConnectionAtOnce = 5
)

Functions

func NewClientTLSConfig

func NewClientTLSConfig(caPem, certPem, keyPem []byte, insecureSkipVerify bool, serverName string) *tls.Config

NewClientTLSConfig: generate TLS config for client side if insecureSkipVerify is set to true, serverName will not be validated

Types

type Conn

type Conn struct {
	*packet.Conn

	// Connection read and write timeouts to set on the connection
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	// The buffer size to use in the packet connection
	BufferSize int
	// contains filtered or unexported fields
}

func Connect

func Connect(addr, user, password, dbName string, options ...Option) (*Conn, error)

Connect to a MySQL server, addr can be ip:port, or a unix socket domain like /var/sock. Accepts a series of configuration functions as a variadic argument.

func ConnectWithContext added in v1.8.0

func ConnectWithContext(ctx context.Context, addr, user, password, dbName string, timeout time.Duration, options ...Option) (*Conn, error)

ConnectWithContext to a MySQL addr using the provided context.

func ConnectWithDialer added in v1.4.0

func ConnectWithDialer(ctx context.Context, network, addr, user, password, dbName string, dialer Dialer, options ...Option) (*Conn, error)

ConnectWithDialer to a MySQL server using the given Dialer.

func ConnectWithTimeout added in v1.9.0

func ConnectWithTimeout(addr, user, password, dbName string, timeout time.Duration, options ...Option) (*Conn, error)

ConnectWithTimeout to a MySQL address using a timeout.

func (*Conn) Begin

func (c *Conn) Begin() error

func (*Conn) BeginTx added in v1.12.0

func (c *Conn) BeginTx(readOnly bool, txIsolation string) error

func (*Conn) CapabilityString added in v1.8.0

func (c *Conn) CapabilityString() string

CapabilityString is returning a string with the names of capability flags separated by "|". Examples of capability names are CLIENT_DEPRECATE_EOF and CLIENT_PROTOCOL_41. These are defined as constants in the mysql package.

func (*Conn) Close

func (c *Conn) Close() error

Close directly closes the connection. Use Quit() to first send COM_QUIT to the server and then close the connection.

func (*Conn) Commit

func (c *Conn) Commit() error

func (*Conn) CompareServerVersion added in v1.8.0

func (c *Conn) CompareServerVersion(v string) (int, error)

CompareServerVersion is comparing version v against the version of the server and returns 0 if they are equal, and 1 if the server version is higher and -1 if the server version is lower.

func (*Conn) Execute

func (c *Conn) Execute(command string, args ...interface{}) (*mysql.Result, error)

func (*Conn) ExecuteMultiple added in v1.5.0

func (c *Conn) ExecuteMultiple(query string, perResultCallback ExecPerResultCallback) (*mysql.Result, error)

ExecuteMultiple will call perResultCallback for every result of the multiple queries that are executed.

When ExecuteMultiple is used, the connection should have the SERVER_MORE_RESULTS_EXISTS flag set to signal the server multiple queries are executed. Handling the responses is up to the implementation of perResultCallback.

Example
package main

import (
	"github.com/go-mysql-org/go-mysql/client"
	"github.com/go-mysql-org/go-mysql/mysql"
)

var conn *client.Conn

func main() {
	queries := "SELECT 1; SELECT NOW();"
	conn.ExecuteMultiple(queries, func(result *mysql.Result, err error) {
		// Use the result as you want
	})
}

func (*Conn) ExecuteSelectStreaming

func (c *Conn) ExecuteSelectStreaming(command string, result *mysql.Result, perRowCallback SelectPerRowCallback, perResultCallback SelectPerResultCallback) error

ExecuteSelectStreaming will call perRowCallback for every row in resultset WITHOUT saving any row data to Result.{Values/RawPkg/RowDatas} fields. When given, perResultCallback will be called once per result

ExecuteSelectStreaming should be used only for SELECT queries with a large response resultset for memory preserving.

Example
package main

import (
	"github.com/go-mysql-org/go-mysql/client"
	"github.com/go-mysql-org/go-mysql/mysql"
)

var conn *client.Conn

func main() {
	var result mysql.Result
	conn.ExecuteSelectStreaming(`SELECT ... LIMIT 100500`, &result, func(row []mysql.FieldValue) error {
		// Use the row as you want.
		// You must not save FieldValue.AsString() value after this callback is done. Copy it if you need.
		return nil
	}, nil)
}

func (*Conn) FieldList

func (c *Conn) FieldList(table string, wildcard string) ([]*mysql.Field, error)

FieldList uses COM_FIELD_LIST to get a list of fields from a table

func (*Conn) GetCharset

func (c *Conn) GetCharset() string

func (*Conn) GetCollation added in v1.8.0

func (c *Conn) GetCollation() string

func (*Conn) GetConnectionID

func (c *Conn) GetConnectionID() uint32

func (*Conn) GetDB

func (c *Conn) GetDB() string

func (*Conn) GetServerVersion added in v1.8.0

func (c *Conn) GetServerVersion() string

GetServerVersion returns the version of the server as reported by the server in the initial server greeting.

func (*Conn) HandleErrorPacket

func (c *Conn) HandleErrorPacket(data []byte) error

func (*Conn) HandleOKPacket

func (c *Conn) HandleOKPacket(data []byte) *mysql.Result

func (*Conn) HasCapability added in v1.9.0

func (c *Conn) HasCapability(cap uint32) bool

HasCapability returns true if the connection has the specific capability

func (*Conn) IncludeLine added in v1.12.0

func (c *Conn) IncludeLine(frame int)

IncludeLine can be passed as option when connecting to include the file name and line number of the caller as query attribute `_line` when sending queries. The argument is used the dept in the stack. The top level is go-mysql and then there are the levels of the application.

func (*Conn) IsAutoCommit

func (c *Conn) IsAutoCommit() bool

IsAutoCommit returns true if SERVER_STATUS_AUTOCOMMIT is set

func (*Conn) IsInTransaction

func (c *Conn) IsInTransaction() bool

IsInTransaction returns true if SERVER_STATUS_IN_TRANS is set

func (*Conn) Ping

func (c *Conn) Ping() error

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (*Stmt, error)

func (*Conn) Quit added in v1.8.0

func (c *Conn) Quit() error

Quit sends COM_QUIT to the server and then closes the connection. Use Close() to directly close the connection.

func (*Conn) ReadOKPacket

func (c *Conn) ReadOKPacket() (*mysql.Result, error)

func (*Conn) Rollback

func (c *Conn) Rollback() error

func (*Conn) SetAttributes added in v1.5.0

func (c *Conn) SetAttributes(attributes map[string]string)

SetAttributes sets connection attributes

func (*Conn) SetAutoCommit

func (c *Conn) SetAutoCommit() error

func (*Conn) SetCapability added in v1.4.0

func (c *Conn) SetCapability(cap uint32)

SetCapability enables the use of a specific capability

func (*Conn) SetCharset

func (c *Conn) SetCharset(charset string) error

func (*Conn) SetCollation added in v1.8.0

func (c *Conn) SetCollation(collation string) error

func (*Conn) SetQueryAttributes added in v1.12.0

func (c *Conn) SetQueryAttributes(attrs ...mysql.QueryAttribute) error

SetQueryAttributes sets the query attributes to be send along with the next query

func (*Conn) SetTLSConfig

func (c *Conn) SetTLSConfig(config *tls.Config)

SetTLSConfig: use user-specified TLS config pass to options when connect

func (*Conn) StatusString added in v1.8.0

func (c *Conn) StatusString() string

StatusString returns a "|" separated list of status fields. Example status values are SERVER_QUERY_WAS_SLOW and SERVER_STATUS_AUTOCOMMIT. These are defined as constants in the mysql package.

func (*Conn) UnsetCapability added in v1.4.0

func (c *Conn) UnsetCapability(cap uint32)

UnsetCapability disables the use of a specific capability

func (*Conn) UseDB

func (c *Conn) UseDB(dbName string) error

func (*Conn) UseSSL

func (c *Conn) UseSSL(insecureSkipVerify bool)

UseSSL: use default SSL pass to options when connect

type Connection added in v1.3.0

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

type ConnectionStats added in v1.3.0

type ConnectionStats struct {
	// Uses internally
	TotalCount int

	// Only for stats
	IdleCount    int
	CreatedCount int64
}

type Dialer added in v1.4.0

type Dialer func(ctx context.Context, network, address string) (net.Conn, error)

Dialer connects to the address on the named network using the provided context.

type ExecPerResultCallback added in v1.5.0

type ExecPerResultCallback func(result *mysql.Result, err error)

This function will be called once per result from ExecuteMultiple

type LogFunc added in v1.3.0

type LogFunc func(format string, args ...interface{})

type Option added in v1.9.0

type Option func(*Conn) error

type Pool added in v1.3.0

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

func NewPool deprecated added in v1.3.0

func NewPool(
	logger *slog.Logger,
	minAlive int,
	maxAlive int,
	maxIdle int,
	addr string,
	user string,
	password string,
	dbName string,
	options ...Option,
) *Pool

NewPool initializes new connection pool and uses params: addr, user, password, dbName and options. minAlive specifies the minimum number of open connections that the pool will try to maintain. maxAlive specifies the maximum number of open connections (for internal reasons, may be greater by 1 inside newConnectionProducer). maxIdle specifies the maximum number of idle connections (see DefaultIdleTimeout).

Deprecated: use NewPoolWithOptions

func NewPoolWithOptions added in v1.8.0

func NewPoolWithOptions(
	addr string,
	user string,
	password string,
	dbName string,
	options ...PoolOption,
) (*Pool, error)

NewPoolWithOptions initializes new connection pool and uses params: addr, user, password, dbName and options.

func (*Pool) Close added in v1.8.0

func (pool *Pool) Close()

Close only shutdown idle connections. we couldn't control the connection which not in the pool. So before call Close, Call PutConn to put all connections that in use back to connection pool first.

func (*Pool) DropConn added in v1.3.0

func (pool *Pool) DropConn(conn *Conn)

DropConn closes the connection without any checks

func (*Pool) GetConn added in v1.3.0

func (pool *Pool) GetConn(ctx context.Context) (*Conn, error)

GetConn returns connection from the pool or create new

func (*Pool) GetStats added in v1.3.0

func (pool *Pool) GetStats(stats *ConnectionStats)

func (*Pool) PutConn added in v1.3.0

func (pool *Pool) PutConn(conn *Conn)

PutConn returns working connection back to pool

type PoolOption added in v1.8.0

type PoolOption func(o *poolOptions)

func WithConnOptions added in v1.8.0

func WithConnOptions(options ...Option) PoolOption

func WithLogger added in v1.12.0

func WithLogger(logger *slog.Logger) PoolOption

func WithNewPoolPingTimeout added in v1.8.0

func WithNewPoolPingTimeout(timeout time.Duration) PoolOption

WithNewPoolPingTimeout enables connect & ping to DB during the pool initialization

func WithPoolLimits added in v1.8.0

func WithPoolLimits(minAlive, maxAlive, maxIdle int) PoolOption

WithPoolLimits sets pool limits:

  • minAlive specifies the minimum number of open connections that the pool will try to maintain.
  • maxAlive specifies the maximum number of open connections (for internal reasons, may be greater by 1 inside newConnectionProducer).
  • maxIdle specifies the maximum number of idle connections (see DefaultIdleTimeout).

type SelectPerResultCallback added in v1.4.0

type SelectPerResultCallback func(result *mysql.Result) error

This function will be called once per result from ExecuteSelectStreaming

type SelectPerRowCallback

type SelectPerRowCallback func(row []mysql.FieldValue) error

This function will be called for every row in resultset from ExecuteSelectStreaming.

type Stmt

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

func (*Stmt) Close

func (s *Stmt) Close() error

func (*Stmt) ColumnNum

func (s *Stmt) ColumnNum() int

func (*Stmt) Execute

func (s *Stmt) Execute(args ...interface{}) (*mysql.Result, error)

func (*Stmt) ExecuteSelectStreaming added in v1.4.0

func (s *Stmt) ExecuteSelectStreaming(result *mysql.Result, perRowCb SelectPerRowCallback, perResCb SelectPerResultCallback, args ...interface{}) error

func (*Stmt) ParamNum

func (s *Stmt) ParamNum() int

func (*Stmt) WarningsNum added in v1.4.0

func (s *Stmt) WarningsNum() int

type Timestamp added in v1.3.0

type Timestamp int64

Jump to

Keyboard shortcuts

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