Best way to change values of a primary key referenced by many tables

From: Andreas Joseph Krogh <andreas(at)visena(dot)com>
To: pgsql-sql(at)lists(dot)postgresql(dot)org
Subject: Best way to change values of a primary key referenced by many tables
Date: 2020-10-21 20:27:29
Message-ID: VisenaEmail.45.50d53c6557c272d6.1754cb2dafc@tc7-visena
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


Hi.

I'm looking for the easiest way to change the vaules of a PK of a table
(my_user), which is referenced by many FKs, with the minimum effort.

Here's an example-schema:

CREATE TABLE my_user ( id BIGSERIAL PRIMARY KEY, username VARCHAR NOT NULL
UNIQUE); CREATE TABLE my_person ( entity_id BIGSERIAL PRIMARY KEY, user_id
BIGINT REFERENCESmy_user (id), name VARCHAR NOT NULL ); CREATE TABLE my_project
(entity_id BIGINT PRIMARY KEY, name VARCHAR NOT NULL, created_by BIGINT NOT
NULL REFERENCESmy_user (id) );
CREATE TABLE my_company ( entity_id BIGINT PRIMARY KEY, name VARCHAR NOT NULL,
created_byBIGINT NOT NULL REFERENCES my_user (id) DEFERRABLE INITIALLY DEFERRED
); CREATE TABLE my_product ( entity_id BIGINT PRIMARY KEY, name VARCHAR NOT NULL
,created_by BIGINT NOT NULL REFERENCES my_user (id) ON DELETE CASCADE );

Now - I want to refactor so that my_user.id has the same value as my_person.
entity_id

Updating the value of my_user.id sounds simple, but how do I do that, and
update all other tables pointing to it with this new value, with as little
effort as possible, ie. don't have to ALTER/UPDATE every table having an FK to
my_user.id?

Not that some FKs are DEFERRABLE, others have "ON DELETE", and the requirement
is to not mess with that.

So - I'm basically looking for (I think) a way to add "ON UPDATE CASCADE" to
all columns referencing it, update the values and then removing all "ON UPDATE
CASCADE" on the referencing columns.

Appreciate suggestions, thanks.

--
Andreas Joseph Krogh

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message David G. Johnston 2020-10-21 21:25:41 Re: Best way to change values of a primary key referenced by many tables
Previous Message Simon Riggs 2020-10-20 08:56:42 Re: get counts of multiple field values in a jsonb column