From: | Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> |
---|---|
To: | Ben Hoyt <benhoyt(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org |
Subject: | Re: Any way to insert rows with ID used in another column |
Date: | 2014-04-03 14:59:19 |
Message-ID: | 533D7747.2080101@aklaver.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 04/03/2014 07:41 AM, Ben Hoyt wrote:
> 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.
Write a BEFORE INSERT trigger function?
>
> Thanks,
> Ben
>
--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com
From | Date | Subject | |
---|---|---|---|
Next Message | Thomas Kellerer | 2014-04-03 15:01:36 | Re: COPY v. java performance comparison |
Previous Message | Tom Lane | 2014-04-03 14:53:51 | Re: size of interval type |