Any way to insert rows with ID used in another column - Mailing list pgsql-general

From Ben Hoyt
Subject Any way to insert rows with ID used in another column
Date
Msg-id CAL9jXCHJ6GMmMw8dUaZzhTks+0_1G39W1hqcNmhqEzT4K_jwiQ@mail.gmail.com
Whole thread Raw
Responses Re: Any way to insert rows with ID used in another column  (Adrian Klaver <adrian.klaver@aklaver.com>)
Re: Any way to insert rows with ID used in another column  (Francisco Olarte <folarte@peoplecall.com>)
Re: Any way to insert rows with ID used in another column  (Alban Hertroys <haramrae@gmail.com>)
List 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

pgsql-general by date:

Previous
From: Kasahara Tatsuhito
Date:
Subject: size of interval type
Next
From: Tom Lane
Date:
Subject: Re: size of interval type