-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
53 lines (47 loc) · 1.39 KB
/
db.go
File metadata and controls
53 lines (47 loc) · 1.39 KB
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
package main
// db module
//
// Copyright (c) 2023 - Valentin Kuznetsov <vkuznet@gmail.com>
//
import (
"errors"
"time"
srvConfig "github.com/CHESSComputing/golib/config"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func initDB(dbKind string) (*gorm.DB, error) {
var db *gorm.DB
var err error
dbConfig := &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
}
if srvConfig.Config.Authz.WebServer.Verbose == 0 {
dbConfig = &gorm.Config{}
}
if dbKind == "mysql" {
// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
// dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(srvConfig.Config.Authz.DBUri), dbConfig)
} else if dbKind == "sqlite" {
db, err = gorm.Open(sqlite.Open(srvConfig.Config.Authz.DBUri), dbConfig)
} else {
return nil, errors.New("Unsupported database")
}
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)
return db, nil
}