Wednesday, November 2, 2011

Indexed DB: Transactions

Today, I’ll handle the transaction subject. As said in previous posts, every request made to the database needs to be done in a transaction. So for every read or write request we need to create a new transaction. There for we need a database connection and 2 argument that we will pass to the transaction method.

The first argument will define the scope of the transaction. Here we pass all the object stores we want to use during the transaction. We do this by passing the object store names in an array. Providing an empty array will allow to use all available object stores in the database.

The second argument is the mode we want to use to access the data. This is an optional parameter and if not provided the transaction will be created read only by default. If you want to manipulate data, you’ll need to pass IDBTransaction.READ_WRITE. There is also a third mode, CHANGE_VERSION, but this type of transaction can only be created in the setVersion method. More about this method can be found in my post about Indexed DB: Defining the database structure

var txn = dbconnection.transaction([], IDBTransaction.READ_WRITE);

txn.oncomplete = function () {
     // Transaction successful
txn.onabort = function () {
    // Code to handle the abort of the transaction
txn.onerror = function () {
// Code to handle the error

For a transaction we have 3 possible outcomes. The first one is that the transaction is committed and so got completed. This function will be called if the transaction was successful and in the case we were reading data, we can here write the code to show the retrieved data it in the browser. Keep in mind that a transaction in the Indexed DB API is committed by default, but in IE9 you still need to do this manually.

The onabort function will be called when we manually call the abort function on the transaction object. This means the transaction must do a rollback.

The last one will handle all the errors that can occur within the transaction, this will also mean that the transaction must rollback.

Now that we know how to create a transaction, we can start retrieving and manipulating data from our database. This will be the next subject of my future posts.

No comments:

Post a Comment