Knex 在事务中创建 mysql 个表

Knex create mysql tables in a transaction

我正在尝试使用 knex 创建两个表作为事务的一部分,因此如果其中一个表的创建失败,所有内容都会回滚。文档不是很好。

我 运行 有两个问题。一个是它似乎不是 运行 作为事务并正确回滚,因为 user 存在,但是 user1 在 运行 这段代码之前不存在,但是 user1 仍然被创建。

代码也永远不会完成,所以我相信我有一个未处理的承诺,但没有收到错误说明。

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 在每个 DDL 查询后进行隐式提交,因此无法在单个事务中使用 mysql.

创建多个表

相关回答