IndexedDB

Overview

This article demonstrates IndexedDB usage in Tizen. LocalStorage is used to store only key-value pairs, if you want to store key with multiple values, IndexedDB is one good example which implements using B-Tree.

Creating IndexedDB

To create IndexedDB in Tizen use webkit based IndexedDB using webkitIndexedDB window attribute. First it check whether databases base exists or not, if it exists onsuccess callbdack is called, else onupgradeneeded callaback is called where db is created and create object store which is nothing but tables. Below code shows how to create Database PeopleDB and objectsotre people. Objectstore creates two keys name and email, where we can specify whether it should contain unique values to avoid duplicate records.

function createDb(){

	var tizenDB = {};
	window.indexedDB = window.webkitIndexedDB ;
	var request = window.indexedDB.open("PeopleDB");
	request.onsuccess = function (evt) {
		console.log("inside onsuccess");
		db = request.result;                                                            
	};

	request.onerror = function (evt) {
		console.log("IndexedDB error: " + evt.target.errorCode);
	};
	request.onupgradeneeded = function(evt) 
	{  
		console.log("inside onupgradeneeded");

		var objectStore = evt.currentTarget.result.createObjectStore(
				"people", { keyPath: "id", autoIncrement: true });

		objectStore.createIndex("name", "name", { unique: false });
		objectStore.createIndex("email", "email", { unique: true });

		for (i in peopleData) {
			objectStore.add(peopleData[i]);
			console.log("added objectstore to db");
		}
	};
}

Reading ObjectStore Data

Below code shows to retrieve data from object store "people". Transaction session has to opened with read mode to read database which returns pointer to objectstore. opencursor method of objectstore is called to retrieve key values pairs

function showDb(){
	var tizenDB = {};
	window.indexedDB = window.webkitIndexedDB ;
	var request = window.indexedDB.open("PeopleDB");
	request.onsuccess = function (evt) {
		console.log("inside onsuccess");
		db = request.result;   
		var IDBTransaction =  window.webkitIDBTransaction;
		var transaction = db.transaction("people", IDBTransaction.READ_WRITE);
		var objectStore = transaction.objectStore("people");

		var request = objectStore.openCursor();
		request.onsuccess = function(evt) {  
			var cursor = evt.target.result;  
			if (cursor) {  

				var textContent = "id: " + cursor.key + 
				" is " + cursor.value.name + " ";   
				console.log("data----------" + textContent) ;
				cursor.continue();  
			}  
			else {  
				console.log("No more entries!");  
			}  
		};  
	};
}

Reading Specific Record

Instead of whole objectstore user can retrieve particular record using IDBKeyRange as shown in below code.

function showDataRecord()
{
	var tizenDB = {};
	window.indexedDB = window.webkitIndexedDB ;
	var request = window.indexedDB.open("PeopleDB");
	request.onsuccess = function (evt) {
		db = request.result;   
		var IDBTransaction =  window.webkitIDBTransaction;
		var transaction = db.transaction("people", IDBTransaction.READ_WRITE);
		var objectstore = transaction.objectStore("people");
		if(objectstore != null )
		{
			var index = objectstore.index("email" );
			var IDBKeyRange = window.webkitIDBKeyRange;
			if(IDBKeyRange != null)
			{
				console.log("range is not null");
				var range = IDBKeyRange.only("john@company.com") ;
				var request = index.get("john@company.com") ;
				if( request != null){
					request.onsuccess=function(event){
						var cursor = event.target.result;
						alert(cursor);
					}}
				else
					console.log("request is null");

			}
		}
	}
}

Delete ObjectStore and Database

deleteDatabase and deleteObjectStore interfaces are used to delete objectstore and databases.

IndexedDb functionality using IndexedDB wrapper library

Using this IndexedDB library, databases can created with simple interfaces as shown below.

Source

https://github.com/jensarps/IDBWrapper

Create ObjectStore

The Wrapper librabry provides an interface to create ObjectStore by specifying version, storename, success callback is called after creating objectstore.

function createDBUsingWrapper(){
	customers = new IDBStore({
		dbVersion: 1,
		storeName: 'customer',
		keyPath: 'id',
		autoIncrement: true,
		onStoreReady: function(){
			console.log('Store ready!');
			
		}
	});
	
}

Add data to ObjectStore

To add indexes to the object below code is used, onsuccess callback is called after adding values to objectstore.

function addToDB(){
	console.log("inside addToDB");
	var dude = {
			firstname: 'John',
			lastname: 'Doe',
			age: 52,
			emails: [
			         'johndoe@example.com',
			         'jd@example.com'
			         ]
	};

	var onsuccess = function(id){
		console.log('Data is added: ' + id);
	}
	var onerror = function(error){
		console.log('Error', error);
	}

	customers.put(dude, onsuccess, onerror);
	
}

Reading data from ObjectStore

Data from database can be retrived using id of the index as shown in below code

function readFromDB(){
	var id = 1; 
	 
	var onsuccess = function(data){
	console.log('here is our dude:', data);
	}
	var onerror = function(error){
	console.log('Oh noes, sth went wrong!', error);
	}
	 
	customers.get(id, onsuccess, onerror);
}

User can retrieve data from datastore using filter as shown in below code. onItem callback is called for each search item.

customers.iterate(onItem, {
  index: 'lastname',
  keyRange: IDBKeyRange,
  order: 'ASC',
  filterDuplicates: false,
  writeAccess: false,
  onEnd: onEndCallback,
  onError: onErrorCallback
});

References

http://www.w3.org/TR/IndexedDB
http://www.codeproject.com/Articles/325135/Getting-Started-with-IndexedDB
http://jensarps.de/2011/11/25/working-with-idbwrapper-part-1
http://jensarps.de/2012/11/13/working-with-idbwrapper-part-2/