knex: Rolling back a transaction without an error

I’m using transacting with knex and I want to rollback the transaction during normal execution. But whenever transaction.rollback() is called it throws an unhandled exception. Providing a custom error object and trying to catch it doesn’t help since it is inside a callback.

Is there a way to rollback a transaction without throwing an error? Or is there a way to handle that error without littering the output?

Sample code:

// some previous inserts using `trans` done by now
db('actions')
.transacting(trans)
.select()
.where('id', data)
.then(function(rows) {
  // do some stuff with rows
  // we don't need the data anymore and want to roll back the transaction
  trans.rollback();
});

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 18 (9 by maintainers)

Most upvoted comments

It’s actually really hard to get unit tests with rollback working. I expected this to work:

beforeEach(function () {
  this.tx = knex.transaction()
})

afterEach(function () {
  this.tx.rollback()
})

What i actually had to do was …

Prevent connection pooling

var knex = require("knex")

var config = {
  client: "pg",
  connection: process.env["DATABASE_URL"]
}

var env = process.env["NODE_ENV"]

if (env == "test") {
  config.pool = {
    min: 1,
    max: 1,
  }
}

module.exports = knex(config)

Raw transaction in tests

beforeEach(function () {
  return knex.raw("BEGIN")
})

afterEach(function () {
  return knex.raw("ROLLBACK")
})

it("should do whatever", function () {
  var tx = knex
  return CallAction(tx, { options: true })
  .then(function (result) {
    assert(result)
  })
})

@rapodaca rolling back changes like that is really limited way to do testing and prevent you from testing many real world use-cases. Of course some specific cases that approach is legit. Just for your information and anyone else checking this issue out 😃

That did the trick. Thanks! Would be nice to have such examples in the docs 😉