summaryrefslogtreecommitdiffstats
path: root/sqlr.go
blob: 4ac798f5c82dbc9379ef0aa996fa6295fe2cf402 (plain) (blame)
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
// Package sqlr ("squealer") provides some convenience wrappers around
// database/sql in the spirit of encoding/json.
package sqlr

import (
	"database/sql"
	"fmt"
	"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...)
}