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
|
// Copyright 2026 Rose Hogenson <r@roseh.moe>
//
// This file is part of roseh.moe/pkg/sqlr.
//
// roseh.moe/pkg/sqlr is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// roseh.moe/pkg/sqlr is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// roseh.moe/pkg/sqlr. If not, see <https://www.gnu.org/licenses/>.
// Package sqlr provides some convenience wrappers around database/sql
// in the spirit of encoding/json.
package sqlr
import (
"context"
"database/sql"
"fmt"
"iter"
"reflect"
)
// Scan calls rows.Scan to unpack a single row into the fields of v.
func Scan(rows *sql.Rows, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct {
return fmt.Errorf("Scan needs a pointer to a struct")
}
inner := rv.Elem()
fields := reflect.VisibleFields(inner.Type())
cols, err := rows.Columns()
if err != nil {
return err
}
dest := make([]any, len(cols))
Cols:
for i, c := range cols {
for _, f := range fields {
if !f.IsExported() {
continue
}
tag := f.Tag.Get("sql")
if tag == "" {
tag = f.Name
}
if tag == c {
dest[i] = inner.FieldByIndex(f.Index).Addr().Interface()
continue Cols
}
}
return fmt.Errorf("no field with tag %q", c)
}
return rows.Scan(dest...)
}
// Querier is the underlying type used to query the database,
// usually *sql.DB or *sql.Tx.
type Querier interface {
QueryContext(context.Context, string, ...any) (*sql.Rows, error)
}
// Query returns an iterator over the rows matched by a query.
func Query[Row any](ctx context.Context, querier Querier, query string, args ...any) iter.Seq2[Row, error] {
return func(yield func(Row, error) bool) {
rows, err := querier.QueryContext(ctx, query, args...)
if err != nil {
var zero Row
yield(zero, err)
return
}
defer rows.Close()
for rows.Next() {
var row Row
if err := Scan(rows, &row); err != nil {
yield(row, err)
return
}
if !yield(row, nil) {
return
}
}
if err := rows.Err(); err != nil {
var zero Row
yield(zero, err)
}
}
}
|