#2111·bookshelf

How to know if a transaction has been committed?

Author: nicolas-goudryCreated Jun 30, 2021Updated Nov 30, 2022

Introduction

When a transaction is started and its callback calls external functions which add queries to the transaction, it is vague about how to know transaction has been committed.

Issue Description

We have a function, defined in file A, which starts a transaction :

javascript
function myFn() {
    return bookshelf.transaction((transacting) => {
        return MyModel.where({ id: 1 }).query((qb) => { qb.forUpdate() })
        .fetch({ transacting })
        .then((res) => {
            // code omitted
            return anotherFn(transacting)
            .then((res2) => {
                // code omitted
                return Bluebird.props({
                    prop: yetAnotherFn(transacting),
                })
            })
        })
    })
}

In file B, we have yetAnotherFn which is part of the transaction and defines some code which must be called after transaction has been committed :

javascript
function yetAnotherFn(transacting) {
    return MyModel2.where({ id: 2 }).query((qb) => { qb.transacting(transacting).forUpdate() })
    .fetch()
    .then((res) => {
        // Here we used to create an event listener (as described in knex issue 1641) to act on transaction commit
        // but it’s not valid anymore. We need to do it here because we use properties of `res` variable.
    })
}

This example is oversimplified, we have much more functions / queries that are part of the transaction, but I hope you get our point.

Expected behaviour

It would be nice to have a clean way to tell a transaction has been committed. Actually, if we could simply use the transacting argument as a promise, we could call .then on it when we need to act on transaction commit. An event system would also be great, like the one used in knex issue 1641 for example.

Actual behaviour

We found a way to achieve needed behavior, following insights of this comment :

javascript
function yetAnotherFn(transacting) {
    return MyModel2.where({ id: 2 }).query((qb) => { qb.transacting(transacting).forUpdate() })
    .fetch()
    .then((res) => {
        transacting.on('query', ({ sql }) => {
            if (sql === 'COMMIT;') {
                // Transaction committed, code omitted
            }
        })
    })
}

As of our understanding, we cannot use yetAnotherFn transacting's argument as a promise because it seems to be a knex query builder instance. Therefore, trying to use transacting.then throws transacting.then is not a function.

This solution works, but is clearly not safe (if ever the sql property changes for trx commits, it will break), and kind of ugly.