如何使用 pg-promise 插入助手将名称作为别名插入 table?

How to insert into table name as alias using pg-promise insert helper?

这是

的后续问题

用例适用于以下查询:

INSERT INTO "GamingLogs" AS GL ("GameName", "TimeSpent")
VALUES ('LOL', '2'),
    ('DOTA2', '1'),
    ('Mobius Final Fantasy', '3')
ON CONFLICT ("GameName") DO UPDATE
SET "TimeSpent" = GL."TimeSpent" + EXCLUDED."TimeSpent"

假设数据 table 包含 GameName 上的主字符串键和一个整数列 TimeSpent。目的让我们假设它在给定的 GameName.

上记录我一生的总游戏时间

更新:简化了查询并添加了数据结构。

您可以使用 helpers 命名空间中的灵活类型来生成您自己的自定义插入:

const pgp = require('pg-promise')(/*initialization options*/);

// data = either one object or an array of objects;
// cs = your ColumnSet object, with table name specified
// alias = the alias name string
function createInsertWithAlias(data, cs, alias) {
    return pgp.as.format('INSERT INTO  AS ~ (^) VALUES ^', [
        cs.table, alias, cs.names, pgp.helpers.values(data, cs)
    ]);
}

然后您只需将冲突解决子句附加到它,因为它是静态的。

API示例中使用: