Skip to main content
Version: 1.0 (Latest)

Transactions

Transactions allow you to group together a number of database operations that must either succeed together or not at all. DefraDB wraps all database operations in transactions by default – you can however also manually start a transaction, enqueue a number of operations in it (ex. create or update a number of documents), and commit or discard it.

Open transactions

Open a new transaction with the CLI command defradb client tx new. The returned transaction ID is needed for all operations that want to act within this transaction.

Example – Open a new transaction
defradb client tx new
Result
{"id":27}
Expiration

A transaction automatically expires after 60 seconds of inactivity. Tweak the default expiration with the flag --ttl <seconds>.

Run operations within transactions

Execute database operations (such as creating or altering collections/documents) within a transaction by providing the flag --tx <id> to the CLI commands running such operations.

Example – Create a collection and a document within a transaction
defradb client collection add --tx 27 '
type Book {
title: String!
plot: String
rating: Float
}
'
defradb client query --tx 27 '
mutation {
add_Book(input:{
title: "The meaning of it all"
}) { title }
}
'

Commit transactions

Commit a transaction with the CLI command defradb client tx commit, providing the ID of an open transaction. All changes get written into memory.

Example – Commit the transaction with ID 27
defradb client tx commit 27

Discard transactions

Discard a transaction with the CLI command defradb client tx discard, providing the ID of an open transaction. All changes enqueued in the transaction are discarded.

Example – Discard the transaction with ID 27
defradb client tx discard 27