Has anyone written PG_SQL or such method that would generate left outer join queries from reference constraint data only.
Generating these queries, when you need to always takes time, and for most cases this highly mechanical work.
Lets say we have tables ( just as an example to make the question more concrete ).
create table aaa ( id bigint, name varchar);
create table aaa_option( id bigint,aaa_id bigint, name varchar, value varchar);
create table aaa_sub_option( id bigint,option_id bigint, name varchar, value varchar);
CREATE UNIQUE INDEX on aaa(id) ;
CREATE UNIQUE INDEX ON aaa_sub_option(id) ;
ALTER TABLE aaa_option ADD CONSTRAINT aaa_const FOREIGN KEY (aaa_id) REFERENCES aaa(id);
ALTER TABLE aaa_sub_option ADD CONSTRAINT aaa_sub_const FOREIGN KEY (option_id) REFERENCES aaa_sub_option(id);
I am looking for a function like:
rquery('aaa',1);
would give me
select aaa.id as aaa_X_id, aaa.name as aaa_X_name from aaa;
rquery(aaa,2)
would give me:
select aaa.id as aaa_X_id, aaa.name as aaa_X_name,
X1.id as aaa_option_X_id, X1.aaa_id as aaa_option_X_aaa_id, X1.name as aaa_option_X_name,X1.value as aaa_option_X_value from aaa
left outer join aaa_option as X1 on aaa.id=X1.aaa_id;
rquery(aaa,3)
would give me:
… to be writen …
2
Answers
I kind of assumed no such thing exists, but wanted to check no-one disagrees on this.
I think I would probably some time to get this done.
Will get neat info
It looks like all the information I need is there, not that I doubled it would not be accessible.
I would only need to write some PG_PSQL or java to process it into a query generation.
... perhaps I could use recursive querying here.
There’s no such thing, or at least it’s not very common. The use case sounds a bit like what GraphQL is for. In PostgreSQL, you can store and operate on graphs using
pgrouting
or Apache AGE (yourrquery
resembles variable-length edge query), but they don’t necessarily structure the graph data the way you do.You can try those out, or you can even do something like that in vanilla PostgreSQL with a self-referencing table and a recursive query on that: replace the 3 tables with a single one: demo at db<>fiddle
And then your
rquery(N)
is this:fiddle