DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Handle Setup Logic with IndexedDB

How to Handle Setup Logic with IndexedDB

Raymond Camden user avatar by
Raymond Camden
·
Apr. 29, 12 · Interview
Like (0)
Save
Tweet
Share
3.65K 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

  • Integrating AWS Secrets Manager With Spring Boot
  • Apache Kafka Is NOT Real Real-Time Data Streaming!
  • What Are SLOs, SLIs, and SLAs?
  • LazyPredict: A Utilitarian Python Library to Shortlist the Best ML Models for a Given Use Case

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: