Skip to Content
fusion-orm

Transactions

Callback-style Transaction with commit/rollback/panic handling, savepoint nesting, and manual Begin/Commit/Rollback.

fusion-orm gives you two ways to run work atomically: a callback-style Transaction that manages commit and rollback for you, and manual Begin/Commit/Rollback when you need the handle yourself.

Transaction(fc)

// Transaction runs fc inside a transaction: commit on nil error, rollback on
// error or panic (the panic still propagates after rollback). When the
// receiver is already inside a transaction, fc runs against a savepoint
// instead — RELEASE on success, ROLLBACK TO on failure — unless
// Config.DisableNestedTransaction runs it inline.
err := db.Transaction(func(tx *fusion.DB) error {
	return tx.Exec("INSERT INTO users (name) VALUES (?)", "alice").Error
})

The three exits:

  • fc returns nil — the transaction commits (transaction.go:62-64).
  • fc returns an error — the transaction rolls back and the error is returned unchanged (transaction_test.go:67-71).
  • fc panics — the transaction rolls back, then the panic is re-thrown; it does not become an error (transaction_test.go:88-108).

A failed transaction leaves the root *DB usable; the next statement opens a fresh transaction (transaction_test.go:79-85).

Manual Begin / Commit / Rollback

Begin returns a derivative whose Statement.ConnPool is the *sql.Tx, so every statement chained off it runs inside the transaction (transaction.go:74). Commit and Rollback finish it:

tx := db.Begin()
if tx.Error != nil {
	t.Fatalf("Begin: %v", tx.Error)
}
tx.Exec("INSERT INTO users (name) VALUES (?)", "alice")
if err := tx.Commit().Error; err != nil {
	t.Fatalf("Commit: %v", err)
}

tx = db.Begin()
tx.Exec("INSERT INTO users (name) VALUES (?)", "bob")
tx.Rollback() // the insert is undone

Begin accepts optional *sql.TxOptions and forwards them to BeginTx (transaction.go:79-81).

Commit outside a transaction

Commit or Rollback on an instance that is not inside a transaction records fusion.ErrInvalidTransaction in the error slot — it never panics (transaction.go:104, transaction.go:118).

Calling Commit twice on the same transaction surfaces sql.ErrTxDone from the driver on the second call (error_paths_test.go:85-99).

Nesting through savepoints

Calling Transaction on a tx that is already inside a transaction does not begin a second transaction — it creates a savepoint, runs the callback against it, and releases the savepoint on success or rolls back to it on failure (transaction.go:24-48). The inner failure does not doom the outer:

err := db.Transaction(func(outer *fusion.DB) error {
	outer.Exec("INSERT INTO users (name) VALUES (?)", "outer")

	innerErr := outer.Transaction(func(inner *fusion.DB) error {
		inner.Exec("INSERT INTO users (name) VALUES (?)", "inner")
		return errors.New("inner fails")
	})
	// innerErr != nil, but the outer insert is still live: the inner
	// failure rolled back to the savepoint only.
	return nil
})

Savepoint names are generated (sp1, sp2, …) from a process-wide counter, so they are unique and reusable across rounds (transaction.go:31, transaction_test.go:144-161).

DisableNestedTransaction

Set Config.DisableNestedTransaction (or the matching Session flag) and nested Transaction calls run inline instead: there is no savepoint, so an inner failure fails the outer call too and everything rolls back (fusion.go:70, transaction_test.go:163-186).

Manual savepoints

SavePoint(name) and RollbackTo(name) are public when you want the same control by hand. RollbackTo undoes statements back to the savepoint; the savepoint itself stays active (transaction.go:136).

tx := db.Begin()
tx.SavePoint("sp1")
tx.Exec("INSERT INTO users (name) VALUES (?)", "kept")
tx.SavePoint("sp2")
tx.Exec("INSERT INTO users (name) VALUES (?)", "undone")
tx.RollbackTo("sp2") // "kept" survives, "undone" does not
tx.Commit()

Two validations guard every savepoint call:

  • The name must be a plain identifier — [A-Za-z_][A-Za-z0-9_]* — quoted through the dialector. Anything hostile, including empty strings, records ErrInvalidValue (transaction.go:154-157, transaction_test.go:271):
err := tx.SavePoint("bad name; DROP TABLE users").Error
// errors.Is(err, fusion.ErrInvalidValue) == true
  • The dialect must declare feature.Savepoint — otherwise the call records an UnsupportedFeatureError naming the feature without executing anything (transaction.go:150-153). Both shipped dialects declare it (transaction_test.go:347-356).

The implicit transaction

Single Create/Update/Delete calls are wrapped in an implicit transaction by the default callback chains, so hook and association failures roll the whole operation back. Two escape hatches:

  • Config.SkipDefaultTransaction disables the wrapper globally (fusion.go:53).
  • Even with it enabled, a provably single-statement write — no relations, no hooks, no multi-chunk batch — skips the BEGIN/COMMIT round-trip, because a single statement is already atomic (callbacks_default.go:70-77).

Prepared statements inside transactions

When PrepareStmt is enabled, transactions get their own transaction-scoped statement cache (preparedTx), which is drained when the transaction commits or rolls back — cached statements never leak past the transaction boundary (prepared_stmt.go:222, prepared_stmt.go:291-309). See Prepared statements.

Next

On this page