node-postgres:caching的参数化插入查询,在第二次运行时失败

我试图运行两个使用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参数,它将被caching。 虽然从挖掘它的来源,似乎并不认为我的查询具有名称属性。

有没有人有任何想法如何可以避免?

第一个插入为id提供一个值,所以串行不会递增。 第一次插入后序列号仍为1。 第二个插入不提供id的值,所以使用序列(= 1)。 这是重复的。 最好的解决scheme是使用第二个语句,并让应用程序使用返回的id,如果需要的话。

总之:不要干涉连续剧。


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

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