gpt4 book ai didi

node.js - node-postgres:缓存的参数化插入查询,第二次运行失败

转载 作者:行者123 更新时间:2023-11-29 13:27:16 25 4
gpt4 key购买 nike

我正在尝试使用 node-postgres 运行两个参数化插入查询: 第一个指定主键列,第二个不指定。

第二个查询,即使没有指定主键列,也失败了,说有一个重复的主键。

我的 pg 表:

CREATE TABLE teams (
id serial PRIMARY KEY,
created_by int REFERENCES users,
name text,
logo text
);

重现此问题的代码:

var pg = require('pg');

var insertWithId = 'INSERT INTO teams(id, name, created_by) VALUES($1, $2, $3) RETURNING id';
var insertWithoutId = 'INSERT INTO teams(name, created_by) VALUES($1, $2) RETURNING id';

pg.connect(process.env.POSTGRES_URI, function (err, client, releaseClient) {
client.query(insertWithId, [1, 'First Team', 1], function (err, result) {
releaseClient();

if (err) {
throw err;
}

console.log('first team created');
});
});

pg.connect(process.env.POSTGRES_URI, function (err, client, releaseClient) {
client.query(insertWithoutId, ['Second Team', 1], function (err, result) {
releaseClient();

if (err) {
console.log(err);
}
});
});

运行这个的输出:

first team created

{ [error: duplicate key value violates unique constraint "teams_pkey"]
name: 'error',
length: 173,
severity: 'ERROR',
code: '23505',
detail: 'Key (id)=(1) already exists.',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'teams',
column: undefined,
dataType: undefined,
constraint: 'teams_pkey',
file: 'nbtinsert.c',
line: '406',
routine: '_bt_check_unique' }

我从阅读 node-postgres 源代码中收集到的信息是,参数化查询被视为准备好的查询,如果它们重用 name 参数,则会被缓存;尽管通过挖掘它的来源,它似乎并不认为我的查询具有名称属性。

有没有人知道如何避免这种情况?

最佳答案

第一个插入为 id 提供了一个值,因此序列号不会递增。第一次插入后序列号仍然是 1。第二个插入id 提供值,因此使用序列号(=1)。这是重复的。最好的解决方案是使用第二条语句,并让应用程序在需要时使用返回的 id。

简而言之:不要干扰连续剧。


如果您需要更正序列的下一个值,您可以使用类似下面的语句。

SELECT setval('teams_id_seq', (SELECT MAX(id) FROM teams) )
;

关于node.js - node-postgres:缓存的参数化插入查询,第二次运行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com