Files
dbx/query.go
T
end 8d697eda5b feat: add delete, context, and tx helpers
Add Delete/DeleteAffected, context-aware CRUD helpers, WithTx, ContainsCol,
and queryReturning deduplication for returning statements.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 17:49:57 -07:00

73 lines
2.4 KiB
Go

package dbx
import (
"context"
"errors"
)
// Fetch queries the database and returns the result as a slice. If the query
// returns no rows, it returns an empty slice and no error.
func Fetch[T any](sqlo Queryable, stmt Statement) ([]*T, error) {
return FetchContext[T](context.Background(), sqlo, stmt)
}
// FetchContext is the context-aware variant of [Fetch].
func FetchContext[T any](ctx context.Context, sqlo Queryable, stmt Statement) ([]*T, error) {
var result []*T
if err := stmt.QueryContext(ctx, sqlo, &result); err != nil && !errors.Is(err, ErrNoRows) {
return nil, err
}
return result, nil
}
// MustFetch queries the database and returns the result as a slice. If the query
// returns no rows, it returns an empty slice and the desired error.
func MustFetch[T any](sqlo Queryable, stmt Statement, notFoundErr error) ([]*T, error) {
return MustFetchContext[T](context.Background(), sqlo, stmt, notFoundErr)
}
// MustFetchContext is the context-aware variant of [MustFetch].
func MustFetchContext[T any](ctx context.Context, sqlo Queryable, stmt Statement, notFoundErr error) ([]*T, error) {
result, err := FetchContext[T](ctx, sqlo, stmt)
if err != nil {
return nil, err
}
if len(result) == 0 {
return nil, notFoundErr
}
return result, nil
}
// FetchOne queries the database and returns a single result. If the query
// returns no rows, it returns nil and no error.
func FetchOne[T any](sqlo Queryable, stmt Statement) (*T, error) {
return FetchOneContext[T](context.Background(), sqlo, stmt)
}
// FetchOneContext is the context-aware variant of [FetchOne].
func FetchOneContext[T any](ctx context.Context, sqlo Queryable, stmt Statement) (*T, error) {
result, err := FetchContext[T](ctx, sqlo, stmt)
if err != nil {
return nil, err
}
if len(result) == 0 {
return nil, nil
}
return result[0], nil
}
// MustFetchOne queries the database and returns a single result. If the query
// returns no rows, it returns nil and the desired error.
func MustFetchOne[T any](sqlo Queryable, stmt Statement, notFoundErr error) (*T, error) {
return MustFetchOneContext[T](context.Background(), sqlo, stmt, notFoundErr)
}
// MustFetchOneContext is the context-aware variant of [MustFetchOne].
func MustFetchOneContext[T any](ctx context.Context, sqlo Queryable, stmt Statement, notFoundErr error) (*T, error) {
result, err := MustFetchContext[T](ctx, sqlo, stmt, notFoundErr)
if err != nil {
return nil, err
}
return result[0], nil
}