1

我正在尝试使用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参数,它们会被缓存;尽管通过挖掘它的来源,它似乎并不认为我的查询具有名称属性。

有人对如何避免这种情况有任何想法吗?

4

1 回答 1

1

The first insert supplies a value for id, so the serial is not incremented. The serial still is 1 after the first insert. The second insert does not supply a value for id, so the serial (=1) is used. Which is a duplicate. Best solution is to only use the second statement, and let the application use the returned id, if needed.

In short: don't interfere with serials.


If you need to correct the next value for a sequence, you can use something like the below statement.

SELECT setval('teams_id_seq', (SELECT MAX(id) FROM teams) )
        ;
于 2015-07-18T11:46:02.553 回答