Wednesday, November 4, 2009

API Reference: Database.jsm library

Database.jsm library
OR Mapper for the SQLite RDBMS builted in the Firefox.
Developped by tombloo.

Example.
// Make a Model for "Bookmark".
var Bookmark = Entity({
name : 'bookmarks',
fields : {
id : 'INTEGER PRIMARY KEY',
url : 'TEXT UNIQUE NOT NULL',
title : 'TEXT',
date : 'TIMESTAMP NOT NULL',
last_visited : 'TIMESTAMP',
comment : 'TEXT',
}
})
// Get the file of database(at "ProfD/foobar/foobar.sqlite").
function dbFile() {
var pd = DirectoryService.get("ProfD", Ci.nsIFile);
pd.append("foobar");
if (!pd.exists() || !pd.isDirectory()) {
pd.create(Ci.nsIFile.DIRECTORY_TYPE, 0755);
}
pd.append("foobar.sqlite");
return pd;
}

// Construct an instance of the Database class.
var db = new Database(dbFile());
// Set the instance to the model of Bookmark.
Bookmark.db = db;
// initialize the model.
Bookmark.initialize();
...
//Bookmark.insert, find, update, deleteById, and so on.
...
// Close the database.
db.close();

Remarks#1: TIMESTAMP type, LIST type.

