mirror of
https://github.com/gofiber/storage.git
synced 2025-10-06 09:07:14 +08:00
Allow reuse of an existing db connection when creating a MySQL Store
This commit is contained in:
@@ -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 ""
|
||||
|
@@ -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,
|
||||
|
@@ -40,11 +40,18 @@ var (
|
||||
|
||||
// New creates a new storage
|
||||
func New(config ...Config) *Storage {
|
||||
var err error
|
||||
var db *sql.DB
|
||||
|
||||
// Set default config
|
||||
cfg := configDefault(config...)
|
||||
|
||||
if cfg.Db != nil {
|
||||
// Use passed db
|
||||
db = cfg.Db
|
||||
} else {
|
||||
// Create db
|
||||
db, err := sql.Open("mysql", cfg.dsn())
|
||||
db, err = sql.Open("mysql", cfg.dsn())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -53,6 +60,7 @@ func New(config ...Config) *Storage {
|
||||
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 {
|
||||
|
Reference in New Issue
Block a user