From 0e6e7e45f476a4eacbe1f4b44c149cf35c47e263 Mon Sep 17 00:00:00 2001 From: Paul Trowbridge Date: Tue, 26 May 2020 12:43:46 -0400 Subject: [PATCH] create aggregate function that unwraps 2 arrays and returns one with distinct values from both provided --- postgres/concat_distinct_array_values.sql | 27 +++++++++++++++++++++++ postgres/jsonb_arr_aggcd.sql | 27 +++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 postgres/concat_distinct_array_values.sql create mode 100644 postgres/jsonb_arr_aggcd.sql diff --git a/postgres/concat_distinct_array_values.sql b/postgres/concat_distinct_array_values.sql new file mode 100644 index 0000000..a4ca3b0 --- /dev/null +++ b/postgres/concat_distinct_array_values.sql @@ -0,0 +1,27 @@ +DO $$ +DECLARE + +_a1 jsonb; +_a2 jsonb; +_a3 jsonb; + +BEGIN + +_a1 := (select '["A","B","A"]'::jsonb); +_a2 := (select '["A","B","A"]'::jsonb); +SELECT + jsonb_agg(DISTINCT x.ae) +INTO + _a3 +FROM + ( + SELECT jsonb_array_elements(_a1) ae + UNION ALL + SELECT jsonb_array_elements(_a2) ae +) x; + +raise notice '%', _a3; + +END; +$$ +language plpgsql diff --git a/postgres/jsonb_arr_aggcd.sql b/postgres/jsonb_arr_aggcd.sql new file mode 100644 index 0000000..79bc18a --- /dev/null +++ b/postgres/jsonb_arr_aggcd.sql @@ -0,0 +1,27 @@ +CREATE OR REPLACE FUNCTION public.jsonb_concat_distinct_arr( + state jsonb, + concat jsonb) + RETURNS jsonb AS +$BODY$ +BEGIN + --RAISE notice 'state is %', state; + --RAISE notice 'concat is %', concat; + RETURN + jsonb_agg(DISTINCT ae) + FROM + ( + SELECT jsonb_array_elements(state) ae + UNION ALL + SELECT jsonb_array_elements(concat) ae + ) x; +END; +$BODY$ +LANGUAGE plpgsql; + +DROP AGGREGATE IF EXISTS public.jsonb_arr_aggcd(jsonb); +CREATE AGGREGATE public.jsonb_arr_aggcd(jsonb) ( + SFUNC=public.jsonb_concat_distinct_arr, + STYPE=jsonb, + INITCOND='[]' +); +