Documentation
¶
Overview ¶
Package mysql provides a MySQL driver for Go's database/sql package.
The driver should be used via the database/sql package:
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", "user:password@/dbname")
See https://github.com/go-sql-driver/mysql#usage for details
Index ¶
- Variables
- func DeregisterDialContext(net string)
- func DeregisterLocalFile(filePath string)
- func DeregisterReaderHandler(name string)
- func DeregisterServerPubKey(name string)
- func DeregisterTLSConfig(key string)
- func NewConnector(cfg *Config) (driver.Connector, error)
- func RegisterAuthPlugin(name string, factory func() AuthPlugin)
- func RegisterDial(network string, dial DialFunc)deprecated
- func RegisterDialContext(net string, dial DialContextFunc)
- func RegisterLocalFile(filePath string)
- func RegisterReaderHandler(name string, handler func() io.Reader)
- func RegisterServerPubKey(name string, pubKey *rsa.PublicKey)
- func RegisterTLSConfig(key string, config *tls.Config) error
- func SetLogger(logger Logger) error
- type AuthContext
- type AuthPlugin
- type Config
- type DialContextFunc
- type DialFuncdeprecated
- type Logger
- type MySQLDriver
- type MySQLError
- type NopLogger
- type NullTimedeprecated
- type Option
- func AddParam(name, value string) Option
- func BeforeConnect(fn func(context.Context, *Config) error) Option
- func Charset(charset, collation string) Option
- func EnableCompression(yes bool) Option
- func OIDCToken(token string) Option
- func TimeTruncate(d time.Duration) Option
- func TinyInt1IsBool(yes bool) Option
- type Result
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidConn = errors.New("invalid connection") ErrMalformPkt = errors.New("malformed packet") ErrNoTLS = errors.New("TLS requested but server does not support TLS") ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") ErrNativePassword = errors.New("this user requires mysql native password authentication") ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") ErrUnknownPlugin = errors.New("this authentication plugin is not supported") ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") ErrPktSync = errors.New("commands out of sync. You can't run this command now") ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the `Config.MaxAllowedPacket`") ErrBusyBuffer = errors.New("busy buffer") ErrOpenIDConnectToken = errors.New("OpenID Connect requires a non-empty token") ErrOpenIDConnectTLS = errors.New("OpenID Connect requires driver-managed TLS") ErrOpenIDConnectSwitch = errors.New("OpenID Connect does not allow authentication switches") ErrOpenIDConnectCapabilities = errors.New("OpenID Connect requires plugin authentication and length-encoded authentication data") )
Various errors the driver might return. Can change between driver versions.
Functions ¶
func DeregisterDialContext ¶ added in v1.8.0
func DeregisterDialContext(net string)
DeregisterDialContext removes the custom dial function registered with the given net.
func DeregisterLocalFile ¶
func DeregisterLocalFile(filePath string)
DeregisterLocalFile removes the given filepath from the allowlist.
func DeregisterReaderHandler ¶
func DeregisterReaderHandler(name string)
DeregisterReaderHandler removes the ReaderHandler function with the given name from the registry.
func DeregisterServerPubKey ¶ added in v1.4.0
func DeregisterServerPubKey(name string)
DeregisterServerPubKey removes the public key registered with the given name.
func DeregisterTLSConfig ¶ added in v1.1.0
func DeregisterTLSConfig(key string)
DeregisterTLSConfig removes the tls.Config associated with key.
func NewConnector ¶ added in v1.5.0
NewConnector returns new driver.Connector.
func RegisterAuthPlugin ¶ added in v1.11.0
func RegisterAuthPlugin(name string, factory func() AuthPlugin)
RegisterAuthPlugin registers a factory for the server's authentication plugin name, replacing any existing registration for that name, including built-in plugins. Authentication-method permissions still apply to the registered name. Registration does not call the factory. The driver calls factory for each authentication exchange, possibly concurrently for different connections. The factory must return a new, non-nil AuthPlugin whose mutable state is not shared with other exchanges.
func RegisterDial
deprecated
added in
v1.2.0
RegisterDial registers a custom dial function. It can then be used by the network address mynet(addr), where mynet is the registered new network. addr is passed as a parameter to the dial function.
Deprecated: users should call RegisterDialContext instead
func RegisterDialContext ¶ added in v1.5.0
func RegisterDialContext(net string, dial DialContextFunc)
RegisterDialContext registers a custom dial function. It can then be used by the network address mynet(addr), where mynet is the registered new network. The current context for the connection and its address is passed to the dial function.
func RegisterLocalFile ¶
func RegisterLocalFile(filePath string)
RegisterLocalFile adds the given file to the file allowlist, so that it can be used by "LOAD DATA LOCAL INFILE <filepath>". Alternatively you can allow the use of all local files with the DSN parameter 'allowAllFiles=true'
filePath := "/home/gopher/data.csv"
mysql.RegisterLocalFile(filePath)
err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo")
if err != nil {
...
func RegisterReaderHandler ¶
RegisterReaderHandler registers a handler function which is used to receive a io.Reader. The Reader can be used by "LOAD DATA LOCAL INFILE Reader::<name>". If the handler returns a io.ReadCloser Close() is called when the request is finished.
mysql.RegisterReaderHandler("data", func() io.Reader {
var csvReader io.Reader // Some Reader that returns CSV data
... // Open Reader here
return csvReader
})
err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo")
if err != nil {
...
func RegisterServerPubKey ¶ added in v1.4.0
RegisterServerPubKey registers a server RSA public key which can be used to send data 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.
data, err := os.ReadFile("mykey.pem")
if err != nil {
log.Fatal(err)
}
block, _ := pem.Decode(data)
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 ¶ added in v1.1.0
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 := os.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 AuthContext ¶ added in v1.11.0
type AuthContext struct {
// contains filtered or unexported fields
}
AuthContext contains the credentials and transport information for the current authentication exchange. The driver creates a new snapshot whenever it starts a plugin and does not change it during that exchange. Plugins must not modify it.
func (*AuthContext) Password ¶ added in v1.11.0
func (a *AuthContext) Password() string
Password returns the password selected for this authentication exchange.
func (*AuthContext) ServerPublicKey ¶ added in v1.11.0
func (a *AuthContext) ServerPublicKey() *rsa.PublicKey
ServerPublicKey returns a copy of the configured server RSA public key, or nil if none was configured. Modifying the copy does not affect the driver or subsequent calls to ServerPublicKey.
func (*AuthContext) TLS ¶ added in v1.11.0
func (a *AuthContext) TLS() bool
TLS reports whether the driver has completed the MySQL TLS handshake. It does not indicate whether the server's certificate was verified, nor does it describe encryption provided by a custom dialer or an external tunnel.
func (*AuthContext) UnixSocket ¶ added in v1.11.0
func (a *AuthContext) UnixSocket() bool
UnixSocket reports whether the connection uses the configured unix network.
func (*AuthContext) User ¶ added in v1.11.0
func (a *AuthContext) User() string
User returns the username supplied for the connection.
type AuthPlugin ¶ added in v1.11.0
type AuthPlugin interface {
// InitAuth initializes the authentication process and returns the initial response.
// authData is the challenge data from the server. It must not be modified
// and must be copied if retained after the call.
// auth is the snapshot for this exchange, shared with ContinuationAuth.
// A nil or empty response sends an empty authentication response.
// Plugins must check any transport requirements here before returning credentials.
InitAuth(ctx context.Context, authData []byte, auth *AuthContext) ([]byte, error)
// ContinuationAuth processes the server's continuation payload after the
// driver has handled OK, ERR, and auth switch packets and stripped any
// AuthMoreData prefix. authData is the challenge passed to InitAuth.
// Neither slice may be modified; copy them if retaining them after the call.
// A nil response reads the next server packet without sending. A non-nil
// empty response sends an empty packet. An error aborts authentication.
// Only a server OK packet completes authentication successfully.
ContinuationAuth(ctx context.Context, packet, authData []byte, auth *AuthContext) (nextPacket []byte, err error)
}
AuthPlugin represents an authentication plugin for MySQL/MariaDB. The driver creates an instance for each authentication exchange and calls its methods sequentially. ctx is the connection's context and may be canceled while a method is running. Plugins should use it to cancel blocking work.
type Config ¶ added in v1.3.0
type Config struct {
User string // Username
Passwd string // Password (requires User)
Net string // Network (e.g. "tcp", "tcp6", "unix". default: "tcp")
Addr string // Address (default: "127.0.0.1:3306" for "tcp" and "/tmp/mysql.sock" for "unix")
DBName string // Database name
Params map[string]string // Connection parameters. Use Apply(AddParam(...)) to preserve insertion order.
ConnectionAttributes string // Connection Attributes, comma-delimited string of user-defined "key:value" pairs
Collation string // Connection collation. When set, this will be set in SET NAMES <charset> COLLATE <collation> query
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
TLS *tls.Config // TLS configuration, its priority is higher than TLSConfig
Timeout time.Duration // Dial timeout
ReadTimeout time.Duration // I/O read timeout
WriteTimeout time.Duration // I/O write timeout
Logger Logger // Logger
// DialFunc specifies the dial function for creating connections
DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
AllowAllFiles bool // Allow all files to be used with LOAD DATA LOCAL INFILE
AllowCleartextPasswords bool // Allows the cleartext client side plugin
AllowFallbackToPlaintext bool // Allows fallback to unencrypted connection if server does not support TLS
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
// contains filtered or unexported fields
}
Config is a configuration parsed from a DSN string. If a new Config is created instead of being parsed from a DSN string, the NewConfig function should be used, which sets default values.
func NewConfig ¶ added in v1.4.0
func NewConfig() *Config
NewConfig creates a new Config and sets default values.
func (*Config) FormatDSN ¶ added in v1.3.0
FormatDSN formats the given Config into a DSN string which can be passed to the driver.
Note: use NewConnector and database/sql.OpenDB to open a connection from a *Config.
type DialContextFunc ¶ added in v1.5.0
DialContextFunc is a function which can be used to establish the network connection. Custom dial functions must be registered with RegisterDialContext
type Logger ¶ added in v1.2.0
type Logger interface {
Print(v ...any)
}
Logger is used to log critical error messages.
type MySQLDriver ¶ added in v1.1.0
type MySQLDriver struct{}
MySQLDriver is exported to make the driver directly accessible. In general the driver is used via the database/sql package.
func (MySQLDriver) Open ¶ added in v1.1.0
func (d MySQLDriver) Open(dsn string) (driver.Conn, error)
Open new Connection. See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how the DSN string is formatted
func (MySQLDriver) OpenConnector ¶ added in v1.5.0
func (d MySQLDriver) OpenConnector(dsn string) (driver.Connector, error)
OpenConnector implements driver.DriverContext.
type MySQLError ¶
MySQLError is an error type which represents a single MySQL error
func (*MySQLError) Error ¶
func (me *MySQLError) Error() string
func (*MySQLError) Is ¶ added in v1.7.0
func (me *MySQLError) Is(err error) bool
type NopLogger ¶ added in v1.8.0
type NopLogger struct{}
NopLogger is a nop implementation of the Logger interface.
type NullTime
deprecated
NullTime represents a time.Time that may be NULL. NullTime implements the Scanner interface so it can be used as a scan destination:
var nt NullTime
err := db.QueryRow("SELECT time FROM foo WHERE id=?", id).Scan(&nt)
...
if nt.Valid {
// use nt.Time
} else {
// NULL value
}
This NullTime implementation is not driver-specific ¶
Deprecated: NullTime doesn't honor the loc DSN parameter. NullTime.Scan interprets a time as UTC, not the loc DSN parameter. Use sql.NullTime instead.
type Option ¶ added in v1.8.0
Functional Options Pattern https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
func AddParam ¶ added in v1.11.0
AddParam adds a connection parameter.
Parameters added with AddParam retain their order in Config.FormatDSN and are applied to the connection in that order. If name already exists, it is moved to the end of the parameter order.
func BeforeConnect ¶ added in v1.8.0
BeforeConnect sets the function to be invoked before a connection is established. If the function changes Config.Addr while Config.TLS is non-nil and its InsecureSkipVerify field is false, it must also update ServerName to match the hostname in the new address.
func Charset ¶ added in v1.9.1
Charset sets the connection charset and collation.
charset is the connection charset. collation is the connection collation. It can be null or empty string.
When collation is not specified, `SET NAMES <charset>` command is sent when the connection is established. When collation is specified, `SET NAMES <charset> COLLATE <collation>` command is sent when the connection is established.
func EnableCompression ¶ added in v1.9.0
EnableCompression enables compression. Import mysql/zstd to prefer zstd when supported by the server; otherwise connections use zlib when supported.
func OIDCToken ¶ added in v1.11.0
OIDCToken sets the JWT for OpenID Connect authentication. Empty tokens return ErrOpenIDConnectToken without changing the configuration. Use BeforeConnect to refresh the token with cfg.Apply(OIDCToken(token)). The token is omitted from Config.FormatDSN. OIDC requires driver-managed TLS with application-configured server verification and rejects authentication switches.
func TimeTruncate ¶ added in v1.8.0
TimeTruncate sets the time duration to truncate time.Time values in query parameters.
func TinyInt1IsBool ¶ added in v1.11.0
TinyInt1IsBool controls whether signed TINYINT(1) columns are treated as boolean. It is disabled by default.
type Result ¶ added in v1.8.0
type Result interface {
driver.Result
// AllRowsAffected returns a slice containing the affected rows for each
// executed statement.
AllRowsAffected() []int64
// AllLastInsertIds returns a slice containing the last inserted ID for each
// executed statement.
AllLastInsertIds() []int64
}
Result exposes data not available through *connection.Result.
This is accessible by executing statements using sql.Conn.Raw() and downcasting the returned result:
res, err := rawConn.Exec(...) res.(mysql.Result).AllRowsAffected()
Source Files
¶
- auth.go
- auth_caching_sha2.go
- auth_cleartext.go
- auth_context.go
- auth_ed25519.go
- auth_mysql_native.go
- auth_oidc.go
- auth_old_password.go
- auth_parsec.go
- auth_plugin.go
- auth_sha256.go
- buffer.go
- collations.go
- compress.go
- conncheck.go
- conncheck_error.go
- connection.go
- connector.go
- const.go
- driver.go
- dsn.go
- errors.go
- fields.go
- infile.go
- nulltime.go
- packets.go
- result.go
- rows.go
- rows_column_scanner.go
- rows_decode.go
- statement.go
- transaction.go
- utils.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
compression
Package compression connects optional compression implementations to the driver.
|
Package compression connects optional compression implementations to the driver. |
|
Package zstd enables automatic Zstandard compression for MySQL connections with compression enabled.
|
Package zstd enables automatic Zstandard compression for MySQL connections with compression enabled. |

