Skip to content

Instantly share code, notes, and snippets.

@arbakker
Created April 1, 2022 23:08
Show Gist options
  • Save arbakker/4e821b3f54a595120283e213d43d6981 to your computer and use it in GitHub Desktop.
Save arbakker/4e821b3f54a595120283e213d43d6981 to your computer and use it in GitHub Desktop.
PostgreSQL trigger to add field to jsonb on insert #postgres #postgis #jsonb #json
drop function if exists add_puuid_fuuid_fields;
CREATE FUNCTION add_puuid_fuuid_fields()
RETURNS trigger AS $$
BEGIN
IF NEW.json -> 'properties' ->> 'puuid' IS NULL OR NEW.json -> 'properties' ->> 'puuid' = '' THEN
NEW.json = jsonb_insert(NEW.json, '{properties,puuid}', ('"'|| (md5(random()::text || clock_timestamp()::text)::uuid) || '"' :: text)::jsonb);
NEW.json = jsonb_insert(NEW.json, '{properties,fuuid}', ('"' || 'bgtterugmeldingen.' || (new.json -> 'properties' ->> 'puuid') || '"' :: text)::jsonb);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql
DROP trigger if exists add_puuid_fuuid_fields_trigger ON bgtterugmeldingen.bgtterugmeldingen_json;
CREATE TRIGGER add_puuid_fuuid_fields_trigger
BEFORE INSERT ON bgtterugmeldingen.bgtterugmeldingen_json
FOR EACH ROW
EXECUTE PROCEDURE add_puuid_fuuid_fields();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment