Permalink
Browse files

Adding node-sqlite support to persistencejs

  • Loading branch information...
1 parent 30010aa commit 3e48e679b9874f4aa2a217b5f60766198976a7db @eugeneware eugeneware committed Feb 10, 2011
Showing with 193 additions and 2 deletions.
  1. +119 −0 lib/persistence.store.sqlite.js
  2. +2 −2 package.json
  3. +72 −0 test/node/test.sqlite.store.js
@@ -0,0 +1,119 @@
+/**
+ * This back-end depends on the node.js asynchronous MySQL driver as found on:
+ * http://github.com/felixge/node-mysql/
+ * Easy install using npm:
+ * npm install mysql
+ */
+var sys = require('sys');
+var sql = require('persistencejs/persistence.store.sql');
+var sqlite = require('sqlite');
+
+var db, username, password;
+
+function log(o) {
+ sys.print(sys.inspect(o) + "\n");
+}
+
+
+exports.config = function(persistence, dbPath) {
+ exports.getSession = function(cb) {
+ var that = {};
+ var conn = new sqlite.Database();
+ conn.open(dbPath, cb);
+
+ var session = new persistence.Session(that);
+ session.transaction = function (explicitCommit, fn) {
+ if (typeof arguments[0] === "function") {
+ fn = arguments[0];
+ explicitCommit = false;
+ }
+ var tx = transaction(conn);
+ if (explicitCommit) {
+ tx.executeSql("START TRANSACTION", null, function(){
+ fn(tx)
+ });
+ }
+ else
+ fn(tx);
+ };
+
+ session.close = function(cb) {
+ conn.close(cb);
+ //conn._connection.destroy();
+ };
+ return session;
+ };
+
+ function transaction(conn){
+ var that = {};
+ // TODO: add check for db opened or closed
+ that.executeSql = function(query, args, successFn, errorFn){
+ function cb(err, result){
+ if (err) {
+ log(err.message);
+ that.errorHandler && that.errorHandler(err);
+ errorFn && errorFn(null, err);
+ return;
+ }
+ if (successFn) {
+ successFn(result);
+ }
+ }
+ if (persistence.debug) {
+ sys.print(query + "\n");
+ args && args.length > 0 && sys.print(args.join(",") + "\n")
+ }
+ if (!args) {
+ conn.execute(query, cb);
+ }
+ else {
+ conn.execute(query, args, cb);
+ }
+ }
+
+ that.commit = function(session, callback){
+ session.flush(that, function(){
+ that.executeSql("COMMIT", null, callback);
+ })
+ }
+
+ that.rollback = function(session, callback){
+ that.executeSql("ROLLBACK", null, function() {
+ session.clean();
+ callback();
+ });
+ }
+ return that;
+ }
+
+ ///////////////////////// SQLite dialect
+
+ persistence.sqliteDialect = {
+ // columns is an array of arrays, e.g.
+ // [["id", "VARCHAR(32)", "PRIMARY KEY"], ["name", "TEXT"]]
+ createTable: function(tableName, columns) {
+ var tm = persistence.typeMapper;
+ var sql = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (";
+ var defs = [];
+ for(var i = 0; i < columns.length; i++) {
+ var column = columns[i];
+ defs.push("`" + column[0] + "` " + tm.columnType(column[1]) + (column[2] ? " " + column[2] : ""));
+ }
+ sql += defs.join(", ");
+ sql += ')';
+ return sql;
+ },
+
+ // columns is array of column names, e.g.
+ // ["id"]
+ createIndex: function(tableName, columns, options) {
+ options = options || {};
+ return "CREATE "+(options.unique?"UNIQUE ":"")+"INDEX IF NOT EXISTS `" + tableName + "__" + columns.join("_") +
+ "` ON `" + tableName + "` (" +
+ columns.map(function(col) { return "`" + col + "`"; }).join(", ") + ")";
+ }
+ };
+
+ sql.config(persistence, persistence.sqliteDialect);
+};
+
View
@@ -1,8 +1,8 @@
{
"name": "persistencejs",
- "version": "0.2.4",
+ "version": "0.2.5",
"engine": "node >=0.2.0",
"author": "Zef Hemel",
"directories": {"lib": "./lib"},
- "dependencies": {"mysql": ">=0.7.0"}
+ "dependencies": {"mysql": ">=0.7.0", "sqlite": ">=1.0.2"}
}
@@ -0,0 +1,72 @@
+// $ expresso -s test.sqlite.store.js
+
+var assert = require('assert');
+var persistence = require('../../lib/persistence').persistence;
+var persistenceStore = require('../../lib/persistence.store.sqlite');
+
+var dbPath = __dirname + '/test.db';
+persistenceStore.config(persistence, dbPath);
+
+var Task = persistence.define('Task', {
+ username: 'TEXT'
+});
+
+var data = {
+ username: 'test'
+};
+
+var task, session;
+
+// remove test database
+function removeDb() {
+ try {
+ require('fs').unlinkSync(dbPath);
+ } catch (err) {
+ }
+}
+
+module.exports = {
+ init: function(done) {
+ removeDb();
+ session = persistenceStore.getSession(function () {
+ session.schemaSync(done);
+ });
+ },
+ add: function(done) {
+ task = new Task(data);
+ session.add(task);
+ session.flush(function(result, err) {
+ assert.ifError(err);
+ done();
+ });
+ },
+ get: function(done) {
+ Task.findBy(session, 'id', task.id, function(task) {
+ assert.equal(task.username, data.username);
+ done();
+ });
+ },
+ update: function(done) {
+ task.username = 'test2';
+ Task.findBy(session, 'id', task.id, function(task) {
+ assert.equal(task.username, 'test2');
+ done();
+ });
+ },
+ remove: function(done) {
+ session.remove(task);
+ session.flush(function(result, err) {
+ assert.ifError(err);
+ Task.findBy(session, 'id', task.id, function(task) {
+ assert.equal(task, null);
+ done();
+ });
+ });
+ },
+ afterAll: function(done) {
+ session.close(function() {
+ removeDb();
+ done();
+ });
+ }
+};

0 comments on commit 3e48e67

Please sign in to comment.