Files
sponge/pkg/mysql/option.go
2022-11-21 22:12:49 +08:00

91 lines
2.1 KiB
Go

package mysql
import (
"time"
)
// Option set the mysql options.
type Option func(*options)
type options struct {
isLog bool
slowThreshold time.Duration
maxIdleConns int
maxOpenConns int
connMaxLifetime time.Duration
disableForeignKey bool
enableTrace bool
}
func (o *options) apply(opts ...Option) {
for _, opt := range opts {
opt(o)
}
}
// default settings
func defaultOptions() *options {
return &options{
isLog: false, // whether to output logs, default off
slowThreshold: time.Duration(0), // if greater than 0, only print logs that are longer than the threshold, higher priority than isLog
maxIdleConns: 3, // set the maximum number of connections in the idle connection pool
maxOpenConns: 50, // set the maximum number of open database connections
connMaxLifetime: 30 * time.Minute, // sets the maximum amount of time a connection can be reused
disableForeignKey: true, // disables the use of foreign keys, true is recommended for production environments, enabled by default
enableTrace: false, // whether to enable link tracing, default is off
}
}
// WithLog set log sql
func WithLog() Option {
return func(o *options) {
o.isLog = true
}
}
// WithSlowThreshold Set sql values greater than the threshold
func WithSlowThreshold(d time.Duration) Option {
return func(o *options) {
o.slowThreshold = d
}
}
// WithMaxIdleConns set max idle conns
func WithMaxIdleConns(size int) Option {
return func(o *options) {
o.maxIdleConns = size
}
}
// WithMaxOpenConns set max open conns
func WithMaxOpenConns(size int) Option {
return func(o *options) {
o.maxOpenConns = size
}
}
// WithConnMaxLifetime set conn max lifetime
func WithConnMaxLifetime(t time.Duration) Option {
return func(o *options) {
o.connMaxLifetime = t
}
}
// WithEnableForeignKey use foreign keys
func WithEnableForeignKey() Option {
return func(o *options) {
o.disableForeignKey = false
}
}
// WithEnableTrace use trace
func WithEnableTrace() Option {
return func(o *options) {
o.enableTrace = true
}
}