I am trying to create two tables as part of a transaction using knex, so if the creation of one of the tables fails, everything is rolled back. The documentation is not very good.
I am running into two issues. One is that it appears to not be running as a transaction and rolling back properly because user
exists, but user1
does not exist before running this code, yet user1
still gets created.
The code also never finishes so I believe I have an unhandled promise, but not getting an error stating that.
const knex = require('knex')({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'root',
password: 'pass',
database: 'test'
}
});
return knex.transaction(trx => {
return Promise.all([
knex.raw('CREATE TABLE user1 (name VARCHAR(20));').transacting(trx),
knex.raw('CREATE TABLE user (name VARCHAR(20));').transacting(trx)
])
.then(trx.commit)
.catch(trx.rollback);
}).then(()=>{
console.log('success')
}).catch((err)=>{
console.log('fail')
});
Mysql does implicit commit after each DDL query, So there is no way to create multiple tables in a single transaction with mysql.
Related answer https://stackoverflow.com/a/54180024/360060