title: Mutations and transactions description: Execute writes, read returned rows, and control transaction boundaries with pgx. #
Generated mutation methods depend on whether the SQL includes RETURNING.
Use Exec for an affected-row count or the query result methods
to read returned rows. Both accept pgx connections, pools, and transactions.
Execute without RETURNING #
An INSERT, UPDATE, or DELETE without RETURNING generates an Exec method:
affected, err := store.DeleteBook(id).Exec(ctx, pool)
affected is the number of affected rows as an int64. Zero matched rows is a
successful count of zero. Context cancellation and database errors are returned
through err.
Read returned rows #
A mutation with RETURNING generates the same result-reading methods as a SELECT:
book, err := store.RenameBook(id, "Kindred").SelectOne(ctx, pool)
Use Select when the mutation can return multiple rows. SelectAs and
SelectOneAs let you choose an application result type; see
Querying for mapping rules.
A query with RETURNING currently has no Exec method.
Transactions #
The application owns transaction boundaries. Pass the transaction directly to generated methods:
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err := store.RenameBook(id, "Kindred").SelectOne(ctx, tx); err != nil {
return err
}
return tx.Commit(ctx)
A cardinality error from SelectOne does not undo a mutation. If an unexpected number of returned rows must invalidate a write, roll back the transaction. Transaction retries, locking, and business validation remain application decisions. Check SQL support for locking clauses the compiler does not yet support.