Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 11 USING THE STORAGE APIS

A WORD ABOUT BULLETPROOFING

Brian says: “We’ve accomplished a lot in this example using only a few lines of script code. But don’t be lulled into thinking everything is this easy in a real, publicly accessible website. We took some shortcuts that simply are not acceptable for a production application.

For example, our message format does not support similarly named racers and would best be replaced by a unique identifier representing each racer. Our distance calculation is “as the crow flies” and not truly indicative of progress in an off-road race. Standard disclaimers apply—more localization, more error checking, and more attention to detail will make your site work for all participants.”

This same technique we demonstrated in this example can be applied to any number of data types: chat, e-mail, and sports scores are other examples that can be cached and displayed from page to page using local or session storage just as we’ve shown here. If your application sends user-specific data back and forth from browser to server at regular intervals, consider using Web Storage to streamline your flow.

The Future of Browser Database Storage

The key-value Storage API is great for persisting data, but what about indexed storage that can be queried? HTML5 applications will eventually have access to indexed databases as well. The exact details of the database APIs are still solidifying, and there are two primary proposals.

The Web SQL Database

One of the proposals, Web SQL Database, has been implemented in Safari, Chrome, and Opera. Table 11-2 shows the browser support for Web SQL Database.

Table 11-2. Browser Support for HTML5 Web SQL Database

Browser

Details

Chrome

Supported in version 3.0 and greater

Firefox

Not supported

Internet Explorer

Not supported

Opera

Supported in version 10.5 and greater

Safari

Supported in version 3.2 and greater

 

 

Web SQL Database allows applications access to SQLite through an asynchronous JavaScript interface. Although it will not be part of the common Web platform nor the eventual recommended database API for HTML5 applications, the SQL API can be useful when targeting a specific platform such

286

CHAPTER 11 USING THE STORAGE APIS

as mobile Safari. In any case, this API shows off the power of databases in the browser. Just like the other storage APIs, the browser can limit the amount of storage available to each origin and clear out the data when user data is cleared.

The Fate of Web SQL Database

Frank says: “Even though Web SQL DB is already in Safari, Chrome, and Opera, it will not be implemented in Firefox and it is listed as ‘stalled’ on the WHATWG wiki. The specification defines an API for executing SQL statements given as strings and defers to SQLite for the SQL dialect. Since it is undesirable for a standard to require a specific implementation of SQL, Web SQL Database has been surpassed by a newer specification, Indexed Database (formerly WebSimpleDB), which is simpler and not tied to a specific SQL database version. Browser implementations of Indexed Database are currently in progress, and we’ll cover them in the next section.”

Because Web SQL Database is already implemented in the wild, we are including a basic example but omiting the complete details of the API. This example demonstrates the basic use of the Web SQL Database API. It opens a database called mydb, creates a racers table if a table by that name does not already exist, and populates the table with a list of predefined names. Figure 11-11 shows this database with racers table in Safari’s Web Inspector.

Figure 11-11. Database with racers table in Safari’s Web Inspector

To begin, we open a database by name. The window.openDatabase() function returns a Database object through which database interaction takes place. The openDatabase() function takes a name as well as an optional version and description. With an open database, application code can now start transactions. SQL statements are executed in the context of a transaction using the

287

CHAPTER 11 USING THE STORAGE APIS

transaction.executeSql() function. This simple example uses executeSql() to create a table, insert racer names into the table, and later query the database to create an HTML table. Figure 11-12 shows the output HTML file with the list of names retrieved from the table.

Figure 11-12. sql.html displaying the results of SELECT * FROM racers

Database operations can take some time to complete. Instead of blocking script execution until a result set is available, queries run in the background. When the results are available, a function given as the third argument to executeSQL() is called back with the transaction and the result set as arguments.

Listing 11-13 shows the complete code for the file sql.html; the sample code shown is also located in the code/storage folder.

Listing 11-13. Using the Web SQL Database API

<!DOCTYPE html>

<title>Web SQL Database</title> <script>

// open a database by name

var db = openDatabase('db', '1.0', 'my first database', 2 * 1024 * 1024);

