简体   繁体   中英

Knex create mysql tables in a transaction

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM