New types and helpers for context-aware DB routing and per-test transactions: - PoolProxy: wraps pgxpool.Pool, routes queries through context transaction when active - Querier: interface accepted by fixture/helper functions for decoupling - ContextWithTx / TxFromContext: store/extract pgx.Tx in context.Context - SetupTestTx (in testutils): begins tx, stores in context, auto-rolls back on cleanup - SetupTestTx (in testtx): package-level variant with semaphore for parallel safety Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
25 lines
625 B
Go
25 lines
625 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type ctxKey string
|
|
|
|
const txCtxKey ctxKey = "poolproxy_tx"
|
|
|
|
// ContextWithTx stores a pgx.Tx in the context for PoolProxy routing.
|
|
// When PoolProxy.Exec/Query/QueryRow sees this context key, it routes the
|
|
// call through the stored transaction instead of the pool.
|
|
func ContextWithTx(ctx context.Context, tx pgx.Tx) context.Context {
|
|
return context.WithValue(ctx, txCtxKey, tx)
|
|
}
|
|
|
|
// TxFromContext extracts a pgx.Tx from context (returns nil if none active).
|
|
func TxFromContext(ctx context.Context) pgx.Tx {
|
|
tx, _ := ctx.Value(txCtxKey).(pgx.Tx)
|
|
return tx
|
|
}
|