Mojo Storage Database

From WebOS Internals
Revision as of 07:45, 10 August 2009 by Bertel (talk | contribs) (Added non-anonymous call example)
Jump to navigation Jump to search

This page was created to help others by giving a basic example of creating a new database for your application and storing some data in it.


SQL Overview

It needs to be mentioned that SQLite (what HTML5 uses), is not as controlling as other databases. For one it's not going to give you an error when you insert text into an integer, or anything like that so regex all input for users or limit it in some way.

Data Type Example
INTEGER '0' '123' '3939'
REAL '1.1' '10.0'
TEXT 'foo' 'bar'
BLOB [binary data / images]
NULL absolutely nothing

Creating a Database and a Table

<source lang="javascript"> var name = "MyDB"; // required var version = "0.1"; // required var displayName = "My Mojo-Driven database"; // optional var size = 200000; // optional

var db = openDatabase(name, version, displayName, size);

if (!db) {

 Mojo.Log.error("Could not open database");

} else {

 var sql = "CREATE TABLE IF NOT EXISTS 'my_table' (id INTEGER PRIMARY KEY, num REAL, data TEXT)";  // check sqlite data types for other values
 db.transaction( function (transaction) {
   transaction.executeSql(sql,  // SQL to execute
                          [],    // array of substitution values (if you were inserting, for example)
                          function(transaction, results) {    // success handler
                            Mojo.Log.info("Successfully created table"); 
                          },
                          function(transaction, error) {      // error handler
                            Mojo.Log.error("Could not create table: " + error.message);
                          }
   );
 });

} </source>

In order to use non-anonymous event handlers, the function supplied to db.transaction has to be bound to the current context, as in the folling, modified example:

<source lang="javascript"> SceneAssistant.prototype.createMyTable = function(){

 var name = "MyDB";  // required
 var version = "0.1";  // required
 var displayName = "My Mojo-Driven database"; // optional
 var size = 200000;  // optional
 var db = openDatabase(name, version, displayName, size);
 if (!db) {
   Mojo.Log.error("Could not open database");
 } else {
   var sql = "CREATE TABLE IF NOT EXISTS 'my_table' (id INTEGER PRIMARY KEY, num REAL, data TEXT)";  // check sqlite data types for other values
   db.transaction(
     function (transaction) { 
       transaction.executeSql(sql, [],
         this.dbSuccessHandler.bind(this),
         this.dbErrorHandler.bind(this)); 
     }.bind(this));
 }

}

SceneAssistant.prototype.dbSuccessHandler = fuction(transaction, results){} SceneAssistant.prototype.dbErrorHandler = fuction(transaction, errors){} </source>

Note: I have been unable to use my own function as a success or an error handler. Some of the existing applications seem to be able to do so, but others write anonymous functions as in the example.

openDatabase

If you try to look for MyDB on the filesystem, you won't find it. The openDatabase method creates an entry in the Databases table in /var/usr/home/root/html5-databases/Databases.db which points to the actual location of your database. Note that the details in the Databases table are what you specified in openDatabase except version. Version is contained in the __WebKitDatabaseInfoTable__ table in the actual database.


In the examples contained in this page, the database that is created has a maximum storage capacity of 1 MB. If you need a larger database, then append ext: to the beginning of the database name. For example:

<source lang="javascript"> var db = openDatabase("ext:MyDB", "0.1"); </source>

This will create the database in /media/internal/.app-storage.

Inserting a Row

<source lang="javascript"> var myNum = 512.785; var test = "I'm test data!";

var db = openDatabase("MyDB", "0.1"); // this is all that is required to open an existing DB var sql = "INSERT INTO 'my_table' (num, data) VALUES (?, ?)";

db.transaction( function (transaction) {

 transaction.executeSql(sql,  [myNum, test], 
                        function(transaction, results) {    // success handler
                          Mojo.Log.info("Successfully inserted record"); 
                        },
                        function(transaction, error) {      // error handler
                          Mojo.Log.error("Could not insert record: " + error.message);
                        }
 );

}); </source>

Inserting Multiple Rows

With asynchronous database methods, you can really screw things up if you try to do too many transacations in rapid succession. Luckily, you can run as many executeSql methods inside a single transaction as you need.

<source lang="javascript"> var dataArray = []; for(var i = 0; i < 100; i++) {

 dataArray[i] = i;

}

var db = openDatabase("MyDB", "0.1");

db.transaction( function (transaction) {

 for(var i=0; i < dataArray.length; i++) {
   var sql = "INSERT INTO 'my_table' (num, data) VALUES (?, ?)";
   transaction.executeSql(sql,  [dataArray[i], dataArray[i]], 
                          function(transaction, results) {    // success handler
                            Mojo.Log.info("Successfully inserted record"); 
                          },
                          function(transaction, error) {      // error handler
                            Mojo.Log.error("Could not insert record: " + error.message);
                          }
   );
 }

}); </source>

Retrieving Data

When a query returns results to the success handler, the rows are contained in .rows.

<source lang="javascript"> var db = openDatabase("MyDB", "0.1"); var sql = "SELECT * FROM 'my_table'";

db.transaction(function(transaction) {

 transaction.executeSql(sql, [],
                        function(transaction, results) {
                          // results.rows holds the rows returned by the query
                          var my_num = results.rows.item(0).num; // returns value of column num from first row
                        },
                        function(transaction, error) {
                          Mojo.Log.error("Could not read");
                        });

}); </source>