Transactions, concurrency and queries · 4 MIN READ

Transactions and RETURNING: all-or-nothing changes that hand back what they wrote

Group related writes in a database/sql transaction that always rolls back on failure, read generated values with RETURNING, and classify a constraint failure by its extended SQLite result code.

A transfer that debits one account and fails to credit the other is worse than no transfer at all. A transaction makes the two updates one unit: SQLite commits both or neither, even if the process dies halfway. RETURNING, available since SQLite 3.35, lets an INSERT or UPDATE report the values it produced, so you learn the new id, a default or the updated balance without a second query that could see a different state.

sqlite · A MAP OF THE IDEA

  1. BeginTx with request ctx
  2. defer tx.Rollback()
  3. Writes with RETURNING
  4. Commit and map codes

Useful when

  • Constraints enforce invariants even if application code has a bug.
  • RETURNING removes a second query and its race.

Watch out

  • Statements on db instead of tx escape the transaction.
  • A long transaction holds the single write lock.

Implementation & operation cost: One pinned connection per transaction and an error-mapping function; the discipline is keeping slow work outside the transaction.

01

BeginTx, defer Rollback, Commit

db.BeginTx borrows one connection from the pool and pins it to the *sql.Tx until Commit or Rollback; every statement must go through tx, not db, or it runs on a different connection outside the transaction. The idiom is to defer tx.Rollback() immediately after BeginTx. On every early return the deferred call undoes the partial work; after a successful Commit it returns sql.ErrTxDone and changes nothing, so it is safe to ignore. A failed statement, such as a constraint violation, undoes only that statement: the transaction stays open with the earlier writes, and a Commit at that point would keep them. The deferred Rollback is what discards them and returns the connection to the pool in a clean state.

go
tx, err := db.BeginTx(ctx, nil)
if err != nil {
	return err
}
defer tx.Rollback() // no-op once Commit has succeeded

if _, err := tx.ExecContext(ctx, debit, amount, from); err != nil {
	return err // the deferred Rollback undoes nothing committed
}
if _, err := tx.ExecContext(ctx, credit, amount, to); err != nil {
	return err // the debit is undone too
}
return tx.Commit()
Read the code

Both writes go through tx, so they share one connection and one transaction. Any error returns before Commit and the deferred Rollback discards the debit; only the final Commit makes the pair visible to other connections.

02

A transfer with a CHECK constraint and RETURNING

The program stores balances with CHECK (balance >= 0), so the database itself refuses an overdraft. Accounts are opened with INSERT ... RETURNING id, opened, which returns the generated rowid and the column default in the same statement. The debit is UPDATE ... RETURNING balance read with QueryRowContext: when the WHERE clause matches no row, RETURNING produces no row and Scan reports sql.ErrNoRows, so an unknown account fails loudly instead of silently crediting money that was never debited.

go
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"modernc.org/sqlite"
	sqlite3 "modernc.org/sqlite/lib"
)

// transfer moves amount between two accounts atomically: both updates commit or neither does.
func transfer(ctx context.Context, db *sql.DB, from, to string, amount int) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() // a no-op after a successful Commit

	var left int
	if err := tx.QueryRowContext(ctx,
		"UPDATE accounts SET balance = balance - ? WHERE name = ? RETURNING balance",
		amount, from).Scan(&left); err != nil {
		return fmt.Errorf("debit %s: %w", from, err)
	}
	if _, err := tx.ExecContext(ctx,
		"UPDATE accounts SET balance = balance + ? WHERE name = ?", amount, to); err != nil {
		return fmt.Errorf("credit %s: %w", to, err)
	}
	if err := tx.Commit(); err != nil {
		return err
	}
	fmt.Printf("moved %d from %s to %s, %s now has %d\n", amount, from, to, from, left)
	return nil
}

