0

I have a PostgreSQL 15 database containing several schemas.
In each schema (representing topics) they are a bunch of tables.

Tables are of two kinds:

  • child tables, often having up to 10 FK to some parent tables (some, not all, can be in an other schema)
  • parent tables, having an id referenced by the FK of the child tables, and some other column, upon which a table called description which contain a human readable description.

I wish I could automatically create a VIEW which expose the description field of each linked parent table along the original fields of the child tables.

E.g.:

CREATE SCHEMA schema1;
CREATE SCHEMA schema2;
...

CREATE TABLE schema1.parent1 (
  id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  description TEXT
);

CREATE TABLE schema1.parent2 (
  id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  description TEXT
);

CREATE TABLE schema2.parent1 (
  id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  description TEXT
);
...

CREATE TABLE schema1.child1 (
  id INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  x INT,
  y INT,
  z FLOAT,
  ...,
  schema1_parent1_id INT REFERENCES schema1.parent1(id),
  schema1_parent2_id INT REFERENCES schema1.parent2(id),
  schema2_parent1_id INT REFERENCES schema2.parent1(id),
  ...
);

I'd like to automatically create such VIEW:


CREATE OR REPLACE VIEW schema1.child1_view AS
SELECT
  child1.x,
  child1.y, 
  child1.z,
  child1.schema1_parent1_id,
  child1.schema1_parent2_id,
  child1.schema2_parent1_id,
  ...,
  par1.description AS parent1_description,
  par2.description AS schema1_parent2_id_description,
  spar1.description AS schema2_parent1_description
FROM schema1.child1 child1
LEFT JOIN schema1.parent1 par1 ON par1.id = child1.schema1_parent1_id
LEFT JOIN schema1.parent2 par2 ON par2.id = child1.schema1_parent2_id
LEFT JOIN schema2.parent1 spar1 ON spar1.id = child1.schema2_parent1_id
...;

The fields names are not so rigorous in reality.

Writing all the JOIN by hand is rather tedious because with ~10 FK per child table, having 10 child tables in 10 schema can quickly lead to lot of manual work.

I'm simply wondering if there is some kind of function in PostgreSQL for doing that task as I'm certainly not the first who want to achieve that?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.