-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
db.go
86 lines (71 loc) 路 1.6 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package db
import (
"database/sql"
"fmt"
"time"
"github.com/cyberhorsey/errors"
"gorm.io/gorm"
)
type DB struct {
gormdb *gorm.DB
}
func (db *DB) DB() (*sql.DB, error) {
return db.gormdb.DB()
}
func (db *DB) GormDB() *gorm.DB {
return db.gormdb
}
func New(gormdb *gorm.DB) *DB {
return &DB{
gormdb: gormdb,
}
}
var (
ErrNoDB = errors.Validation.NewWithKeyAndDetail("ERR_NO_DB", "DB is required")
)
type DBConnectionOpts struct {
Name string
Password string
Host string
Database string
MaxIdleConns uint64
MaxOpenConns uint64
MaxConnLifetime uint64
OpenFunc func(dsn string) (*DB, error)
}
func OpenDBConnection(opts DBConnectionOpts) (*DB, error) {
dsn := ""
if opts.Password == "" {
dsn = fmt.Sprintf(
"%v@tcp(%v)/%v?charset=utf8mb4&parseTime=True&loc=%v",
opts.Name,
opts.Host,
opts.Database,
"UTC",
)
} else {
dsn = fmt.Sprintf(
"%v:%v@tcp(%v)/%v?charset=utf8mb4&parseTime=True&loc=%v",
opts.Name,
opts.Password,
opts.Host,
opts.Database,
"UTC",
)
}
db, err := opts.OpenFunc(dsn)
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(int(opts.MaxOpenConns))
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(int(opts.MaxIdleConns))
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Duration(opts.MaxConnLifetime))
return db, nil
}