From 076df67d62e252fa625f1738344f64701ac9c14c Mon Sep 17 00:00:00 2001 From: Jason Date: Thu, 4 Aug 2022 21:08:04 +0000 Subject: [PATCH] docs: Update transactions how to example --- docs/howto/transactions.md | 55 +++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/docs/howto/transactions.md b/docs/howto/transactions.md index ce822b07b4..bc93ebd661 100644 --- a/docs/howto/transactions.md +++ b/docs/howto/transactions.md @@ -1,32 +1,40 @@ # Using transactions +In the code generated by sqlc, the `WithTx` method allows a `Queries` instance to be associated with a transaction. +For example, with the following SQL structure: + +`schema.sql`: ```sql CREATE TABLE records ( id SERIAL PRIMARY KEY, counter INT NOT NULL ); +``` +`query.sql` +```sql -- name: GetRecord :one SELECT * FROM records WHERE id = $1; -``` -The `WithTx` method allows a `Queries` instance to be associated with a transaction. +-- name: UpdateRecord :exec +UPDATE records SET counter = $2 +WHERE id = $1; +``` +And the generated code from sqlc in `db.go`: ```go -package db +package tutorial import ( "context" "database/sql" ) -type Record struct { - ID int - Counter int -} - type DBTX interface { + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) QueryRowContext(context.Context, string, ...interface{}) *sql.Row } @@ -38,38 +46,29 @@ type Queries struct { db DBTX } -func (*Queries) WithTx(tx *sql.Tx) *Queries { - return &Queries{db: tx} +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } } -const getRecord = `-- name: GetRecord :one -SELECT id, counter FROM records -WHERE id = $1 -` - -func (q *Queries) GetRecord(ctx context.Context, id int) (Record, error) { - row := q.db.QueryRowContext(ctx, getRecord, id) - var i Record - err := row.Scan(&i.ID, &i.Counter) - return i, err -} ``` -With pgx you'd use it like this for example: +You'd use it like this: ```go -func bumpCounter(ctx context.Context, p *pgx.Conn, id int) error { - tx, err := db.Begin(ctx) +func bumpCounter(ctx context.Context, db *sql.DB, queries *tutorial.Queries, id int32) error { + tx, err := db.Begin() if err != nil { return err } defer tx.Rollback() - q := db.New(tx) - r, err := q.GetRecord(ctx, id) + qtx := queries.WithTx(tx) + r, err := qtx.GetRecord(ctx, id) if err != nil { return err } - if err := q.UpdateRecord(ctx, db.UpdateRecordParams{ + if err := qtx.UpdateRecord(ctx, tutorial.UpdateRecordParams{ ID: r.ID, Counter: r.Counter + 1, }); err != nil { @@ -77,4 +76,4 @@ func bumpCounter(ctx context.Context, p *pgx.Conn, id int) error { } return tx.Commit() } -``` +``` \ No newline at end of file