func balances(ctx context.Context, db *sql.DB) string {
	rows, err := db.QueryContext(ctx, "SELECT name, balance FROM accounts ORDER BY name")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var name string
		var balance int
		if err := rows.Scan(&name, &balance); err != nil {
			log.Fatal(err)
		}
		out = append(out, fmt.Sprintf("%s=%d", name, balance))
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
	return strings.Join(out, " ")
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "tx")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	db, err := sql.Open("sqlite", filepath.Join(dir, "bank.db"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if _, err := db.ExecContext(ctx, `CREATE TABLE accounts (
		id      INTEGER PRIMARY KEY,
		name    TEXT NOT NULL UNIQUE,
		balance INTEGER NOT NULL CHECK (balance >= 0),
		opened  TEXT NOT NULL DEFAULT 'day-1'
	)`); err != nil {
		log.Fatal(err)
	}

	// RETURNING hands back generated values from the same statement.
	for _, name := range []string{"alice", "bob"} {
		var id int64
		var opened string
		if err := db.QueryRowContext(ctx,
			"INSERT INTO accounts (name, balance) VALUES (?, 100) RETURNING id, opened",
			name).Scan(&id, &opened); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("opened %s: id=%d opened=%s\n", name, id, opened)
	}

	if err := transfer(ctx, db, "alice", "bob", 30); err != nil {
		log.Fatal(err)
	}
	fmt.Println("after first transfer:", balances(ctx, db))

	err = transfer(ctx, db, "alice", "bob", 500)
	fmt.Println("second transfer failed:", err)
	var se *sqlite.Error
	if errors.As(err, &se) {
		fmt.Println("extended code:", se.Code(), "is CHECK:", se.Code() == sqlite3.SQLITE_CONSTRAINT_CHECK,
			"primary code:", se.Code()&0xff)
	}
	fmt.Println("after failed transfer:", balances(ctx, db))

	err = transfer(ctx, db, "carol", "bob", 10)
	fmt.Println("unknown account:", errors.Is(err, sql.ErrNoRows))
	fmt.Println("after unknown account:", balances(ctx, db))
}
Read the code

alice and bob receive ids 1 and 2 and the default opened value day-1. The first transfer moves 30 and the RETURNING clause reports alice at 70. The second asks for 500; the CHECK fails with extended code 275, SQLITE_CONSTRAINT_CHECK, whose low byte is 19, SQLITE_CONSTRAINT, and the balances stay 70 and 130. The transfer from carol fails with sql.ErrNoRows before any credit is written.

03

Classify errors by code, not by message

modernc.org/sqlite returns *sqlite.Error, whose Code method gives the extended result code, and modernc.org/sqlite/lib defines the constants. The low eight bits are the primary code: 19 is SQLITE_CONSTRAINT for every constraint, and the extended codes tell them apart, such as 2067 for UNIQUE, 1555 for PRIMARY KEY, 787 for FOREIGN KEY, 1299 for NOT NULL and 275 for CHECK. Map those to your own domain errors in the repository layer, for example a UNIQUE violation on email to ErrEmailTaken, so handlers never parse driver text. Other drivers expose the same numbers through their own error types, which is another reason to keep this mapping in one place.

04

What RETURNING can and cannot do

RETURNING works on INSERT, UPDATE and DELETE, and an UPSERT can return the row it inserted or updated. It reports each row as the statement wrote it, including defaults and generated rowids. SQLite documents its limits: it is available only on top-level statements, not inside triggers; it cannot contain aggregate or window functions; the order of rows from a multi-row statement is arbitrary; and it reports only rows the statement itself changed, not changes made by triggers or foreign key actions. SQLite performs all the changes on the first step and buffers the returned rows, but the Rows value still holds the transaction's connection, so read and close it before the next statement. Run such statements with Query or QueryRow, not Exec, when you want the values.

05

Keep transactions short

A write transaction in SQLite holds the database-wide write lock from its first write until Commit. Do the slow work, such as calling another service, hashing a password or rendering a template, before BeginTx, and do only SQL inside it. Pass the request context to BeginTx: database/sql rolls the transaction back if that context is cancelled before Commit, so an abandoned request cannot keep the lock. Never wait for user input or a network reply while a transaction is open, and never mix tx and db statements in the same unit of work.

TAKE THIS WITH YOU

Run related writes on one *sql.Tx with a deferred Rollback and a final Commit, let constraints enforce invariants, use RETURNING to read generated values and to detect a missing row, and classify failures by extended result code.

Check your understanding

A transfer debits with UPDATE ... RETURNING balance read through QueryRowContext. What happens when the source account does not exist?

Go to the source

Progress stays in this browser. No account needed.