mercury/internal/database/sql/queries.go

51 lines
1.2 KiB
Go
Raw Normal View History

2023-09-03 00:23:48 +02:00
package sql
import (
"context"
"emperror.dev/errors"
"github.com/georgysavva/scany/v2/pgxscan"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/keegancsmith/sqlf"
)
type Querier interface {
Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
}
type ReleaseableQuerier interface {
Querier
Release()
}
type Tx interface {
Querier
Commit(ctx context.Context) error
Rollback(ctx context.Context) error
}
func Select[T any](ctx context.Context, querier Querier, query *sqlf.Query) ([]T, error) {
dst := make([]T, 0)
err := pgxscan.Select(ctx, querier, &dst, query.Query(sqlf.PostgresBindVar), query.Args()...)
if err != nil {
return []T{}, errors.Wrap(err, "executing query")
}
return dst, nil
}
func Get[T any](ctx context.Context, querier Querier, query *sqlf.Query) (T, error) {
var dst T
err := pgxscan.Get(ctx, querier, &dst, query.Query(sqlf.PostgresBindVar), query.Args()...)
if err != nil {
return dst, errors.Wrap(err, "executing query")
}
return dst, nil
}