Sunday, May 20, 2012

HTML5 WEB SQL = Amazing Concept

The Web SQL database API isn’t actually part of the HTML5 specification, but it is part of the suite of specifications that allows us developers to build fully fledged web applications.
  1. It is just like it says on the tin: an offline SQL database. Implementations today are based on SQLite, a general-purpose open-source SQL engine. It comes with all the pros and cons of traditional databases.
  2. On the one hand, you have a fully relational structure, allowing you to rapidly query and manipulate data via joins, e.g. "delete all saved game where the level is less than 10 and the game hasn't been loaded in the past 30 days". You can express that in a line of SQL, whereas you'd have to manually wander through the equivalent corpus of Web Storage data. And if you have a strong need for performance, you can also lean on several decades of research on database optimisation (though tuning would have to be done separately for each possible SQL engine being used).
  3. Furthermore, there's support for transactions, your database is protected from the kind of race conditions that can arise with Web Storage.

There are three core methods in the spec that I’m going to cover in this article:
  1. openDatabase
  2. transaction
  3. executeSql
Support is a little patchy at the moment. Only Webkit (Safari, SafariMobile and Chrome) and Opera support web databases.

Creating and opening databases

If you try to open a database that doesn’t exist, the API will create it on the fly for you. You also don’t have to worry about closing databases.
To create and open a database, use the following code:
var db = openDatabase('mydb', '1.0', 'my first database', 2 *1024 * 1024);

We have passed four arguments to the openDatabase method. These are:
  1. Database name
  2. Version number
  3. Text description
  4. Estimated size of database

Now that we’ve opened our database, we can create transactions. Transactions give us the ability to rollback. This means that if a transaction — which could contain one or more SQL statements — fails (either the SQL or the code in the transaction), the updates to the database are never committed — i.e. it’s as if the transaction never happened.
There are also error and success callbacks on the transaction, so you can manage errors, but it’s important to understand that transactions have the ability to rollback changes.
The transaction is simply a function that contains some code:

var db = openDatabase('mydb', '1.0', 'my first database', 2 *1024 * 1024);
db.transaction(function (tx) {
  // here be the transaction
  // do SQL magic here using the tx object

executeSql is used for both read and write statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written.
Once we have a transaction object, we can call executeSql:

var db = openDatabase('mydb', '1.0', 'my first database', 2 *1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE foo (id unique, text)');

This will now create a simple table called “foo” in our database called “mydb”. Note that if the database already exists the transaction will fail, so any successive SQL wouldn’t run. So we can either use another transaction, or we can only create the table if it doesn’t exist, which I’ll do now so I can insert a new row in the same transaction:

var db = openDatabase('mydb', '1.0', 'my first database', 2 *1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "synergies")');

Now our table has a single row inside it. What if we want to capture the text from the user or some external source? We’d want to ensure it can’t compromise the security of our database (using something nasty like SQL injection). The second argument to executeSql maps field data to the query, like so:
tx.executeSql('INSERT INTO foo (id, text) VALUES (?, ?)', [id,userValue]);
id and userValue are external variables, and executeSql maps each item in the array argument to the “?”s.

Finally, if we want to select values from the table, we use a callback to capture the results:

tx.executeSql('SELECT * FROM foo', [], function (tx, results){
  var len = results.rows.length, i;
for (i = 0; i < len; i++) {

(Notice that in this query, there are no fields being mapped, but in order to use the third argument, I need to pass in an empty array for the second argument.)

The callback receives the transaction object (again) and the results object. The results object contains a rows object, which is array-like but isn’t an array. It has a length, but to get to the individual rows, you need to use results.rows.item(i), where i is the index of the row. This will return an object representation of the row. For example, if your database has a name and an age field, the row will contain a name and an age property. The value of the age field could be accessed using results.rows.item(i).age.

Sample example to demonstrate the usage of WEB SQL api’s is as follows:

<script type="text/javascript">
var db;
db=openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
document.write("Your browser does not support WEB SQL");
function checkBrowser(){
function insertToDb(){
var id=document.getElementById("id").value;
var message=document.getElementById("message").value;
var table=document.getElementById("table").value;
tx.executeSql('INSERT INTO '+table+' (id,message) VALUES (?, ?)',[id,message]);
function deleteRow(id){
var table=document.getElementById('table').value;
tx.executeSql('DELETE FROM '+table+' WHERE id=?',[id]);
function displayDbContents(){
var table=document.getElementById("table").value;
tx.executeSql('SELECT * FROM '+table,[],function(tx,results){
var i,len=results.rows.length;
var buffer="<table border='1px'><tr><th>ID</th><th>MESSAGE</th><th>DELETE</th></tr>";
buffer=buffer+"<tr><td>"+results.rows.item(i).id+"</td><td>"+results.rows.item(i).message+"</td><td><input id="+results.rows.item(i).id+" type='button' value='Delete' onclick='deleteRow('/></td></tr>";
function createTable(){
db.transaction(function (tx) {
var table=document.getElementById('table').value;
tx.executeSql('CREATE TABLE IF NOT EXISTS '+table+' (id unique, message)');
alert("Table created with 2 columns(id, message)");
function dropTable(){
var table=document.getElementById('table').value;
tx.executeSql('DROP TABLE '+table,[]);
function clearAll(){
<body onload="checkBrowser()">
<div id="content">
<table width="100%" border="1px">
<tr><td align="center">Create and Insert data</td><td align="center">Table Contents</td></tr>
<td width="50%" align="center">
<tr><td>Create Table</td><td><input type="text" id="table" placeholder="Enter Table Name"/><input type="button" id="createid" value="Create Table" onclick="createTable()"/></td></tr>
<tr><td>ID</td><td><input type="text" id="id" placeholder="Enter ID" disabled/></td></tr>
<tr><td>Message</td><td><input type="text" id="message" placeholder="Enter Message" disabled/></td></tr>
<tr><td><input type="button" value="Submit" id="submit" onclick="insertToDb()" disabled/></td><td></td></tr>
<td width="50%" align="center">
<div id="result">
<input type="button" value="Drop table" onclick="dropTable()" id="drop" disabled/>

Observations on different browsers:

Internet Explorer

Mozilla Firefox



Google Chrome

Browser compatibilities

From the observation made in the test applications, the conclusions are as follows.
WEB SQL support
Internet ExplorerNo
Mozilla FirefoxNo
Google ChromeYes