I have a database with the following structure
table_a
| id | username |
| -------- | -------- |
| 1 | 'a.a' |
| 2 | 'a.a' |
table_b
| id | table_a_id |
| -------- | ---------- |
| 1 | 1 |
| 2 | 3 |
table_c
| id | table_a_id |
| -------- | ---------- |
| 1 | 2 |
| 2 | 3 |
I want to automattically find the dependences of table_a in the database and change the ids of the second user to the one of the first user so that the end result would look like this:
table_a
| id | username |
| -------- | -------- |
| 1 | 'a.a' |
| 2 | 'a.a' |
table_b
| id | table_a_id |
| -------- | ---------- |
| 1 | 1 |
| 2 | 3 |
table_c
| id | table_a_id |
| -------- | ---------- |
| 1 | 1 |
| 2 | 3 |
I can do it by listing the known tables, but I haven’t been able to automatically find all the dependencies in the database.
2
Answers
Something like this:
Explanation:
table_b
table_a
current
that is the current match oftable_b
intable_a
table_a
min_a
which represents the record intable_a
having the minimum id with the same usernametable_a
earlier
to guarantee thatmin_a
is indeed the minimum matchearlier.id
is to benull
current
match is already the minimumThe PostgreSQL system catalogs can be used to identify referential dependencies and to generate code to delete redundant values from the parent table after updating the references in the child tables.
The following script creates and populates tables to demonstrate addressing redundant references:
The resulting table contents are:
Table A:
Table B:
Table C:
The following
DO
block uses the system catalogs to generate a statement for each parent table. The generated statement employs chained CTEs to identify redundant parent rows, update the child table references to the redundant rows, and then delete the redundant rows. (This code addresses cases where each foreign key references a single column and none of the child tables has a unique index that will be violated when references are updated.)Below is a formatted example of the generated SQL:
After running the script, the demonstration tables have the following content:
Table A:
Table B:
Table C: