4 // Open a Web SQL database.
6 if (typeof window.openDatabase == "undefined") {
7 document.write("Error: Web SQL databases are not supported.");
10 g_db = openDatabase("test", "1.0", "test database", 1024 * 1024);
12 document.write("Error: cannot open database.");
15 // Creates a table named "table1" with one text column named "data".
16 function createTable() {
21 tx.executeSql("CREATE TABLE table1 (data TEXT)");
24 sendValueToTest(error);
27 sendValueToTest("done");
31 // Inserts a record into the database.
32 function insertRecord(text) {
35 tx.executeSql("INSERT INTO table1 VALUES (?)", [text]);
38 sendValueToTest(error);
41 sendValueToTest("done");
46 // Updates a record at the given index with the given text. The indices are
47 // 0-based and are ordered from oldest record, to newest record.
48 function updateRecord(index, text) {
49 var didUpdate = false;
50 findId(index, function(rowId) {
54 "UPDATE table1 SET data=? WHERE ROWID=?",
56 function(tx, result) {
57 if (result.rowsAffected == 1)
59 else if (result.rowsAffected == 0)
60 sendValueToTest("could not update index: " + index);
62 sendValueToTest("multiple rows with index: " + index);
66 sendValueToTest("update error: " + error);
70 sendValueToTest("done");
75 // Deletes a record at the given index.
76 function deleteRecord(index) {
77 findId(index, function(rowId) {
80 tx.executeSql("DELETE FROM table1 WHERE ROWID=?", [rowId]);
83 sendValueToTest("delete error: " + error);
86 sendValueToTest("done");
91 // Gets all the records in the database, ordered by their age.
92 function getRecords() {
93 g_db.readTransaction(function(tx) {
95 "SELECT data FROM table1 ORDER BY ROWID",
97 function(tx, result) {
99 for (var i = 0; i < result.rows.length; i++) {
102 items += result.rows.item(i).data;
104 sendValueToTest(items);
106 function(tx, error) {
107 sendValueToTest("getRecords error: " + error);
112 // Helper function that finds the ID for a record based on a given index.
113 function findId(index, callback) {
114 g_db.readTransaction(function(tx) {
115 // |ROWID| is a special sqlite column. It is unique and is incremented
116 // automatically when a new record is created.
117 // |LIMIT| is a nonstandard clause supported by sqlite that lets us pick
118 // rows from the database by index. E.g., LIMIT 2,10 will give us 10 records
119 // starting at offset 2.
121 "SELECT ROWID AS id FROM table1 ORDER BY ROWID LIMIT ?,1",
123 function(tx, result) {
124 if (result.rows.length >= 1)
125 callback(result.rows.item(0).id);
127 sendValueToTest("could not find row with index: " + index);
129 function(tx, error) {
130 sendValueToTest("findId error: " + error);
135 function sendValueToTest(value) {
137 window.domAutomationController.setAutomationId(0);
138 window.domAutomationController.send(value);
144 This page is used for testing Web SQL databases.