From 809ff8c96f548e98233af98fda8a4827be6a13ac Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Wed, 4 Sep 2024 19:16:43 +0545 Subject: [PATCH] feat: sync identities with people table --- views/011_users.sql | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/views/011_users.sql b/views/011_users.sql index 33538d2e..905132ba 100644 --- a/views/011_users.sql +++ b/views/011_users.sql @@ -1,23 +1,29 @@ -- Insert identities in people table -CREATE -OR REPLACE FUNCTION insert_identity_to_people () RETURNS TRIGGER AS $$ +CREATE OR REPLACE FUNCTION sync_identity_to_people () +RETURNS TRIGGER AS $$ BEGIN + IF TG_OP = 'INSERT' THEN INSERT INTO people (id, name, email) VALUES (NEW.id, concat(NEW.traits::json->'name'->>'first', ' ', NEW.traits::json->'name'->>'last'), NEW.traits::json->>'email'); + ELSIF TG_OP = 'UPDATE' THEN + UPDATE people SET + name = concat(NEW.traits::json->'name'->>'first', ' ', NEW.traits::json->'name'->>'last'), + email = NEW.traits::json->>'email' + WHERE id = NEW.id; + END IF; - RETURN NEW; + RETURN NEW; END $$ LANGUAGE plpgsql; DO $$ BEGIN - IF EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'identities') THEN - CREATE OR REPLACE TRIGGER identity_to_people - AFTER INSERT - ON identities - FOR EACH ROW - EXECUTE PROCEDURE insert_identity_to_people(); - END IF; + IF EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'identities') THEN + CREATE OR REPLACE TRIGGER identity_to_people + AFTER INSERT OR UPDATE ON identities + FOR EACH ROW + EXECUTE PROCEDURE sync_identity_to_people(); + END IF; END $$; CREATE OR REPLACE VIEW