postgresql: how to get primary keys of rows inserted with a bulk copy_from?

我与影子孤独终老i 提交于 2019-12-05 20:44:28

Generate the IDs yourself.

  1. BEGIN transaction
  2. Lock table a
  3. call nextval() - that's your first ID
  4. generate your COPY with IDs in place
  5. same for table b
  6. call setval() with your final ID + 1
  7. COMMIT transaction

At step 2 you probably want to lock the sequence's relation too. If code calls nextval() and stashes that ID somewhere it might be already in use by the time it uses it.

Slightly off-topic fact: there is a "cache" setting that you can set if you have lots of backends doing lots of inserts. That increments the counter in blocks.

http://www.postgresql.org/docs/9.1/static/sql-createsequence.html

Actually you can do it differently, what you need is:

  • Start transaction
  • Create temp table with same (or almost same) schema
  • COPY data to that temp table
  • Perform regullar INSERT INTO .. FROM temp_table ... RETURNING id, other_columns
  • Commit

taken from here (in c#, but algo is the same)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!