/
dao.go
104 lines (88 loc) · 2.38 KB
/
dao.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package comm
import (
"fmt"
"time"
"github.com/easysoft/zendata/cmd/test/others/func/model"
"github.com/fatih/color"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/plugin/dbresolver"
)
const (
dbUser = "root"
dbUrl = "127.0.0.1:3306"
dbPasswd = "P2ssw0rd"
dbName = "zendata"
)
var (
DB *gorm.DB
)
func GetDB() *gorm.DB {
if DB != nil {
return DB
}
DB = GormMySQL()
_ = DB.Use(
dbresolver.Register(
dbresolver.Config{}).
SetConnMaxIdleTime(time.Hour).
SetConnMaxLifetime(24 * time.Hour).
SetMaxIdleConns(100).
SetMaxOpenConns(200),
)
DB.Session(&gorm.Session{FullSaveAssociations: true, AllowGlobalUpdate: false})
err := DB.AutoMigrate(
&model.DataCategory1{},
&model.DataCategory2{},
&model.DataFood{},
&model.DataAnimalPlant{},
&model.DataAnimalPlant{},
&model.DataFruit{},
&model.DataConstellation{},
&model.DataZodiac{},
&model.EightDiagram{},
&model.Dynasty{},
&model.CarBrand{},
&model.CarComponent{},
&model.PcOs{},
&model.PcFileExt{},
&model.PhoneModel{},
&model.Place{},
&model.Song{},
&model.Bank{},
&model.Advert{},
&model.IdiomSimple{},
&model.PoetryAncient{},
&model.PoetryCategory{},
&model.Medicine{},
&model.Joke{},
&model.AreaCodeCity{},
&model.AreaCodeCountry{},
)
if err != nil {
fmt.Printf(color.RedString("migrate models failed, error: %s.", err.Error()))
}
return DB
}
func GormMySQL() *gorm.DB {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s", dbUser, dbPasswd, dbUrl, dbName, "charset=utf8mb4&parseTime=True&loc=Local")
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
}); err != nil {
return nil
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(0)
sqlDB.SetMaxOpenConns(0)
return db
}
}