Skip to content

Transactions

Robert Gaggl edited this page Sep 30, 2012 · 4 revisions

Transactions

SQLstore supports transactions in multiple ways. The first is to manually open a transaction and pass it to every call of an entity's save or remove method.

var transaction = store.createTransaction();
var author = new Author({
    "name": "John Doe"
});
author.save(transaction);
// ...
transaction.commit();

To roll back a transaction call .rollback() of the Transaction instance. Every transaction instance has a method isDirty() that returns true for transactions having uncommitted changes.

Keeping a reference to the created transaction instance to pass it to save() or remove() can be cumbersome, so SQLstore supports a second, albeit less explicit way of using transactions:

// create a new transaction
store.beginTransaction();
var author = new Author({
    "name": "John Doe"
});
author.save();

// ...

// commit the transaction
store.commitTransaction();

beginTransaction() creates a new transaction instance and binds it to the current thread. After calling this method you can operate freely without having to pass a transaction instance to save() or remove(). You can even manually create a separate transaction and use this one for a subset of operations if necessary. To commit the thread's transaction call the store's method .commitTransaction(), to abort it .abortTransaction().

Initiating a transaction like above has an additional benefit: all database operations will use the connection of the transaction, so even if data modifications aren't committed yet they are visible in queries etc. within the thread owning the transaction. Even if collections are invalidated within an open transaction, up-to-then uncommitted changes (eg. an added entity instance) will be visible, again only for the owning thread.

The latter method of creating and committing transactions is used by RingoJS' transaction middleware.

Clone this wiki locally