-
Notifications
You must be signed in to change notification settings - Fork 27
/
db.go
45 lines (42 loc) · 1.12 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
// Package service
// Date: 2024/3/6 11:08
// Author: Amu
// Description:
package service
import (
"strings"
"github.com/amuluze/amprobe/service/model"
"github.com/amuluze/amutool/database"
)
func NewDB(config *Config, models *model.Models) (*database.DB, error) {
if config.Gorm.GenDoc {
return nil, nil
}
gormConfig := config.Gorm
dbConfig := config.DB
db, err := database.NewDB(
database.WithDebug(gormConfig.Debug),
database.WithType(gormConfig.DBType),
database.WithHost(dbConfig.Host),
database.WithPort(dbConfig.Port),
database.WithUsername(dbConfig.User),
database.WithPassword(dbConfig.Password),
database.WithDBName(dbConfig.DBName),
database.WithMaxLifetime(gormConfig.MaxLifetime),
database.WithMaxOpenConns(gormConfig.MaxOpenConns),
database.WithMaxIdleConns(gormConfig.MaxIdleConns),
)
if err != nil {
return nil, err
}
if gormConfig.EnableAutoMigrate {
if dbType := gormConfig.DBType; strings.ToLower(dbType) == "mysql" {
db.Set("gorm:table_options", "ENGINE=InnoDB")
}
err := db.AutoMigrate(models.GetAllModels()...)
if err != nil {
return nil, err
}
}
return db, nil
}