sqlc transaction wrapper that keeps call sites clean

13158
0

When using sqlc, the generated query set usually has a WithTx method. I wrap that pattern so business logic can depend on an interface and still run inside a transaction. The key is to keep transaction boundaries explicit while avoiding passing *sql.Tx everywhere. The helper below begins a transaction, creates a transaction-bound querier via WithTx, runs the function, and commits on success. defer tx.Rollback() is the boring safety net that prevents leaked transactions on early returns. In production, I also set an isolation level via sql.TxOptions and I ensure ctx has a deadline so transactions don’t sit open. This is a small abstraction, but it keeps service methods tidy and makes unit testing easier because you can mock the interface.