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(trxmit)
.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 'trxmit'. I was expecting that it wont apply the query but it did. From what I understand, if trxmit 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.
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.mit)
.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.mit'. I was expecting that it wont apply the query but it did. From what I understand, if trx.mit 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.
Share Improve this question asked Jan 26, 2019 at 17:07 KevCepKevCep 371 silver badge5 bronze badges 1-
I have also noticed that sometimes it mits correctly when you forget to return a promise or call
.mit
. That being said knex.js is bad about undefined behavior and breaking it between versions. Don't stress about things it does that are not documented - stick to using patterns that make sense and match the docs. Also beware their non-semver breaking changes. – Catalyst Commented Jan 26, 2019 at 17:23
1 Answer
Reset to default 7knex.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.mit
it should not mit at all. I remend actually returning a promise to the transaction callback - then it will auto-mit 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)
]);
})