Web Storage Portability Layer: Abstract on top of HTML5 and Gears Storage
Robert Kroeger has released a nice library for local database access. The Web Storage Portability Layer nicely abstracts on top of HTML5 and Gears for database access.
The WSPL consists of a collection of classes that provide asynchronous transactional access to both Gears and HTML5 databases and can be found on Project Hosting on Google Code.
There are five basic classes:
google.wspl.Statement – A parametrizable SQL statement class
google.wspl.Transaction – Used to execute one or more Statements with ACID properties
google.wspl.ResultSet – Arrays of JavaScript hash objects, where the hash key is the table column name
google.wspl.Database – A connection to the backing database, also provides transaction support
google.wspl.DatabaseFactory – Creates the appropriate HTML5 or Gears database implementation
Also included in the distribution is a simple note-taking application with a persistent database cache built using the WSPL library. This application (along with Gmail mobile for iPhone and Android-powered devices) is an example of the cache pattern for building offline web applications. In the cache pattern, we insert a browser-local cache into the web application to break the synchronous link between user actions in the browser and server-generated responses. Instead, as shown below, we have two data flows. First, entirely local to the device, contents flow from the cache to the UI while changes made by the user update the cache. In the second flow, the cache asynchronously forwards user changes to the web server and receives updates in response.
By using this architectural pattern, a web application can made tolerant of a flaky (or even absent) network connection!
You can of course take a peak at the code to see how it works, for example:
JAVASCRIPT:
1 | google.wspl.DatabaseFactory.createDatabase = function(dbName, dbworkerUrl) { |
2 |
var dbms; |
3 | if (window.openDatabase) { |
4 | // We have HTML5 functionality. |
5 | dbms = new google.wspl.html5.Database(dbName); |
6 | } else { |
7 | // Try to use Google Gears. |
8 | var gearsDb = goog.gears.getFactory().create(‘beta.database’); |
9 | var wp = goog.gears.getFactory().create(‘beta.workerpool’); |
10 | // Note that Gears will not allow file based URLs when creating a worker. |
11 | dbms = new wireless.db.gears.Database(); |
12 | dbms.openDatabase(”, dbName, gearsDb); |
13 | wp.onmessage = google.bind(dbms.onMessage_, dbms); |
14 | |
15 | // Comment this line out to use the synchronous database. |
16 | dbms.startWorker(wp, dbworkerUrl, 0); |
17 | } |
18 | return dbms; |
19 | }; |
20 |
Nicely done. It would be great to see a version that acts as a shim and when in Gears mode manually implements the HTML5 standard API so you can write your user code to that and not a new google package.