I have a non-empty PostgreSQL table with a GENERATED ALWAYS AS IDENTITY
column id
. I do a bulk insert with the C++ binding pqxx::stream_to, which I'm assuming uses COPY FROM
. My problem is that I want to know the id
s of the newly created rows, but COPY FROM
has no RETURNING
clause. I see several possible solutions, but I'm not sure if any of them is good, or which one is the least bad:
Provide the
id
s manually throughCOPY FROM
, taking care to give the values which the identity sequence would have provided, then afterwards synchronize the sequence withsetval(...)
.First stream the data to a temp-table with a custom index column for ordering. Then do something like
and depend on the fact that the identity sequence produces ascending numbers to correlate them withINSERT INTO foo (col1, col2) SELECT ttFoo.col1, ttFoo.col2 FROM ttFoo ORDER BY ttFoo.idx RETURNING foo.id
ttFoo.idx
(I cannot doRETURNING ttFoo.idx
too because only the inserted row is available for that which doesn't containidx
)Query the current value of the identity sequence prior to insertion, then check afterwards which rows are new.
I would assume that this is a common situation, yet I don't see an obviously correct solution. What do you recommend?