-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
115 lines (97 loc) · 2.33 KB
/
model.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
113
114
115
package model
import (
"github.com/sohaha/zlsgo/zarray"
"github.com/sohaha/zlsgo/zdi"
"github.com/sohaha/zlsgo/zerror"
"github.com/sohaha/zlsgo/zutil"
"github.com/zlsgo/app_core/service"
"github.com/zlsgo/app_module/model/define"
"github.com/zlsgo/zdb"
)
type (
Options struct {
Prefix string
ModelsDefine []define.Define
DisabledMigrator bool
GetDB func() (*zdb.DB, error)
}
)
func New(o ...func(*Options)) (m *Module) {
opt := zutil.Optional(Options{Prefix: "model_", ModelsDefine: make([]define.Define, 0)}, o...)
return &Module{
Options: opt,
ModuleLifeCycle: service.ModuleLifeCycle{
OnDone: func(di zdi.Invoker) error {
return di.InvokeWithErrorOnly(func() (err error) {
var db *zdb.DB
if opt.GetDB == nil {
err = di.Resolve(&db)
} else {
db, err = opt.GetDB()
}
if err != nil {
return zerror.With(err, "get db error")
}
mod := NewModels(di.(zdi.Injector), NewSQL(db, func(o *SQLOptions) {
o.Prefix = m.Options.Prefix
}))
mapper := di.(zdi.TypeMapper)
opers := &Operations{m: zarray.NewHashMap[string, *Operation]()}
for _, d := range opt.ModelsDefine {
if opt.DisabledMigrator {
d.Options.DisabledMigrator = true
}
m, err := mod.Reg(d.Name, d, false)
if err != nil {
return err
}
opers.m.Set(d.Name, m.Operation())
// mapper.Map(d)
}
_ = mapper.Maps(mod, opers)
// m.Models = mod
// m.Operations = mops
return nil
})
},
},
}
}
func (m *Model) Name() string {
return m.model.Name
}
func (m *Model) Alias() string {
return m.alias
}
func (m *Model) Define() define.Define {
return m.model
}
func (m *Model) TableName() string {
return m.tablePrefix + m.model.Table.Name
}
func (m *Model) Migration() Migrationer {
return m.Storage.Migration(m)
}
func (m *Model) GetFields(exclude ...string) []string {
f := m.fullFields
if len(exclude) == 0 {
exclude = m.Define().Options.LowFields
if len(exclude) == 0 {
return f
}
}
return zarray.Filter(f, func(_ int, v string) bool {
return !zarray.Contains(exclude, v)
})
}
func (m *Model) DI() zdi.Injector {
return m.di
}
func (m *Model) hook(name string) error {
// TODO: 钩子
// if m.model.Hook == nil {
// return nil
// }
// return m.model.Hook(name, m)
return nil
}