Search code examples
javascriptknex.js

knex.raw and trx.commit in knex.transactions


Im just new to knex and came across Transactions. I think it's useful to use since it has a rollback feature. Tried using it (see code below)

await knex.transaction(trx => {
knex.raw(delete from myTable where "id" = 1 )
  .transacting(trx) 
  .then(trx.commit)
  .catch(trx.rollback) 
})

I just wanted to delete a row with a certain id nothing more and less. Works fine, then i tried to remove 'trx.commit'. I was expecting that it wont apply the query but it did. From what I understand, if trx.commit is not called the query will not run and wont affect the database.

Is my understanding wrong? Did I use knex.raw improperly inside knex.transactions? I dont see examples of transactions that uses raw queries. I am connected to a database in my localhost(postgresql) btw.


Solution

  • knex.js has a modified promise interface.

    Calling .then triggers the query to actually fire (including the BEGIN transaction if it is the first query). Note that in a single knex query you won't need to call rollback since a single query to the database should be transactional and abort/rollback if any errors are encountered.

    Based on your usage (and the docs) if you remove trx.commit it should not commit at all. I recommend actually returning a promise to the transaction callback - then it will auto-commit on promise resolution, and auto-rollback on promise failure.

    In the following usage if either query failed it would auto-rollback everything.

    knex.transaction(trx => {
      return Promise.all([
         knex.raw(`update table x`).transacting(trx),
         knex.raw(`update table y`).transacting(trx)
        ]);
    })