function log(id, name) {

var row = document.createElement("tr"); var idCell = document.createElement("td");

var nameCell = document.createElement("td"); idCell.textContent = id; nameCell.textContent = name; row.appendChild(idCell); row.appendChild(nameCell);

288

CHAPTER 11 USING THE STORAGE APIS

document.getElementById("racers").appendChild(row);

}

function doQuery() { db.transaction(function (tx) {

tx.executeSql('SELECT * from racers', [], function(tx, result) { // log SQL result set

for (var i=0; i<result.rows.length; i++) { var item = result.rows.item(i); log(item.id, item.name);

}

});

});

}

function initDatabase() {

var names = ["Peter Lubbers", "Brian Albers", "Frank Salim"];

db.transaction(function (tx) {

tx.executeSql('CREATE TABLE IF NOT EXISTS racers (id integer primary keyautoincrement, name)');

for (var i=0; i<names.length; i++) {

tx.executeSql('INSERT INTO racers (name) VALUES (?)', [names[i]]);

}

doQuery();

});

}

initDatabase();

</script>

<h1>Web SQL Database</h1>

<table id="racers" border="1" cellspacing="0" style="width:100%"> <th>Id</th>

<th>Name</th>

</table>

The Indexed Database API

A second proposal for browser database storage gained prominence in 2010. The Indexed Database API is supported by Microsoft and Mozilla and is seen as a counter to the Web SQL Database. Where the Web SQL Database looks to bring the established SQL language into browsers, the Indexed Database aims to bring low-level indexed storage capabilities, with the hope that more developer-friendly libraries will be built on top of the indexed core.

While the Web SQL API supports using query languages to issue SQL statements against tables of data, the Indexed DB API issues synchronous or asynchronous function calls directly against a tree-like object storage engine. Unlike Web SQL, the Indexed DB does not work with tables and columns.

289

CHAPTER 11 USING THE STORAGE APIS

The support for the Indexed Database API is growing (see Table 11-3).

Table 11-3. Browser Support for the Indexed Database API

Browser

Details

Chrome

Supported in current versions

Firefox

Supported in current versions

Internet Explorer

Supported in version 10+

Opera

Not currently supported

Safari

Not currently supported

 

 

Microsoft and Mozilla have announced that they will not support the Web SQL Database and have thrown their weight behind the Indexed Database instead. Google’s Chrome has joined in with support, and as such, it is likely that the Indexed Database is the future of standardized structured storage in the browser. Among their reasons are the fact that SQL is not a true standard and also that the only implementation of Web SQL was the SQLite project. With only one implementation and a loose standard, they could not support WebSQL in the HTML5 specification.

The Indexed Database API eschews query strings in favor of a low-level API that allows values to be stored directly in JavaScript objects. Values stored in the database can be retrieved by key or using indexes, and the API can be accessed in either synchronous or asynchronous manner. Like the WebSQL proposal, indexed databases are scoped by origin so that you can only access the storage created in your own web pages.

Creation or modification of Indexed Database storage is done under the context of transactions, which can be classified as either READ_ONLY, READ_WRITE, or VERSION_CHANGE. While the first two are probably self-explanatory, the VERSION_CHANGE transaction type is used whenever an operation will modify the structure of the database.

Retrieving records from an Indexed Database is done via a cursor object. A cursor object iterates over a range of records in either increasing or decreasing order. At any time a cursor either has a value or does not, due to the fact that it is either in the process of loading or has reached the end of its iteration.

A detailed description of the Indexed Database API is beyond the scope of this book. If you are intending to implement a query engine on top of the built-in API, you should consult the official specification at http://www.w3.org/TR/IndexedDB/. Otherwise, you would be wise to wait for one of the proposed engines layered on top of the standard to be made available to use a more developer-friendly database API. At this point, no third-party libraries have gained prominence or significant backing.

Why Use a Hammer…

Brian says: “…when you can instead use these ingots, that forge, and the mold of your choosing? On the Mozilla blog, Arun Ranganathan argued that he would welcome APIs like the Web SQL API being built on top of the Indexed Database standard. This attitude has perplexed many developers, as there is a widespread belief that, in order to make the Indexed Database usable, it will require third-party JavaScript

290