-
Notifications
You must be signed in to change notification settings - Fork 2
/
meta.go
417 lines (354 loc) · 10.2 KB
/
meta.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package goen
import (
"encoding"
"encoding/hex"
"fmt"
"reflect"
"strings"
"sync"
"github.com/kamichidu/goen/internal"
)
// MetaTable represents a table meta info.
type MetaTable interface {
// Type gets go struct type associated with this table.
Type() reflect.Type
// TableName gets a table name.
TableName() string
// PrimaryKey gets primary key meta columns.
PrimaryKey() []MetaColumn
// ReferenceKeys gets all reference meta columns by other entities.
ReferenceKeys() [][]MetaColumn
// Columns gets all meta columns of this table.
Columns() []MetaColumn
}
type metaTable struct {
typ reflect.Type
tableName string
primaryKey []MetaColumn
referenceKeys [][]MetaColumn
columns []MetaColumn
}
func (m *metaTable) Type() reflect.Type {
return m.typ
}
func (m *metaTable) TableName() string {
return m.tableName
}
func (m *metaTable) PrimaryKey() []MetaColumn {
return m.primaryKey
}
func (m *metaTable) ReferenceKeys() [][]MetaColumn {
return m.referenceKeys
}
func (m *metaTable) Columns() []MetaColumn {
return m.columns
}
var _ MetaTable = (*metaTable)(nil)
// MetaColumn represents a column meta info.
type MetaColumn interface {
// Field gets go struct field associated with this column.
Field() reflect.StructField
// OmitEmpty indicates this column allowing to omit column specifier on a insert statement.
OmitEmpty() bool
// PartOfPrimaryKey indicates this column is part of primary key of the table.
PartOfPrimaryKey() bool
// ColumnName gets this column name.
ColumnName() string
}
type metaColumn struct {
field reflect.StructField
omitEmpty bool
partOfPrimaryKey bool
columnName string
}
func (m *metaColumn) Field() reflect.StructField {
return m.field
}
func (m *metaColumn) OmitEmpty() bool {
return m.omitEmpty
}
func (m *metaColumn) PartOfPrimaryKey() bool {
return m.partOfPrimaryKey
}
func (m *metaColumn) ColumnName() string {
return m.columnName
}
var _ MetaColumn = (*metaColumn)(nil)
// MetaSchema manages meta schemata computed by struct (tags).
// Provide some utility functions for using with DBContext.
type MetaSchema interface {
// Register adds given object type to this MetaSchema.
Register(entity interface{})
// Compute computes meta schemata for registered entities.
Compute()
// LoadOf gets meta schema of table that associated with given entity.
LoadOf(entity interface{}) MetaTable
// KeyStringFromRowKey gets identity string for given RowKey.
KeyStringFromRowKey(RowKey) string
// PrimaryKeyOf gets RowKey that represents given entity.
PrimaryKeyOf(entity interface{}) RowKey
// ReferenceKeysOf gets reference RowKey by other entities.
ReferenceKeysOf(entity interface{}) []RowKey
// InsertPatchOf gets a patch that represents insert statement.
InsertPatchOf(entity interface{}) *Patch
// UpdatePatchOf gets a patch that represents update statement.
UpdatePatchOf(entity interface{}) *Patch
// DeletePatchOf gets a patch that represents delete statement.
DeletePatchOf(entity interface{}) *Patch
}
type metaSchema struct {
typlist []reflect.Type
once sync.Once
built *sync.Map
}
// NewMetaSchema creates new MetaSchema object.
func NewMetaSchema() MetaSchema {
return new(metaSchema)
}
func (m *metaSchema) KeyStringFromRowKey(rowKey RowKey) string {
m.Compute()
cols, vals := rowKey.RowKey()
params := make([]string, len(cols))
for i := range cols {
var valStr string
perr := safeDo(func() {
if m, ok := vals[i].(encoding.TextMarshaler); ok {
if b, err := m.MarshalText(); err != nil {
panic(err)
} else {
valStr = string(b)
}
} else if m, ok := vals[i].(encoding.BinaryMarshaler); ok {
if b, err := m.MarshalBinary(); err != nil {
panic(err)
} else {
valStr = hex.EncodeToString(b)
}
} else {
valStr = fmt.Sprint(vals[i])
}
})
if perr != nil {
valStr = perr.Error()
}
params[i] = cols[i] + "=" + valStr
}
return rowKey.TableName() + ";" + strings.Join(params, ";")
}
func (m *metaSchema) PrimaryKeyOf(entity interface{}) RowKey {
m.Compute()
metaT := m.LoadOf(entity)
rv := reflect.ValueOf(entity)
rv = reflect.Indirect(rv)
rowKey := &MapRowKey{}
rowKey.Table = metaT.TableName()
rowKey.Key = map[string]interface{}{}
for _, pk := range metaT.PrimaryKey() {
rfv := rv.FieldByName(pk.Field().Name)
rowKey.Key[pk.ColumnName()] = rfv.Interface()
}
return rowKey
}
func (m *metaSchema) ReferenceKeysOf(entity interface{}) []RowKey {
m.Compute()
metaT := m.LoadOf(entity)
rv := reflect.ValueOf(entity)
rv = reflect.Indirect(rv)
var refes []RowKey
for _, refeKey := range metaT.ReferenceKeys() {
refe := &MapRowKey{}
refe.Table = metaT.TableName()
refe.Key = map[string]interface{}{}
for _, col := range refeKey {
rfv := rv.FieldByName(col.Field().Name)
refe.Key[col.ColumnName()] = rfv.Interface()
}
refes = append(refes, refe)
}
return refes
}
func (m *metaSchema) LoadOf(entity interface{}) MetaTable {
m.Compute()
typ := m.typeOf(entity)
if metaT, ok := m.built.Load(typ); ok {
return metaT.(MetaTable)
} else {
panic("goen: not registered type of " + typ.String())
}
}
func (m *metaSchema) InsertPatchOf(entity interface{}) *Patch {
metaT := m.LoadOf(entity)
var (
cols = make([]string, 0, len(metaT.Columns()))
vals = make([]interface{}, 0, len(metaT.Columns()))
)
rv := reflect.ValueOf(entity)
rv = reflect.Indirect(rv)
for _, metaC := range metaT.Columns() {
rfv := rv.FieldByName(metaC.Field().Name)
if !rfv.IsValid() || metaC.OmitEmpty() && isEmptyValue(rfv) {
continue
}
cols = append(cols, metaC.ColumnName())
vals = append(vals, rfv.Interface())
}
return &Patch{
Kind: PatchInsert,
TableName: metaT.TableName(),
Columns: cols,
Values: vals,
}
}
func (m *metaSchema) UpdatePatchOf(entity interface{}) *Patch {
metaT := m.LoadOf(entity)
var (
cols = make([]string, 0, len(metaT.Columns()))
vals = make([]interface{}, 0, len(metaT.Columns()))
)
rv := reflect.ValueOf(entity)
rv = reflect.Indirect(rv)
for _, metaC := range metaT.Columns() {
// non-pk columns appears in set clause
if metaC.PartOfPrimaryKey() {
continue
}
rfv := rv.FieldByName(metaC.Field().Name)
if !rfv.IsValid() || metaC.OmitEmpty() && isEmptyValue(rfv) {
continue
}
cols = append(cols, metaC.ColumnName())
vals = append(vals, rfv.Interface())
}
return &Patch{
Kind: PatchUpdate,
TableName: metaT.TableName(),
Columns: cols,
Values: vals,
// update only given entitty filtered by its primary key
RowKey: m.PrimaryKeyOf(entity),
}
}
func (m *metaSchema) DeletePatchOf(entity interface{}) *Patch {
metaT := m.LoadOf(entity)
return &Patch{
Kind: PatchDelete,
TableName: metaT.TableName(),
// delete only given entitty filtered by its primary key
RowKey: m.PrimaryKeyOf(entity),
}
}
func (m *metaSchema) typeOf(entity interface{}) reflect.Type {
typ := reflect.TypeOf(entity)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
panic("goen: not a struct type")
}
return typ
}
func (m *metaSchema) Register(entity interface{}) {
if m.built != nil {
panic("goen: already computed meta tables")
}
m.typlist = append(m.typlist, m.typeOf(entity))
}
func (m *metaSchema) Compute() {
m.once.Do(func() {
m.built = new(sync.Map)
for _, typ := range m.typlist {
metaT := m.computeOf(typ)
m.built.Store(typ, metaT)
}
})
}
func elemType(typ reflect.Type) reflect.Type {
for typ.Kind() == reflect.Ptr || typ.Kind() == reflect.Slice {
typ = typ.Elem()
}
return typ
}
func (m *metaSchema) computeOf(typ reflect.Type) MetaTable {
if typ.Kind() != reflect.Struct {
panic("goen: given typ is not a struct")
}
strct := internal.NewStructFromReflect(typ)
tbl := &metaTable{
typ: typ,
tableName: internal.TableName(strct),
}
fields := internal.FieldsByFunc(strct.Fields(), internal.IsColumnField)
for _, field := range fields {
isPrimaryKey := internal.IsPrimaryKeyField(field)
col := &metaColumn{
field: field.Value().(reflect.StructField),
partOfPrimaryKey: isPrimaryKey,
columnName: internal.ColumnName(field),
omitEmpty: internal.OmitEmpty(field),
}
if isPrimaryKey {
tbl.primaryKey = append(tbl.primaryKey, col)
}
tbl.columns = append(tbl.columns, col)
}
// collect reference keys by other entities
// it includes typ myself for self-referential
for _, refeTyp := range m.typlist {
refeTyp = elemType(refeTyp)
refeStrct := internal.NewStructFromReflect(refeTyp)
// expected field types is one of:
// - []*RefeTyp
// - []RefeTyp
// - *RefeTyp
// - RefeTyp
refeFields := internal.FieldsByFunc(refeStrct.Fields(), func(refeField internal.StructField) bool {
if internal.IsIgnoredField(refeField) {
return false
} else if !internal.IsForeignKeyField(refeField) {
return false
}
refeFieldTyp := refeField.Type().Value().(reflect.Type)
refeFieldTyp = elemType(refeFieldTyp)
return refeFieldTyp == typ
})
// referenceKey is typ's table column list
// so we collect them by foreign key struct tag
for _, refeField := range refeFields {
var key []MetaColumn
refeKey := internal.ReferenceKey(refeField)
for _, refeColName := range refeKey {
foreField, ok := internal.FieldByFunc(strct.Fields(), internal.EqColumnName(refeColName))
if !ok {
// should panic?
continue
}
key = append(key, &metaColumn{
field: foreField.Value().(reflect.StructField),
partOfPrimaryKey: internal.IsPrimaryKeyField(foreField),
columnName: internal.ColumnName(foreField),
omitEmpty: internal.OmitEmpty(foreField),
})
}
tbl.referenceKeys = append(tbl.referenceKeys, key)
}
}
return tbl
}
var _ MetaSchema = (*metaSchema)(nil)
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return false
}