-
Notifications
You must be signed in to change notification settings - Fork 66
/
db.go
52 lines (42 loc) · 1.06 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
package util
import (
"fmt"
"strings"
"time"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
const DefaultBatchSize int = 100000
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
}
func FindAndProcessLargeRequests(db *gorm.DB, fc func(tx *gorm.DB, batch int) error, dest interface{}, query ...interface{}) (tx *gorm.DB) {
return db.Where(query).FindInBatches(&dest, DefaultBatchSize, fc)
}