如何:使用 pg-promise 顺序 db.batch

How to: Sequential db.batch with pg-promise

我不知道如何按顺序对生成的查询执行批量调用。

我正在尝试截断数据库中的每个 table。我的代码:

db.any(`
  SELECT table_name
  FROM information_schema.tables
  WHERE table_schema='public'
  AND table_type='BASE TABLE';
`)
.then(res => res.map(item => item.table_name)) // To get only an array with the names
.then(tables => tables.map(tableName => db.none(`TRUNCATE TABLE ${tableName} CASCADE`))) // ES6 template strings, because the table name must be bare here (no quotes)
.then(queries => db.tx(t => t.batch(queries)))

我收到 检测到死锁 错误。很明显我遇到死锁的原因:查询级联并尝试截断与另一个查询相同的 table。这就是为什么我需要同步调用查询。我不知道该怎么做。我尝试使用 db.sequence(),但我遇到了同样的错误。使用 pg-promise 顺序执行生成的查询的正确方法是什么?非常感谢。

pg-promise 支持的语法非常灵活。下面只是一种这样的语法,它最容易用于您的案例,也是最现代的语法:

await db.tx(async t => {
    const tables = await t.map(`
        SELECT table_name
        FROM information_schema.tables
        WHERE table_schema = 
        AND table_type = 
    `, ['public', 'BASE TABLE'], a => a.table_name);

    for (let i = 0; i < tables.length; i++) {
        await t.none('TRUNCATE TABLE :name CASCADE', tables[i]);
    }
});

// ES6 template strings, because the table name must be bare here (no quotes)

这是错误的,名称必须用双引号引起来,这是我们提供的 SQL Names 过滤器。

另见来自here

Never use the reserved ${} syntax inside ES6 template strings, as those have no knowledge of how to format values for PostgreSQL.