Performance Zone is brought to you in partnership with:

Leigh has been in the technology industry for over 15 years, writing marketing and technical documentation for Sun Microsystems, Wells Fargo, and more. She currently works at New Relic as a Marketing Manager. Leigh is a DZone MVB and is not an employee of DZone and has posted 106 posts at DZone. You can read more from them at their website. View Full User Profile

Who Needs MySQL When There Is IndexedDB?

12.07.2012
| 4251 views |
  • submit to reddit

Matthew Setter is a professional technical writer and passionate web application developer. He’s also the founder of Malt Blue, the community for PHP web application development professionals and PHP Cloud Development Casts – learn Cloud Development through the lens of PHP. You can connect with him on TwitterFacebookLinkedIn or Google+ anytime.

Recently, I discussed an alternative to Cookies with the introduction of HTML5 or Web Storage. I took a look at what it is and why it’s such a great alternative to (the much maligned) cookies.

Just in case you missed it, here’s a quick summary. Local_ and SessionStorage provide a much more efficient way of storing information client-side in the browser. What’s more, they don’t have the overhead that Cookies do since they aren’t included with page requests. We looked at how it works, potential security implications, browser support and more.

But Local- and SessionStorage aren’t the only available options when we’re looking to increase the complexity of the web applications that we develop and deliver today. With HTML5, the W3C provides another standard that may be more of what you’re looking for, especially if you’re a fan of the NoSQL based technologies. This option is IndexedDB.

So in this series, we’re going to look at what IndexedDB is, what its advantages and disadvantages are, and where it would be a good fit for your development needs. In the next installment, we’ll finish off with a sample application so you can get a hands on understanding of how it works.

Technology Overview
IndexedDB is an alternative to the (now deprecated) W3C standard WebSQL Database (WebSQL). It was introduced around April 23, 2009. This is a description from Wikipedia:

“… is a web page API for storing data in databases that can be queried using a variant of SQL”

As it says on the tin, WebSQL brings client-side application development the full power of SQL. Based on SQLite, it allows us to employ one of the fundamental skills we have in our development toolkit – database development – both on the client and the server side.

On November 18, 2010, the W3C made the decision to no longer support the standard. This was due to disagreement from a number of vendors – including Mozilla and Microsoft – on how it should be practically implemented and incomplete browser support. As a result, IndexedDB was introduced as an alternative standard for web data storage.

However, IndexedDB is not a browser database but an Object Store. It allows for applications to design, store and manipulate objects, without sterilization, and the ability to conduct high performance searches on them.

As I mentioned earlier, it’s a lot like NoSQL databases, such as mongoDB and CouchDB. Objects are created and manipulated in JavaScript, and then stored and updated in the object store.

But it’s not exactly the same as say a standard PHP, Ruby or Python script creating and persisting objects. There are a few key points to know and remember when using it

Operations Require Transactions
Every operation that you perform when using IndexedDB must be carried out within a transaction. Whether that’s reading information from an object store, manipulating data in it or changing its structure.

Transactions can have three modes:

Mode

Description

readonly (snapshot) Be able to read object stores of the database without being able to change anything.
readwrite Be able to read and write object stores in the database, without being able to change its structure.
versionchange Be able to change the structure of, add and remove object stores in a database along with managing indexes on them.

Operations are Ashynchronous

Here’s the difference. With SQL, you run a query and receive back the result. With IndexedDB, you run a transaction and set up a callback to handle the success or failure of the transaction, which you can check in on later. You don’t fire off the request and wait for the result, such as retrieving a list of objects matching an index.

If you’re familiar with jQuery, you’ll know what I’m referring to. If not, have a look at the following code:

