dbutils.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function trans(db, workFn, finalCB) {
  2. function commit(data) {
  3. db.query('COMMIT', function(err, res) {
  4. if(err) {
  5. db.query('ROLLBACK', function(err2, res2) {
  6. if(err2) return finalCB([err, err2]);
  7. finalCB(err, res2);
  8. });
  9. }
  10. finalCB(null, data);
  11. });
  12. };
  13. function rollback(data) {
  14. db.query('ROLLBACK', function(err, res) {
  15. if(err) return finalCB(err);
  16. finalCB('rollback', data);
  17. });
  18. };
  19. db.query('BEGIN', function(err, res) {
  20. if(err) finalCB(err);
  21. workFN(db, rollback, commit);
  22. });
  23. };
  24. function transList(db, queries, finalCB) {
  25. function work(trandb, rollback, commit) {
  26. var i = 0;
  27. var acc = [];
  28. function nibble() {
  29. var q = queries[i++];
  30. var p = {};
  31. if(!q) return commit(acc); // TODO test this part to see if it works
  32. if(typeof q == 'object') {
  33. p = q.p;
  34. q = q.q;
  35. }
  36. trandb.query(q, p, function(err, res) {
  37. if(err) {
  38. return rollback([err, acc]);
  39. }
  40. acc.push(res);
  41. process.nextTick(nibble);
  42. });
  43. }
  44. nibble();
  45. }
  46. trans(db, work, finalCB);
  47. };
  48. module.exports = {
  49. trans: trans,
  50. transList: transList,
  51. };