Skip to content

API Reference

/

Core

Transaction

A Transaction is an interactive transaction on a WebSocket connection. Unlike a text transaction, it runs statements one at a time, so your code can read each result and then commit or cancel. Every query and CRUD function, such as Query, Select and QueryStream, takes a *Transaction in place of a *DB. See Transactions for explanations and examples.

A transaction runs as the signed-in user of its session, in the namespace and database of that session. A transaction cannot change that state. For this reason, it has no SignIn, Use or Let methods, and Live and Kill do not take it. When the client loses the connection, it also loses any open transaction.

Source: transaction.go

Starts a transaction in the default session.

Syntax
tx, err := db.Begin(ctx)

Returns: (*Transaction, error). On an HTTP connection, the error is constants.ErrTransactionsNotSupported.

Starts a transaction in a session.

Syntax
tx, err := session.Begin(ctx)

Returns: (*Transaction, error). After session.Detach(), the error is constants.ErrSessionClosed.

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

if _, err := surrealdb.Create[any](ctx, tx, "event", map[string]any{
	"type":   "transfer",
	"amount": 100,
}); err != nil {
	log.Fatal(err)
}

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

Returns the UUID of the transaction.

Syntax
id := tx.ID()

Returns: *models.UUID

Returns the UUID of the session that started the transaction, or nil for a transaction in the default session.

Syntax
sessionID := tx.SessionID()

Returns: *models.UUID

Reports whether the transaction was committed or cancelled.

Syntax
closed := tx.IsClosed()

Returns: bool

Commits the transaction, and makes its changes permanent. After that, you cannot use the transaction.

Syntax
err := tx.Commit(ctx)

Returns: error. For a transaction that was already committed or cancelled, the error is constants.ErrTransactionClosed. When another transaction changed the same data, surrealdb.IsTransactionConflict reports the conflict, and you can run the transaction again.

Cancels the transaction, and discards its changes. After that, you cannot use the transaction.

Syntax
err := tx.Cancel(ctx)

Returns: error

On a transaction that was already committed or cancelled, .Cancel() returns constants.ErrTransactionClosed and changes nothing. This makes defer tx.Cancel(ctx) safe directly after .Begin().

  • DB for starting a transaction in the default session

  • Session for starting a transaction in a session

  • Transactions for transaction usage patterns

  • Errors for ErrTransactionClosed and ErrTransactionsNotSupported

Was this page helpful?

Last updated