Fork me on GitHub

MySQL-Node Specific Issues

Sadly the node.js server environment requires slight changes to persistence.js to make it work with multiple database connections:

  • A Session object needs to be passed as an extra argument to certain method calls, typically as a first argument.
  • Methods previously called on the persistence object itself are now called on the Session object.

After setting up the MySQL store, obtain new Sessions using:

var session = persistenceStore.getSession();

and close a session using:

session.close();

Commit and Rollback

persistence.js works in autocommit mode by default.

You can override this behavior and enable explicit commit and rollback by passing true as first argument to persistence.transaction. You can then use the following two methods to control the transaction:

  • transaction.commit(session, callback) commits the changes.
  • transaction.rollback(session, callback) rollbacks the changes.

Typical code will look like:

session.transaction(true, function(tx) {
  // create/update/delete objects
  modifyThings(session, tx, function(err, result) {
    if (err) {
      // something went wrong
      tx.rollback(session, function() {
        console.log('changes have been rolled back: ' + ex.message);
      });
    }
    else {
      // success
      tx.commit(session, function() {
        console.log('changes have been committed: ' result);
    });
  });
});

Explicit commit and rollback is only supported on MySQL (server side) for now.

Defining your data model

Defining your data model is done in exactly the same way as regular persistence.js:

var Task = persistence.define('Task', {
  name: "TEXT",
  description: "TEXT",
  done: "BOOL"
});

A schemaSync is performed on the session object instead of persistence object:

session.schemaSync(tx, function() {
  ...
});

Creating and manipulating objects

Creating and manipulating objects is done much the same way as with regular persistence.js, except that in the entity's constructor you need to reference the Session again:

var t = new Task(session);
...
session.add(t);

session.flush(tx, function() {
  ...
});

Query collections

Query collections work the same way as in regular persistence.js with the exception of the Entity.all(), Entity.findBy(), and Entity.load() methods that now also require a Session to be passed to it:

Task.all(session).filter('done', '=', true).list(tx, function(tasks) {
  ...
});
stores/mysql-node.txt · Last modified: 2011/02/02 10:21 by Zef Hemel