summaryrefslogtreecommitdiffstats
path: root/sqlr.go
blob: 0224c7c2633e1ac431f77060ea4215f0757b0b20 (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
45
46
47
48
49
50
51
// 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()
	innerType := inner.Type()

	fields := make(map[string]reflect.StructField)
	inner.FieldByNameFunc(func(fieldName string) bool {
		field, ok := innerType.FieldByName(fieldName)
		if !ok {
			return false
		}
		tag, ok := field.Tag.Lookup("sql")
		if !ok {
			fields[fieldName] = field
			return false
		}
		if tag != "-" {
			fields[tag] = field
		}
		return false
	})

	cols, err := rows.Columns()
	if err != nil {
		return err
	}
	dest := make([]any, len(cols))
	for i, c := range cols {
		field, ok := fields[c]
		if !ok {
			return fmt.Errorf("no field with tag %q", c)
		}
		dest[i] = inner.FieldByIndex(field.Index).Addr().Interface()
	}

	return rows.Scan(dest...)
}