-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.go
571 lines (473 loc) · 14 KB
/
schema.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
package makroud
import (
"fmt"
"reflect"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/ulule/makroud/reflectx"
)
// Mapper will be used to mutate a Model with row values.
type Mapper map[string]interface{}
// Schema is a model schema.
type Schema struct {
model Model
modelName string
tableName string
pk PrimaryKey
fields map[string]Field
references map[string]ForeignKey
associations map[string]Reference
createdKey *Field
updatedKey *Field
deletedKey *Field
}
// Model returns the schema model.
func (schema Schema) Model() Model {
return schema.model
}
// ModelName returns the schema model name.
func (schema Schema) ModelName() string {
return schema.modelName
}
// TableName returns the schema table name.
func (schema Schema) TableName() string {
return schema.tableName
}
// PrimaryKey returns the schema primary key.
func (schema Schema) PrimaryKey() PrimaryKey {
return schema.pk
}
// PrimaryKeyPath returns schema primary key column path.
func (schema Schema) PrimaryKeyPath() string {
return schema.pk.ColumnPath()
}
// PrimaryKeyName returns schema primary key column name.
func (schema Schema) PrimaryKeyName() string {
return schema.pk.ColumnName()
}
// HasCreatedKey returns if a created key is defined for current schema.
func (schema Schema) HasCreatedKey() bool {
return schema.createdKey != nil
}
// CreatedKeyPath returns schema created key column path.
func (schema Schema) CreatedKeyPath() string {
if schema.HasUpdatedKey() {
return schema.createdKey.ColumnPath()
}
panic(fmt.Sprint("makroud: ", ErrSchemaCreatedKey))
}
// CreatedKeyName returns schema created key column name.
func (schema Schema) CreatedKeyName() string {
if schema.HasUpdatedKey() {
return schema.createdKey.ColumnName()
}
panic(fmt.Sprint("makroud: ", ErrSchemaCreatedKey))
}
// HasUpdatedKey returns if an updated key is defined for current schema.
func (schema Schema) HasUpdatedKey() bool {
return schema.updatedKey != nil
}
// UpdatedKeyPath returns schema updated key column path.
func (schema Schema) UpdatedKeyPath() string {
if schema.HasUpdatedKey() {
return schema.updatedKey.ColumnPath()
}
panic(fmt.Sprint("makroud: ", ErrSchemaUpdatedKey))
}
// UpdatedKeyName returns schema deleted key column name.
func (schema Schema) UpdatedKeyName() string {
if schema.HasUpdatedKey() {
return schema.updatedKey.ColumnName()
}
panic(fmt.Sprint("makroud: ", ErrSchemaUpdatedKey))
}
// HasDeletedKey returns if a deleted key is defined for current schema.
func (schema Schema) HasDeletedKey() bool {
return schema.deletedKey != nil
}
// DeletedKeyPath returns schema deleted key column path.
func (schema Schema) DeletedKeyPath() string {
if schema.HasDeletedKey() {
return schema.deletedKey.ColumnPath()
}
panic(fmt.Sprint("makroud: ", ErrSchemaDeletedKey))
}
// DeletedKeyName returns schema deleted key column name.
func (schema Schema) DeletedKeyName() string {
if schema.HasDeletedKey() {
return schema.deletedKey.ColumnName()
}
panic(fmt.Sprint("makroud: ", ErrSchemaDeletedKey))
}
// Columns returns schema columns without table prefix.
func (schema Schema) Columns() Columns {
return schema.columns(false)
}
// ColumnPaths returns schema column with table prefix.
func (schema Schema) ColumnPaths() Columns {
return schema.columns(true)
}
// columns generates column slice.
func (schema Schema) columns(withTable bool) Columns {
columns := Columns{}
if withTable {
columns = append(columns, schema.pk.ColumnPath())
} else {
columns = append(columns, schema.pk.ColumnName())
}
for _, field := range schema.fields {
if withTable {
columns = append(columns, field.ColumnPath())
} else {
columns = append(columns, field.ColumnName())
}
}
return columns
}
// HasColumn returns if a schema has a column or not.
func (schema Schema) HasColumn(column string) bool {
if schema.pk.ColumnName() == column || schema.pk.ColumnPath() == column {
return true
}
_, ok := schema.fields[column]
if ok {
return true
}
column = strings.TrimPrefix(column, fmt.Sprint(schema.TableName(), "."))
_, ok = schema.fields[column]
return ok
}
// nolint: gocyclo
func (schema Schema) getValues(value reflect.Value, columns []string, model Model) ([]interface{}, error) {
values := make([]interface{}, len(columns))
rest := make([]string, 0)
associationsColumns := map[string]map[string]int{}
for i, column := range columns {
if schema.pk.ColumnName() == column || schema.pk.ColumnPath() == column {
values[i] = reflectx.GetReflectFieldByIndexes(value, schema.pk.FieldIndex())
continue
}
field, ok := schema.fields[column]
if ok {
values[i] = reflectx.GetReflectFieldByIndexes(value, field.FieldIndex())
continue
}
column = strings.TrimPrefix(column, fmt.Sprint(schema.TableName(), "."))
field, ok = schema.fields[column]
if ok {
values[i] = reflectx.GetReflectFieldByIndexes(value, field.FieldIndex())
continue
}
// sorting associations columns in case of JOIN
found := false
for key, association := range schema.associations {
trimed := strings.TrimPrefix(column, fmt.Sprint(association.Remote().TableName(), "."))
if trimed != column {
_, ok := associationsColumns[key]
if !ok {
associationsColumns[key] = map[string]int{}
}
// we keep the index in values for the scan
associationsColumns[key][trimed] = i
found = true
break
}
}
if found {
continue
}
rest = append(rest, column)
}
if len(rest) > 0 {
return nil, errors.Wrapf(ErrSchemaColumnRequired,
"missing destination name %s in %T", strings.Join(rest, ", "), model)
}
for key, columns := range associationsColumns {
// retrieve reflect field based on index
model := reflectx.GetReflectFieldByIndexes(value, schema.associations[key].Field.FieldIndex())
remote := schema.associations[key].Remote()
associationValue := reflectx.GetIndirectValue(model)
// columns concerned by the association
rest := make([]string, 0, len(columns))
for key := range columns {
rest = append(rest, key)
}
associationValues, err := remote.Schema().getValues(associationValue, rest, remote.Model())
if err != nil {
return nil, err
}
for i := range associationValues {
// index previous stored
index := associationsColumns[key][rest[i]]
values[index] = associationValues[i]
}
}
return values, nil
}
// ScanRow executes a scan from given row into model.
func (schema Schema) ScanRow(row Row, model Model) error {
columns, err := row.Columns()
if err != nil {
return err
}
value := reflectx.GetIndirectValue(model)
if !reflectx.IsStruct(value) {
return errors.Wrapf(ErrStructRequired, "cannot use mapper on %T", model)
}
values, err := schema.getValues(value, columns, model)
if err != nil {
return err
}
return row.Scan(values...)
}
// ScanRows executes a scan from current row into model.
func (schema Schema) ScanRows(rows Rows, model Model) error {
columns, err := rows.Columns()
if err != nil {
return err
}
value := reflectx.GetIndirectValue(model)
if !reflectx.IsStruct(value) {
return errors.Wrapf(ErrStructRequired, "cannot use mapper on %T", model)
}
values, err := schema.getValues(value, columns, model)
if err != nil {
return err
}
return rows.Scan(values...)
}
// ----------------------------------------------------------------------------
// Initializers
// ----------------------------------------------------------------------------
// GetSchema returns the schema from given model.
// If the schema does not exists, it returns an error.
func GetSchema(driver Driver, model Model) (*Schema, error) {
return getSchema(driver, model, true)
}
// getSchema returns the schema from given model.
// If the schema does not exists, it returns an error.
// If throughout is true, it will execute a full scan of given model:
// this is a trick to allow circular import of model.
func getSchema(driver Driver, model Model, throughout bool) (*Schema, error) {
if !driver.HasCache() {
return newSchema(driver, model, throughout)
}
schema := driver.GetCache().GetSchema(model)
if schema != nil {
return schema, nil
}
schema, err := newSchema(driver, model, throughout)
if err != nil {
return nil, err
}
if throughout {
driver.GetCache().SetSchema(schema)
}
return schema, nil
}
// defaultModelOpts returns the default model configuration.
func defaultModelOpts() ModelOpts {
return ModelOpts{
PrimaryKey: "id",
CreatedKey: "created_at",
UpdatedKey: "updated_at",
DeletedKey: "deleted_at",
}
}
// analyzeModelOpts analyzes given model to extract it's configuration.
func analyzeModelOpts(model Model) ModelOpts {
opts := defaultModelOpts()
mpk, ok := model.(interface {
PrimaryKey() string
})
if ok {
opts.PrimaryKey = mpk.PrimaryKey()
}
cpk, ok := model.(interface {
CreatedKey() string
})
if ok {
opts.CreatedKey = cpk.CreatedKey()
}
upk, ok := model.(interface {
UpdatedKey() string
})
if ok {
opts.UpdatedKey = upk.UpdatedKey()
}
dpk, ok := model.(interface {
DeletedKey() string
})
if ok {
opts.DeletedKey = dpk.DeletedKey()
}
return opts
}
// newSchema returns a schema from given model, extracted by reflection.
// The returned schema is a mapping of a model to table and columns.
// For example: Model.FieldName -> table_name.column_name
//
// If throughout is true, it will execute a full and complete scan of given model:
// this is a trick to allow circular import of model.
func newSchema(driver Driver, model Model, throughout bool) (*Schema, error) {
fields, err := reflectx.GetFields(model)
if err != nil {
return nil, errors.Wrapf(err, "cannot use reflections to obtain %T fields", model)
}
modelOpts := analyzeModelOpts(model)
schema := &Schema{
model: reflectx.MakeZero(model).(Model),
modelName: reflectx.GetIndirectTypeName(model),
tableName: model.TableName(),
fields: map[string]Field{},
references: map[string]ForeignKey{},
associations: map[string]Reference{},
}
relationships := map[string]*Field{}
err = getSchemaFields(driver, schema, model, modelOpts, fields, relationships)
if err != nil {
return nil, err
}
if throughout {
err = getSchemaAssociations(driver, schema, model, relationships)
if err != nil {
return nil, err
}
}
err = inferSchemaPrimaryKey(model, modelOpts, schema)
if err != nil {
return nil, err
}
return schema, nil
}
func getSchemaFields(driver Driver, schema *Schema, model Model, modelOpts ModelOpts,
fields []string, relationships map[string]*Field) error {
for _, name := range fields {
field, err := NewField(driver, schema, model, name, modelOpts)
if err != nil {
return err
}
if field.IsExcluded() {
continue
}
err = inferSchemaTimeKey(model, modelOpts, schema, field)
if err != nil {
return err
}
if field.IsPrimaryKey() {
err = handleSchemaPrimaryKey(schema, model, name, field)
if err != nil {
return err
}
continue
}
if field.IsForeignKey() {
err = handleSchemaForeignKey(schema, model, name, field)
if err != nil {
return err
}
}
if !field.IsAssociation() {
schema.fields[field.ColumnName()] = *field
continue
}
relationships[name] = field
}
return nil
}
func handleSchemaPrimaryKey(schema *Schema, model Model, name string, field *Field) error {
pk, err := NewPrimaryKey(field)
if err != nil {
return errors.Wrapf(err, "cannot use '%s' as primary key for %T", name, model)
}
if schema.pk.TableName() != "" {
return errors.Errorf("%T must have only one primary key", model)
}
schema.pk = *pk
return nil
}
func handleSchemaForeignKey(schema *Schema, model Model, name string, field *Field) error {
fk, err := NewForeignKey(field)
if err != nil {
return errors.Wrapf(err, "cannot use '%s' as foreign key for %T", name, model)
}
schema.references[fk.ColumnName()] = *fk
return nil
}
func getSchemaAssociations(driver Driver, schema *Schema, model Model, relationships map[string]*Field) error {
for name, field := range relationships {
_, ok := schema.associations[field.FieldName()]
if ok {
continue
}
reference, err := NewReference(driver, schema, field)
if err != nil {
return errors.Wrapf(err, "cannot use '%s' as association for %T", name, model)
}
schema.associations[field.FieldName()] = *reference
}
return nil
}
func inferSchemaTimeKey(model Model, opts ModelOpts, schema *Schema, field *Field) error {
if field.IsCreatedKey() {
if schema.createdKey != nil {
return errors.Errorf("%T must have only one created_at key", model)
}
schema.createdKey = field
}
if field.IsUpdatedKey() {
if schema.updatedKey != nil {
return errors.Errorf("%T must have only one updated_at key", model)
}
schema.updatedKey = field
}
if field.IsDeletedKey() {
if schema.deletedKey != nil {
return errors.Errorf("%T must have only one deleted_at key", model)
}
schema.deletedKey = field
}
return nil
}
func inferSchemaPrimaryKey(model Model, opts ModelOpts, schema *Schema) error {
if schema.pk.TableName() != "" {
return nil
}
for key := range schema.fields {
field := schema.fields[key]
if field.ColumnName() == opts.PrimaryKey {
pk, err := NewPrimaryKey(&field)
if err != nil {
return errors.Wrapf(err, "cannot use primary key of %T", model)
}
schema.pk = *pk
delete(schema.fields, key)
return nil
}
}
return errors.Errorf("%T must have a primary key", model)
}
// ----------------------------------------------------------------------------
// Columns
// ----------------------------------------------------------------------------
// Columns is a list of table columns.
type Columns []string
// Returns string representation of slice.
func (c Columns) String() string {
sort.Strings(c)
return strings.Join(c, ", ")
}
// List returns table columns.
func (c Columns) List() []string {
return c
}
// GetColumns returns a comma-separated string representation of a model's table columns.
func GetColumns(driver Driver, model Model) (Columns, error) {
schema, err := GetSchema(driver, model)
if err != nil {
return nil, errors.Wrap(err, "makroud: cannot fetch schema informations")
}
columns := schema.ColumnPaths()
return columns, nil
}