Skip to content

Concepts

Transactions

An interactive transaction groups statements into one unit that succeeds or fails as a whole. A text transaction puts all its statements in one query (BEGIN TRANSACTION; ... COMMIT TRANSACTION;), and the query builder can build one. An interactive transaction lets your Go code run statements one at a time and read their results. Your code can then decide whether to commit or cancel.

This page shows how to start a transaction and run statements in it. It also lists the limits of a transaction.

Interactive transactions need a WebSocket connection (ws:// or wss://). On an HTTP connection, Begin returns constants.ErrTransactionsNotSupported.

Method

Description

db.Begin(ctx)

Starts a transaction in the default session

session.Begin(ctx)

Starts a transaction in a session

tx.Commit(ctx)

Commits the transaction, applying its changes

tx.Cancel(ctx)

Cancels the transaction, discarding its changes

tx.ID()

Returns the UUID of the transaction

tx.IsClosed()

Reports whether the transaction was committed or cancelled

Call .Begin() on a *DB or a *Session. The transaction runs as the signed-in user of the session, in the namespace and database of the session:

tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)
Note

Call defer tx.Cancel(ctx) directly after .Begin(), so that .Cancel() discards the transaction when a later step fails or returns early. After a commit, .Cancel() returns constants.ErrTransactionClosed and changes nothing.

Every query and CRUD function takes a *Transaction in place of the *DB:

tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

if _, err := surrealdb.Create[any](ctx, tx, models.NewRecordID("account", "alice"), map[string]any{
	"balance": 1000,
}); err != nil {
	log.Fatal(err)
}

if _, err := surrealdb.Create[any](ctx, tx, models.NewRecordID("account", "bob"), map[string]any{
	"balance": 500,
}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}

Other sessions and connections cannot see the changes in a transaction until you commit it.

Because each statement returns before the next one runs, your code can read a result and decide what to do. This transfer reads a balance first. When the balance is too low, the code cancels the transaction:

type Account struct {
	ID      *models.RecordID `json:"id,omitempty"`
	Balance int              `json:"balance"`
}

tx, err := db.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

alice, err := surrealdb.Select[Account](ctx, tx, models.NewRecordID("account", "alice"))
if err != nil {
	log.Fatal(err)
}

amount := 100
if alice == nil || alice.Balance < amount {
	fmt.Println("insufficient balance")
	return
}

if _, err := surrealdb.Query[any](ctx, tx, `
	UPDATE account:alice SET balance -= $amount;
	UPDATE account:bob SET balance += $amount;
`, map[string]any{"amount": amount}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}

When return runs, the deferred .Cancel() discards the transaction.

QueryStream works in a transaction too. When you leave the loop early, the SDK waits for the server to end the cancelled query. This makes sure that a later .Commit() or .Cancel() comes after the end of that query. The statements that ran before you left the loop stay in the transaction. To discard them, call .Cancel() rather than .Commit().

A transaction cannot change the state of its session. A *Transaction has none of these methods:

  • .SignIn(), .SignUp(), .Authenticate() and .Invalidate()

  • .Use()

  • .Let() and .Unset()

Live queries belong to a session, so Live and Kill do not take a *Transaction.

An open transaction is lost when the connection is lost. When the client reconnects, it does not start the transaction again, and later calls on it fail. In that case, retry the whole transaction.

A transaction can fail to commit because another transaction changed the same data. surrealdb.IsTransactionConflict reports this failure. Running the transaction again usually succeeds.

Was this page helpful?

Last updated