From 0f698d562152836d535e5ea3c3528c2fbc53d1c3 Mon Sep 17 00:00:00 2001 From: Paul Trowbridge Date: Thu, 22 Oct 2020 23:08:11 -0400 Subject: [PATCH] include foreign key setup --- sql/build_master_tables.sql | 8 ++++++-- sql/target_info.sql | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/sql/build_master_tables.sql b/sql/build_master_tables.sql index 6961ab3..af14deb 100644 --- a/sql/build_master_tables.sql +++ b/sql/build_master_tables.sql @@ -9,13 +9,16 @@ BEGIN FOR f IN SELECT -------------------------------------------create table--------------------------------------------------------------------------------------------------------- - 'DROP TABLE IF EXISTS fc.'||func||'; CREATE TABLE IF NOT EXISTS fc.'||func||' (' || + 'DROP TABLE IF EXISTS fc.'||func||' CASCADE; CREATE TABLE IF NOT EXISTS fc.'||func||' (' || string_agg(format('%I',cname) || ' ' || dtype,', ' ORDER BY opos ASC) || ', PRIMARY KEY ('||string_agg(format('%I',cname),', ') FILTER (WHERE fkey = func)||'));' AS ddl, -------------------------------------------populate table------------------------------------------------------------------------------------------------------- ---need to add a clause to exclude where the key is null '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 + 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 FROM fc.target_meta GROUP BY @@ -26,6 +29,7 @@ BEGIN loop EXECUTE format('%s',f.ddl); EXECUTE format('%s',f.pop); + EXECUTE format('%s',f.fk); END LOOP; END; $$ diff --git a/sql/target_info.sql b/sql/target_info.sql index ddb0e6a..0c5486b 100644 --- a/sql/target_info.sql +++ b/sql/target_info.sql @@ -13,8 +13,8 @@ SELECT FROM information_schema.columns WHERE - table_name = 'osm_dev' - AND table_schema = 'rlarp' + table_name = 'live' + AND table_schema = 'fc' ON CONFLICT ON CONSTRAINT target_meta_pk DO UPDATE SET opos = EXCLUDED.opos ,dtype = EXCLUDED.dtype;