Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Knex transacting() vs chaining off the trx object

Knex's documentation for transactions has code that looks like this:

knex.transaction(function(trx) {
    var books = [
        {title: 'Canterbury Tales'},
        {title: 'Moby Dick'},
        {title: 'Hamlet'}
    ];

    return trx
    .insert({name: 'Old Books'}, 'id')
    .into('catalogues')
    .then(function(ids) {
    return Promise.map(books, function(book) {
        book.catalogue_id = ids[0];

        // Some validation could take place here.

        return trx.insert(info).into('books');
    });
    });
})

Here on SO I've seen extensive use of a function transacting() with examples that look like this:

knex.transaction(function(trx) {
   knex('foo')
  .transacting(trx)
  .insert({id:"bar", username:"bar"})
  // etc
 })

Knex describes transacting() with examples similar to above:

Used by knex.transaction, the transacting method may be chained to any query and passed the object you wish to join the query as part of the transaction for.

My question is:

What is the difference between trx.insert().into('foo') and knex('foo').transacting(trx).insert() and why would you use one instead of the other?

like image 538
Mark Avatar asked Oct 18 '17 07:10

Mark


1 Answers

It is convenient to use .transacting(trx) when you want to perform multiple operations in the same transaction:

knex.transaction(function (trx) {
    return Promise.all([
        knex('foo').insert({ name: 'My Name' }).transacting(trx),
        knex('bar').insert({ field: 'Value' }).transacting(trx)
    ])
    // ---- or something like ----
    return Promise.all(SOME_INPUT_VALUES.map(function (value) {
        return knex('foo_bar').update('lul', value.lul).where('id', value.id).transacting(trx)
    }))
})

Don't know really of a particular usage of the other method. It might be just a matter of style. You got two interfaces and you can pick one whatever you like most. As for me, I'm used to .transacing(trx)

like image 175
coockoo Avatar answered Nov 14 '22 23:11

coockoo