(TL;DR at the end)
I am working on merging 2 well sized postgres databases.
As there are ID conflicts and many foreign keys I would have enjoyed that UPDATE foo SET bar_id = bar_id + 100000 CASCADE was a thing in SQL so it magically update everything accordingly. Unfortunately, it's not.
So I want to use a LOOP structure (see below) that will simply edit the references everywhere. I want a select query the return all table_name, column_name that references the column I want.
DO
$$
DECLARE
rec record;
BEGIN
FOR rec IN
(SELECT table_name, column_name FROM /*??*/ WHERE /*??*/) -- <<< This line
LOOP
EXECUTE format('UPDATE %I SET %s = %s + 100000 ;',
rec.table_name,rec.column_name,rec.column_name);
END LOOP;
END;
$$
LANGUAGE plpgsql;
I know already how to get all tables (+column_name) having a specific column_name that I use when the foreign key column share the name with the column it references. Or even if it's a list of column_name I know:
SELECT col.table_name, col.column_name
FROM information_schema.columns col
right join
information_schema.tables tab
ON col.table_name = tab.table_name
WHERE column_name = 'foo_id'
-- IN ('FOO_ID','BAR_FOO_ID') | or : like '%foo_id' | both works well most of the time
and tab.table_type = 'BASE TABLE'
But...
I am now with a table PLACES with the place_id column being referenced on at least 60 different constraints (matching LIKE '%place_id'). Then there is columns referencing the place id named otherwise like 'foo_currentplace','foo_storageroom', 'foo_lastrecomposition_place', 'operating_theatre' and so on. In the other hand, there is columns referring 'placetype_id' from placetype table which are LIKE '%place%' and I do NOT want to change the placetype_id, so we can not guess which column is to include or not only from their name.
I know there is the information_schema.table_constraints table, but it does NOT tell the referenced column.
If we can have the definition from the constraint name, it could be possible to match :
ILIKE format('%%REFERENCES %s(%s)%%',table_name,column_name)
but the definition isn't part of the table_constraints table either.
(For those wondering, I'm working on Hospital databases related to sterilization services.)
WHAT I WANT / TL;DR
I need a SELECT query (or a function definition ) returning all column of the whole database (schema_name,table_name,column_name) or (table_name,column_name) having a foreign key constraint referencing a specified column (parameter).