Channels ▼
RSS

Database

Exploring IndexedDB


Index

  • An index is specialized persistent key-value storage and has a referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. There can be several indexes referencing the same object store, thus changes to the object store causes all such indexes to get updated.

Transaction

  • A transaction is used to interact with the data in a database. Whenever data is read or written to the database, it is done via a transaction.
  • Every transaction has a mode that determines which types of interactions can be performed upon that transaction. The mode, such as READ_WRITE, is set when the transaction is created and remains for the life of the transaction.
  • The transaction also has a scope that determines the object stores with which the transaction may interact.

Requests

  • Each reading and writing operation on a database is done using a request.
  • Every Request object represents one read or write operation.
  • Requests have a done flag that initially is false, and a source object. Every request also has a result and an errorCode, neither of which are accessible until the done flag is set to true.

IndexedDB Demo

In this example, we perform basic operations of insert/select/delete on the object store.

Opening a Database

To perform any transaction, we need to open the database. Different browser vendors provide different predefined JavaScript objects for IndexedDB support. Google Chrome provides the object window.webkitIndexedDB, whereas Mozilla Firefox provides the object window.mozIndexedDB. Both objects support an open() method, which accepts the name of a database as a parameter. In the event there is no database, a new database is created and a reference is returned. In the following example, we store the reference in the JavaScript variable db.


window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB;

var myDAO = {}; //our Composite JavaScript object

//make a DB open call and provide asynchronous callback handler

var request = window.indexedDB.open("BookShop1");

request.onsuccess = function(event) { 

//the returned Database is being stored in variable db in our DAO object

    myDAO.db = request.result; 

    document.write("Database Opened");

};

request.onerror = function(e)

{

    document.write(e);

};

Creating an Object Store

When a new IndexedDB database is created, no object store is as yet be present in the database. To perform any further operations, you need to create object stores first. And this can be done only inside a setVersion() transaction on the db object reference. Note that SetVersion is the only place in our code that we can alter the structure of the database, such as creating and deleting object stores or building/removing indexes. A call to setVersion() returns a Request object in whose callbacks we create our object stores and indexes. If we try to create an object store with a name that already exists in the database, it will throw an exception.


request = myDAO.db.setVersion( parseInt(Math.random() * 100));

request.onsuccess = function(e) {

    myDAO.objectStore = myDAO.db.createObjectStore("BookList", 

   {

        "keyPath": "id"

    });

};

Opening the Object Store

Once the object store is created we need to open the it to perform any operation. To perform operations, we need a transaction object, which is obtained by invoking the transaction() method of the database (db) object, where we pass the name of the object stores. This becomes the scope of the transaction object, and the mode of the transaction (that is, READ/WRITE/SNAPSHOT or any combination of these thre)e. This transaction object is used to get a reference of the object store in the given mode, over which the desired transactions can be done. Also note that multiple object stores can be specified in the transaction method call, separating the store names by a comma.


transaction = myDAO.db.transaction(["BookList"], IDBTransaction.READ_WRITE);

var objectStore = transaction.objectStore("BookList");

Adding Data to an Object Store

As already mentioned, once the transaction object is obtained for any object store, we can simply call the IndexedDB API methods to perform other operations on that store. In the case of Insert, we call the add() method of the object store (objectStore) object, and pass the data to be inserted.


var data = {

   "bookname":"Book1",

    "author":"Kausar",

    "id":"2"

};

transaction =

    myDAO.db.transaction(["BookList1","BookList2"],IDBTransaction.READ_WRITE);

request = transaction.objectStore("BookList1").add(data);

request.onsuccess = function(event)

{

};

request.onerror = function(e)

{

};

Deleting Data from an Object Store

Deleting is similar to adding data from a database. We need to invoke the delete() method of the object store (objectStore), passing the unique identifier that identifies the object to be deleted.


//delete a sample object with id having some value

var id = 2;

transaction = myDAO.db.transaction(["BookList"], IDBTransaction.READ_WRITE);

request = transaction.objectStore("BookList").delete(id); //["delete"](id);

request.onsuccess = function(event)

{

};

request.onerror = function(e)

{

};


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video