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

package pgruntime

import (
	"context"
	"database/sql"
	"strings"

	"go.xyrillian.de/gg/errext"
	"go.xyrillian.de/gg/gsql"
)

// Convenience function for executing a one-off SQL query returning no rows.
// TODO: move to gsql
func execQuery(ctx context.Context, db gsql.Handle, query string, args []any) (sql.Result, error) {
	stmt, err := db.GSQLPrepare(ctx, query, false)
	if err != nil {
		return nil, err
	}
	result, err := stmt.Exec(ctx, args)
	return result, errext.WithCleanup(err, "stmt.Close", stmt.Close())
}

// Convenience function for executing a one-off SQL query returning one row.
func queryRow(ctx context.Context, db gsql.Handle, query string, args, slots []any) error {
	stmt, err := db.GSQLPrepare(ctx, query, false)
	if err != nil {
		return err
	}
	err = stmt.QueryRow(ctx, args, slots)
	return errext.WithCleanup(err, "stmt.Close", stmt.Close())
}

// Convenience function for executing a one-off SQL query returning one value.
// TODO: move to gsql
func selectOneValue[T any](ctx context.Context, db gsql.Handle, query string, args ...any) (T, error) {
	stmt, err := db.GSQLPrepare(ctx, query, false)
	if err != nil {
		var none T
		return none, err
	}

	var result T
	err = stmt.QueryRow(ctx, args, []any{&result})
	return result, errext.WithCleanup(err, "stmt.Close", stmt.Close())
}

// Convenience function for executing a one-off SQL query returning several single-column rows.
// TODO: move to gsql (and also add ForeachValue with a callback instead of a slice return, maybe even ForeachPair and ForeachTriple)
func selectSeveralValues[T any](ctx context.Context, db gsql.Handle, query string, args ...any) ([]T, error) {
	rows, err := db.GSQLQuery(ctx, query, args)
	if err != nil {
		return nil, err
	}
	var result []T
	for rows.Next() {
		// TODO: this should share growRecordSlice() from Oblast to optimize allocations
		var value T
		err := rows.Scan(&value)
		if err != nil {
			return nil, errext.WithCleanup(err, "rows.Close", rows.Close())
		}
		result = append(result, value)
	}
	return result, errext.WithCleanup(nil, "rows.Err", rows.Err())
}

// Convenience function for preparing an identifier that needs to be inserted into a query verbatim
// (e.g. a database name for CREATE DATABASE).
func quoteIdentifier(name string) string {
	return `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
}