Using IndexedDB: creating a database

Using IndexedDB: creating and deleting a database

Creating a database

Our online example at JSBin shows how to create and populate an object store named “CustomerDB”. This example should work on both mobile and desktop versions of all major post-2012 browsers.

We suggest that you follow what is happening using Google Chrome’s developer tools. Other browsers offer equivalent means for debugging Web applications that use IndexedDB.

With Chrome, please open the JSBin example and activate the Developer tool console (F12 or cmd-alt-i). Open the JavaScript and HTML tabs on JSBin.

Then, click the “Create CustomerDB” button in the HTML user interface of the example: it will call the createDB() JavaScript function that:

    1. creates a new IndexedDB database and an object store in it (“customersDB”), and
    2. inserts two javascript objects (look at the console in your devtools – the Web app prints lots of traces in there, explaining what it does under the hood). Note that the social security number is the “Primary key”, called a key path in the IndexedDB vocabulary (red arrow on the right of the screenshot).

Chrome DevTools (F12 or cmd-alt-i) shows the IndexedDB databases, object stores and data:

chrome dev tools show the content of the IndexedDB database that has been created and populated

Normally, when you create a database for the first time, the console should show this message:

Message displayed in console when the database is created the first time you run the example

This message comes from the JavaScript request.onupgradeneeded callback. Indeed, the first time we open the database we ask for a specific version (in this example: version 2) with:

  1. var request = indexedDB.open(dbName, 2);

…and if there is no version “2” of the database, then we enter the onupgradeneeded callback where we actually create the database.

You can try to click again on the button “CreateCustomerDatabase”, if database version “2” exists, this time the request.onsuccess callback will be called. This is where we will add/remove/search data (you should see a message on the console).

Notice that the version number cannot be a float: “1.2” and “1.4” will automatically be rounded to “1”.

JavaScript code from the example:

  1. var db; // the database connection we need to initialize
  2. function createDatabase() {
  3.   if(!window.indexedDB) {
  4.      window.alert(“Your browser does not support a stable version
  5.                    of IndexedDB”);
  6.   }
  7.   // This is what our customer data looks like.
  8.   var customerData = [
  9.     { ssn: “444-44-4444”, name: “Bill”, age: 35, email:
  10.                                            “bill@company.com” },
  11.     { ssn: “555-55-5555”, name: “Donna”, age: 32, email:
  12.                                            “donna@home.org” }
  13.   ];
  14.   var dbName = “CustomerDB”;
  15.   // version must be an integer, not 1.1, 1.2 etc…
  16.   var request = indexedDB.open(dbName, 2);
  17.   request.onerror = function(event) {
  18.      // Handle errors.
  19.      console.log(“request.onerror errcode=” + event.target.error.name);
  20.   };
  21.   request.onupgradeneeded = function(event) {
  22.       console.log(“request.onupgradeneeded, we are creating a
  23.                    new version of the dataBase”);
  24.       db = event.target.result;
  25.       // Create an objectStore to hold information about our
  26.       // customers. We’re going to use “ssn” as our key path because
  27.       //  it’s guaranteed to be unique
  28.       var objectStore = db.createObjectStore(“customers”,
  29.                                                { keyPath: “ssn” });
  30.       // Create an index to search customers by name. We may have            
  31.       // duplicates so we can’t use a unique index.
  32.       objectStore.createIndex(“name”, “name”, { unique: false });
  33.       // Create an index to search customers by email. We want to
  34.       // ensure that no two customers have the same email, so use a
  35.       // unique index.
  36.       objectStore.createIndex(“email”, “email”, { unique: true });
  37.       // Store values in the newly created objectStore.
  38.       for (var i in customerData) {
  39.           objectStore.add(customerData[i]);
  40.       }
  41.   }; // end of request.onupgradeneeded
  42.   request.onsuccess = function(event) {
  43.      // Handle errors.
  44.      console.log(“request.onsuccess, database opened, now we can add
  45.                   / remove / look for data in it!”);
  46.      // The result is the database itself
  47.      db = event.target.result;
  48.   };
  49. } // end of function createDatabase

Explanations:

All the “creation” process is done in the onupgradeneeded callback (lines 26-50):

    • Line 30: get the database created in the result of the dom event: db = event.target.result;
    • Line 35: create an object store named “customers” with the primary key being the social security number (“ssn” property of the JavaScript objects we want to store in the object store): var objectStore = db.createObjectStore(“customers”, {keyPath: “ssn”});
    • Lines 39 and 44: create indexes on the “name” and “email” properties of JavaScript objects: objectStore.createIndex(“name”, “name”, {unique: false});
    • Lines 48-50: populate the database: objectStore.add(…).

Note that we did not create any transaction, as the onupgradeneeded callback on a create database request is always in a default transaction that cannot overlap with another transaction at the same time.

If we try to open a database version that exists, then the request.onsuccess callback is called. This is where we are going to work with data. The DOM event result attribute is the database itself, so it is wise to store it in a variable for later use: db = event.target.result;

Deleting a database

You can delete a database simply by running this command: 

  1. indexedDB.deleteDatabase(“databaseName”);

A common practice, while learning how IndexedDB works,  is to type this command in the devtool console. For example, we can delete the CustomerDB database used in all examples of this course section by opening one of the JsBin examples , then opening the devtool console, then executing indexedDB.deleteDatabase(“CustomerDB”); in the console:

deleting indexed DB part 1, open the devtool console

Run the command

Execute the command

Refresh IndexedDB display of objectStores

Final result: the objectStore has been deleted

Leave a comment