-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.go
More file actions
198 lines (175 loc) · 6.35 KB
/
insert.go
File metadata and controls
198 lines (175 loc) · 6.35 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
package seedling
import (
"context"
"fmt"
"reflect"
"testing"
"github.com/mhiro2/seedling/internal/executor"
"github.com/mhiro2/seedling/internal/planner"
)
// InsertOne creates and inserts a single record of type T with all required
// dependencies automatically resolved. Fails the test on error.
func InsertOne[T any](tb testing.TB, db DBTX, opts ...Option) Result[T] {
tb.Helper()
return NewSession[T](nil).InsertOne(tb, db, opts...)
}
// InsertOne creates and inserts a single record of type T with all required
// dependencies automatically resolved. Fails the test on error.
func (s Session[T]) InsertOne(tb testing.TB, db DBTX, opts ...Option) Result[T] {
tb.Helper()
ctx, filtered := extractContext(tb.Context(), opts)
result, err := s.InsertOneE(ctx, db, filtered...)
if err != nil {
tb.Fatal(err)
}
return result
}
// InsertOneE creates and inserts a single record of type T, returning an error on failure.
func InsertOneE[T any](ctx context.Context, db DBTX, opts ...Option) (Result[T], error) {
return NewSession[T](nil).InsertOneE(ctx, db, opts...)
}
// InsertOneE creates and inserts a single record of type T, returning an error on failure.
func (s Session[T]) InsertOneE(ctx context.Context, db DBTX, opts ...Option) (Result[T], error) {
ctx, filtered := extractContext(ctx, opts)
plan, err := s.BuildE(filtered...)
if err != nil {
var zero Result[T]
return zero, err
}
return plan.InsertE(ctx, s.resolveDB(db))
}
// InsertMany creates and inserts n records of type T with the same options.
// Shared belongs-to dependencies are inserted once when their resolved options
// are identical across records. Fails the test on error.
func InsertMany[T any](tb testing.TB, db DBTX, n int, opts ...Option) []T {
tb.Helper()
return NewSession[T](nil).InsertMany(tb, db, n, opts...)
}
// InsertMany creates and inserts n records of type T with the same options.
// Shared belongs-to dependencies are inserted once when their resolved options
// are identical across records. Fails the test on error.
func (s Session[T]) InsertMany(tb testing.TB, db DBTX, n int, opts ...Option) []T {
tb.Helper()
ctx, filtered := extractContext(tb.Context(), opts)
result, err := s.InsertManyE(ctx, db, n, filtered...)
if err != nil {
tb.Fatal(err)
}
return result.rootsView()
}
// InsertManyE creates and inserts n records of type T, returning a [BatchResult]
// for cleanup and graph inspection.
// When Seq options are present, the sequence function is called with the 0-based
// index for each record. Shared belongs-to dependencies are inserted once when
// their resolved options are identical across records.
func InsertManyE[T any](ctx context.Context, db DBTX, n int, opts ...Option) (BatchResult[T], error) {
return NewSession[T](nil).InsertManyE(ctx, db, n, opts...)
}
// InsertManyE creates and inserts n records of type T, returning a [BatchResult]
// for cleanup and graph inspection.
// When Seq options are present, the sequence function is called with the 0-based
// index for each record. Shared belongs-to dependencies are inserted once when
// their resolved options are identical across records.
func (s Session[T]) InsertManyE(ctx context.Context, db DBTX, n int, opts ...Option) (BatchResult[T], error) {
ctx, opts = extractContext(ctx, opts)
var zero BatchResult[T]
if n < 0 {
return zero, fmt.Errorf("validate insert count: n must be >= 0, got %d: %w", n, ErrInvalidOption)
}
if n == 0 {
return emptyBatchResult[T](), nil
}
rootType := reflect.TypeFor[T]()
collected := make([]*optionSet, n)
internalOpts := make([]*planner.OptionSet, n)
for i := range n {
resolved := resolveSeqs(opts, i)
prepared, err := prepareRootOptions(s.registry, rootType, resolved)
if err != nil {
return zero, err
}
collected[i] = prepared
internalOpts[i] = toOptionSet(prepared)
}
adapter := newRegistryAdapter(s.registry)
plan, err := planner.PlanMany(adapter, rootType, internalOpts)
if err != nil {
return zero, fmt.Errorf("build plan: %w", err)
}
execResult, err := executor.Execute(ctx, s.resolveDB(db), plan.Graph, adapter, toExecutorLogFn(collected[0].logFn))
if err != nil {
return zero, fmt.Errorf("execute plan: %w", err)
}
roots := make([]T, len(plan.RootIDs))
for i, rootID := range plan.RootIDs {
node, ok := execResult.Nodes[rootID]
if !ok {
return zero, fmt.Errorf("seedling: root node %q not found in batch result", rootID)
}
root, ok := node.Value.(T)
if !ok {
return zero, fmt.Errorf("%w: root node %q has value %T, want %s", ErrTypeMismatch, rootID, node.Value, rootType)
}
roots[i] = root
}
result := BatchResult[T]{
roots: roots,
rootIDs: plan.RootIDs,
nodes: execResult.Nodes,
graph: execResult.Graph,
registry: s.registry,
deleteFns: snapshotDeleteFns(s.registry, execResult.Nodes),
}
for i, root := range roots {
for _, fn := range collected[i].afterInserts {
switch cb := fn.(type) {
case func(T, DBTX):
cb(root, s.resolveDB(db))
case func(T, DBTX) error:
if err := cb(root, s.resolveDB(db)); err != nil {
return result, fmt.Errorf("run after-insert callback: %w", err)
}
}
}
}
return result, nil
}
// extractContext extracts a WithContext option from opts and returns
// the context and the remaining options.
func extractContext(defaultCtx context.Context, opts []Option) (context.Context, []Option) {
ctx := defaultCtx
filtered := make([]Option, 0, len(opts))
for _, o := range opts {
if co, ok := o.(contextOption); ok {
ctx = co.ctx
continue
}
filtered = append(filtered, o)
}
if ctx == nil {
ctx = context.Background()
}
return ctx, filtered
}
// resolveSeqs converts Seq options into Set options by calling the sequence
// function with the given index. Non-Seq options are passed through.
func resolveSeqs(opts []Option, index int) []Option {
resolved := make([]Option, 0, len(opts))
for _, o := range opts {
switch sq := o.(type) {
case seqOption:
resolved = append(resolved, Set(sq.field, sq.fn(index)))
case seqRefOption:
resolved = append(resolved, Ref(sq.name, resolveSeqs(sq.fn(index), index)...))
case seqUseOption:
resolved = append(resolved, Use(sq.name, sq.fn(index)))
case refOption:
resolved = append(resolved, Ref(sq.name, resolveSeqs(sq.opts, index)...))
case inlineTraitOption:
resolved = append(resolved, InlineTrait(resolveSeqs(sq.opts, index)...))
default:
resolved = append(resolved, o)
}
}
return resolved
}