aboutsummaryrefslogtreecommitdiff
path: root/query.go
blob: 94dc17b1585cfe63abcb3afc46e31ff22f3c66fc (plain)
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
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0

package oblast

import (
	"context"
	"fmt"
	"reflect"
)

func Select[T any](ctx context.Context, db *DB, query string, args ...any) ([]T, error) {
	// TODO: minimize function body to avoid binary size blowup from monomorphization
	// TODO: catch error from rows.Close(), if any
	// TODO: add context to errors

	plan, err := db.getPlan(reflect.TypeFor[T]())
	if err != nil {
		return nil, err
	}
	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	columnNames, err := rows.Columns()
	if err != nil {
		return nil, err
	}
	indexes := make([][]int, len(columnNames))
	for idx, columnName := range columnNames {
		var ok bool
		indexes[idx], ok = plan.IndexByColumnName[columnName]
		if !ok {
			var zero T
			return nil, fmt.Errorf("result has column %q in position %d, but no field in %T has `db:%[1]q`",
				columnName, idx, zero)
		}
	}

	var result []T
	slots := make([]any, len(indexes))
	for rows.Next() {
		var target T
		rvalue := reflect.ValueOf(&target).Elem()
		for idx, index := range indexes {
			slots[idx] = rvalue.FieldByIndex(index).Addr().Interface()
		}
		err := rows.Scan(slots...)
		if err != nil {
			return nil, err
		}
		result = append(result, target)
	}

	return result, nil
}