-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsqlrange.go
343 lines (310 loc) · 9.78 KB
/
sqlrange.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
// Package sqlrange integrates database/sql with Go 1.23 range functions.
package sqlrange
import (
"context"
"database/sql"
"fmt"
"iter"
"reflect"
"slices"
"sync/atomic"
)
// ExecOption is a functional option type to configure the [Exec] and [ExecContext]
// functions.
type ExecOption[Row any] func(*execOptions[Row])
// ExecArgsFields constructs an option that specifies the fields to include in
// the query arguments from a list of column names.
//
// This option is useful when the query only needs a subset of the fields from
// the row type, or when the query arguments are in a different order than the
// struct fields.
func ExecArgsFields[Row any](columnNames ...string) ExecOption[Row] {
structFieldIndexes := make([][]int, len(columnNames))
for columnName, structField := range Fields(reflect.TypeOf(new(Row)).Elem()) {
if columnIndex := slices.Index(columnNames, columnName); columnIndex >= 0 {
structFieldIndexes[columnIndex] = structField.Index
}
}
for i, structFieldIndex := range structFieldIndexes {
if structFieldIndex == nil {
panic(fmt.Errorf("column %q not found", columnNames[i]))
}
}
return ExecArgs(func(args []any, row Row) []any {
rowValue := reflect.ValueOf(row)
for _, structFieldIndex := range structFieldIndexes {
args = append(args, rowValue.FieldByIndex(structFieldIndex).Interface())
}
return args
})
}
// ExecArgs is an option that specifies the function being called to generate
// the list of arguments passed when executing a query.
//
// By default, the Row value is converted to a list of arguments by taking the
// fields with a "sql" struct tag in the order they appear in the struct,
// as defined by the [reflect.VisibleFields] function.
//
// The function must append the arguments to the slice passed as argument and
// return the resulting slice.
func ExecArgs[Row any](fn func([]any, Row) []any) ExecOption[Row] {
return func(opts *execOptions[Row]) { opts.args = fn }
}
// ExecQuery is an option that specifies the function being called to generate
// the query to execute for a given Row value.
//
// The function receives the original query value passed to [Exec] or [ExecContext],
// and returns the query to execute.
//
// This is useful when parts of the query depend on the Row value that the query
// is being executed on, for example when the query is an insert.
func ExecQuery[Row any](fn func(string, Row) string) ExecOption[Row] {
return func(opts *execOptions[Row]) { opts.query = fn }
}
type execOptions[Row any] struct {
args func([]any, Row) []any
query func(string, Row) string
}
// Executable is the interface implemented by [sql.DB], [sql.Conn], or [sql.Tx].
type Executable interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
// Exec is like [ExecContext] but it uses the background context.
func Exec[Row any](e Executable, query string, seq iter.Seq2[Row, error], opts ...ExecOption[Row]) iter.Seq2[sql.Result, error] {
return ExecContext[Row](context.Background(), e, query, seq, opts...)
}
// ExecContext executes a query for each row in the sequence.
//
// To ensure that the query is executed atomically, it is usually useful to
// call ExecContext on a transaction ([sql.Tx]), for example:
//
// tx, err := db.BeginTx(ctx, nil)
// if err != nil {
// ...
// }
// defer tx.Rollback()
// for r, err := range sqlrange.ExecContext[RowType](ctx, tx, query, rows) {
// if err != nil {
// ...
// }
// ...
// }
// if err := tx.Commit(); err != nil {
// ...
// }
//
// Since the function makes one query execution for each row read from the
// sequence, latency of the query execution can quickly increase. In some cases,
// such as inserting values in a database, the program can amortize the cost of
// query latency by batching the rows being inserted, for example:
//
// for r, err := range sqlrange.ExecContext(ctx, tx,
// `insert into table (col1, col2, col3) values `,
// // yield groups of rows to be inserted in bulk
// func(yield func([]RowType, error) bool) {
// ...
// },
// // append values for the insert query
// sqlrange.ExecArgs(func(args []any, rows []RowType) []any {
// for _, row := range rows {
// args = append(args, row.Col1, row.Col2, row.Col3)
// }
// return args
// }),
// // generate placeholders for the insert query
// sqlrange.ExecQuery(func(query string, rows []RowType) string {
// return query + strings.Repeat(`(?, ?, ?)`, len(rows))
// }),
// ) {
// ...
// }
//
// Batching operations this way is necessary to achieve high throughput when
// inserting values into a database.
func ExecContext[Row any](ctx context.Context, e Executable, query string, seq iter.Seq2[Row, error], opts ...ExecOption[Row]) iter.Seq2[sql.Result, error] {
return func(yield func(sql.Result, error) bool) {
options := new(execOptions[Row])
for _, opt := range opts {
opt(options)
}
if options.args == nil {
row := new(Row)
val := reflect.ValueOf(row).Elem()
fields := Fields(val.Type())
options.args = func(args []any, in Row) []any {
*row = in
for _, structField := range fields {
args = append(args, val.FieldByIndex(structField.Index).Interface())
}
return args
}
}
if options.query == nil {
options.query = func(query string, _ Row) string { return query }
}
var execArgs []any
var execQuery string
for r, err := range seq {
if err != nil {
yield(nil, err)
return
}
execArgs = options.args(execArgs[:0], r)
execQuery = options.query(query, r)
res, err := e.ExecContext(ctx, execQuery, execArgs...)
if !yield(res, err) {
return
}
if err != nil {
return
}
}
}
}
// Queryable is an interface implemented by types that can send SQL queries,
// such as [sql.DB], [sql.Conn], or [sql.Tx].
type Queryable interface {
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}
// Query is like [QueryContext] but it uses the background context.
func Query[Row any](q Queryable, query string, args ...any) iter.Seq2[Row, error] {
return QueryContext[Row](context.Background(), q, query, args...)
}
// QueryContext returns the results of the query as a sequence of rows.
//
// The returned function automatically closes the underlying [sql.Rows] value when
// it completes its iteration.
//
// A typical use of QueryContext is:
//
// for row, err := range sqlrange.QueryContext[RowType](ctx, db, query, args...) {
// if err != nil {
// ...
// }
// ...
// }
//
// The q parameter represents a queryable type, such as [sql.DB], [sql.Conn],
// or [sql.Tx].
//
// See [Scan] for more information about how the rows are mapped to the row type
// parameter Row.
func QueryContext[Row any](ctx context.Context, q Queryable, query string, args ...any) iter.Seq2[Row, error] {
return func(yield func(Row, error) bool) {
if rows, err := q.QueryContext(ctx, query, args...); err != nil {
var zero Row
yield(zero, err)
} else {
scan[Row](yield, rows)
}
}
}
// Scan returns a sequence of rows from a [sql.Rows] value.
//
// The returned function automatically closes the rows passed as argument when
// it completes its iteration.
//
// A typical use of Scan is:
//
// rows, err := db.QueryContext(ctx, query, args...)
// if err != nil {
// ...
// }
// for row, err := range sqlrange.Scan[RowType](rows) {
// if err != nil {
// ...
// }
// ...
// }
//
// Scan uses reflection to map the columns of the rows to the fields of the
// struct passed as argument. The mapping is done by matching the name of the
// columns with the name of the fields. The name of the columns is taken from
// the "sql" tag of the fields. For example:
//
// type Row struct {
// ID int64 `sql:"id"`
// Name string `sql:"name"`
// }
//
// The fields of the struct that do not have a "sql" tag are ignored.
//
// Ranging over the returned function will panic if the type parameter is not a
// struct.
func Scan[Row any](rows *sql.Rows) iter.Seq2[Row, error] {
return func(yield func(Row, error) bool) { scan(yield, rows) }
}
func scan[Row any](yield func(Row, error) bool, rows *sql.Rows) {
defer rows.Close()
var zero Row
columns, err := rows.Columns()
if err != nil {
yield(zero, err)
return
}
scanArgs := make([]any, len(columns))
row := new(Row)
val := reflect.ValueOf(row).Elem()
for columnName, structField := range Fields(val.Type()) {
if columnIndex := slices.Index(columns, columnName); columnIndex >= 0 {
scanArgs[columnIndex] = val.FieldByIndex(structField.Index).Addr().Interface()
}
}
for rows.Next() {
if err := rows.Scan(scanArgs...); err != nil {
yield(zero, err)
return
}
if !yield(*row, nil) {
return
}
*row = zero
}
if err := rows.Err(); err != nil {
yield(zero, err)
}
}
// Fields returns a sequence of the fields of a struct type that have a "sql"
// tag.
func Fields(t reflect.Type) iter.Seq2[string, reflect.StructField] {
return func(yield func(string, reflect.StructField) bool) {
cache, _ := cachedFields.Load().(map[reflect.Type][]field)
fields, ok := cache[t]
if !ok {
fields = appendFields(nil, t, nil)
newCache := make(map[reflect.Type][]field, len(cache)+1)
for k, v := range cache {
newCache[k] = v
}
newCache[t] = fields
cachedFields.Store(newCache)
}
for _, f := range fields {
if !yield(f.name, f.field) {
return
}
}
}
}
type field struct {
name string
field reflect.StructField
}
var cachedFields atomic.Value // map[reflect.Type][]field
func appendFields(fields []field, t reflect.Type, index []int) []field {
for i, n := 0, t.NumField(); i < n; i++ {
if f := t.Field(i); f.IsExported() {
if len(index) > 0 {
f.Index = append(index, f.Index...)
}
if f.Anonymous {
if f.Type.Kind() == reflect.Struct {
fields = appendFields(fields, f.Type, f.Index)
}
} else if s, ok := f.Tag.Lookup("sql"); ok {
fields = append(fields, field{s, f})
}
}
}
return fields
}