-
Notifications
You must be signed in to change notification settings - Fork 66
/
db.go
46 lines (38 loc) · 837 Bytes
/
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
package util
import (
"fmt"
"strings"
"time"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func SetupDatabase(dbval string) (*gorm.DB, error) {
parts := strings.SplitN(dbval, "=", 2)
if len(parts) == 1 {
return nil, fmt.Errorf("format for database string is 'DBTYPE=PARAMS'")
}
var dial gorm.Dialector
switch parts[0] {
case "sqlite":
dial = sqlite.Open(parts[1])
case "postgres":
dial = postgres.Open(parts[1])
default:
return nil, fmt.Errorf("unsupported or unrecognized db type: %s", parts[0])
}
db, err := gorm.Open(dial, &gorm.Config{
SkipDefaultTransaction: true,
})
if err != nil {
return nil, err
}
sqldb, err := db.DB()
if err != nil {
return nil, err
}
sqldb.SetMaxIdleConns(80)
sqldb.SetMaxOpenConns(99)
sqldb.SetConnMaxIdleTime(time.Hour)
return db, nil
}