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

package gg_pgx

import (
	"context"
	"database/sql"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
	"go.xyrillian.de/gg/gsql"
)

type pgxExecutor interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) // TODO: remove after splitting Handle types
	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

var (
	_ pgxExecutor = &pgx.Conn{}
	_ pgxExecutor = &pgxpool.Conn{}
	_ pgxExecutor = pgx.Tx(&pgxpool.Tx{})
)

type wrappedPreparedStatement struct {
	ctx        context.Context
	statement  *pgconn.StatementDescription
	executor   pgxExecutor
	deallocate func(ctx context.Context, name string) error
}

type wrappedUnpreparedStatement struct {
	query    string
	executor pgxExecutor
}

var (
	_ gsql.Statement = wrappedPreparedStatement{}
	_ gsql.Statement = wrappedUnpreparedStatement{}
)

// Close implements the [gsql.Statement] interface.
func (s wrappedPreparedStatement) Close() error {
	return s.deallocate(s.ctx, s.statement.Name)
}

// Close implements the [gsql.Statement] interface.
func (s wrappedUnpreparedStatement) Close() error {
	return nil
}

// Exec implements the [gsql.Statement] interface.
func (s wrappedPreparedStatement) Exec(ctx context.Context, args []any) (sql.Result, error) {
	result, err := s.executor.Exec(ctx, s.statement.Name, args...)
	return wrappedResult{result}, err
}

// Exec implements the [gsql.Statement] interface.
func (s wrappedUnpreparedStatement) Exec(ctx context.Context, args []any) (sql.Result, error) {
	result, err := s.executor.Exec(ctx, s.query, args...)
	return wrappedResult{result}, err
}

// QueryRow implements the [gsql.Statement] interface.
func (s wrappedPreparedStatement) QueryRow(ctx context.Context, args, slots []any) error {
	return s.executor.QueryRow(ctx, s.statement.Name, args...).Scan(slots...)
}

// QueryRow implements the [gsql.Statement] interface.
func (s wrappedUnpreparedStatement) QueryRow(ctx context.Context, args, slots []any) error {
	return s.executor.QueryRow(ctx, s.query, args...).Scan(slots...)
}