nettools/pg/pg.go

51 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-11-12 08:45:45 +00:00
package pgUtils
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/matchsystems/werr"
2024-11-12 08:45:45 +00:00
)
type PgxQuerier interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}
// Query executes query on a provided querier and tries to parse db response
// Works only with structs
2024-11-12 08:45:45 +00:00
//
// Usage:
//
// type User struct {
2024-11-12 08:53:46 +00:00
// Id int `db:"id"`
// Name string `db:"name"`
2024-11-12 08:45:45 +00:00
// }
//
// db := pgx.Connect(context.Background(), "<url>")
// users, err := pgUtils.Query[User](context.Background(), db, "SELECT id, name FROM users")
func Query[T any](ctx context.Context, db PgxQuerier, query string, args ...any) (out []T, err error) {
2024-11-12 08:45:45 +00:00
rows, err := db.Query(ctx, query, args)
if err != nil {
return nil, err
}
entities, err := pgx.CollectRows(rows, pgx.RowToStructByNameLax[T])
if err != nil {
return nil, werr.Wrapf(err, "failed to parse query results")
2024-11-12 08:45:45 +00:00
}
return entities, nil
2024-11-12 08:45:45 +00:00
}
// Tx creates new transaction. Cancels it if returned not nil err
func Tx(ctx context.Context, db *pgxpool.Pool, exec func(ctx context.Context, tx pgx.Tx) error) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
err = exec(ctx, tx)
if err != nil {
_ = tx.Rollback(ctx)
return err
}
return tx.Commit(ctx)
}