Search code examples
sqlpostgresqltransactionsknex.js

How to implement transaction in knex?


How to implement transaction in knex if functions are used? util.insert calls knex on table2 and similarly util.mark.

 knex('tab1').where({ col1: 'val1' }).update({ col2: 'val2'}).returning('col3').then(function(result1) {
                    if (result1 != 0) {
                        var data2 = {
                            "key": "value"
                        };
                      util.insert(data1, function(err1, data2) {
                            if (err1) {
                                cb(err1);
                                return;
                            }
                            util.mark(data2, function(err2, data3) {
                                if (err2) {
                                    cb(err2);
                                    return;
                                }
                                cb(null, true);
                                return;
                            });
                        });
                    } else {
                        cb(null, false);
                    }
                })

Solution

  • knex.transaction((trx) => {
      return knex('tab1')
      .update({ col2: 'val2' })
      .where({ col1: 'val1' })
      .transacting(trx)
      .then((result) => {
        let promise;
        if (result1 != 0) {
          promise = util.insert(data1);
        } else {
          promise = util.mark(data2);
        }
        return promise
        .transacting(trx);
      })
      .then(trx.commit)
      .catch(trx.rollback)
    })
    .then(() => {
      // blabla
    })
    .catch((err) => {
      // handle your error together
    });
    

    and if util.insert or util.mark take io operation, they better accept the trx as arguments.