aboutsummaryrefslogtreecommitdiff
path: root/db.go
blob: 8f1a050deac12d3101bcbf022dcfbf9a52a2103e (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
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
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0

package oblast

import (
	"context"
	"database/sql"
	"fmt"
	"reflect"
	"sync"
)

// DB wraps an [sql.DB] instance for use with Oblast's query interface.
type DB struct {
	*sql.DB
	dialect   Dialect
	plans     map[reflect.Type]plan
	planMutex sync.Mutex
}

func NewDB(db *sql.DB, dialect Dialect) *DB {
	return &DB{
		DB:      db,
		dialect: dialect,
		plans:   make(map[reflect.Type]plan),
	}
}

// TODO: remove
func Keks[T IsTable](ctx context.Context, db *DB) error {
	_, err := db.getPlan(reflect.TypeFor[T]())
	return err
}

// TODO: Begin() -> custom Tx type; add interface to allow Select() et all to take either *DB or *Tx

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
}