Repository navigation
Expand file tree
/
Copy pathunit.go
More file actions
2530 lines (2026 loc) · 61.9 KB
/
Copy pathunit.go
File metadata and controls
2530 lines (2026 loc) · 61.9 KB
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 ant
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"slices"
"time"
"unsafe"
"github.com/skudra-go/ant/dialect"
"github.com/skudra-go/ant/internal/exec"
"github.com/skudra-go/ant/internal/meta"
"github.com/skudra-go/ant/internal/track"
"github.com/skudra-go/ant/qb"
)
// node is one entity in a unit of work. Its entity pointer may be a private copy
// of the snapshot, for a row whose memory no longer belongs to it.
type node struct {
model *meta.Model
entity unsafe.Pointer
entry *track.Entry // nil if the entity is not tracked
insert bool
remove bool
forced bool // write every field, from MarkModified
links []fkLink // foreign keys to fill before writing
changed []*meta.Field // fields written by UPDATE
// scratch says entity is a private copy of the entry's row, as orphan and
// vacate make, which the unit may write into as into the entity itself.
scratch bool
// first says the node's statement runs before every other: the row a
// has-one relation let go of gives its foreign key up before the row that
// replaces it takes the key, which a unique key on it needs.
first bool
// linked holds the foreign keys of an untracked row put into a loaded
// relation, written even if they hold the parent's key already, so a row
// that is gone, as one this context deleted, fails rather than vanishing.
linked []*meta.Field
// scoped holds target-side Eq values assigned to an existing untracked row,
// whose other fields must not be overwritten by the relation.
scoped []*meta.Field
walked bool // its relations were followed, as InsertOnly's are not
// dropped says the unit let go of the node, as when its entry moved to
// another address, so it is no longer the node of its entity.
dropped bool
// wrote says the node's own statement ran. Outside a transaction it stays
// when a later statement of the unit fails.
wrote bool
generated []*meta.Field // filled by the database in this unit
stamped []*meta.Field // filled in Go in this unit
restore []prior // values the unit replaced, put back if it fails
// written is what the row was given, taken before an After hook ran.
written track.Copy
}
// prior is a value a unit replaced in an entity, such as the version it moved on.
type prior struct {
field *meta.Field
value reflect.Value
}
// copyOf returns a copy of f's value in entity.
func copyOf(f *meta.Field, entity unsafe.Pointer) reflect.Value {
v := reflect.New(f.Type).Elem()
v.Set(f.Value(entity))
return v
}
// undoing returns how a rollback takes back what the unit wrote into n's entity
// once its row is gone: the values the database filled, such as a generated key,
// and those the unit filled, such as timestamps and the version. It is given
// the address the entity has by then, and a value changed since stays. A key
// given back to the database lets the next save insert the entity again. With
// no transaction whose rollback ant would see, there is nothing to take back.
func (u *unit) undoing(n *node) func(entity unsafe.Pointer) {
if u.s.tx == nil || !u.s.tx.sees() {
return nil
}
filled := slices.Clone(n.restore)
for _, f := range slices.Concat(n.generated, n.stamped) {
filled = append(filled, prior{f, reflect.Zero(f.Type)})
}
if len(filled) == 0 {
return nil
}
left := make([]any, len(filled))
for i, p := range filled {
left[i] = copyOf(p.field, n.entity).Interface()
}
return func(entity unsafe.Pointer) {
for i, p := range filled {
if v := p.field.Value(entity); reflect.DeepEqual(v.Interface(), left[i]) {
v.Set(p.value)
}
}
}
}
// fkLink fills a foreign key from a parent just before a node is written.
type fkLink struct {
parent *node
field *meta.Field // on this node
source *meta.Field // on the parent
}
// unit is one atomic write. It finds what must change, orders it so parents
// exist before their children, and runs it in one transaction.
type unit struct {
s *state
nodes map[unsafe.Pointer]*node
order []*node // in discovery order
pivots []pivotChange
// versions holds the version each versioned row has after a write of this
// unit, so that another instance of the row is written over it. It is made
// by the first such write.
versions map[rowID]reflect.Value
// inTx reports whether the statements of this unit run in a transaction,
// whether the caller's or one the unit opens itself.
inTx bool
// dry plans the unit without changing any entity, for HasChanges.
dry bool
// held holds the rows the relations of tracked entities hold now, other
// than parents, made the first time a has-one relation lets go of one.
held map[rowID]bool
}
// pivotChange adds or removes one join table row.
type pivotChange struct {
r *meta.Relation
link meta.Link
parent *node
target *node // when adding
key any // the target's key, when removing
remove bool
}
func (c pivotChange) run(ctx context.Context, u *unit, to exec.Executor) error {
local, ok := c.link.Local.Key(c.parent.entity)
if !ok {
return ErrNoKey
}
p := c.r.Pivot
if c.remove {
_, err := u.s.runOn(ctx, to, pivotDelete(p, local, []any{c.key}))
return err
}
foreign, ok := c.link.Foreign.Key(c.target.entity)
if !ok {
return ErrNoKey
}
_, err := u.s.runOn(ctx, to, pivotInsert(u.s.dialect, p, local, []any{foreign}))
return err
}
// pivotInsert adds join rows, skipping those already there: with ON CONFLICT DO
// NOTHING, or, on a database with no such clause, a MERGE that inserts only
// the pairs it does not find. A key given twice is added once.
func pivotInsert(d dialect.Dialect, p *meta.Pivot, local any, foreign []any) qb.Statement {
seen := make(map[any]struct{}, len(foreign))
rows := make([][]qb.Expr, 0, len(foreign))
for _, key := range foreign {
if _, twice := seen[key]; twice {
continue
}
seen[key] = struct{}{}
rows = append(rows, []qb.Expr{qb.Param{Value: local}, qb.Param{Value: key}})
}
columns := []string{p.Local, p.Foreign}
if dialect.Supports(d, dialect.OnConflict) {
return &qb.Insert{
Table: p.Table,
Columns: columns,
Rows: rows,
Conflict: &qb.Conflict{},
}
}
const source = "ant_pairs"
on := make([]qb.Cond, len(columns))
values := make([]qb.Expr, len(columns))
for i, c := range columns {
values[i] = qb.Column{Alias: source, Name: c}
on[i] = qb.Compare{Left: qb.Column{Table: p.Table, Name: c}, Op: qb.OpEq, Right: values[i]}
}
return &qb.Merge{
Table: p.Table,
Using: qb.Source{Values: &qb.Values{Columns: columns, Rows: rows}, Alias: source},
On: on,
Actions: []qb.MergeAction{{Columns: columns, Values: values}},
}
}
func pivotDelete(p *meta.Pivot, local any, foreign []any) *qb.Delete {
values := make([]qb.Expr, len(foreign))
for i, key := range foreign {
values[i] = qb.Param{Value: key}
}
return &qb.Delete{
Table: p.Table,
Where: []qb.Cond{
qb.Compare{Left: qb.Column{Name: p.Local}, Op: qb.OpEq, Right: qb.Param{Value: local}},
qb.In{Left: qb.Column{Name: p.Foreign}, Values: values},
},
}
}
func newUnit(s *state) *unit {
return &unit{s: s, nodes: map[unsafe.Pointer]*node{}}
}
func (u *unit) add(model *meta.Model, entity unsafe.Pointer) *node {
if n, ok := u.nodes[entity]; ok {
return n
}
n := &node{model: model, entity: entity}
if entry := u.s.tracker.Get(entity); entry != nil && entry.Holds(entity) {
n.entry = entry
}
u.nodes[entity] = n
u.order = append(u.order, n)
return n
}
// insert schedules an entity, and with related set, walks its relations.
func (u *unit) insert(model *meta.Model, entity unsafe.Pointer, related bool) error {
n := u.add(model, entity)
n.insert = true
if related {
return u.walk(n)
}
return nil
}
// collect gathers every tracked entity and its pending changes. Relations are
// reconciled first, because slice elements may have moved in memory, and until
// they are matched by key, an entry's memory may hold another row.
func (u *unit) collect() error {
entries := u.s.tracker.Entries()
// Every entry has an address of its own and the unit is new, so each gets a
// node, made here in one block and not looked up one by one.
nodes := make([]node, len(entries))
fresh := len(u.nodes) == 0
if fresh {
u.nodes = make(map[unsafe.Pointer]*node, len(entries))
u.order = make([]*node, 0, len(entries))
}
for i, e := range entries {
var n *node
if fresh {
n = &nodes[i]
n.model, n.entity = e.Model, e.Entity
u.nodes[e.Entity] = n
u.order = append(u.order, n)
} else {
n = u.add(e.Model, e.Entity)
}
n.entry = e
switch e.State {
case track.Added:
n.insert = true
case track.Deleted:
n.remove = true
case track.Modified:
n.forced = true
}
}
claimed, err := u.claims()
if err != nil {
return err
}
for _, n := range slices.Clone(u.order) {
if u.current(n) && n.entry != nil {
if err := u.reconcile(n, claimed); err != nil {
return err
}
}
}
if err := u.adopt(); err != nil {
return err
}
for _, n := range slices.Clone(u.order) {
if u.current(n) && !n.remove {
if err := u.walk(n); err != nil {
return err
}
}
}
for _, n := range u.order {
if n.entry != nil && n.entity == n.entry.Entity && !n.remove && n.entry.KeyChanged() {
return fmt.Errorf("%w: %s", ErrKeyChanged, n.model.Type.Name())
}
}
return nil
}
// current reports whether n has not been replaced during reconciliation. Only
// drop takes a node out, and it says so on the node, which spares a lookup for
// every tracked entity of every save.
func (u *unit) current(n *node) bool { return !n.dropped }
// claims finds, by key, the entity that each relation of a tracked entity holds,
// so a row moved to another parent is not mistaken for one removed. A relation
// counts whether it was loaded or not, and a parent whether it is new or not,
// so a child moved to a parent added in this save, or to one whose relation was
// never loaded, is moved there.
func (u *unit) claims() (map[rowID]unsafe.Pointer, error) {
claimed := map[rowID]unsafe.Pointer{}
for _, n := range u.order {
if n.entry == nil {
continue
}
for _, r := range n.model.Relations {
if r.Kind != meta.Many || r.Pivot != nil || r.Empty(n.entity) {
continue
}
link, err := linkFor(r)
if err != nil {
return nil, err
}
for _, entity := range r.Related(n.entity) {
if key, ok := link.Target.KeyOf(entity); ok {
claimed[rowID{link.Target, key}] = entity
}
}
}
}
return claimed, nil
}
// adopt finds the elements that moved with a relation slice of a parent whose
// members the tracker has no record of, as one detached and attached again:
// reconcile follows the moves of the members it knows, and this the rest. An
// element no entry holds, whose row a tracked element held at an address that
// no tracked parent's relation holds any more, is that element moved, and its
// entry goes with it. Without this the edit made to it would be lost, since the
// entry would compare its old memory, which nothing changes, with its snapshot.
func (u *unit) adopt() error {
held := map[unsafe.Pointer]bool{}
type orphan struct {
row rowID
entity unsafe.Pointer
}
var untracked []orphan
for _, n := range u.order {
if n.entry == nil || !u.current(n) {
continue
}
for _, r := range n.model.Relations {
if r.Kind != meta.Many || r.Pivot != nil || r.Empty(n.entity) {
continue
}
link, err := linkFor(r)
if err != nil {
return err
}
for _, entity := range r.Related(n.entity) {
held[entity] = true
if u.s.tracker.Get(entity) != nil {
continue
}
if key, ok := link.Target.KeyOf(entity); ok {
untracked = append(untracked, orphan{rowID{link.Target, key}, entity})
}
}
}
}
if len(untracked) == 0 {
return nil
}
// The elements left behind, by row. A row left behind twice is not
// guessed at.
left := map[rowID]*track.Entry{}
for _, n := range u.order {
e := n.entry
if e == nil || !e.Element() || held[e.Entity] || !u.current(n) || n.remove {
continue
}
key, ok := e.Model.KeyOf(e.Entity)
if !ok {
continue
}
row := rowID{e.Model, key}
if _, twice := left[row]; twice {
left[row] = nil
} else {
left[row] = e
}
}
for _, o := range untracked {
if e := left[o.row]; e != nil && u.nodes[o.entity] == nil {
u.relocate(e, o.entity)
delete(left, o.row)
}
}
return nil
}
// reconcile matches a parent's loaded relations against what they hold now.
func (u *unit) reconcile(n *node, claimed map[rowID]unsafe.Pointer) error {
for r, members := range n.entry.Members {
link, err := linkFor(r)
if err != nil {
return err
}
for _, entity := range r.Related(n.entity) {
if key, ok := link.Target.KeyOf(entity); ok {
if entry := members[key]; entry != nil && entry.Entity != entity {
u.relocate(entry, entity)
}
}
}
current := map[any]struct{}{}
for _, entity := range r.Related(n.entity) {
if key, ok := link.Target.KeyOf(entity); ok {
current[key] = struct{}{}
}
}
for key, entry := range members {
if _, kept := current[key]; kept {
continue
}
if r.Pivot != nil {
u.pivots = append(u.pivots, pivotChange{
r: r,
link: link,
parent: n,
key: key,
remove: true,
})
u.vacate(entry)
continue
}
// A child the application detached is no longer the tracker's to
// delete or unlink, and one it removed is deleted as it asked.
if entry == nil || !u.s.tracker.Tracks(entry) || entry.State == track.Deleted {
continue
}
if entity, moved := claimed[rowID{link.Target, key}]; moved {
u.relocate(entry, entity)
continue
}
u.orphan(link, entry)
}
}
// A has-one pointer is the truth about its relation, as a slice is. One
// that picks a row of many is a view of them, and one through another
// table does not own its row. The model's relations, in their order, keep
// the order of the statements the same from one save to the next.
for _, r := range n.model.Relations {
key := n.entry.Parents[r]
if key == nil || r.Pick != nil || r.ThroughKey != nil || r.Pivot != nil {
continue
}
link, err := linkFor(r)
if err != nil {
return err
}
if link.BelongsTo || holdsRow(r, link, n.entity, key) {
continue
}
if err := u.letGo(link, key); err != nil {
return err
}
}
return nil
}
// holdsRow reports whether entity's relation r holds the row with the key.
func holdsRow(r *meta.Relation, link meta.Link, entity unsafe.Pointer, key any) bool {
for _, related := range r.Related(entity) {
if k, ok := link.Target.KeyOf(related); ok && k == key {
return true
}
}
return false
}
// letGo settles the row a has-one relation held when last loaded or saved, and
// holds no longer. A row that another relation holds now has moved there, and
// the new parent's link writes it. Any other is orphaned, as a child taken out
// of a slice is: deleted, or unlinked if its key is nullable.
func (u *unit) letGo(link meta.Link, key any) error {
entry := u.s.tracker.Find(link.Target, key)
if entry == nil || entry.State == track.Deleted {
return nil
}
held, err := u.heldRows()
if err != nil {
return err
}
if !held[rowID{link.Target, key}] {
u.orphan(link, entry).first = true
}
return nil
}
// heldRows returns the rows the relations of tracked entities hold now, other
// than their parents. Like claims, it sees the relations of tracked entities,
// new or loaded.
func (u *unit) heldRows() (map[rowID]bool, error) {
if u.held != nil {
return u.held, nil
}
u.held = map[rowID]bool{}
for _, n := range u.order {
if n.entry == nil || !u.current(n) {
continue
}
for _, r := range n.model.Relations {
if r.Pivot != nil || r.Empty(n.entity) {
continue
}
link, err := linkFor(r)
if err != nil {
return nil, err
}
if link.BelongsTo {
continue
}
for _, entity := range r.Related(n.entity) {
if key, ok := link.Target.KeyOf(entity); ok {
u.held[rowID{link.Target, key}] = true
}
}
}
}
return u.held, nil
}
// vacate lets go of the node of a target unlinked from a many-to-many relation
// whose memory holds another row now, as when its slice element was set to
// another target: the row itself is not written, and its entry is forgotten
// once the save commits, as the memory is not its own any longer.
func (u *unit) vacate(entry *track.Entry) {
if entry == nil || entry.Holds(entry.Entity) {
return
}
u.drop(entry)
copied := entry.Scratch()
n := &node{
model: entry.Model,
entity: copied,
entry: entry,
scratch: true,
// Nothing to write: the entry's memory holds another row, which its
// diff would take for this row's edits.
changed: []*meta.Field{},
}
u.nodes[copied] = n
u.order = append(u.order, n)
}
// isNew reports whether a related entity the tracker does not know must be
// inserted rather than linked: it has no key yet, or one the application chose.
func isNew(model *meta.Model, entity unsafe.Pointer) bool {
key := model.Key()
return key == nil || !(key.Generated || key.Generator != nil) || key.Value(entity).IsZero()
}
// walk follows a node's relations, scheduling new entities and foreign keys.
func (u *unit) walk(n *node) error {
n.walked = true
for _, r := range n.model.Relations {
if r.Pivot != nil && r.Pivot.ReadOnly {
continue
}
if r.Empty(n.entity) && !u.tracksRelation(n, r) {
continue
}
link, err := linkFor(r)
if err != nil {
return err
}
for _, entity := range r.Related(n.entity) {
if err := u.follow(n, r, link, entity); err != nil {
return err
}
}
// A pointer that held a parent when last loaded or saved, and is empty
// now, unlinks; one that was empty then leaves the key to the
// application, which may have set it directly.
if n.entry != nil && r.Kind == meta.One {
if parent, loaded := n.entry.Parents[r]; loaded && parent != nil && link.BelongsTo &&
r.Empty(n.entity) && nullable(link.Local) {
u.unlink(n, link.Local)
}
}
}
return nil
}
// unlink clears the foreign key of a relation the application emptied. A dry
// unit notes the change instead.
func (u *unit) unlink(n *node, f *meta.Field) {
switch v := f.Value(n.entity); {
case v.IsZero():
case u.dry:
n.changed = append(n.changed, f)
default:
v.SetZero()
}
}
func (u *unit) tracksRelation(n *node, r *meta.Relation) bool {
if n.entry == nil {
return false
}
_, members := n.entry.Members[r]
_, parent := n.entry.Parents[r]
return members || parent
}
// relocate points an entry at the entity's new address, after a slice moved.
func (u *unit) relocate(entry *track.Entry, entity unsafe.Pointer) {
u.drop(entry)
u.s.tracker.Move(entry, entity)
n := u.add(entry.Model, entity)
n.entry = entry
}
// drop removes the node an entry had, if it still owns its address.
func (u *unit) drop(entry *track.Entry) {
if stale := u.nodes[entry.Entity]; stale != nil && stale.entry == entry {
stale.dropped = true
delete(u.nodes, entry.Entity)
u.order = slices.DeleteFunc(u.order, func(other *node) bool { return other == stale })
}
}
// follow schedules one related entity and the foreign key between the two. A
// tracked relation that still holds what was loaded adds no link, so that a
// foreign key changed directly is not overwritten.
func (u *unit) follow(n *node, r *meta.Relation, link meta.Link, entity unsafe.Pointer) error {
seen := u.nodes[entity] != nil
other := u.add(link.Target, entity)
if !seen && other.entry == nil && isNew(link.Target, entity) {
other.insert = true
}
unmoved := u.unmoved(n, r, link, entity)
switch {
case unmoved && !keyless(n, r, link, entity):
case r.Kind == meta.Many && r.Pivot == nil && !link.BelongsTo && other.entry == nil &&
!other.insert && u.tracksRelation(n, r):
other.links = append(other.links, fkLink{n, link.Foreign, link.Local})
other.linked = append(other.linked, link.Foreign)
u.morph(other, r)
case r.Pivot != nil:
u.pivots = append(u.pivots, pivotChange{
r: r,
link: link,
parent: n,
target: other,
})
case link.BelongsTo:
n.links = append(n.links, fkLink{other, link.Local, link.Foreign})
u.morph(n, r)
default:
other.links = append(other.links, fkLink{n, link.Foreign, link.Local})
u.morph(other, r)
}
if !unmoved && r.Pivot == nil {
u.scope(other, r)
}
if seen {
return nil
}
return u.walk(other)
}
// morph records which table n's polymorphic foreign key refers to, unless the
// unit is dry; the link it goes with counts as a write either way.
func (u *unit) morph(n *node, r *meta.Relation) {
if !u.dry {
n.setMorph(r)
}
}
// scope applies target-side Eq conditions when a relation gains a row. Other
// conditions remain read filters, and an unmoved relation leaves edits alone.
func (u *unit) scope(n *node, r *meta.Relation) {
if u.dry {
return
}
for _, cond := range r.Scope {
compare, ok := cond.(qb.Compare)
if !ok || compare.Op != qb.OpEq || ownerSide(r, cond) {
continue
}
column, ok := compare.Left.(qb.Column)
if !ok || column.Table != n.model.Table {
continue
}
f := n.model.Column(column.Name)
param, ok := qb.ParamOf(compare.Right)
if f == nil || !ok || !slices.Contains(n.model.Writable(), f) ||
!n.insert && !slices.Contains(n.model.Updatable(), f) {
continue
}
value := param.Value
if secret, ok := value.(qb.Secret); ok {
value = secret.V
}
current := f.Value(n.entity)
equal := reflect.DeepEqual(current.Interface(), value)
v := reflect.ValueOf(value)
if v.Kind() == reflect.Pointer && !v.IsNil() {
cloned := reflect.New(v.Type().Elem())
cloned.Elem().Set(v.Elem())
v = cloned
}
current.Set(v)
if equal {
continue
}
if n.entry == nil && !n.insert && !slices.Contains(n.scoped, f) {
n.scoped = append(n.scoped, f)
}
}
}
// setMorph records which table a polymorphic foreign key refers to.
func (n *node) setMorph(r *meta.Relation) {
if f := r.MorphField; f != nil && n.model.Has(f) {
f.Value(n.entity).Set(reflect.ValueOf(r.MorphValue))
}
}
// keyless reports whether the required foreign key between n and a related
// entity holds its zero value, which names no parent, as in a child decoded from
// a request body that gave none and put in place of a loaded one. Such a key is
// set from the relation, as a moved child's is, while a nullable one left empty
// is the application's to clear (#152).
func keyless(n *node, r *meta.Relation, link meta.Link, entity unsafe.Pointer) bool {
holder, f := entity, link.Foreign
switch {
case r.Pivot != nil:
return false
case link.BelongsTo:
holder, f = n.entity, link.Local
}
return !nullable(f) && f.Value(holder).IsZero()
}
// unmoved reports whether entity is where the tracker last saw it in r.
func (u *unit) unmoved(n *node, r *meta.Relation, link meta.Link, entity unsafe.Pointer) bool {
if n.entry == nil {
return false
}
key, ok := link.Target.KeyOf(entity)
if !ok {
return false
}
if r.Kind == meta.Many {
_, member := n.entry.Members[r][key]
return member
}
parent, loaded := n.entry.Parents[r]
return loaded && parent == key
}
// orphan schedules a child removed from its relation, working from a private
// copy, because its slice element may hold another row by now. As in EF Core, a
// required child is deleted and an optional one is unlinked, which writes its
// version and UpdatedAt as any update does. Where the element still holds the
// child, the copy is of what it holds, so an edit made before the child left
// the slice is saved with the unlink; otherwise the copy is of the snapshot.
func (u *unit) orphan(link meta.Link, entry *track.Entry) *node {
u.drop(entry)
copied, edited := entry.Scratch(), []*meta.Field(nil)
if entry.Holds(entry.Entity) {
copied, edited = entry.Current(), entry.Changed()
}
n := &node{
model: link.Target,
entity: copied,
entry: entry,
scratch: true,
}
u.nodes[copied] = n
u.order = append(u.order, n)
if nullable(link.Foreign) {
link.Foreign.Value(copied).SetZero()
n.changed = append(
slices.DeleteFunc(edited, func(f *meta.Field) bool {
return f == link.Foreign
}),
link.Foreign,
)
n.forced = true
return n
}
n.remove = true
return n
}
// nullable reports whether a field's zero value is written as NULL, so that
// clearing it unlinks a row. A pointer is, and so is a driver.Valuer whose zero
// value is NULL, such as sql.Null. A Valuer whose zero value is a real value,
// such as uuid.UUID, is not, and neither is a column configured NotNull.
func nullable(f *meta.Field) bool {
if declared := f.Storage.Nullable; declared != nil && !*declared {
return false
}
if f.Type.Kind() == reflect.Pointer {
return true
}
valuer, ok := reflect.Zero(f.Type).Interface().(driver.Valuer)
if !ok {
return false
}
value, err := valuer.Value()
return err == nil && value == nil
}
// sorted returns the nodes with every new parent before its children. Only new
// parents matter: an existing row can be referred to in any order, and a cycle
// among existing rows is not a problem.
func (u *unit) sorted() ([]*node, error) {
const (
visiting = 1
done = 2
)
out := make([]*node, 0, len(u.order))
// A node with no parent to write first has nothing to visit, which is every
// node of most saves, so the marks are made only when one has.
var marks map[*node]int
var visit func(*node) error
visit = func(n *node) error {
if len(n.links) == 0 && marks == nil {
out = append(out, n)
return nil
}
if marks == nil {
marks = make(map[*node]int, len(u.order))
for _, seen := range out {
marks[seen] = done
}
}
switch marks[n] {
case done:
return nil
case visiting:
return ErrCycle
}
marks[n] = visiting
for _, l := range n.links {
if l.parent.insert {