Wednesday, January 25, 2012

Indexed DB: Defining your structure, the new way

Some months ago I posted a blog post about defining your database structure. Because Indexed DB is still in draft, specifications can change from time to time. This is the case for the way you want to define your database structure. As I am typing now the only browser that is currently implementing this new specification is FireFox Nightly.
The way you create object stores and indexes hasn’t changed, but the way you can change it did. Changing your database structure still happens in a VERSION_CHANGE transaction, but the developer won’t be able to manually create a new VERSION_CHANGE transaction. Instead, the version of database you want to use needs to be provided when opening a database connection. When the database doesn’t have the version you requested, an onupgradeneeded event will occur. In this event you will be able to handle all your database changes like creating and deleting objectstores, creating and deleting indexes, …
But this all means that the SetVersion method for creating a VERSION_CHANGE transaction will become obsolete. So this means you will always have to define your database structure before you can start using them, even for indexes.
So how does this new way look like?
   1: var req =, databaseVersion);
   2: req.onsuccess = function (e) {
   3:     // Opening of the databas in the given version was succesfull
   4: }
   6: req.onerror = function (e) {
   7:     // Error while opening the database
   8: }
  10: req.onupgradeneeded = function (e){
  11:     // Event for handeling the database structure changes
  12: }
  14: req.onblocked = function (e){
  15:     // Handles the database open request while the database gets upgraded
  16: }

The onblocked event was also added with the onupgradeneeded event. The onblock event will handle attempts to open the database while the database is upgrading to a more recent version. This way you can notify the user the request was blocked and they need to retry later.

As last there is an onversionchange event added on the databse object. This event will be called when the database is about to upgraded to a newer version. This way you’ll be able to close your current connection so you don’t get an error later on.

   1: var req =, databaseVersion);
   3: req.onsuccess = function (e) {
   4:     req.result.onversionchange = function(){
   5:         // Close your connection
   6:     }  
   7: }

1 comment:

  1. Well done thanks for the updates