Any way to insert rows with ID used in another column

From: Ben Hoyt <benhoyt(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Any way to insert rows with ID used in another column
Date: 2014-04-03 14:41:56
Message-ID: CAL9jXCHJ6GMmMw8dUaZzhTks+0_1G39W1hqcNmhqEzT4K_jwiQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi folks,

We have a table images in our db with id (serial primary key) and filename
columns, where the filename is a unique text column that looks something
like "pool-1234.jpg".

The catch is that the "1234" in the filename is the image ID. We want the
filename to include the image ID because it's a nice way of making it
unique and gives the benefit of being able to easily map from the filename
back to the ID for debugging and the like.

Currently I insert new image rows in multiple steps:

1) begin transaction
2) insert a whole bunch of image rows in one multiple-row INSERT, using a
temporary random filename
3) use the RETURNING clause on the above insert to get a mapping between
the database IDs and filenames just inserted
4) loop through all images just inserted, and for each image, execute
UPDATE to set the filename to the real filename which includes the new
image ID
5) commit

This works, but it's pretty cumbersome, and requires N UPDATE statements
which is also slow.

Is there some way to do something like this:

INSERT INTO images (filename) VALUES
('foo' || image_id_about_to_used_for_this_row::text || '.jpg')
('bar' || image_id_about_to_used_for_this_row::text || '.jpg')

I tried using currval() to see if that'd work, but it gave an error, I
guess because I was using it multiple times per session.

Thanks,
Ben

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Rob Sargent 2014-04-03 14:52:38 Re: COPY v. java performance comparison
Previous Message Kasahara Tatsuhito 2014-04-03 14:33:05 size of interval type