/
db.go
112 lines (87 loc) · 2.3 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
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
105
106
107
108
109
110
111
112
package mysql
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"github.com/ipfs-force-community/sophon-messager/config"
"github.com/ipfs-force-community/sophon-messager/models/repo"
)
type Repo struct {
*gorm.DB
}
func (d Repo) ActorCfgRepo() repo.ActorCfgRepo {
return newMysqlActorCfgRepo(d.DB)
}
func (d Repo) MessageRepo() repo.MessageRepo {
return newMysqlMessageRepo(d.DB)
}
func (d Repo) AddressRepo() repo.AddressRepo {
return newMysqlAddressRepo(d.DB)
}
func (d Repo) SharedParamsRepo() repo.SharedParamsRepo {
return newMysqlSharedParamsRepo(d.DB)
}
func (d Repo) NodeRepo() repo.NodeRepo {
return newMysqlNodeRepo(d.DB)
}
func (d Repo) AutoMigrate() error {
return d.GetDb().AutoMigrate(mysqlActorCfg{}, mysqlMessage{}, mysqlAddress{}, mysqlSharedParams{}, mysqlNode{})
}
func (d Repo) GetDb() *gorm.DB {
return d.DB
}
func (d Repo) DbClose() error {
// return d.DbClose()
// todo:
return nil
}
func (d Repo) Transaction(cb func(txRepo repo.TxRepo) error) error {
return d.DB.Transaction(func(tx *gorm.DB) error {
txRepo := &TxMysqlRepo{tx}
return cb(txRepo)
})
}
var _ repo.TxRepo = (*TxMysqlRepo)(nil)
type TxMysqlRepo struct {
*gorm.DB
}
func (t *TxMysqlRepo) ActorCfgRepo() repo.ActorCfgRepo {
return newMysqlActorCfgRepo(t.DB)
}
func (t *TxMysqlRepo) SharedParamsRepo() repo.SharedParamsRepo {
return newMysqlSharedParamsRepo(t.DB)
}
func (t *TxMysqlRepo) NodeRepo() repo.NodeRepo {
return newMysqlNodeRepo(t.DB)
}
func (t *TxMysqlRepo) MessageRepo() repo.MessageRepo {
return newMysqlMessageRepo(t.DB)
}
func (t *TxMysqlRepo) AddressRepo() repo.AddressRepo {
return newMysqlAddressRepo(t.DB)
}
func OpenMysql(cfg *config.MySqlConfig) (repo.Repo, error) {
db, err := gorm.Open(mysql.Open(cfg.ConnectionString), &gorm.Config{
// Logger: logger.Default.LogMode(logger.Info), // 日志配置
})
if err != nil {
return nil, fmt.Errorf("[db connection failed] Database name: %s %w", cfg.ConnectionString, err)
}
db.Set("gorm:table_options", "CHARSET=utf8mb4")
if cfg.Debug {
db = db.Debug()
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
sqlDB.SetMaxOpenConns(cfg.MaxOpenConn)
sqlDB.SetMaxIdleConns(cfg.MaxIdleConn)
sqlDB.SetConnMaxLifetime(time.Minute * cfg.ConnMaxLifeTime)
// 使用插件
// db.Use(&TracePlugin{})
return &Repo{
db,
}, nil
}