Allow reuse of an existing db connection when creating a MySQL Store

This commit is contained in:
DGivney
2022-10-10 16:50:34 +11:00
parent 4e6f1c95ff
commit e5eb169055
3 changed files with 39 additions and 11 deletions

View File

@@ -51,8 +51,16 @@ store := mysql.New(mysql.Config{
})
// Initialize custom config using connection string
store := postgres.New(postgres.Config{
ConnectionURI: "mysql://user:password@localhost:3306/fiber"
store := mysql.New(mysql.Config{
ConnectionURI: "<username>:<pw>@tcp(<HOST>:<port>)/<dbname>"
Reset: false,
GCInterval: 10 * time.Second,
})
// Initialize custom config using sql db connection
db, _ := sql.Open("mysql", "<username>:<pw>@tcp(<HOST>:<port>)/<dbname>")
store := mysql.New(mysql.Config{
Db: db,
Reset: false,
GCInterval: 10 * time.Second,
})
@@ -61,6 +69,11 @@ store := postgres.New(postgres.Config{
### Config
```go
type Config struct {
// DB Will override ConnectionURI and all other authentication values if used
//
// Optional. Default is nil
Db *sql.DB
// Connection string to use for DB. Will override all other authentication values if used
//
// Optional. Default is ""

View File

@@ -1,12 +1,18 @@
package mysql
import (
"database/sql"
"fmt"
"time"
)
// Config defines the config for storage.
type Config struct {
// DB Will override ConnectionURI and all other authentication values if used
//
// Optional. Default is nil
Db *sql.DB
// Connection string to use for DB. Will override all other authentication values if used
//
// Optional. Default is ""
@@ -63,6 +69,7 @@ type Config struct {
// ConfigDefault is the default config
var ConfigDefault = Config{
Db: nil,
ConnectionURI: "",
Host: "127.0.0.1",
Port: 3306,

View File

@@ -40,19 +40,27 @@ var (
// New creates a new storage
func New(config ...Config) *Storage {
var err error
var db *sql.DB
// Set default config
cfg := configDefault(config...)
// Create db
db, err := sql.Open("mysql", cfg.dsn())
if err != nil {
panic(err)
}
if cfg.Db != nil {
// Use passed db
db = cfg.Db
} else {
// Create db
db, err = sql.Open("mysql", cfg.dsn())
if err != nil {
panic(err)
}
// Set options
db.SetMaxOpenConns(cfg.maxOpenConns)
db.SetMaxIdleConns(cfg.maxIdleConns)
db.SetConnMaxLifetime(cfg.connMaxLifetime)
// Set options
db.SetMaxOpenConns(cfg.maxOpenConns)
db.SetMaxIdleConns(cfg.maxIdleConns)
db.SetConnMaxLifetime(cfg.connMaxLifetime)
}
// Ping database to ensure a connection has been made
if err := db.Ping(); err != nil {