pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tim Landscheidt <tim@tim-landscheidt.de>
To: pgsql-sql@postgresql.org
Subject: Re: safely exchanging primary keys?
Date: Mon, 24 May 2010 14:38:39 +0000
Message-ID: <m3d3wl1i1c.fsf@passepartout.tim-landscheidt.de> (raw)
References: <20100524085101.GA21249@apartia.fr>

Louis-David Mitterrand <vindex+lists-pgsql-sql@apartia.org> wrote:

> I have this function which swaps primary keys for cabin_types (so that
> id_cabin_type ordering reflects natural data ordering):

> 	CREATE OR REPLACE FUNCTION swap_cabin_types(id1 integer, id2 integer) RETURNS integer
> 		AS $$
> 	declare
> 		tmp integer;
> 	begin
> 		tmp := nextval('cabin_type_id_cabin_type_seq');
> 		update cabin_type set id_cabin_type=tmp where id_cabin_type=id1;
> 		update cabin_type set id_cabin_type=id1 where id_cabin_type=id2;
> 		update cabin_type set id_cabin_type=id2 where id_cabin_type=tmp;
> 		return tmp;
> 	end;
> 	$$
> 	LANGUAGE plpgsql;

> 'id_cabin_type' is a foreign key for two other tables, 'cabin_category'
> and 'alert_cabin_type', which have an "on update cascade" clause.

> When I run that function it seems the foreign keys are not properly
> updated and the data ends up in a mess.

> Did I forget something?

What does "are not properly updated" mean? Anyhow, why don't
you use something simple like (untested):

| UPDATE cabin_type
|   SET id_cabin_type =
|     CASE
|       WHEN id_cabin_type = id1 THEN
|         id2
|       ELSE
|         id1
|     END
|   WHERE id_cabin_type IN (id1, id2);

Tim




view thread (9+ messages)  latest in thread

Message-ID: <m3d3wl1i1c.fsf@passepartout.tim-landscheidt.de>
Permalink:  ../m3d3wl1i1c.fsf@passepartout.tim-landscheidt.de/
Also on:    postgresql.org/message-id/m3d3wl1i1c.fsf@passepartout.tim-landscheidt.de

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tim@tim-landscheidt.de
  Subject: Re: safely exchanging primary keys?
  In-Reply-To: <m3d3wl1i1c.fsf@passepartout.tim-landscheidt.de>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox