2020-10-22 11:42:50 -04:00
|
|
|
SELECT
|
2020-10-22 23:09:34 -04:00
|
|
|
-------------------------------------------create table---------------------------------------------------------------------------------------------------------
|
|
|
|
'DROP TABLE IF EXISTS fc.'||func||' CASCADE; CREATE TABLE IF NOT EXISTS fc.'||func||' (' ||
|
2020-10-22 12:24:10 -04:00
|
|
|
string_agg(format('%I',cname) || ' ' || dtype,', ' ORDER BY opos ASC) ||
|
|
|
|
', PRIMARY KEY ('||string_agg(format('%I',cname),', ') FILTER (WHERE fkey = func)||'));' AS ddl,
|
2020-10-22 23:09:34 -04:00
|
|
|
-------------------------------------------populate table-------------------------------------------------------------------------------------------------------
|
2020-10-22 11:42:50 -04:00
|
|
|
---need to add a clause to exclude where the key is null
|
2020-10-22 23:09:34 -04:00
|
|
|
'INSERT INTO fc.'||func||' SELECT DISTINCT ' || string_agg(format('%I',cname),', ' ORDER BY opos ASC) || ' FROM '||tname||' WHERE '||
|
|
|
|
string_agg(format('%I',cname)||' IS NOT NULL ',' AND ') FILTER (WHERE fkey = func)||' ON CONFLICT DO NOTHING' AS pop,
|
|
|
|
-------------------------------------------setup foreign keys---------------------------------------------------------------------------------------------------
|
|
|
|
'ALTER TABLE fc.live ADD CONSTRAINT fk_'||func||' FOREIGN KEY ('||string_agg(format('%I',cname),', ') FILTER (WHERE fkey = func)||') REFERENCES fc.'||func||' ('||
|
|
|
|
string_agg(format('%I',cname),', ') FILTER (WHERE fkey = func)||')' AS fk
|
2020-10-22 11:42:50 -04:00
|
|
|
FROM
|
|
|
|
fc.target_meta
|
|
|
|
GROUP BY
|
2020-10-22 23:09:34 -04:00
|
|
|
tname
|
|
|
|
,func
|
2020-10-22 12:24:10 -04:00
|
|
|
HAVING
|
|
|
|
string_agg(cname,', ') FILTER (WHERE fkey = func) <> ''
|