/
db.go
66 lines (53 loc) · 1.35 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
package db
import (
"context"
"sync"
"time"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/wfusion/gofusion/common/infra/drivers/orm"
"github.com/wfusion/gofusion/common/utils"
"github.com/wfusion/gofusion/db/plugins"
)
const (
defaultSlowThreshold = 200 * time.Millisecond
)
var (
rwlock = new(sync.RWMutex)
appInstances map[string]map[string]*Instance
)
type Instance struct {
name string
db *orm.DB
tableShardingPlugins map[string]plugins.TableSharding
}
func (d *Instance) GetProxy() *gorm.DB {
return d.db.GetProxy()
}
type DB struct {
*orm.DB
Name string
tableShardingPlugins map[string]plugins.TableSharding
}
type useOption struct {
appName string
}
func AppName(name string) utils.OptionFunc[useOption] {
return func(o *useOption) {
o.appName = name
}
}
func Use(ctx context.Context, name string, opts ...utils.OptionExtender) *DB {
opt := utils.ApplyOptions[useOption](opts...)
rwlock.RLock()
defer rwlock.RUnlock()
instances, ok := appInstances[opt.appName]
if !ok {
panic(errors.Errorf("db instance not found for app: %s", opt.appName))
}
instance, ok := instances[name]
if !ok {
panic(errors.Errorf("db instance not found for name: %s", name))
}
return &DB{DB: instance.db.WithContext(ctx), Name: name, tableShardingPlugins: instance.tableShardingPlugins}
}