var jqxhr = $.ajax( "http://www.newrelic.com" )
    .done(function() { alert("success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

With the code above, we’re making an ajax request to newrelic.com. We then setup three handlers or callbacks; one for the done, fail and always events. We also do this in IndexedDB. Have a look at the sample below:

// open the library data store
var request = indexedDB.open("library");
 
request.onsuccess = function(e) {
    newrelic.indexedDB.getAllbooksList();
};
 
request.onerror = function(e) {
    console.log("Error Opening Object Store. : ", e);
};

Here we make a request to open the library datastore. If the request is successful, we fire off the getAllbooksList function, which in turn, follows a similar pattern. If the request fails, we log the reason why.

Indexes & Cursors
Continuing the database analogy, objects in the object store can have one or a collection of indexes to speed up data retrieval. Creating them is rather simple, as shown in this code from the Mozilla Development Network (MDN):

// This is what our customer data looks like.
const customerData = [
  { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
  { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
];
 
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique.
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
 
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });

With cursors, we are able to iterate over the data that we retrieve from the object store. We can also use an index to limit the data that we retrieve. In the example below, also from MDN, we perform a ‘getall’ type query:

var customers = [];
 
objectStore.openCursor().onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    customers.push(cursor.value);
    cursor.continue();
  }
  else {
    alert("Got all customers: " + customers);
  }
};

Browser Support
Unfortunately, it’s not all good news yet. At this time, IndexedDB is only supported by the following browsers:

Browser

Version

Mozilla Firefox

10

Google Chrome

23

IE version

10

As WebSQL is deprecated, it’s likely that support for IndexedDB will continue to grow over time as the spec becomes more refined. To find out exactly which browsers (and their versions) support it, try it out at caniuse.com.

Although Safari, Chrome and Opera still support WebSQL – and technically you could develop apps with it — it’s not a good idea to do so. Some, however, suggest a middle ground with the use of a wrapper library allowing you to have the both of best worlds.

Advantages

1. An Emerging Standard
With lots of support from the W3C, Mozilla, Microsoft and Google, IndexedDB is rapidly emerging as a standard. It is likely that it will be around for quite some time, meaning you can reliably develop against it. What’s more, it offers a sense of stability and vendor independence that WebSQL does not.

2. Use Objects – Not SQL
Additionally, Indexed DB lets you work with objects as best suits the needs and designs of your application (whereas WebSQL required that you had a solid grasp of SQL.)

Disadvantages

1. Lack of Browser Support
At this stage, the primary disadvantage is clearly lack of browser support. Yes, it’s already available in the latest versions of Firefox and Chrome, and it’s going to be in IE 10. But it’s only available in the full release of IE 10 and that’s only available on Windows 8.  And since IE 10 has only been released recently, it will take awhile before it’s the dominant version of IE in use.

The good news about this is that Chrome and Firefox make up about 54% of the browsers in use. See this in the graph below from StatCounter:

StatCounter Global Stats

Where Is It a Good Fit?
As I’ve alluded to, IndexedDB is a good fit if your client-side data needs are more complex than what Local/SessionStorage can provide (i.e. you’re looking for more than a simple Key/Value store in your application).

Yes, you can use JavaScript functions (such as JSON.stringify and JSON.parse) to manage information stored in it. But it doesn’t offer you the flexibility and power that IndexedDB does. So if you want a storage layer that offers higher performance, duplicate key values or an efficient way to search through the data stored, then go with IndexedDB. But if your needs are simpler, then go with Session and LocalStorage. Remember, your needs are what should guide your choice.

Is It the Right Choice?
There’s been a lot of debate for and against WebSQL and IndexDB. Personally, I don’t see WebSQL as a bad technology, but I see IndexedDB as a better choice. I recently was reading Paul Harrison’s blog and his three points for IndexedDB sums up why I think it’s a better choice:

* SQL is an entirely different system, unrelated to the languages it’s usually embedded within.
* It’s easy for inexperienced programmers to embed security flaws in their SQL statement
* It’s easy for inexperienced programmers to develop overly complex queries that database systems find impossible to process in a reasonable period of time

In the article he supports WebSQL and I don’t want to quote him out of context here. But for me at least, web applications are getting ever more complex, and it’s not right to take a technology that predated the web and attempt to retro-fit it into it. I believe the better choice is to split from the past and to provide a data storage layer that is more appropriate to its needs. And this is what I believe IndexedDB is.

Conclusion
So there you have it. IndexedDB is set to be one of the two key new standards for client-side data storage in the years to come. It allows us to store complex objects that we create and manipulate in JavaScript combined with a decent amount of index performance when searching for the information stored.

We’ve looked at the advantages and disadvantages and touched on whether it or WebSQL is the right standard for the future. So what do you think about it? Do you believe it’s the right fit for the future of web application development? Or do you believe that WebSQL would have been the better choice? Voice your opinion in the comments. We want to know what you think.

For an interesting discussion about whether WebSQL or IndexedDB should be the standard to use for web developers, check out this thread on Kevin Dangoor’s (Mozilla) Google+ page. It makes for some interesting reading with a wealth of opinions.



Published at DZone with permission of Leigh Shevchik, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)