Web Development

Exploring IndexedDB

IndexedDB is arguably the most useful of the client-side storage options for Web apps introduced in HTML 5. With just a few tricks, its API can be surprisingly easy to use

Client-side local storage can be used for storing the preferences and the runtime state of Web applications. There are four principal options for client-side storage. In this article, We quickly look at all four, then explore IndexedDB and how it can aid Web application development.

The principal mechanisms for persistent local storage of data on the client side are:

Cookies

Web-Storage

Web SQL Database

IndexedDB

These technologies were compared in some depth by a recent pairof articles written by Pamela Fox for Dr. Dobb's.

Cookies

Cookies have been in use almost since the advent of Web applications, and are normally deployed for storing small amounts of data on the client side. They do have some shortcomings:

They are included with every Http Request

Data is sent unencrypted over the Internet

Very limited data can be stored on the client side (restricted to 4KB)

Web Storage

Web storage is designed to provide a larger, more secure, and easier to use alternative to storing information in cookies. It is also known as localStorage or DOMStorage. Two key features of Web storage that it is limited to around 5MB per application and it stores data in the form of key-value pair.

It, too, has some drawbacks:

It cannot store structured data.

It doesn't provide in-order retrieval of keys, efficient searching over-values, or storage of duplicate keys. Thus, if we want to store details about an employee, we have to store it as "ename : John," "empid : 12020," "dept : IT." And there is no way to corelate the data (these are just key-value pairs)  there is no way to tell that the empid : 12020 belongs to the employee John.

These limitations led to the Web SQL Database specification.

Web SQL Database Specification

The Web SQL Database specification provides a thin wrapper around a SQL Database. We query the database using SQL statements, such as: t.executeSql('CREATE TABLE docids(id,name)');. Here, we can pass any valid SQL statement to the method executeSql(). The problem with the Web SQL Database specification is that although there is an actual SQL specification (SQL_92), it is not fully supported by all database vendors. SQLite, being the better implementation, is not widely accepted by all. As a result, many developers use a new specification called IndexedDB, which does away with the drawbacks and limitations of the earlier ways of storing data locally in Web environment.

IndexedDB

Indexed DB enables fast searches on client-side stored data using indexes. It is not an RDBMS; rather, it is a client-side object store. Features of IndexedDB include:

Developers are insulated from changes to SQLite or any other database vendor by exposing an API that isn't based on vendor-specific syntax.

The IndexedDB API exposes an object store.

IndexedDB uses the Asynchronous API, which is a non-blocking system and, as such, will not get data through return values. Rather, it will get data delivered through to a defined callback function.

It is transactional in nature. It is not possible to perform any operation (read/write) outside of a transaction (we need to create a transaction object, specific to an object store, and as long as the object is alive, we can perform any operation on that object store.

Browsers with robust support for HTML5 (such as Google Chrome and Mozilla FireFox) support IndexedDB. For more details, please refer to http://caniuse.com/indexeddb.

IndexedDB API Constructs

To understand IndexedDB, you must be familiar with key concepts implemented by the technology:

Database:

Applications from each origin (domain name) have an associated set of databases: The domain name acts as a namespace for the databases created on the client's browser.

A database comprises one or more object stores, which hold the data stored in the database.

Every database has a name that identifies it within a specific origin. The name can be any string value, including an empty string, and stays constant for the lifetime of the database.

Each database also has a current version. When a database is first created, its version is 0.

Object Store:

An object store is the primary storage mechanism for storing data in a database.

Each database contains a set of object stores. When a new database is created, it doesn't contain any object stores.

The object store has a list of records, which hold the data stored in the object store. Each record consists of key-value pairs. The records are sorted according to a primary key in ascending order. Records in a given object store cannot have the same primary key.

It is the equivalent of a table in relational database.

Keys

To efficiently retrieve records stored in an IndexedDB database, each record is organized according to its primary key, which has one of the following types: Arrays, JavaScript objects, DOMString, Date, or float. However, arrays are only valid keys if every item in the array is defined. Additionally, if the value is of type float, it is only a valid key if it is not NaN (not a number).

Values

Values specified for the keys in each record can be of simple types such as DOMString and Date as well as object and array instances.

Key Path

A key path is a DOMString that defines the primary key for the record. A valid key path is either the empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods.

It is defined at the time the object store is created.

Example of key path:

db.createObjectStore("BookList",{"keyPath":"id"} );

Example of a record with the id as primary key:

var data = {
"bookname":"Book1",
"author":"Kausar",
"id":"2"
};

The JavaScript object data is the value to be stored in the object store.

The property "id":"2" in the aforementioned JavaScript object is the primary key according to the specified key path. Hence, every object to be stored in this object store should have unique value for the field/property id.

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.

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!