DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > How to Handle Setup Logic with IndexedDB

How to Handle Setup Logic with IndexedDB

Raymond Camden user avatar by
Raymond Camden
·
Apr. 29, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
3.47K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • Basic Concepts Behind IndexedDB
  • Using IndexedDB

 

 

Database Object (computer science) Execution (computing) sql Concept (generic programming) application Data (computing) EGG (file format) Blocks

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Augmented Analytics: The Future of Business Intelligence
  • Modern REST API Design Principles and Rules
  • Portfolio Architecture Examples: Retail Collection
  • 6 Things Startups Can Do to Avoid Tech Debt

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo