diff --git a/README.md b/README.md index f8afa6f..afedb9e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,43 @@ db.transaction(function (err, transaction) { }); ``` +## Pool Example + +```js +var orm = require("orm"); +var transaction = require("orm-transaction"); + +orm.connect("mysql://username:password@host/database", function (err, db) { + if (err) throw err; + + db.use(transaction); + + var Person = db.define("person", { + name : String, + surname : String, + age : Number + }); + + db.transaction(function (err, t) { + + Person.create({name: "John"}, t.id, function(err, result) { + + Person.find({ surname: "Doe" }).each(function (person) { + person.useConnection(t.id).remove(function () { + t.commit(function (err) { + if (!err) { + console.log("success!"); + } + }); + }); + }); + + }); + + }); +}); +``` + ## Example ```js @@ -48,14 +85,15 @@ orm.connect("mysql://username:password@host/database", function (err, db) { db.transaction(function (err, t) { Person.find({ surname: "Doe" }).each(function (person) { - person.remove(); + person.remove(function () { + t.commit(function (err) { + if (!err) { + console.log("success!"); + } + }); + }); }); - t.commit(function (err) { - if (!err) { - console.log("success!"); - } - }); }); }); ``` diff --git a/lib/plugin.js b/lib/plugin.js index 5ce316d..12ebb23 100644 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -4,28 +4,59 @@ module.exports = Plugin; function Plugin(db) { db.transaction = function (cb) { - db.driver.execQuery("BEGIN", function (err) { - if (err) { - return cb(err); - } + if (db.driver.opts.pool) + db.driver.createPool(function (err, id) { + if (err) + return cb(err); + db.driver.execQuery("BEGIN", id, function (err) { + if (err) { + return cb(err); + } - debug("init transaction!"); + debug("init transaction!"); - return cb(null, { - commit: function (cb) { - db.driver.execQuery("COMMIT", function (err) { - debug("transaction committed!"); - return cb(err || null); - }); - }, - rollback: function (cb) { - db.driver.execQuery("ROLLBACK", function (err) { - debug("transaction rolled back!"); - return cb(err || null); + return cb(null, { + id: id, + commit: function (cb) { + db.driver.execQuery("COMMIT", id, function (err) { + debug("transaction committed!"); + db.driver.releasePool(id); + return cb(err || null); + }); + }, + rollback: function (cb) { + db.driver.execQuery("ROLLBACK", id, function (err) { + debug("transaction rolled back!"); + db.driver.releasePool(id); + return cb(err || null); + }); + } }); + }); + }); + else + db.driver.execQuery("BEGIN", function (err) { + if (err) { + return cb(err); } + + debug("init transaction!"); + + return cb(null, { + commit: function (cb) { + db.driver.execQuery("COMMIT", function (err) { + debug("transaction committed!"); + return cb(err || null); + }); + }, + rollback: function (cb) { + db.driver.execQuery("ROLLBACK", function (err) { + debug("transaction rolled back!"); + return cb(err || null); + }); + } + }); }); - }); }; return {