Knexjs:事务和原始查询

时间:2019-09-23 12:26:37

标签: knex.js

我们在nodejs中使用knexjs。我们正在尝试将事务与原始查询一起使用,但无法正常工作。引发错误时,将调用回滚函数,但可以在数据库中看到数据

  const trx = await knex.transaction();

  await trx.schema.createTable("test", function(table) {
    table.increments();
    table.string("name");
  });

  await trx("test").insert({ name: "foo1" });
  await trx("test").insert({ name: "foo2" });

  await trx.rollback();

是否可以将事务与原始查询一起使用?

1 个答案:

答案 0 :(得分:0)

根据https://github.com/tgriesser/knex/issues/3452#issuecomment-534952063,创建表会导致隐式提交。因此,事务已关闭,回滚无效。 可能的解决方法是对创建表以外的所有语句使用事务。

下面您可以看到我的代码段已根据此变通办法进行了修改

await knex.schema.createTable("test", function(table) {
  table.increments();
  table.string("name");
});

const trx = await knex.transaction();

await trx("test").insert({ name: "foo1" });
await trx("test").insert({ name: "foo2" });

await trx.rollback();