By specifing a TIMESTAMP type, you can read and write the Javascript's Date object transparently.
(Note: Actually the SQLite doesn't have the Date type, so the library store the value of "Date.getTime()" as INTEGER type.)

Similarly, by specifing a LIST type, you can do the Array object transparently.
(Note: The library store the value of "A CSV-format string made from the array" as TEXT type.)

Remarks#2: findByFoo, findByFooAndBar, countByFoo、countByFooAndBar

You can find and count the model with its value of "Foo" or "Bar". This is realized by hooking the __noSuchMethod__.

Reference Manual
Database Class

function: Database aFile
Construct an instance of the Database class.
aFile a file path of the database file of the SQLite. An instance of nsIFlie.

getter: version
Get the version of the database, corresponding to the PRAGMA's user_version(not to the schema_version).

setter: version
Set the version of the database.

function: getPragma aName
Get the value of the PRAGMA.
aName A name of the PRAGMA. String.

function: setPragma aName aVal
Set the value of the PRAGMA.
aName A name of the PRAGMA. String.
aVal A value to set. String.

function: createStatement aSQL
Create a statement. It returns a mozIStorageStatementWrapper.
aSQL A SQL statement. String.

function: bindParams aWrapper aParams
Bind a parameter to the statement. It returns a mozIStorageStatementWrapper of the binded statement.
aWrapper A statement. An instance of the mozIStorageStatementWrapper.
aParams A parameter. Dispatch for its type in the followings manner.

object: bind as a named parameter.
array: bind the elements in order in the array.
value: bind to the first parameter.
null: do nothing.

function: getParamNames aWrapper
Get an array of the named parameters of the statement.
aWrapper A statement. An instance of the mozIStorageStatementWrapper.

function: getColumnNames aStatement
Get an array of the column names of the statement.
aStatement A statement. An instance of the mozIStorageStatement or the mozIStorageStatementWrapper.

function: getRow aRow aColumnNames
Get a object which converted the table rows.
aRow A table row. An instance of the mozIStorageStatementRow.
aColumnNames A list of the column names. Array.

function: execute aSQL aParams
Execute the SQL query. You can use both DDL and DML.
aSQL A SQL statement. String or mozIStorageStatementWrapper.
aParams A parameter for the SQL statement. Object or Array or Statement, same with the bindParams.

function: transaction aProc
Execute operations in a transaction.
Use for a batch processing which requires high performance.
When it raise an error, we'll rollback the transaction.
Otherwise, we'll commit it automatically.
If another transaction was already started, we don't start any transaction.
aProc A oparation. A function with no arguments.

function: beginTransaction
Begin a transaction.
We don't raise error still the transaction is already started.

function: commitTransaction
Commit a transaction.
We don't raise error still the transaction is not started.

function: rollbackTransaction
Rollback a transaction.
We don't raise error still the transaction is not started.

function: throwException aError
Interpret an error of the database and throw it again.
aError An error of the database.

function: close
Close the database.
You have to close it to delete the file, as it's locked.

function: tableExists aName
Check wheather a database exists or not.
aName A name of the tabel. String.

function: vacuum
Vacuum a waste of the data area in the database.

Model Class

function: save
Save a model to the database. Firstly do with "insert" with a generated id, nextly with "update".

function: remove
Remove a model from the database. We use deleteById internally.

property: definitions
An object indicates the entity definition of the model.

function: initialize
CREATE a table.
We execute the following SQL internally.

CREATE TABLE IF NOT EXISTS {def.name} (
{def.fields.join(', ')}
)

function: deinitialize
DROP a table.
We execute the following SQL internally.

DROP TABLE {def.name}

function: insert
INSERT a model.
We execute the following SQL internally.

INSERT INTO {def.name} (
{fields.join(', ')}
) VALUES (
{params.join(', ')}
)
function: update
UPDATE a model.
We execute the following SQL internally.

UPDATE {def.name}
SET {fields}
WHERE id = :id

function: deleteById aId
DELETE a model by id.
aId An id of the model. Integer.
We execute the following SQL internally.

DELETE FROM {def.name}
WHERE id = :id

function: deleteAll
DELETE all of models.
We execute the following SQL internally.

DELETE FROM {def.name}

function: countAll
Count all of models.
We execute the following SQL internally.

SELECT count(*) AS count
FROM {def.name}

function: findAll
Find all of models.
We execute the following SQL internally.

SELECT *
FROM {def.name}

function: findFirst aParams
Find a model with a parameter "LIMIT 1".
aParams A parameter, same with Database.execute.
We execute the following SQL internally.
SELECT *
FROM {def.name}
...Contents of aParams...
LIMIT 1 OFFSET 0

function: find aSQL aParams
Find models with a parameter.
aSQL An object or an instance of the mozIStorageStatementWrapper.
aParams A parameter, same with Database.execute.
We execute the following SQL internally when aParams is null, aSQL is object, and aSQL.where is string.

SELECT *
FROM {def.name}
WHERE {sql.where}

We execute the following SQL internally when aParams is null, aSQL is object.

SELECT *
FROM {def.name}

Otherwise, We do the Database.execute internally.

Model.db.execute(sql, params).map(Model.rowToObject);

function: findByFoo aFoo
function: findByFooAndBarAnd... aFoo aBar ...
Find models by a value of the Foo or the Bar. This is realized by hooking the __noSuchMethod__.
We execute the following SQL internally.

SELECT *
FROM {def.name}
WHERE foo = aFoo and bar = aBar and ...

function: countByFoo aFoo
function: countByFooAndBar... aFoo aBar ...
Count models by a value of the Foo or the Bar. This is realized by hooking the __noSuchMethod__.

We execute the following SQL internally.

SELECT count(id) AS count
FROM {def.name}
WHERE foo = aFoo and bar = aBar and ...

function: rowToObject aObject
Construct an instance of the model from an object, except when you call the "save" method, we will call the "update".
aObject An object with proper elements for the entity definition.

Entity Class


function: Entity aDefinition
Construct an instance of the model with the entity definition.
aDefinition An object indicates the entity definition.
(name property is a name of the table, fields property is a mapping between a name of entity and its type.

Example.
var Bookmark = Entity({
name : 'bookmarks',
fields : {
id : 'INTEGER PRIMARY KEY',
url : 'TEXT UNIQUE NOT NULL',
title : 'TEXT',
date : 'TIMESTAMP NOT NULL',
last_visited : 'TIMESTAMP',
comment : 'TEXT',
}
})

function: createWhereClause aFields
Create a string for a WHERE clause.
aFields An array of parameters' name for WHERE.

function: createInitializeSQL aDefinition
Create a string for a "CREATE TABLE IF NOT EXISTS..." statement.
aDefinition An object indicates the entity definition, same with Entity.

function: createInsertSQL aDefinition
Create a string for a "INSERT INTO..." statement.
aDefinition An object indicates the entity definition, same with Entity.

function: createUpdateSQL aDefinition
Create a string for a "UPDATE ..." statement.
aDefinition An object indicates the entity definition, same with Entity.

function: compactSQL aSQL
Remove useless whitespaces from a SQL statement and create a compact string of it.
This aims to hold the variation of the statement's representation to a minimum and increase a cache-hit rate of interpreted statements.

aSQL A string of the SQL statements.

Bibliography

* Storage - MDC
* mozIStorageStatement - MDC
* mozIStorageStatementWrapper - MDC

No comments: