-
Notifications
You must be signed in to change notification settings - Fork 1
/
reference.go
389 lines (332 loc) · 8.62 KB
/
reference.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Package mongo
package mongo
import (
"context"
"fmt"
"reflect"
"strings"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const foreignKeyErrStr = "foreign keys must use mongo.Foreign[ForeignCollectionStruct] or mongo.Foreign[ForeignList]"
// refQ Mongo ref query
type refQ struct {
From string
Ref *Reference
DB *Database
Query *Query
}
func (q *refQ) getData(colName string) ([]interface{}, int) {
if q.DB == nil {
panic("refQ collection can not nil")
}
if q.Ref == nil {
panic("refQ ref can not nil")
}
if q.From == "" {
panic("from can not empty")
}
c := q.Query.Cond()
if len(c) <= 0 {
panic("refQ ORM can not Empty")
}
ref := q.Ref.getRef(q.From, colName)
if ref == nil {
panic("refQ ref data can not nil")
}
collection := q.DB.Collection(ref.To)
opt := NewFindOptions()
opt.Select([]string{"_id"})
var idData []map[string]interface{}
err := collection.FindDocs(q.DB.ctx, q.Query, &idData, opt)
if err != nil {
panic(err)
}
arr := []interface{}{}
for _, v := range idData {
arr = append(arr, v["_id"])
}
return arr, ref.RefType
}
type dataType interface{}
// Foreign mongotool 外键
// tag: `bson "test" json:"test" ref:"def"` ref values [def, all, match]
// def: 有交集即可;all:所有的外键均存在;match:所有的外键均存在,并且与条件完全一致
type Foreign[T dataType] struct {
Ref string `bson:"$ref" json:"ref"`
ID ObjectID `bson:"$id" json:"id"`
}
// ForeignList mongotool 外键数组
// tag: `bson "test" json:"test" ref:"def"` ref values [def, all, match]
// def: 有交集即可;all:所有的外键均存在;match:所有的外键均存在,并且与条件完全一致
type ForeignList[T dataType] []*Foreign[T]
func (r *Foreign[T]) ToData(ctx context.Context, db *Database, data interface{}) error {
if r.Ref == "" || ObjectIDIsZero(r.ID) {
return nil
}
collection := db.Collection(r.Ref)
opt := NewFindOneOptions()
q := MixQ(map[string]interface{}{
"_id": r.ID,
})
err := collection.FindOne(ctx, q, data, opt)
if err != nil {
return err
}
return nil
}
func (r *Foreign[T]) GetData(ctx context.Context, db *Database) (*T, error) {
var d T
err := r.ToData(ctx, db, &d)
if err != nil {
return nil, err
}
return &d, nil
}
func (r ForeignList[T]) ToData(ctx context.Context, db *Database, data interface{}) error {
if len(r) <= 0 {
return nil
}
collectionName := ""
var ids []primitive.ObjectID
for _, ref := range r {
if ref.Ref != "" {
collectionName = ref.Ref
}
if !ObjectIDIsZero(ref.ID) {
ids = append(ids, ref.ID)
}
}
if collectionName == "" || len(ids) <= 0 {
return nil
}
collection := db.Collection(collectionName)
opt := NewFindOptions()
q := MixQ(map[string]interface{}{
"_id__in": ids,
})
err := collection.FindDocs(ctx, q, data, opt)
if err != nil {
return err
}
return nil
}
func (r ForeignList[T]) GetData(ctx context.Context, db *Database) ([]*T, error) {
var arr []*T
err := r.ToData(ctx, db, &arr)
if err != nil {
return nil, err
}
return arr, nil
}
// Reference 表定义
type Reference struct {
tableDef map[string]reflect.Type
tableRef map[string]map[string]*refType
structToTable map[string]string
}
const (
mongoRefDefault = 1
mongoRefAll = 2
mongoRefMatch = 3
)
// 关联类型
type refType struct {
To string
RefType int // 1: def; 2: all; 3: match
}
func NewReference() *Reference {
ref := new(Reference)
ref.tableDef = map[string]reflect.Type{}
ref.tableRef = map[string]map[string]*refType{}
ref.structToTable = map[string]string{}
return ref
}
func (r *Reference) getTableName(structFullName string) string {
return r.structToTable[structFullName]
}
func (r *Reference) AddTableDef(tbName string, def interface{}) {
if _, ok := r.tableDef[tbName]; ok {
panic(fmt.Sprintf("collection [%s] is already in def", tbName))
}
tp := reflect.TypeOf(def)
if tp.Kind() != reflect.Struct {
panic(fmt.Sprintf("collection [%s] type must be struct", tbName))
}
structFullName := fmt.Sprintf("%s.%s", tp.PkgPath(), tp.Name())
if _, ok := r.structToTable[structFullName]; ok {
panic(fmt.Sprintf("table [%s] struct [%s] is exist", tbName, structFullName))
}
r.structToTable[structFullName] = tbName
r.tableDef[tbName] = tp
for i := 0; i < tp.NumField(); i++ {
colName := tp.Field(i).Tag.Get("bson")
if colName == "" || !tp.Field(i).IsExported() {
continue
}
ref := tp.Field(i).Tag.Get("ref")
if ref != "" {
t := mongoRefDefault
if ref == "all" {
t = mongoRefAll
} else if ref == "match" {
t = mongoRefMatch
}
colType := tp.Field(i).Type
if colType.Kind() == reflect.Ptr {
colType = colType.Elem()
}
foreignName := colType.String()
first, second := strings.Index(foreignName, "["), strings.Index(foreignName, "]")
if first < 0 || second < 0 || second <= first {
panic(foreignKeyErrStr)
}
foreignName = foreignName[first+1 : second]
if foreignName == "" {
panic(foreignKeyErrStr)
}
if foreignName[0] == '*' {
panic(foreignKeyErrStr)
}
if _, ok := r.tableRef[tbName]; ok {
r.tableRef[tbName][colName] = &refType{
To: foreignName,
RefType: t,
}
} else {
r.tableRef[tbName] = map[string]*refType{
colName: {
To: foreignName,
RefType: t,
},
}
}
}
}
}
func (r *Reference) BuildRefs() {
for _, refMap := range r.tableRef {
for _, ref := range refMap {
errStr := fmt.Sprintf("table[%s] not be defined", ref.To)
ref.To = r.structToTable[ref.To]
if ref.To == "" {
panic(errStr)
}
}
}
}
func (r *Reference) getDef(tbName string) reflect.Type {
if def, ok := r.tableDef[tbName]; ok {
return def
}
return nil
}
func (r *Reference) getRef(tbName string, colName string) *refType {
if q, ok := r.tableRef[tbName]; ok {
if ref, has := q[colName]; has {
return ref
}
}
return nil
}
func ToRefData[T dataType](r *Reference, data *T) (*Foreign[T], error) {
valValue := reflect.ValueOf(data)
if data == nil || valValue.IsNil() {
return nil, fmt.Errorf("data type must be *struct")
}
if valValue.Kind() != reflect.Ptr {
return nil, fmt.Errorf("data type must be *struct")
}
valValue = valValue.Elem()
valType := valValue.Type()
if valType.Kind() != reflect.Struct {
return nil, fmt.Errorf("data type must be *struct")
}
structFullName := fmt.Sprintf("%s.%s", valType.PkgPath(), valType.Name())
tbName := r.getTableName(structFullName)
if tbName == "" {
return nil, fmt.Errorf("struct[%s] is undefined", structFullName)
}
var objID ObjectID
var err error
for i := 0; i < valValue.NumField(); i++ {
if valValue.Type().Field(i).Tag.Get("bson") == "_id" {
if valValue.Field(i).Kind() == reflect.String {
refID := valValue.Field(i).String()
objID, err = primitive.ObjectIDFromHex(refID)
if err != nil {
return nil, err
}
} else {
b := valValue.Field(i).Bytes()
copy(objID[:], b)
}
break
}
}
if ObjectIDIsZero(objID) {
return nil, fmt.Errorf("ObjectID is zero")
}
return &Foreign[T]{
Ref: tbName,
ID: objID,
}, nil
}
type refListType[T dataType] interface {
[]*T | []T
}
func ToRefListData[T dataType, DT refListType[T]](r *Reference, data DT) (ForeignList[T], error) {
valValue := reflect.ValueOf(data)
if data == nil || valValue.IsNil() {
return nil, fmt.Errorf("data type must be slice of [*]struct")
}
if valValue.Kind() != reflect.Slice {
return nil, fmt.Errorf("data type must be slice of [*]struct")
}
if valValue.Len() <= 0 {
return nil, nil
}
refList := ForeignList[T]{}
if strings.Contains(reflect.TypeOf(refList).Name(), "*") {
return nil, fmt.Errorf("generic type cannot be a pointer")
}
for i := 0; i < valValue.Len(); i++ {
elem := valValue.Index(i)
structName := ""
if elem.Type().Kind() == reflect.Ptr {
elem = elem.Elem()
}
if elem.Type().Kind() != reflect.Struct {
return nil, fmt.Errorf("data type must be slice of [*]struct")
}
structName = fmt.Sprintf("%s.%s", elem.Type().PkgPath(), elem.Type().Name())
tbName := r.getTableName(structName)
if tbName == "" {
return nil, fmt.Errorf("struct[%s] is undefined", structName)
}
var objID ObjectID
var err error
for j := 0; j < elem.NumField(); j++ {
if elem.Type().Field(j).Tag.Get("bson") == "_id" {
if elem.Field(j).Kind() == reflect.String {
refID := elem.Field(j).String()
objID, err = primitive.ObjectIDFromHex(refID)
if err != nil {
return nil, err
}
} else {
b := elem.Field(j).Bytes()
copy(objID[:], b)
}
break
}
}
if ObjectIDIsZero(objID) {
return nil, fmt.Errorf("ObjectID is zero")
}
refList = append(refList, &Foreign[T]{
Ref: tbName,
ID: objID,
})
}
return refList, nil
}