-
Notifications
You must be signed in to change notification settings - Fork 6
/
tmeta.go
574 lines (483 loc) · 16.4 KB
/
tmeta.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Provides SQL table metadata, enabling select field lists, easy getters,
// relations when using a query builder.
package tmeta
import (
"bytes"
"fmt"
"reflect"
"strings"
)
const tmetaTag = "tmeta"
/*
Some conventions for consistency:
- Names of anything in Go have "Go" in them, names of anything in SQL have "SQL" in them; otherwise
it's really easy to confuse what sort of name you mean, we use both in different cases.
- Fields (of anything - structs or tables) are called "Field", not "Column" or "Col" or anything else.
- The "Name" field on an object is its logical name, e.g. TableInfo.Name, but we don't refer to fields
or relations or anything else using "Name", e.g. it's just a "VersionField", not a "VersionFieldName".
- Any time a reflect.Type is passed around it is assumed it has been dereferenced and any pointers
or interfaces removed. Public functions should take care to derefType() or derefValue() as needed.
*/
// DefaultMeta is a global instance, for convenience.
var DefaultMeta = NewMeta()
// Parse is an alias for DefaultMeta.Parse()
func Parse(i interface{}) error {
return DefaultMeta.Parse(i)
}
// MustParse is an alias for DefaultMeta.MustParse()
func MustParse(i interface{}) {
DefaultMeta.MustParse(i)
}
// NewMeta makes a new Meta.
func NewMeta() *Meta {
return &Meta{
tableInfoMap: make(map[reflect.Type]*TableInfo),
}
}
// Meta knows about your tables and the Go structs they correspond to.
type Meta struct {
tableInfoMap map[reflect.Type]*TableInfo
// NOTE: delay DriverName until we actually need it - a better abstraction might be some sort of Dialect
// DriverName string
}
// TableInfo is the information for a single table.
type TableInfo struct {
name string // the short name for this table, by convention this is often the SQLTableName but not required
sqlName string // SQL table names
goType reflect.Type // underlying Go type (pointer removed)
sqlPKFields []string // SQL primary key field names
pkAutoIncr bool // true if keys are auto-incremented by the database
sqlVersionField string // name of version col, empty disables optimistic locking
RelationMap
// TODO: function to generate new version number? (should increment for number or generate nonce for string)
}
// NewTableInfo makes a new instance.
func NewTableInfo(goType reflect.Type) *TableInfo {
var ti TableInfo
return ti.SetGoType(goType)
}
// SetGoType assigns the struct type. Must be of kind struct.
// The Name and SQLName will be assigned to the snake case name of the struct
// if not already set.
func (ti *TableInfo) SetGoType(goType reflect.Type) *TableInfo {
ti.goType = goType
if ti.name == "" {
n := camelToSnake(goType.Name())
return ti.SetName(n)
}
return ti
}
// SetName sets the logical name of this table.
// The SQLName will be set if not already assigned.
func (ti *TableInfo) SetName(name string) *TableInfo {
ti.name = name
if ti.sqlName == "" {
return ti.SetSQLName(name)
}
return ti
}
// SetSQLName sets the SQL name of the table.
func (ti *TableInfo) SetSQLName(sqlName string) *TableInfo {
ti.sqlName = sqlName
return ti
}
// Name returns the logical name.
func (ti *TableInfo) Name() string {
return ti.name
}
// SQLName returns the SQL name of the table.
func (ti *TableInfo) SQLName() string {
return ti.sqlName
}
// GoType returns the reflect.Type.
func (ti *TableInfo) GoType() reflect.Type {
return ti.goType
}
// SQLPKFields returns the SQL table field name(s) of the primary key(s).
func (ti *TableInfo) SQLPKFields() []string {
return ti.sqlPKFields
}
// GoPKFields returns the Go struct field name(s) of the primary key(s).
func (ti *TableInfo) GoPKFields() []string {
var ret []string
for _, pkf := range ti.sqlPKFields {
idx := sqlFieldIndex(ti.GoType(), pkf)
sf := ti.GoType().FieldByIndex(idx)
ret = append(ret, sf.Name)
}
return ret
}
// PKAutoIncr returns true if the primary key is auto incrementing.
func (ti *TableInfo) PKAutoIncr() bool {
return ti.pkAutoIncr
}
// SQLVersionField returns the SQL field name of the version field, empty string
// if the version field/optimistic locking is disabled.
func (ti *TableInfo) SQLVersionField() string {
return ti.sqlVersionField
}
// SetSQLPKFields sets the primary key fields.
func (ti *TableInfo) SetSQLPKFields(isAutoIncr bool, sqlPKFields []string) *TableInfo {
ti.pkAutoIncr = isAutoIncr
ti.sqlPKFields = sqlPKFields
return ti
}
// AddRelation adds a relation.
func (ti *TableInfo) AddRelation(relation Relation) *TableInfo {
if ti.RelationMap == nil {
ti.RelationMap = make(RelationMap)
}
ti.RelationMap[relation.RelationName()] = relation
return ti
}
// SetSQLVersionField sets the version field.
func (ti *TableInfo) SetSQLVersionField(sqlVersionField string) *TableInfo {
ti.sqlVersionField = sqlVersionField
return ti
}
// IsSQLPKField returns true if the SQL field name provided is one of the primary key fields.
func (ti *TableInfo) IsSQLPKField(sqlName string) bool {
for _, f := range ti.sqlPKFields {
if f == sqlName {
return true
}
}
return false
}
// SQLFields returns the SQL field names for this table. If withPK is true
// the primary key(s) are included in the result.
func (ti *TableInfo) SQLFields(withPK bool) []string {
var ret []string
idxes := exportedFieldIndexes(ti.goType)
for _, idx := range idxes {
sf := ti.goType.FieldByIndex(idx)
sfdb := strings.SplitN(sf.Tag.Get("db"), ",", 2)[0]
if sfdb == "" || sfdb == "-" {
continue
}
if !ti.IsSQLPKField(sfdb) || withPK {
ret = append(ret, sfdb)
}
}
return ret
}
// SQLFieldsExcept returns the SQL field names for this table excluding the ones you provide.
func (ti *TableInfo) SQLFieldsExcept(exceptFields ...string) []string {
fs := ti.SQLFields(true)
ret := make([]string, 0, len(fs))
nextField:
for _, f := range fs {
for _, ef := range exceptFields {
if f == ef {
continue nextField
}
}
ret = append(ret, f)
}
return ret
}
// SQLPKWhere returns a where clause with the primary key fields ANDed together and "?" for placeholders.
// For example: "key1 = ? AND key2 = ?"
func (ti *TableInfo) SQLPKWhere() string {
var buf bytes.Buffer
for _, fn := range ti.SQLPKFields() {
fmt.Fprintf(&buf, " AND %s = ?", fn)
}
return strings.TrimPrefix(buf.String(), " AND ")
}
// PKValues scans an object for the pk fields.
// Will panic if pk fields cannot be found (e.g. if `o` is of the wrong type).
func (ti *TableInfo) PKValues(o interface{}) []interface{} {
v := derefValue(reflect.ValueOf(o))
ret := make([]interface{}, 0, len(ti.sqlPKFields))
for _, sfn := range ti.sqlPKFields {
ret = append(ret, sqlFieldValue(v, sfn))
}
return ret
}
// SQLValueMap returns a map of [SQLField]->[Value] for all database fields on this struct.
// If includePks is false then primary key fields are omitted.
func (ti *TableInfo) SQLValueMap(o interface{}, includePks bool) map[string]interface{} {
v := derefValue(reflect.ValueOf(o))
t := v.Type()
idxes := exportedFieldIndexes(t)
ret := make(map[string]interface{}, len(idxes))
for _, idx := range idxes {
sfdb := strings.SplitN(t.FieldByIndex(idx).Tag.Get("db"), ",", 2)[0]
if sfdb == "" || sfdb == "-" { // skip non-db-tagged fields
continue
}
if !ti.IsSQLPKField(sfdb) || includePks {
ret[sfdb] = v.FieldByIndex(idx).Interface()
}
}
return ret
}
// names := ti.SQLPKAndFields()
// ret := make([]string, 0, len(names)-len(ti.sqlPKFields))
// nameLoop:
// for i := 0; i < len(names); i++ {
// name := names[i]
// for _, keyName := range ti.sqlPKFields {
// if keyName == name {
// continue nameLoop
// }
// }
// ret = append(ret, name)
// }
// return ret
// }
// func (ti *TableInfo) SQLPKAndFields() []string {
// numFields := ti.goType.NumField()
// ret := make([]string, 0, numFields)
// for i := 0; i < numFields; i++ {
// structField := ti.goType.Field(i)
// sqlFieldName := strings.SplitN(structField.Tag.Get("db"), ",", 2)[0]
// if sqlFieldName == "" || sqlFieldName == "-" {
// continue
// }
// ret = append(ret, sqlFieldName)
// }
// return ret
// }
// SetTableInfo assigns the TableInfo for a specific Go type, overwriting any existing value.
// This will remove/overwrite the name associated with that type as well, and will also remove
// any entry with the same name before setting. This behavior allows overrides where a package
// a default TableInfo can exist for a type but a specific usage requires it to be assigned differently.
func (m *Meta) SetTableInfo(ty reflect.Type, ti *TableInfo) {
delete(m.tableInfoMap, m.typeForName(ti.name))
m.tableInfoMap[derefType(ty)] = ti
}
// For will return the TableInfo for a struct. Pointers will be dereferenced.
// Nil will be returned if no such table exists.
func (m *Meta) For(i interface{}) *TableInfo {
t := derefType(reflect.TypeOf(i))
return m.ForType(t)
}
// For will return the TableInfo for a struct type. Pointers will be dereferenced.
// Nil will be returned if no such table exists.
func (m *Meta) ForType(t reflect.Type) *TableInfo {
return m.tableInfoMap[derefType(t)]
}
// ForName will return the TableInfo with the given name.
// Nil will be returned if no such table exists.
func (m *Meta) ForName(name string) *TableInfo {
return m.ForType(m.typeForName(name))
}
func (m *Meta) typeForName(name string) reflect.Type {
for t, ti := range m.tableInfoMap {
if ti.name == name {
return t
}
}
return nil
}
// Parse will extract TableInfo data from the type of the value given (must be a properly tagged struct).
// The resulting TableInfo will be set as if by SetTableInfo.
func (m *Meta) Parse(i interface{}) error {
t := derefType(reflect.TypeOf(i))
return m.ParseType(t)
}
// MustParse is like Parse but will panic on error.
func (m *Meta) MustParse(i interface{}) {
err := m.Parse(i)
if err != nil {
panic(err)
}
}
// ParseTypeNamed works like ParseType but allows you to specify the name rather than having
// it being derived from the name of the Go struct. This is intended to allow you to override
// an existing type with your own struct. Example: A package comes with a "Widget" type, named
// "widget", and you make a "CustomWidget" with whatever additional fields (optionally) embedding
// the original "Widget". You can then call meta.ParseTypeNamed(reflect.TypeOf(CustomWidget{}), "widget")
// to override the original definition.
func (m *Meta) ParseTypeNamed(t reflect.Type, name string) error {
t = derefType(t)
var ti TableInfo
ti.SetName(name)
ti.SetGoType(t)
for _, idx := range exportedFieldIndexes(t) {
f := t.FieldByIndex(idx)
tag := f.Tag.Get(tmetaTag)
tagv := structTagToValues(tag)
// check relations
if len(tagv["belongs_to"]) > 0 {
// relation name defaults to snake of Go field name unless specified
name := tagv.Get("relation_name")
if name == "" {
name = camelToSnake(f.Name)
}
sqlIDField := tagv.Get("sql_id_field")
if sqlIDField == "" {
sqlIDField = camelToSnake(f.Name) + "_id"
}
ti.AddRelation(&BelongsTo{
Name: name,
GoValueField: f.Name, // e.g. "Author" (of type *Author)
SQLIDField: sqlIDField, // e.g. "author_id"
})
}
if len(tagv["has_many"]) > 0 {
name := tagv.Get("relation_name")
if name == "" {
name = camelToSnake(f.Name)
}
sqlOtherIDField := tagv.Get("sql_other_id_field")
if sqlOtherIDField == "" {
// sqlOtherIDField = camelToSnake(elemDerefType(f.Type).Name()) + "_id"
sqlOtherIDField = ti.Name() + "_id"
}
ti.AddRelation(&HasMany{
Name: name,
GoValueField: f.Name,
SQLOtherIDField: sqlOtherIDField,
})
}
if len(tagv["has_one"]) > 0 {
name := tagv.Get("relation_name")
if name == "" {
name = camelToSnake(f.Name)
}
sqlOtherIDField := tagv.Get("sql_other_id_field")
if sqlOtherIDField == "" {
// sqlOtherIDField = camelToSnake(derefType(f.Type).Name()) + "_id"
sqlOtherIDField = ti.Name() + "_id"
}
ti.AddRelation(&HasOne{
Name: name,
GoValueField: f.Name,
SQLOtherIDField: sqlOtherIDField,
})
}
if len(tagv["belongs_to_many"]) > 0 {
name := tagv.Get("relation_name")
if name == "" {
name = camelToSnake(f.Name)
}
joinName := tagv.Get("join_name")
if joinName == "" {
return fmt.Errorf("`join_name` not specified for belongs_to_many relation %q", name)
}
sqlIDField := tagv.Get("sql_id_field")
if sqlIDField == "" {
// FIXME: would be nice to depend on the type name + "_id" but it should be the
// same behavior as belongs_to_many_ids and it doesn't have the type name...
sqlIDField = ti.SQLPKFields()[0]
}
sqlOtherIDField := tagv.Get("sql_other_id_field")
if sqlOtherIDField == "" {
// we try to guess this based on the join name
s := strings.Replace(joinName, ti.Name(), "", 1)
if s == joinName { // if the join name doesn't contain the relation name, can't guess
return fmt.Errorf("`sql_other_id_field` tag is required for relation %q, unable to guess it's value", name)
}
s = strings.Trim(s, "_")
sqlOtherIDField = s + "_id"
}
rel := &BelongsToMany{
Name: name,
GoValueField: f.Name,
JoinName: joinName,
SQLIDField: sqlIDField,
SQLOtherIDField: sqlOtherIDField,
}
ti.AddRelation(rel)
}
if len(tagv["belongs_to_many_ids"]) > 0 {
name := tagv.Get("relation_name")
if name == "" {
name = camelToSnake(f.Name)
}
joinName := tagv.Get("join_name")
if joinName == "" {
return fmt.Errorf("`join_name` not specified for belongs_to_many_ids relation %q", name)
}
sqlIDField := tagv.Get("sql_id_field")
if sqlIDField == "" {
// FIXME: see if we can depend on the type name? instead of pk field name on this table, may not be possible
sqlIDField = ti.SQLPKFields()[0]
}
sqlOtherIDField := tagv.Get("sql_other_id_field")
if sqlOtherIDField == "" {
// we try to guess this based on the join name
s := strings.Replace(joinName, ti.Name(), "", 1)
if s == joinName { // if the join name doesn't contain the relation name, can't guess
return fmt.Errorf("`sql_other_id_field` tag is required for relation %q, unable to guess it's value", name)
}
s = strings.Trim(s, "_")
sqlOtherIDField = s + "_id"
}
rel := &BelongsToManyIDs{
Name: name,
GoValueField: f.Name,
JoinName: joinName,
SQLIDField: sqlIDField,
SQLOtherIDField: sqlOtherIDField,
}
ti.AddRelation(rel)
}
// past this point, skip fields not tagged with db
sqlName := strings.Split(f.Tag.Get("db"), ",")[0]
if sqlName == "" || sqlName == "-" {
continue
}
// check for primary key
if len(tagv["pk"]) > 0 {
ti.sqlPKFields = append(ti.sqlPKFields, sqlName)
if len(tagv["auto_incr"]) > 0 {
ti.pkAutoIncr = true
}
continue
}
// check for version (optimistic locking)
if len(tagv["version"]) > 0 {
ti.sqlVersionField = sqlName
continue
}
}
if len(ti.sqlPKFields) < 1 {
return fmt.Errorf("no primary key fields found for type %v", t)
}
m.SetTableInfo(t, &ti)
return nil
}
// ParseType will extract TableInfo data from the given type (must be a properly tagged struct).
// The resulting TableInfo will be set as if by SetTableInfo.
func (m *Meta) ParseType(t reflect.Type) error {
t = derefType(t)
return m.ParseTypeNamed(t, camelToSnake(t.Name()))
}
// ReplaceSQLNames provides the SQLName of each table to a function and sets the
// table name to the return value. For example, you can easily prefix all of the
// tables by doing:
// m.ReplaceSQLNames(func(n string) string { return "prefix_" + n })
func (m *Meta) ReplaceSQLNames(namer func(name string) string) {
for _, ti := range m.tableInfoMap {
ti.sqlName = namer(ti.sqlName)
}
}
// func (m *Meta) AddTable(i interface{}) *TableInfo {
// return m.AddTableWithName(i, TableNameMapper(derefType(reflect.TypeOf(i)).name()))
// }
// func (m *Meta) AddTableWithName(i interface{}, tableName string) *TableInfo {
// t := derefType(reflect.TypeOf(i))
// tableInfo := m[t]
// if tableInfo != nil {
// if tableInfo.SQLTableName != tableName {
// panic(fmt.Errorf("attempt to call AddTableWithName with a different name (expected %q, got %q)", tableInfo.SQLTableName, tableName))
// }
// return tableInfo
// }
// tableInfo = &TableInfo{
// goType: t,
// SQLTableName: tableName,
// }
// m[t] = tableInfo
// return tableInfo
// }
// func (m *Meta) TableFor(i interface{}) *TableInfo {
// return m.TableForType(reflect.TypeOf(i))
// }
// func (m *Meta) TableForType(t reflect.Type) *TableInfo {
// return m[derefType(t)]
// }