postgresql - Using Transaction in Sequelize for Postgres -


i trying transaction sequelize in noodejs. using postgres database. when call testdel transaction autocommitted in testdel. if transaction autocommit set false.

if pass variable t db.transaction testdel, wait manual commit / rollback. can without passing t function? make coding complicated.

the coding following:

db.transaction({autocommit: false}).then((t) => {     args = {vctitle: {$ilike: '%ulie%'}};     let bodelete = true;     testdelpost(t, args)     .then(rersult =>{         if(rersult){             t.commit();         }else{             t.rollback();         }     }) });               function testdel(args){     //the result got deleted , auto committed after destroy,      //doesn't wait above transaction decide commit or rollback.     //if pass t, , set traction: t in destroy, work expected     return db.models.post.destroy({where: args})     .then(result =>{         if(result > 0){             return true;         }else{             return false;         }     })     .error(status =>{         return error;     }) } 

use continuation local storage. assigns global-level sequelize package "namespace", instances created reference namespace when performing transactions.

you initialise sequelize follows (assuming es6 import syntax):

// grab packages need  import sequelize 'sequelize'; import cls 'continuation-local-storage';      // assign namespace database  sequelize.cls = cls.createnamespace('db'); 

this allows perform transactions without explicitly passing t around. rolls on uncaught exceptions (or technically, unresolved promises), , commits on resolved promises:

the following sample function i'm using in production code demonstrates concept in action.

it...

  • starts transaction (begin; in postgresql)
  • creates new account (insert "accounts"...)
  • creates entry joins account account type (insert "account_type_accounts"...)
  • creates entry links user account (insert "users_accounts"...)
  • only performs inserts if of above succeeded (commit;). if not, rolls (rollback;)

here's code:

createaccount (user, accounttype, query = {}) {   // start transaction   return this.db.connection.transaction(() => {     // create new account     return this.db.models.account.create(query).then(account => {       // associate user & account type       return p.all([user.addaccount(account), accounttype.addaccount(account)]).then(()=> {         // return account promise chain         return account;       });     });   }); } 

note lack of t variables or explicit rollback/commit.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -