Package-Level Type Names (total 28, in which 7 are exported)
/* sort exporteds by: | */
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.
// Network address (requires Net)
// Allow all files to be used with LOAD DATA LOCAL INFILE
// Allows the cleartext client side plugin
// Allows the native password authentication method
// Allows the old insecure password method
// Check connections for liveness before using them
// Return number of matching rows instead of rows changed
// Connection collation
// Prepend table alias to column names
// Database name
// Interpolate placeholders into query string
// Location for time.Time values
// Max packet size allowed
// Allow multiple statements in one query
// Network type
// Connection parameters
// Parse time values to time.Time
// Password (requires User)
// I/O read timeout
// Reject read-only connections
// Server public key name
// TLS configuration name
// Dial timeout
// Username
// I/O write timeout
// Server public key
// TLS configuration
(*T) Clone() *Config
FormatDSN formats the given Config into a DSN string which can be passed to
the driver.
(*T) normalize() error
func NewConfig() *Config
func ParseDSN(dsn string) (cfg *Config, err error)
func (*Config).Clone() *Config
func NewConnector(cfg *Config) (driver.Connector, error)
func parseDSNParams(cfg *Config, params string) (err error)
DialContextFunc is a function which can be used to establish the network connection.
Custom dial functions must be registered with RegisterDialContext
func RegisterDialContext(net string, dial DialContextFunc)
DialFunc is a function which can be used to establish the network connection.
Custom dial functions must be registered with RegisterDial
Deprecated: users should register a DialContextFunc instead
func RegisterDial(network string, dial DialFunc)
Logger is used to log critical error messages.
( T) Print(v ...interface{})
*github.com/sirupsen/logrus.Entry
github.com/sirupsen/logrus.Ext1FieldLogger(interface)
github.com/sirupsen/logrus.FieldLogger(interface)
*github.com/sirupsen/logrus.Logger
github.com/sirupsen/logrus.StdLogger(interface)
*log.Logger
func SetLogger(logger Logger) error
var errLog
MySQLDriver is exported to make the driver directly accessible.
In general the driver is used via the database/sql package.
Open new Connection.
See https://github.com/go-sql-driver/mysql#dsn-data-source-name for how
the DSN string is formatted
OpenConnector implements driver.DriverContext.
T : database/sql/driver.Driver
T : database/sql/driver.DriverContext
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.
Timetime.Time
// Valid is true if Time is not NULL
Scan implements the Scanner interface.
The value type must be time.Time or string / []byte (formatted time-string),
otherwise Scan fails.
Value implements the driver Valuer interface.
*T : database/sql.Scanner
T : database/sql/driver.Valuer
atomicBool is a wrapper around uint32 for usage as a boolean value with
atomic access.
_noCopynoCopyvalueuint32
IsSet returns whether the current boolean value is true
Set sets the value of the bool regardless of the previous value
TrySet sets the value of the bool and returns whether the value changed
atomicError is a wrapper for atomically accessed error values
_noCopynoCopyvalueatomic.Value
Set sets the error value regardless of the previous value.
The value must not be nil
Value returns the current error value
A buffer which is used for both reading and writing.
This is possible since communication on each connection is synchronous.
In other words, we can't write and read simultaneously on the same connection.
The buffer is similar to bufio.Reader / Writer but zero-copy-ish
Also highly optimized for this particular use case.
This buffer is backed by two byte slices in a double-buffering scheme
// buf is a byte buffer who's length and capacity are equal.
// dbuf is an array with the two byte slices that back this buffer
// flipccnt is the current buffer counter for double-buffering
idxintlengthintncnet.Conntimeouttime.Duration
fill reads into the buffer until at least _need_ bytes are in it
flip replaces the active buffer with the background buffer
this is a delayed flip that simply increases the buffer counter;
the actual flip will be performed the next time we call `buffer.fill`
returns next N bytes from buffer.
The returned slice is only guaranteed to be valid until the next read
store stores buf, an updated buffer, if its suitable to do so.
takeBuffer returns a buffer with the requested size.
If possible, a slice from the existing buffer is returned.
Otherwise a bigger buffer is made.
Only one buffer (total) can be used at a time.
takeCompleteBuffer returns the complete existing buffer.
This can be used if the necessary buffer size is unknown.
cap and len of the returned buffer will be equal.
Only one buffer (total) can be used at a time.
takeSmallBuffer is shortcut which can be used if length is
known to be smaller than defaultBufSize.
Only one buffer (total) can be used at a time.
func newBuffer(nc net.Conn) buffer
// immutable private copy.
Connect implements driver.Connector interface.
Connect returns a connection to the database.
Driver implements driver.Connector interface.
Driver returns &MySQLDriver{}.
*T : database/sql/driver.Connector
ConvertValue mirrors the reference/default converter in database/sql/driver
with _one_ exception. We support uint64 with their high bit and the default
implementation does not. This function should be kept in sync with
database/sql/driver defaultConverter.ConvertValue() except for that
deliberate difference.
T : database/sql/driver.ValueConverter
Hash password using pre 4.1 (old password) method
https://github.com/atcurtis/mariadb/blob/master/mysys/my_rnd.c
seed1uint32seed2uint32
Tested to be equivalent to MariaDB's floating point variant
http://play.golang.org/p/QHvhd4qved
http://play.golang.org/p/RG0q4ElWDx
func newMyRnd(seed1, seed2 uint32) *myRnd
noCopy may be embedded into structs which must not be copied
after the first use.
See https://github.com/golang/go/issues/8005#issuecomment-190753527
for details.
Lock is a no-op used by -copylocks checker from `go vet`.
for internal use.
the mysql package uses sql.NullTime if it is available.
if not, the package uses mysql.NullTime.
Package-Level Functions (total 56, in which 14 are exported)
DeregisterLocalFile removes the given filepath from the allowlist.
DeregisterReaderHandler removes the ReaderHandler function with
the given name from the registry.
DeregisterServerPubKey removes the public key registered with the given name.
DeregisterTLSConfig removes the tls.Config associated with key.
NewConfig creates a new Config and sets default values.
NewConnector returns new driver.Connector.
ParseDSN parses the DSN string to a Config
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
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.
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 {
...
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 {
...
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 := ioutil.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")
}
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")
SetLogger is used to set the logger for critical errors.
The initial logger is os.Stderr.
callValuerValue returns vr.Value(), with one exception:
If vr.Value is an auto-generated method on a pointer type and the
pointer is nil, it would panic at runtime in the panicwrap
method. Treat it like nil instead.
This is so people can implement driver.Value on value types and
still use nil pointers to those types to mean nil/NULL, just like
string/*string.
This is an exact copy of the same-named unexported function from the
database/sql package.
escapeBytesBackslash escapes []byte with backslashes (\)
This escapes the contents of a string (provided as []byte) by adding backslashes before special
characters, and turning others into specific escape sequences, such as
turning newlines into \n and null bytes into \0.
https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L823-L932
escapeBytesQuotes escapes apostrophes in []byte by doubling them up.
This escapes the contents of a string by doubling up any apostrophes that
it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
effect on the server.
https://github.com/mysql/mysql-server/blob/mysql-5.7.5/mysys/charset.c#L963-L1038
escapeStringBackslash is similar to escapeBytesBackslash but for string.
escapeStringQuotes is similar to escapeBytesQuotes but for string.
parseDSNParams parses the DSN "query string"
Values must be url.QueryEscape'ed
Generate binary hash from byte string using insecure pre 4.1 method
Returns the bool value of the input.
The 2nd return value indicates if the input was a valid bool value
returns the number read, whether the value is NULL and the number of bytes read
returns the string read as a bytes slice, wheter the value is NULL,
the number of bytes read and an error, in case the string is longer than
the input slice
Package-Level Variables (total 49, in which 12 are exported)
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
Various errors the driver might return. Can change between driver versions.
A list of available collations mapped to the internal ID.
To update this map use the following MySQL query:
SELECT COLLATION_NAME, ID FROM information_schema.COLLATIONS WHERE ID<256 ORDER BY ID
Handshake packet have only 1 byte for collation_id. So we can't use collations with ID > 255.
ucs2, utf16, and utf32 can't be used for connection charset.
https://dev.mysql.com/doc/refman/5.7/en/charset-connection.html#charset-connection-impermissible-client-charset
They are commented out to reduce this map.
errBadConnNoWrite is used for connection errors where nothing was sent to the database yet.
If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn
to trigger a resend.
See https://github.com/go-sql-driver/mysql/pull/302
zeroDateTime is used in formatBinaryDateTime to avoid an allocation
if the DATE or DATETIME has the zero value.
It must never be changed.
The current behavior depends on database/sql copying the result.
Package-Level Constants (total 132, none are exported)
The pages are generated with Goldsv0.3.6. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.