-
Notifications
You must be signed in to change notification settings - Fork 72
/
batcher.go
215 lines (180 loc) · 4.4 KB
/
batcher.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
package kallax
import (
"database/sql"
"errors"
"fmt"
"github.com/Masterminds/squirrel"
)
type batchQueryRunner struct {
schema Schema
cols []string
q Query
oneToOneRels []Relationship
oneToManyRels []Relationship
db squirrel.BaseRunner
builder squirrel.SelectBuilder
total int
eof bool
// records is the cache of the records in the last batch.
records []Record
}
var errNoMoreRows = errors.New("kallax: there are no more rows in the result set")
func newBatchQueryRunner(schema Schema, db squirrel.BaseRunner, q Query) *batchQueryRunner {
cols, builder := q.compile()
var (
oneToOneRels []Relationship
oneToManyRels []Relationship
)
for _, rel := range q.getRelationships() {
switch rel.Type {
case OneToOne:
oneToOneRels = append(oneToOneRels, rel)
case OneToMany:
oneToManyRels = append(oneToManyRels, rel)
}
}
return &batchQueryRunner{
schema: schema,
cols: cols,
q: q,
oneToOneRels: oneToOneRels,
oneToManyRels: oneToManyRels,
db: db,
builder: builder,
}
}
func (r *batchQueryRunner) next() (Record, error) {
if r.eof && len(r.records) == 0 {
return nil, errNoMoreRows
}
if len(r.records) == 0 {
var (
records []Record
err error
)
limit := r.q.GetLimit()
if limit == 0 || limit > uint64(r.total) {
records, err = r.loadNextBatch()
if err != nil {
return nil, err
}
}
if len(records) == 0 {
r.eof = true
return nil, errNoMoreRows
}
batchSize := r.q.GetBatchSize()
if batchSize > 0 && (batchSize < limit || limit == 0) {
if uint64(len(records)) < batchSize {
r.eof = true
}
} else if limit > 0 {
if uint64(len(records)) < limit {
r.eof = true
}
}
r.total += len(records)
r.records = records[1:]
return records[0], nil
}
record := r.records[0]
r.records = r.records[1:]
return record, nil
}
func (r *batchQueryRunner) loadNextBatch() ([]Record, error) {
limit := r.q.GetLimit() - uint64(r.total)
if r.q.GetBatchSize() < limit || limit <= 0 {
limit = r.q.GetBatchSize()
}
rows, err := r.builder.
Offset(r.q.GetOffset() + uint64(r.total)).
Limit(limit).
RunWith(r.db).
Query()
if err != nil {
return nil, err
}
return r.processBatch(rows)
}
func (r *batchQueryRunner) processBatch(rows *sql.Rows) ([]Record, error) {
batchRs := NewResultSet(
rows,
r.q.isReadOnly(),
r.oneToOneRels,
r.cols...,
)
var records []Record
for batchRs.Next() {
var rec = r.schema.New()
if err := batchRs.Scan(rec); err != nil {
return nil, err
}
records = append(records, rec)
}
if err := batchRs.Close(); err != nil {
return nil, err
}
var ids = make([]interface{}, len(records))
for i, r := range records {
ids[i] = r.GetID().Raw()
}
for _, rel := range r.oneToManyRels {
indexedResults, err := r.getRecordRelationships(ids, rel)
if err != nil {
return nil, err
}
for _, r := range records {
err := r.SetRelationship(rel.Field, indexedResults[r.GetID().Raw()])
if err != nil {
return nil, err
}
// If the relationship is partial, we can not ensure the results
// in the field reflect the truth of the database.
// In this case, the parent is marked as non-writable.
if rel.Filter != nil {
r.setWritable(false)
}
}
}
return records, nil
}
type indexedRecords map[interface{}][]Record
func (r *batchQueryRunner) getRecordRelationships(ids []interface{}, rel Relationship) (indexedRecords, error) {
fk, ok := r.schema.ForeignKey(rel.Field)
if !ok {
return nil, fmt.Errorf("kallax: cannot find foreign key on field %s for table %s", rel.Field, r.schema.Table())
}
filter := In(fk, ids...)
if rel.Filter != nil {
rel.Filter = And(rel.Filter, filter)
} else {
rel.Filter = filter
}
q := NewBaseQuery(rel.Schema)
q.Where(rel.Filter)
cols, builder := q.compile()
rows, err := builder.RunWith(r.db).Query()
if err != nil {
return nil, err
}
relRs := NewResultSet(rows, false, nil, cols...)
var indexedResults = make(indexedRecords)
for relRs.Next() {
rec, err := relRs.Get(rel.Schema)
if err != nil {
return nil, err
}
val, err := rec.Value(fk.String())
if err != nil {
return nil, err
}
rec.setPersisted()
rec.setWritable(true)
id := val.(Identifier).Raw()
indexedResults[id] = append(indexedResults[id], rec)
}
if err := relRs.Close(); err != nil {
return nil, err
}
return indexedResults, nil
}