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
Creating a transaction
db.Begin()
Starts a transaction in the default session.
tx, err := db.Begin(ctx)Returns: (*Transaction, error). On an HTTP connection, the error is constants.ErrTransactionsNotSupported.
session.Begin()
Starts a transaction in a session.
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)
}Properties
.ID()
Returns the UUID of the transaction.
id := tx.ID()Returns: *models.UUID
.SessionID()
Returns the UUID of the session that started the transaction, or nil for a transaction in the default session.
sessionID := tx.SessionID()Returns: *models.UUID
.IsClosed()
Reports whether the transaction was committed or cancelled.
closed := tx.IsClosed()Returns: bool
Methods
.Commit()
Commits the transaction, and makes its changes permanent. After that, you cannot use the transaction.
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.
.Cancel()
Cancels the transaction, and discards its changes. After that, you cannot use the transaction.
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().
See also
DB for starting a transaction in the default session
Session for starting a transaction in a session
Transactions for transaction usage patterns
Errors for
ErrTransactionClosedandErrTransactionsNotSupported