HTML5 Zone is brought to you in partnership with:

Raymond Camden is a developer evangelist for Adobe. His work focuses on web standards, mobile development and Cold Fusion. He's a published author and presents at conferences and user groups on a variety of topics. He is the happily married proud father of three kids and is somewhat of a Star Wars nut. Raymond can be reached via his blog at www.raymondcamden.com or via email at raymondcamden@gmail.com Raymond is a DZone MVB and is not an employee of DZone and has posted 216 posts at DZone. You can read more from them at their website. View Full User Profile

How to Handle Setup Logic with IndexedDB

04.29.2012
| 2364 views |
  • submit to reddit

So - as much as I'd like to pretend I don't have to, I'm beginning to wrap my head around the joy that is IndexedDB. WebSQL, which is pretty easy to understand if you've done SQL, is unfortunately deprecated and the future is IndexedDB. I like NoSQL/ObjectStore solutions in general. But the implementation of them in the browser is pretty confusing to me. (Quick note - if you've never seen IndexedDB, check out the links at the bottom.) One of the most confusing aspects I've run into so far is the basic idea of dynamically creating an object store. In a WebSQL solution, it is pretty simple. You execute SQL that runs CREATE TABLE IF NOT EXISTS. On the first execution it creates a table. On any other execution it doesn't do anything. (Ok, technically it takes a tiny amount of time to execute, but the end result is no action.) Under IndexedDB this process is a bit weirder. Why?

You can only add an object store (think of this as a table) when the version changes.

Ok - no big deal.

But you can only see if an object store exists after you open it. Chicken - meet Egg. So what to do?

From what I can tell - the best way to handle this is to make use of the onupgradeneeded function and a static version number that represents your current version. So for example, when I build my killer Web 3.0 application, I begin by knowing I need an object store for notes. So I open my database with a version of 2 (1 being the initial version) and use my event handler to create the store. But note I can check inside there too. Why I do that will make sense in a second.

var openRequest = indexedDB.open("notes",2);

    //handle setup
    openRequest.onupgradeneeded = function(e) {
        console.log("running onupgradeneeded");
        var thisDb = e.target.result;

        //Create Note
        if(!thisDb.objectStoreNames.contains("note")) {
            console.log("I need to make the note objectstore");
            var objectStore = thisDb.createObjectStore("note", { keyPath: "id" });
            objectStore.createIndex("title", "title", { unique: false });
        }

    }

    openRequest.onsuccess = function(e) {
        db = e.target.result;
        console.dir(db);

        db.onerror = function(event) {
        // Generic error handler for all errors targeted at this database's
        // requests!
        alert("Database error: " + event.target.errorCode);
        };

        console.log("We have a handle to our indexeddb");
    }

Now - let's say later on I need to add a new table, booger. I need to increment the version manually and add another small block of code.

var openRequest = indexedDB.open("notes",3);

    //handle setup
    openRequest.onupgradeneeded = function(e) {
        console.log("running onupgradeneeded");
        var thisDb = e.target.result;

        //Create Note
        if(!thisDb.objectStoreNames.contains("note")) {
            console.log("I need to make the note objectstore");
            var objectStore = thisDb.createObjectStore("note", { keyPath: "id" });
            objectStore.createIndex("title", "title", { unique: false });
        }

        //Create Booger
        if(!thisDb.objectStoreNames.contains("booger")) {
            console.log("I need to make the booger objectstore");
            var objectStore = thisDb.createObjectStore("booger", { keyPath: "id" });
            objectStore.createIndex("title", "title", { unique: false });
        }

    }

And that's it. Anything wrong this setup? Obviously this is focused on structure and not seeding the data, but I think you get idea.

I strongly recommend the following resources if you are learning IndexedDB:

 

 

Published at DZone with permission of Raymond Camden, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)