Knexjs:交易和原始查询

Knexjs: Transaction and raw queries

我们在 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();

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

根据 https://github.com/tgriesser/knex/issues/3452#issuecomment-534952063,创建 table 会导致隐式提交。所以,事务关闭,回滚没有效果。 一种可能的解决方法是对除 create table.

之外的所有语句使用事务

您可以在下面看到根据此解决方法修改的我的代码段

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();