forked from go-rel/rel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
1283 lines (1032 loc) · 32.4 KB
/
repository.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rel
import (
"context"
"errors"
"reflect"
"runtime"
"strings"
)
// Repository for interacting with database.
type Repository interface {
// Adapter used in this repository.
Adapter(ctx context.Context) Adapter
// Instrumentation defines callback to be used as instrumenter.
Instrumentation(instrumenter Instrumenter)
// Ping database.
Ping(ctx context.Context) error
// Iterate through a collection of entities from database in batches.
// This function returns iterator that can be used to loop all entities.
// Limit, Offset and Sort query is automatically ignored.
Iterate(ctx context.Context, query Query, option ...IteratorOption) Iterator
// Aggregate over the given field.
// Supported aggregate: count, sum, avg, max, min.
// Any select, group, offset, limit and sort query will be ignored automatically.
// If complex aggregation is needed, consider using All instead.
Aggregate(ctx context.Context, query Query, aggregate string, field string) (int, error)
// MustAggregate over the given field.
// Supported aggregate: count, sum, avg, max, min.
// Any select, group, offset, limit and sort query will be ignored automatically.
// If complex aggregation is needed, consider using All instead.
// It'll panic if any error occurred.
MustAggregate(ctx context.Context, query Query, aggregate string, field string) int
// Count entities that match the query.
Count(ctx context.Context, collection string, queriers ...Querier) (int, error)
// MustCount entities that match the query.
// It'll panic if any error occurred.
MustCount(ctx context.Context, collection string, queriers ...Querier) int
// Find a entity that match the query.
// If no result found, it'll return not found error.
Find(ctx context.Context, entity any, queriers ...Querier) error
// MustFind a entity that match the query.
// If no result found, it'll panic.
MustFind(ctx context.Context, entity any, queriers ...Querier)
// FindAll entities that match the query.
FindAll(ctx context.Context, entities any, queriers ...Querier) error
// MustFindAll entities that match the query.
// It'll panic if any error occurred.
MustFindAll(ctx context.Context, entities any, queriers ...Querier)
// FindAndCountAll entities that match the query.
// This is a convenient method that combines FindAll and Count. It's useful when dealing with queries related to pagination.
// Limit and Offset property will be ignored when performing count query.
FindAndCountAll(ctx context.Context, entities any, queriers ...Querier) (int, error)
// MustFindAndCountAll entities that match the query.
// This is a convenient method that combines FindAll and Count. It's useful when dealing with queries related to pagination.
// Limit and Offset property will be ignored when performing count query.
// It'll panic if any error occurred.
MustFindAndCountAll(ctx context.Context, entities any, queriers ...Querier) int
// Insert a entity to database.
Insert(ctx context.Context, entity any, mutators ...Mutator) error
// MustInsert an entity to database.
// It'll panic if any error occurred.
MustInsert(ctx context.Context, entity any, mutators ...Mutator)
// InsertAll entities.
// Does not supports application cascade insert.
InsertAll(ctx context.Context, entities any, mutators ...Mutator) error
// MustInsertAll entities.
// It'll panic if any error occurred.
// Does not supports application cascade insert.
MustInsertAll(ctx context.Context, entities any, mutators ...Mutator)
// Update a entity in database.
// It'll panic if any error occurred.
Update(ctx context.Context, entity any, mutators ...Mutator) error
// MustUpdate a entity in database.
// It'll panic if any error occurred.
MustUpdate(ctx context.Context, entity any, mutators ...Mutator)
// UpdateAny entities tha match the query.
// Returns number of updated entities and error.
UpdateAny(ctx context.Context, query Query, mutates ...Mutate) (int, error)
// MustUpdateAny entities that match the query.
// It'll panic if any error occurred.
// Returns number of updated entities.
MustUpdateAny(ctx context.Context, query Query, mutates ...Mutate) int
// Delete a entity.
Delete(ctx context.Context, entity any, mutators ...Mutator) error
// MustDelete a entity.
// It'll panic if any error occurred.
MustDelete(ctx context.Context, entity any, mutators ...Mutator)
// DeleteAll entities.
// Does not supports application cascade delete.
DeleteAll(ctx context.Context, entities any) error
// MustDeleteAll entities.
// It'll panic if any error occurred.
// Does not supports application cascade delete.
MustDeleteAll(ctx context.Context, entities any)
// DeleteAny entities that match the query.
// Returns number of deleted entities and error.
DeleteAny(ctx context.Context, query Query) (int, error)
// MustDeleteAny entities that match the query.
// It'll panic if any error occurred.
// Returns number of updated entities.
MustDeleteAny(ctx context.Context, query Query) int
// Preload association with given query.
// This function can accepts either a struct or a slice of structs.
// If association is already loaded, this will do nothing.
// To force preloading even though association is already loaeded, add `Reload(true)` as query.
Preload(ctx context.Context, entities any, field string, queriers ...Querier) error
// MustPreload association with given query.
// This function can accept either a struct or a slice of structs.
// It'll panic if any error occurred.
MustPreload(ctx context.Context, entities any, field string, queriers ...Querier)
// Exec raw statement.
// Returns last inserted id, rows affected and error.
Exec(ctx context.Context, statement string, args ...any) (int, int, error)
// MustExec raw statement.
// Returns last inserted id, rows affected and error.
MustExec(ctx context.Context, statement string, args ...any) (int, int)
// Transaction performs transaction with given function argument.
// Transaction scope/connection is automatically passed using context.
Transaction(ctx context.Context, fn func(ctx context.Context) error) error
}
type repository struct {
rootAdapter Adapter
instrumenter Instrumenter
}
func (r repository) Adapter(ctx context.Context) Adapter {
return fetchContext(ctx, r.rootAdapter).adapter
}
func (r *repository) Instrumentation(instrumenter Instrumenter) {
r.instrumenter = instrumenter
r.rootAdapter.Instrumentation(instrumenter)
}
func (r *repository) Ping(ctx context.Context) error {
return r.rootAdapter.Ping(ctx)
}
func (r repository) Iterate(ctx context.Context, query Query, options ...IteratorOption) Iterator {
var (
cw = fetchContext(ctx, r.rootAdapter)
)
return newIterator(cw.ctx, cw.adapter, query, options)
}
func (r repository) Aggregate(ctx context.Context, query Query, aggregate string, field string) (int, error) {
finish := r.instrumenter.Observe(ctx, "rel-aggregate", "aggregating entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
)
return r.aggregate(cw, query, aggregate, field)
}
func (r repository) aggregate(cw contextWrapper, query Query, aggregate string, field string) (int, error) {
query.GroupQuery = GroupQuery{}
query.LimitQuery = 0
query.OffsetQuery = 0
query.SortQuery = nil
return cw.adapter.Aggregate(cw.ctx, query, aggregate, field)
}
func (r repository) MustAggregate(ctx context.Context, query Query, aggregate string, field string) int {
result, err := r.Aggregate(ctx, query, aggregate, field)
must(err)
return result
}
func (r repository) Count(ctx context.Context, collection string, queriers ...Querier) (int, error) {
finish := r.instrumenter.Observe(ctx, "rel-count", "aggregating entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
)
return r.aggregate(cw, Build(collection, queriers...), "count", "*")
}
func (r repository) MustCount(ctx context.Context, collection string, queriers ...Querier) int {
count, err := r.Count(ctx, collection, queriers...)
must(err)
return count
}
func (r repository) Find(ctx context.Context, entity any, queriers ...Querier) error {
finish := r.instrumenter.Observe(ctx, "rel-find", "finding a entity")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
doc = NewDocument(entity)
query = Build(doc.Table(), queriers...).Populate(doc.Meta())
)
return r.find(cw, doc, query)
}
func (r repository) MustFind(ctx context.Context, entity any, queriers ...Querier) {
must(r.Find(ctx, entity, queriers...))
}
func (r repository) find(cw contextWrapper, doc *Document, query Query) error {
query = r.withDefaultScope(doc.meta, query, true)
cur, err := cw.adapter.Query(cw.ctx, query.Limit(1))
if err != nil {
return err
}
finish := r.instrumenter.Observe(cw.ctx, "rel-scan-one", "scanning a entity")
if err := scanOne(cur, doc); err != nil {
finish(err)
return err
}
finish(nil)
for i := range query.PreloadQuery {
if err := r.preload(cw, doc, query.PreloadQuery[i], nil); err != nil {
return err
}
}
return nil
}
func (r repository) FindAll(ctx context.Context, entities any, queriers ...Querier) error {
finish := r.instrumenter.Observe(ctx, "rel-find-all", "finding all entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
col = NewCollection(entities)
query = Build(col.Table(), queriers...).Populate(col.Meta())
)
col.Reset()
return r.findAll(cw, col, query)
}
func (r repository) MustFindAll(ctx context.Context, entities any, queriers ...Querier) {
must(r.FindAll(ctx, entities, queriers...))
}
func (r repository) findAll(cw contextWrapper, col *Collection, query Query) error {
query = r.withDefaultScope(col.meta, query, true)
cur, err := cw.adapter.Query(cw.ctx, query)
if err != nil {
return err
}
finish := r.instrumenter.Observe(cw.ctx, "rel-scan-all", "scanning all entities")
if err := scanAll(cur, col); err != nil {
finish(err)
return err
}
finish(nil)
for i := range query.PreloadQuery {
if err := r.preload(cw, col, query.PreloadQuery[i], nil); err != nil {
return err
}
}
return nil
}
func (r repository) FindAndCountAll(ctx context.Context, entities any, queriers ...Querier) (int, error) {
finish := r.instrumenter.Observe(ctx, "rel-find-and-count-all", "finding all entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
col = NewCollection(entities)
query = Build(col.Table(), queriers...).Populate(col.Meta())
)
col.Reset()
if err := r.findAll(cw, col, query); err != nil {
return 0, err
}
return r.aggregate(cw, r.withDefaultScope(col.meta, query, false), "count", "*")
}
func (r repository) MustFindAndCountAll(ctx context.Context, entities any, queriers ...Querier) int {
count, err := r.FindAndCountAll(ctx, entities, queriers...)
must(err)
return count
}
func (r repository) Insert(ctx context.Context, entity any, mutators ...Mutator) error {
finish := r.instrumenter.Observe(ctx, "rel-insert", "inserting a entity")
defer finish(nil)
if entity == nil {
return nil
}
var (
cw = fetchContext(ctx, r.rootAdapter)
doc = NewDocument(entity)
mutation = Apply(doc, mutators...)
)
if !mutation.IsAssocEmpty() && mutation.Cascade == true {
return r.transaction(cw, func(cw contextWrapper) error {
return r.insert(cw, doc, mutation)
})
}
return r.insert(cw, doc, mutation)
}
func (r repository) insert(cw contextWrapper, doc *Document, mutation Mutation) error {
var (
pField string
pFields = doc.PrimaryFields()
queriers = Build(doc.Table())
)
if mutation.Cascade {
if err := r.saveBelongsTo(cw, doc, &mutation); err != nil {
return err
}
}
if len(pFields) == 1 {
pField = pFields[0]
}
pValue, err := cw.adapter.Insert(cw.ctx, queriers, pField, mutation.Mutates, mutation.OnConflict)
if err != nil {
return mutation.ErrorFunc.transform(err)
}
// update primary value
if pField != "" {
doc.SetValue(pField, pValue)
}
if mutation.Cascade {
if err := r.saveHasOne(cw, doc, &mutation); err != nil {
return err
}
if err := r.saveHasMany(cw, doc, &mutation, true); err != nil {
return err
}
}
return nil
}
func (r repository) MustInsert(ctx context.Context, entity any, mutators ...Mutator) {
must(r.Insert(ctx, entity, mutators...))
}
func (r repository) InsertAll(ctx context.Context, entities any, mutators ...Mutator) error {
finish := r.instrumenter.Observe(ctx, "rel-insert-all", "inserting multiple entities")
defer finish(nil)
if entities == nil {
return nil
}
var (
cw = fetchContext(ctx, r.rootAdapter)
col = NewCollection(entities)
muts = make([]Mutation, col.Len())
)
for i := range muts {
doc := col.Get(i)
if i == 0 {
// only need to apply options from first one
muts[i] = Apply(doc, mutators...)
} else {
muts[i] = Apply(doc)
}
}
return r.insertAll(cw, col, muts)
}
func (r repository) MustInsertAll(ctx context.Context, entities any, mutators ...Mutator) {
must(r.InsertAll(ctx, entities, mutators...))
}
// TODO: support assocs
func (r repository) insertAll(cw contextWrapper, col *Collection, mutation []Mutation) error {
if len(mutation) == 0 {
return nil
}
var (
pField string
pFields = col.PrimaryFields()
queriers = Build(col.Table())
onConflict = mutation[0].OnConflict
fields = make([]string, 0, len(mutation[0].Mutates))
fieldMap = make(map[string]struct{}, len(mutation[0].Mutates))
bulkMutates = make([]map[string]Mutate, len(mutation))
)
// TODO: baypassable if it's predictable.
for i := range mutation {
for field := range mutation[i].Mutates {
if _, exist := fieldMap[field]; !exist {
fieldMap[field] = struct{}{}
fields = append(fields, field)
}
}
bulkMutates[i] = mutation[i].Mutates
}
if len(pFields) == 1 {
pField = pFields[0]
}
ids, err := cw.adapter.InsertAll(cw.ctx, queriers, pField, fields, bulkMutates, onConflict)
if err != nil {
return mutation[0].ErrorFunc.transform(err)
}
// apply ids
if pField != "" {
for i, id := range ids {
col.Get(i).SetValue(pField, id)
}
}
return nil
}
func (r repository) Update(ctx context.Context, entity any, mutators ...Mutator) error {
finish := r.instrumenter.Observe(ctx, "rel-update", "updating a entity")
defer finish(nil)
if entity == nil {
return nil
}
var (
cw = fetchContext(ctx, r.rootAdapter)
doc = NewDocument(entity)
filter = filterDocument(doc)
mutation = Apply(doc, mutators...)
)
if !mutation.IsAssocEmpty() && mutation.Cascade == true {
return r.transaction(cw, func(cw contextWrapper) error {
return r.update(cw, doc, mutation, filter)
})
}
return r.update(cw, doc, mutation, filter)
}
func (r repository) lockVersion(doc Document, unscoped Unscoped) (int, bool) {
if unscoped {
return 0, false
}
if doc.Flag(HasVersioning) {
versionRaw, _ := doc.Value("lock_version")
version, _ := versionRaw.(int)
return version, true
}
return 0, false
}
func (r repository) update(cw contextWrapper, doc *Document, mutation Mutation, filter FilterQuery) error {
if mutation.Cascade {
if err := r.saveBelongsTo(cw, doc, &mutation); err != nil {
return err
}
}
if !mutation.IsMutatesEmpty() {
if err := r.applyMutates(cw, doc, mutation, filter); err != nil {
return err
}
}
if mutation.Cascade {
if err := r.saveHasOne(cw, doc, &mutation); err != nil {
return err
}
if err := r.saveHasMany(cw, doc, &mutation, false); err != nil {
return err
}
}
return nil
}
func (r repository) applyMutates(cw contextWrapper, doc *Document, mutation Mutation, filter FilterQuery) (dbErr error) {
var (
baseQueries = []Querier{filter, mutation.Unscoped, mutation.Cascade}
queries = baseQueries
)
if version, ok := r.lockVersion(*doc, mutation.Unscoped); ok {
Set("lock_version", version+1).Apply(doc, &mutation)
queries = append(queries, lockVersion(version))
defer func() {
if dbErr != nil {
doc.SetValue("lock_version", version)
}
}()
}
var (
pField string
query = r.withDefaultScope(doc.meta, Build(doc.Table(), queries...).Populate(doc.Meta()), false)
)
if len(doc.meta.primaryField) == 1 {
pField = doc.PrimaryField()
}
if updatedCount, err := cw.adapter.Update(cw.ctx, query, pField, mutation.Mutates); err != nil {
return mutation.ErrorFunc.transform(err)
} else if updatedCount == 0 {
return NotFoundError{}
}
if mutation.Reload {
baseQuery := r.withDefaultScope(doc.meta, Build(doc.Table(), baseQueries...).Populate(doc.Meta()), false)
if err := r.find(cw, doc, baseQuery.UsePrimary()); err != nil {
return err
}
}
return nil
}
func (r repository) MustUpdate(ctx context.Context, entity any, mutators ...Mutator) {
must(r.Update(ctx, entity, mutators...))
}
// TODO: support deletion
func (r repository) saveBelongsTo(cw contextWrapper, doc *Document, mutation *Mutation) error {
for _, field := range doc.BelongsTo() {
var (
assoc = doc.Association(field)
assocMuts, changed = mutation.Assoc[field]
)
if !assoc.Autosave() || !changed || len(assocMuts.Mutations) == 0 {
continue
}
var (
assocDoc, loaded = assoc.Document()
assocMut = assocMuts.Mutations[0]
)
if loaded {
filter, err := filterBelongsTo(assoc)
if err != nil {
return err
}
if err := r.update(cw, assocDoc, assocMut, filter); err != nil {
return err
}
} else {
if err := r.insert(cw, assocDoc, assocMut); err != nil {
return err
}
var (
rField = assoc.ReferenceField()
fValue = assoc.ForeignValue()
)
mutation.Add(Set(rField, fValue))
doc.SetValue(rField, fValue)
}
}
return nil
}
// TODO: suppprt deletion
func (r repository) saveHasOne(cw contextWrapper, doc *Document, mutation *Mutation) error {
for _, field := range doc.HasOne() {
var (
assoc = doc.Association(field)
assocMuts, changed = mutation.Assoc[field]
)
if !assoc.Autosave() || !changed || len(assocMuts.Mutations) == 0 {
continue
}
var (
assocDoc, loaded = assoc.Document()
assocMut = assocMuts.Mutations[0]
)
if loaded && (assoc.ForeignField() == "" || !isZero(assoc.ForeignValue())) {
filter, err := filterHasOne(assoc, assocDoc)
if err != nil {
return err
}
if err := r.update(cw, assocDoc, assocMut, filter); err != nil {
return err
}
} else {
var (
fField = assoc.ForeignField()
rValue = assoc.ReferenceValue()
)
assocMut.Add(Set(fField, rValue))
assocDoc.SetValue(fField, rValue)
if err := r.insert(cw, assocDoc, assocMut); err != nil {
return err
}
}
}
return nil
}
// saveHasMany expects has many mutation to be ordered the same as the recrods in collection.
func (r repository) saveHasMany(cw contextWrapper, doc *Document, mutation *Mutation, insertion bool) error {
for _, field := range doc.HasMany() {
var (
assoc = doc.Association(field)
assocMuts, changed = mutation.Assoc[field]
)
if !assoc.Autosave() || !changed {
continue
}
var (
col, _ = assoc.Collection()
table = col.Table()
fField = assoc.ForeignField()
rValue = assoc.ReferenceValue()
muts = assocMuts.Mutations
deletedIDs = assocMuts.DeletedIDs
)
// this shouldn't happen unless there's bug in the mutator.
if len(muts) != col.Len() {
panic("rel: invalid mutator")
}
if !insertion {
var (
filter = Eq(fField, rValue)
)
if deletedIDs == nil {
// if it's nil, then clear old association (used by structset).
if _, err := r.deleteAny(cw, col.meta.flag, Build(table, filter).Populate(col.Meta())); err != nil {
return err
}
} else if len(deletedIDs) > 0 {
filter = filter.AndIn(col.PrimaryField(), deletedIDs...)
if _, err := r.deleteAny(cw, col.meta.flag, Build(table, filter).Populate(col.Meta())); err != nil {
return err
}
}
}
// update and filter for bulk insertion.
updateCount := 0
for i := range muts {
var (
assocDoc = col.Get(i)
)
// When deleted IDs is nil, it's assumed that association will be replaced.
// hence any update request is ignored here.
var fValue, _ = assocDoc.Value(fField)
if deletedIDs != nil && !isZero(assocDoc.PrimaryValue()) && !isZero(fValue) {
var (
filter = filterDocument(assocDoc).AndEq(fField, rValue)
)
if rValue != fValue {
return ConstraintError{
Key: fField,
Type: ForeignKeyConstraint,
Err: errors.New("rel: inconsistent has many ref and fk"),
}
}
if updateCount < i {
col.Swap(updateCount, i)
muts[i], muts[updateCount] = muts[updateCount], muts[i]
}
if err := r.update(cw, assocDoc, muts[updateCount], filter); err != nil {
return err
}
updateCount++
} else {
muts[i].Add(Set(fField, rValue))
assocDoc.SetValue(fField, rValue)
}
}
if len(muts)-updateCount > 0 {
var (
insertMuts = muts
insertCol = col
)
if updateCount > 0 {
insertMuts = muts[updateCount:]
insertCol = col.Slice(updateCount, len(muts))
}
if err := r.insertAll(cw, insertCol, insertMuts); err != nil {
return err
}
}
}
return nil
}
func (r repository) UpdateAny(ctx context.Context, query Query, mutates ...Mutate) (int, error) {
finish := r.instrumenter.Observe(ctx, "rel-update-any", "updating multiple entities")
defer finish(nil)
var (
err error
updatedCount int
cw = fetchContext(ctx, r.rootAdapter)
muts = make(map[string]Mutate, len(mutates))
)
for _, mut := range mutates {
muts[mut.Field] = mut
}
if len(muts) > 0 {
updatedCount, err = cw.adapter.Update(cw.ctx, query, "", muts)
}
return updatedCount, err
}
func (r repository) MustUpdateAny(ctx context.Context, query Query, mutates ...Mutate) int {
updatedCount, err := r.UpdateAny(ctx, query, mutates...)
must(err)
return updatedCount
}
func (r repository) Delete(ctx context.Context, entity any, mutators ...Mutator) error {
finish := r.instrumenter.Observe(ctx, "rel-delete", "deleting a entity")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
doc = NewDocument(entity)
mutation = applyMutators(nil, false, false, mutators...)
)
if mutation.Cascade {
return r.transaction(cw, func(cw contextWrapper) error {
return r.delete(cw, doc, filterDocument(doc), mutation)
})
}
return r.delete(cw, doc, filterDocument(doc), mutation)
}
func (r repository) delete(cw contextWrapper, doc *Document, filter FilterQuery, mutation Mutation) error {
var filters []Querier = []Querier{filter, mutation.Unscoped}
if version, ok := r.lockVersion(*doc, mutation.Unscoped); ok {
filters = append(filters, lockVersion(version))
}
var (
table = doc.Table()
query = Build(table, filters...).Populate(doc.Meta())
)
if mutation.Cascade {
if err := r.deleteHasOne(cw, doc, true); err != nil {
return err
}
if err := r.deleteHasMany(cw, doc); err != nil {
return err
}
}
deletedCount, err := r.deleteAny(cw, doc.meta.flag, query)
if err == nil && deletedCount == 0 {
err = NotFoundError{}
}
if err == nil && mutation.Cascade {
if err := r.deleteBelongsTo(cw, doc, true); err != nil {
return err
}
}
return err
}
func (r repository) deleteBelongsTo(cw contextWrapper, doc *Document, cascade Cascade) error {
for _, field := range doc.BelongsTo() {
var (
assoc = doc.Association(field)
)
if !assoc.Autosave() {
continue
}
if assocDoc, loaded := assoc.Document(); loaded {
filter, err := filterBelongsTo(assoc)
if err != nil {
return err
}
if err := r.delete(cw, assocDoc, filter, Mutation{Cascade: cascade}); err != nil {
return err
}
}
}
return nil
}
func (r repository) deleteHasOne(cw contextWrapper, doc *Document, cascade Cascade) error {
for _, field := range doc.HasOne() {
var (
assoc = doc.Association(field)
)
if !assoc.Autosave() {
continue
}
if assocDoc, loaded := assoc.Document(); loaded {
filter, err := filterHasOne(assoc, assocDoc)
if err != nil {
return err
}
if err := r.delete(cw, assocDoc, filter, Mutation{Cascade: cascade}); err != nil {
return err
}
}
}
return nil
}
func (r repository) deleteHasMany(cw contextWrapper, doc *Document) error {
for _, field := range doc.HasMany() {
var (
assoc = doc.Association(field)
)
if !assoc.Autosave() {
continue
}
if col, loaded := assoc.Collection(); loaded && col.Len() != 0 {
var (
table = col.Table()
fField = assoc.ForeignField()
rValue = assoc.ReferenceValue()
filter = Eq(fField, rValue).And(filterCollection(col))
)
if _, err := r.deleteAny(cw, col.meta.flag, Build(table, filter).Populate(doc.Meta())); err != nil {
return err
}
}
}
return nil
}
func (r repository) MustDelete(ctx context.Context, entity any, mutators ...Mutator) {
must(r.Delete(ctx, entity, mutators...))
}
func (r repository) DeleteAll(ctx context.Context, entities any) error {
finish := r.instrumenter.Observe(ctx, "rel-delete-all", "deleting entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
col = NewCollection(entities)
)
if col.Len() == 0 {
return nil
}
var (
query = Build(col.Table(), filterCollection(col)).Populate(col.Meta())
_, err = r.deleteAny(cw, col.meta.flag, query)
)
return err
}
func (r repository) MustDeleteAll(ctx context.Context, entities any) {
must(r.DeleteAll(ctx, entities))
}
func (r repository) DeleteAny(ctx context.Context, query Query) (int, error) {
finish := r.instrumenter.Observe(ctx, "rel-delete-any", "deleting multiple entities")
defer finish(nil)
var (
cw = fetchContext(ctx, r.rootAdapter)
)
return r.deleteAny(cw, Invalid, query)
}
func (r repository) MustDeleteAny(ctx context.Context, query Query) int {
deletedCount, err := r.DeleteAny(ctx, query)
must(err)
return deletedCount
}
func (r repository) deleteAny(cw contextWrapper, flag DocumentFlag, query Query) (int, error) {
hasDeletedAt := flag.Is(HasDeletedAt)
hasDeleted := flag.Is(HasDeleted)
mutates := make(map[string]Mutate, 1)
if hasDeletedAt {
mutates["deleted_at"] = Set("deleted_at", Now())
}
if hasDeleted {
mutates["deleted"] = Set("deleted", true)
if flag.Is(HasUpdatedAt) && !hasDeletedAt {
mutates["updated_at"] = Set("updated_at", Now())
}
}
if hasDeletedAt || hasDeleted {
if flag.Is(HasVersioning) {
mutates["lock_version"] = Inc("lock_version")
}
return cw.adapter.Update(cw.ctx, query, "", mutates)
}