//go:build test // +build test package testtx import ( "context" "testing" "crussell/db" ) // txSemaphore limits concurrent test transactions per package. var txSemaphore = make(chan struct{}, 8) // SetupTestTx begins a transaction, stores it in context, and auto-rolls back. func SetupTestTx(t *testing.T) (context.Context, db.Querier) { t.Helper() txSemaphore <- struct{}{} pool := db.Conn.Pool() tx, err := pool.Begin(context.Background()) if err != nil { <-txSemaphore t.Fatalf("SetupTestTx: failed to begin transaction: %v", err) } ctx := db.ContextWithTx(context.Background(), tx) t.Cleanup(func() { tx.Rollback(context.Background()) <-txSemaphore }) return ctx, tx }