Skip to content

Transactions

Robert Gaggl edited this page Feb 27, 2016 · 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.

Commit event

Whenever a transaction is committed successfully, the store emits a "commit" event to all bound listeners. The payload of the event consists of an object containing four properties:

{
    "inserted": {},
    "updated": {},
    "deleted": {},
    "collections": {}
}

Each of these payload properties contain an object with the entity instances affected during a transaction. The property name is the cache key, a string used to retrieve an entity data object from SQLstore's entity cache, and the value is the instance.

This commit event can be used to synchronize caches across application instances by binding a listener to the event and transferring the cache keys (eg. via WebSocket) to the other applications, which would in turn remove them from their local entity cache and thus loading the new values from the database whenever they're needed.

For more information on how to bind an event listener see the documentation of RingoJS' events module.

Clone this wiki locally