mercury/internal/database/sql/queries.go

70 lines
1.7 KiB
Go

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"
"github.com/rs/zerolog/log"
)
var LogQueries = true
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)
if LogQueries {
log.Debug().Str("query", query.Query(sqlf.PostgresBindVar)).Msg("executing select query")
}
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
if LogQueries {
log.Debug().Str("query", query.Query(sqlf.PostgresBindVar)).Msg("executing get query")
}
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
}
func Exec(ctx context.Context, querier Querier, query *sqlf.Query) error {
if LogQueries {
log.Debug().Str("query", query.Query(sqlf.PostgresBindVar)).Msg("executing exec query")
}
_, err := querier.Exec(ctx, query.Query(sqlf.PostgresBindVar), query.Args()...)
return err
}