forked from geoffreybauduin/yaorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.go
520 lines (489 loc) · 14.3 KB
/
model.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
package yaorm
import (
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/geoffreybauduin/yaorm/tools"
"github.com/geoffreybauduin/yaorm/yaormfilter"
"github.com/juju/errors"
)
// Model is the interface every model should implement from
type Model interface {
// GetDBP should return the DBProvider tied to this model
GetDBP() DBProvider
// SetDBP allows setting a DBProvider to the model, then returned by GetDBP
SetDBP(dbp DBProvider)
// Save allows saving the model
Save() error
// Load loads the model from database given the current struct
Load(dbp DBProvider) error
// Delete removes the model from database
Delete() error
// DBHookBeforeInsert is a hook called before performing a DB insertion
DBHookBeforeInsert() error
// DBHookBeforeUpdate is a hook called before performing a DB update
DBHookBeforeUpdate() error
// DBHookBeforeDelete is a hook called before performing a DB delete
DBHookBeforeDelete() error
}
// DatabaseModel is the struct every model should compose
type DatabaseModel struct {
dbp DBProvider `db:"-"`
}
// SetDBP allows setting a DBProvider to the model, then returned by GetDBP
func (dm *DatabaseModel) SetDBP(dbp DBProvider) {
dm.dbp = dbp
}
// GetDBP should return the DBProvider tied to this model
func (dm *DatabaseModel) GetDBP() DBProvider {
return dm.dbp
}
// Save allows saving the model
// In order to be usable, this function needs to be redfined by each
// composition of this structure
func (dm *DatabaseModel) Save() error {
return errors.NotImplementedf("Save")
}
// Load loads the model from database given the current struct
// In order to be usable, this function needs to be redfined by each
// composition of this structure
func (dm *DatabaseModel) Load(dbp DBProvider) error {
return errors.NotImplementedf("Load")
}
// Delete removes the model from database
// In order to be usable, this function needs to be redfined by each
// composition of this structure
func (dm *DatabaseModel) Delete() error {
return errors.NotImplementedf("Delete")
}
// DBHookBeforeInsert is a hook called before performing a DB insertion
// By default, this function does not do anything. If needed, you will have
// to implement this function in your structure composing this one
// in order to have your code hook executed
func (dm *DatabaseModel) DBHookBeforeInsert() error {
return nil
}
// DBHookBeforeUpdate is a hook called before performing a DB update
// By default, this function does not do anything. If needed, you will have
// to implement this function in your structure composing this one
// in order to have your code hook executed
func (dm *DatabaseModel) DBHookBeforeUpdate() error {
return nil
}
// DBHookBeforeDelete is a hook called before performing a DB delete
// By default, this function does not do anything. If needed, you will have
// to implement this function in your structure composing this one
// in order to have your code hook executed
func (dm *DatabaseModel) DBHookBeforeDelete() error {
return nil
}
type cnt struct {
Count uint64 `db:"count"`
}
// GenericCount selects counts the row in the database
// panics if filter or dbp is nil
func GenericCount(dbp DBProvider, filter yaormfilter.Filter) (uint64, error) {
table, err := GetTableByFilter(filter)
if err != nil {
return 0, err
}
statement, err := buildCount(dbp, table)
if err != nil {
return 0, err
}
statement = apply(statement, filter, dbp)
query, params, err := statement.ToSql()
if err != nil {
return 0, err
}
counter := &cnt{}
err = dbp.DB().SelectOne(counter, query, params...)
if err != nil {
return 0, err
}
return counter.Count, nil
}
// GenericSelectOne selects one row in the database
// panics if filter or dbp is nil
func GenericSelectOne(dbp DBProvider, filter yaormfilter.Filter) (Model, error) {
table, err := GetTableByFilter(filter)
if err != nil {
return nil, err
}
m, err := table.NewModel()
if err != nil {
return nil, err
}
err = GenericSelectOneWithModel(dbp, filter, m)
if err != nil {
return nil, err
}
return m, nil
}
// GenericSelectOneFromModel selects one row in the database from a model value
// panics if filter or dbp is nil
func GenericSelectOneFromModel(dbp DBProvider, m Model) error {
table, err := GetTableByModel(m)
if err != nil {
return err
}
filter, err := table.NewFilter()
if err != nil {
return err
}
valueM := tools.GetNonPtrValue(m)
typeM := valueM.Type()
for i := 0; i < typeM.NumField(); i++ {
tagValue, ok := typeM.Field(i).Tag.Lookup("db")
if !ok || tagValue == "-" {
continue
}
tagData := strings.Split(tagValue, ",")
value := valueM.Field(i)
if !tools.IsZeroValue(value) {
idx := table.FilterFieldIndex(tagData[0])
if idx < 0 {
return errors.Errorf("Cannot find field with filter tag '%s' in filter %T", tagData[0], filter)
}
filterToApply := reflect.ValueOf(yaormfilter.Equals(value.Interface()))
tools.GetNonPtrValue(filter).Field(idx).Set(filterToApply)
}
}
return GenericSelectOneWithModel(dbp, filter, m)
}
// GenericSelectOneWithModel selects one row in the database providing the destination model directly
// panics if filter or dbp is nil
func GenericSelectOneWithModel(dbp DBProvider, filter yaormfilter.Filter, m Model) error {
statement, err := buildSelect(dbp, m, buildSelectColumns{
loadColumns: filter.GetLoadColumns(),
dontLoadColumns: filter.GetDontLoadColumns(),
})
if err != nil {
return err
}
statement = apply(statement, filter, dbp)
query, params, err := statement.ToSql()
if err != nil {
return err
}
err = dbp.DB().SelectOne(m, query, params...)
if err != nil {
if err == sql.ErrNoRows {
return errors.NotFoundf(formatTablenameFromError(m))
}
return err
}
m.SetDBP(dbp)
if filter != nil {
err = finishSelect(dbp, m, filter)
}
return err
}
// GenericSelectAll selects all rows in the database
// panics if filter or dbp is nil
func GenericSelectAll(dbp DBProvider, filter yaormfilter.Filter) ([]Model, error) {
table, err := GetTableByFilter(filter)
if err != nil {
return nil, err
}
m, err := table.NewModel()
if err != nil {
return nil, err
}
statement, err := buildSelect(dbp, m, buildSelectColumns{
loadColumns: filter.GetLoadColumns(),
dontLoadColumns: filter.GetDontLoadColumns(),
})
if err != nil {
return nil, err
}
sm, _ := table.NewSlicePtr()
statement = apply(statement, filter, dbp)
query, params, err := statement.ToSql()
if err != nil {
return nil, err
}
_, err = dbp.DB().Select(sm, query, params...)
if err != nil {
if err == sql.ErrNoRows {
return nil, errors.NotFoundf(formatTablenameFromError(m))
}
return nil, err
}
models := make([]Model, 0)
smValue := tools.GetNonPtrValue(sm)
for i := 0; i < smValue.Len(); i++ {
m := smValue.Index(i).Interface().(Model)
m.SetDBP(dbp)
models = append(models, m)
}
if filter != nil {
err = finishSelect(dbp, models, filter)
}
return models, err
}
// GenericSave updates or inserts the provided model in the database
// panics if model is nil or not linked to dbp
func GenericSave(m Model) error {
table, err := GetTableByModel(m)
if err != nil {
return err
}
// loop over primary keys
// if they are both to zero value, then it means it's an insert
// if they are both set to values, then it's an update
// otherwise, scream
keys := table.KeyFields()
if len(keys) == 1 {
return genericSaveOnePK(m, keys)
}
return genericSaveMultiplePK(table, m, keys)
}
// SaveWithPrimaryKeys updates or inserts the provided model in the database, using the provided keys to
// check if it exists
func SaveWithPrimaryKeys(m Model, keys []string) error {
table, err := GetTableByModel(m)
if err != nil {
return err
}
keyIndices := table.KeyFields()
keysMap := map[string]int{}
for _, key := range keys {
if _, ok := keyIndices[key]; !ok {
return errors.Errorf("Field %s is not a primary key of table %s", key, table.Name())
}
keysMap[key] = table.FieldIndex(key)
if keysMap[key] == -1 {
return errors.Errorf("Field %s is not defined in table %s", key, table.Name())
}
}
return genericSaveMultiplePK(table, m, keysMap)
}
func genericSaveMultiplePK(table *Table, m Model, keys map[string]int) error {
f, err := table.NewFilter()
if err != nil {
return err
}
reflectedModel := tools.GetNonPtrValue(m)
for fieldName, idx := range keys {
field := reflectedModel.Field(idx)
if tools.IsNil(field) {
return errors.Errorf("Cannot save this model: one Primary Key has zero value")
}
filterIdx := table.FilterFieldIndex(fieldName)
if filterIdx == -1 {
return errors.Errorf("Cannot find field %s inside table %s filter", fieldName, table.Name())
}
tools.GetNonPtrValue(f).Field(filterIdx).Set(reflect.ValueOf(yaormfilter.Equals(field.Interface())))
}
_, err = GenericSelectOne(m.GetDBP(), f)
if err != nil && errors.IsNotFound(err) {
return GenericInsert(m)
} else if err == nil {
return GenericUpdate(m)
}
return err
}
func genericSaveOnePK(m Model, keys map[string]int) error {
isZero := true
reflectedModel := tools.GetNonPtrValue(m)
for _, idx := range keys {
field := reflectedModel.Field(idx)
if !tools.IsZeroValue(field) {
isZero = false
break
}
}
if isZero {
return GenericInsert(m)
}
return GenericUpdate(m)
}
// GenericUpdate updates the provided model in the database
// panics if model is nil or not linked to dbp
func GenericUpdate(m Model) error {
err := m.DBHookBeforeUpdate()
if err != nil {
return err
}
_, err = m.GetDBP().DB().Update(m)
return err
}
// GenericInsert inserts the provided model in the database
// panics if model is nil or not linked to dbp
func GenericInsert(m Model) error {
err := m.DBHookBeforeInsert()
if err != nil {
return err
}
err = m.GetDBP().DB().Insert(m)
return err
}
func formatTablenameFromError(m Model) string {
table, err := GetTableByModel(m)
if err != nil {
return ""
}
tableName := table.Name()
tableName = strings.Replace(tableName, "_", " ", -1)
words := strings.Split(tableName, " ")
for i := 0; i < len(words); i++ {
words[i] = strings.Title(words[i])
}
return strings.Join(words, "")
}
func filterShouldSubqueryload(filterFound reflect.Value) bool {
f := filterFound.Interface()
switch f.(type) {
case yaormfilter.Filter:
return f.(yaormfilter.Filter).ShouldSubqueryload()
case []yaormfilter.Filter:
arr := f.([]yaormfilter.Filter)
for _, arrElem := range arr {
if arrElem.ShouldSubqueryload() {
return true
}
}
}
return false
}
func finishSelect(dbp DBProvider, m interface{}, f yaormfilter.Filter) error {
fkPerModel := map[string]map[interface{}][]reflect.Value{}
valueF := reflect.Indirect(reflect.ValueOf(f))
if !valueF.IsValid() {
return nil
}
st := valueF.Type()
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
dbFieldData, ok := field.Tag.Lookup("filterload")
if !ok || dbFieldData == "-" {
// Skip
continue
}
filterFound := valueF.Field(i)
if !filterFound.IsNil() && filterShouldSubqueryload(filterFound) {
// prevent scope overriding of fkPerModel
var err error
fkPerModel, err = feedFkPerModel(m, fkPerModel, dbFieldData)
if err != nil {
return err
}
}
}
d, err := subqueryload(dbp, fkPerModel)
if err != nil {
return err
}
for model, data := range d {
realModel := strings.Split(model, "_per_")[0]
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
dbFieldData, ok := field.Tag.Lookup("filterload")
if !ok || dbFieldData != realModel {
// Skip
continue
}
filterFound := valueF.Field(i)
if !filterFound.IsNil() && filterShouldSubqueryload(filterFound) {
err = finishSelectFromFilter(dbp, data, filterFound.Interface())
if err != nil {
return err
}
}
}
}
return nil
}
func finishSelectFromFilter(dbp DBProvider, m interface{}, f interface{}) error {
switch f.(type) {
case yaormfilter.Filter:
err := finishSelect(dbp, m, f.(yaormfilter.Filter))
if err != nil {
return err
}
return nil
case []yaormfilter.Filter:
arr := f.([]yaormfilter.Filter)
for _, arrElem := range arr {
err := finishSelect(dbp, m, arrElem)
if err != nil {
return err
}
}
return nil
}
return errors.Errorf("Could not cast filter provided to correct type")
}
func feedFkPerModel(m interface{}, fkPerModel map[string]map[interface{}][]reflect.Value, dbFieldData string) (map[string]map[interface{}][]reflect.Value, error) {
s := reflect.Indirect(reflect.ValueOf(m))
if s.Kind() == reflect.Slice {
for i := 0; i < s.Len(); i++ {
var err error
fkPerModel, err = feedFkPerModel(s.Index(i).Interface(), fkPerModel, dbFieldData)
if err != nil {
return nil, err
}
}
} else {
idx, tag := getFieldInModel(m.(Model), "filterload", dbFieldData)
if idx > -1 {
tagData := strings.Split(tag, ",")
if len(tagData) < 2 {
return nil, errors.Errorf("tag 'filterload' %+v is invalid, must have at least 2 parts", tagData)
}
if len(tagData) == 3 {
// it's a reverse filter
tagData[0] = fmt.Sprintf("%s_per_%s", tagData[0], tagData[2])
}
idxFk, _ := getFieldInModel(m.(Model), "db", tagData[1])
if idxFk > -1 {
fkReflectedvalue := s.Field(idxFk)
if !tools.IsZeroValue(fkReflectedvalue) {
fkValue := reflect.Indirect(fkReflectedvalue).Interface()
if _, ok := fkPerModel[tagData[0]]; !ok {
fkPerModel[tagData[0]] = map[interface{}][]reflect.Value{}
}
if _, ok := fkPerModel[tagData[0]][fkValue]; !ok {
fkPerModel[tagData[0]][fkValue] = []reflect.Value{}
}
fkPerModel[tagData[0]][fkValue] = append(fkPerModel[tagData[0]][fkValue], s.Field(idx).Addr())
}
} else {
t, err := GetTableByModel(m.(Model))
if err != nil {
return nil, err
}
return nil, errors.Errorf("Cannot find fk %s in model %s struct", tagData[1], t.Name())
}
} else {
return nil, errors.Errorf("Cannot find tag filterload:%v in model struct", dbFieldData)
}
}
return fkPerModel, nil
}
func getFieldInModel(m Model, tag, equals string) (int, string) {
st := reflect.Indirect(reflect.ValueOf(m)).Type()
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
dbFieldData, ok := field.Tag.Lookup(tag)
if !ok {
continue
}
tagData := strings.Split(dbFieldData, ",")
if tagData[0] == equals {
return i, dbFieldData
}
}
return -1, ""
}
// GenericDelete will delete the provided model from its database
// Returns the number of rows deleted
func GenericDelete(m Model) (int64, error) {
err := m.DBHookBeforeDelete()
if err != nil {
return 0, err
}
return m.GetDBP().DB().Delete(m)
}