/
association.go
268 lines (220 loc) · 5.79 KB
/
association.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
package rel
import (
"reflect"
"sync"
"github.com/serenize/snaker"
)
// AssociationType defines the type of association in database.
type AssociationType uint8
const (
// BelongsTo association.
BelongsTo = iota
// HasOne association.
HasOne
// HasMany association.
HasMany
)
type associationKey struct {
rt reflect.Type
index int
}
type associationData struct {
typ AssociationType
targetIndex []int
referenceField string
referenceIndex int
foreignField string
foreignIndex int
through string
autoload bool
autosave bool
}
var associationCache sync.Map
// Association provides abstraction to work with association of document or collection.
type Association struct {
data associationData
rv reflect.Value
}
// Type of association.
func (a Association) Type() AssociationType {
return a.data.typ
}
// Document returns association target as document.
// If association is zero, second return value will be false.
func (a Association) Document() (*Document, bool) {
return a.document(false)
}
// LazyDocument is a lazy version of Document.
// If rv is a null pointer, it returns a document that delays setting the value of rv
// until Document#Add() is called.
func (a Association) LazyDocument() (*Document, bool) {
return a.document(true)
}
func (a Association) document(lazy bool) (*Document, bool) {
var (
rv = a.rv.FieldByIndex(a.data.targetIndex)
)
switch rv.Kind() {
case reflect.Ptr:
if rv.IsNil() {
if !lazy {
rv.Set(reflect.New(rv.Type().Elem()))
}
return NewDocument(rv), false
}
var (
doc = NewDocument(rv)
)
return doc, doc.Persisted()
default:
var (
doc = NewDocument(rv.Addr())
)
return doc, doc.Persisted()
}
}
// Collection returns association target as collection.
// If association is zero, second return value will be false.
func (a Association) Collection() (*Collection, bool) {
var (
rv = a.rv.FieldByIndex(a.data.targetIndex)
loaded = !rv.IsNil()
)
if rv.Kind() == reflect.Ptr {
if !loaded {
rv.Set(reflect.New(rv.Type().Elem()))
rv.Elem().Set(reflect.MakeSlice(rv.Elem().Type(), 0, 0))
}
return NewCollection(rv), loaded
}
if !loaded {
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
}
return NewCollection(rv.Addr()), loaded
}
// IsZero returns true if association is not loaded.
func (a Association) IsZero() bool {
var (
rv = a.rv.FieldByIndex(a.data.targetIndex)
)
return isDeepZero(reflect.Indirect(rv), 1)
}
// ReferenceField of the association.
func (a Association) ReferenceField() string {
return a.data.referenceField
}
// ReferenceValue of the association.
func (a Association) ReferenceValue() interface{} {
return indirect(a.rv.Field(a.data.referenceIndex))
}
// ForeignField of the association.
func (a Association) ForeignField() string {
return a.data.foreignField
}
// ForeignValue of the association.
// It'll panic if association type is has many.
func (a Association) ForeignValue() interface{} {
if a.Type() == HasMany {
panic("rel: cannot infer foreign value for has many or many to many association")
}
var (
rv = a.rv.FieldByIndex(a.data.targetIndex)
)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
return indirect(rv.Field(a.data.foreignIndex))
}
// Through return intermediary association.
func (a Association) Through() string {
return a.data.through
}
// Autoload assoc setting when parent is loaded.
func (a Association) Autoload() bool {
return a.data.autoload
}
// Autosave setting when parent is created/updated/deleted.
func (a Association) Autosave() bool {
return a.data.autosave
}
func newAssociation(rv reflect.Value, index int) Association {
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
return Association{
data: extractAssociationData(rv.Type(), index),
rv: rv,
}
}
func extractAssociationData(rt reflect.Type, index int) associationData {
var (
key = associationKey{
rt: rt,
index: index,
}
)
if val, cached := associationCache.Load(key); cached {
return val.(associationData)
}
var (
sf = rt.Field(index)
ft = sf.Type
ref = sf.Tag.Get("ref")
fk = sf.Tag.Get("fk")
fName = fieldName(sf)
assocData = associationData{
targetIndex: sf.Index,
through: sf.Tag.Get("through"),
autoload: sf.Tag.Get("auto") == "true" || sf.Tag.Get("autoload") == "true",
autosave: sf.Tag.Get("auto") == "true" || sf.Tag.Get("autosave") == "true",
}
)
if assocData.autosave && assocData.through != "" {
panic("rel: autosave is not supported for has one/has many through association")
}
for ft.Kind() == reflect.Ptr || ft.Kind() == reflect.Slice {
ft = ft.Elem()
}
var (
refDocData = extractDocumentData(rt, true)
fkDocData = extractDocumentData(ft, true)
)
// Try to guess ref and fk if not defined.
if ref == "" || fk == "" {
// TODO: replace "id" with inferred primary field
if assocData.through != "" {
ref = "id"
fk = "id"
} else if _, isBelongsTo := refDocData.index[fName+"_id"]; isBelongsTo {
ref = fName + "_id"
fk = "id"
} else {
ref = "id"
fk = snaker.CamelToSnake(rt.Name()) + "_id"
}
}
if id, exist := refDocData.index[ref]; !exist {
panic("rel: references (" + ref + ") field not found ")
} else {
assocData.referenceIndex = id
assocData.referenceField = ref
}
if id, exist := fkDocData.index[fk]; !exist {
panic("rel: foreign_key (" + fk + ") field not found")
} else {
assocData.foreignIndex = id
assocData.foreignField = fk
}
// guess assoc type
if sf.Type.Kind() == reflect.Slice || (sf.Type.Kind() == reflect.Ptr && sf.Type.Elem().Kind() == reflect.Slice) {
assocData.typ = HasMany
} else {
if len(assocData.referenceField) > len(assocData.foreignField) {
assocData.typ = BelongsTo
} else {
assocData.typ = HasOne
}
}
associationCache.Store(key, assocData)
return assocData
}