refine trigger

This commit is contained in:
Paul Trowbridge 2018-09-14 01:11:48 -04:00
parent 22ee06d6d9
commit d04617cf2b

View File

@ -1,52 +1,49 @@
CREATE FUNCTION log_insert() RETURNS trigger
WITH LANGUAGE plpgsql
NEW as ( AS
SELECT $${ $func$
"gl": { BEGIN
"lines": [ WITH
{ ------------------------------------full extraction-------------------------------------------
"amount": 2.19, full_ex AS (
"account": "h.food" SELECT
}, ins.id
{ ,a.i gl_line
"amount": -2.19, ,a.rn gl_row
"account": "h.dcard" ,NEW.bpr#>ARRAY['gl','jpath',(a.rn - 1)::text] gl_ref
} ,p.i ref_line
], ,p.rn ref_row
"jpath": [ ,NEW.bpr#>(p.i->>0)::text[] bpr_extract
[ FROM
"{item,0}", ins
"{header}" --gl array hold each gl line
], LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(NEW.bpr->'gl'->'lines') WITH ORDINALITY a(i, rn) ON TRUE
[ --for each
"{item,0}", LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(NEW.bpr#>ARRAY['gl','jpath',(a.rn - 1)::text]) WITH ORDINALITY p(i, rn) ON TRUE
"{header}"
]
]
},
"item": [
{
"item": "green olives",
"amount": 2.19,
"reason": "food",
"account": "h.food"
}
],
"header": {
"entity": "home",
"module": "MHI",
"offset": "h.dcard",
"transaction": "purchase"
}
}$$::jsonb bpr
) )
SELECT --------------------------------re-ggregate extraction to gl line level----------------------
* ,ex_gl_line
FROM SELECT
NEW id
--gl array hold each gl line ,gl_line->>'account' account
LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(NEW.bpr->'gl') WITH ORDINALITY gl(i, rn) ON TRUE ,(gl_line->>'amount')::numeric amount
--eaxpand the array of gl lines ,gl_row
LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(gl.i->'lines') WITH ORDINALITY a(i, rn) ON TRUE ,gl_ref
--for each ,public.jsonb_concat(bpr_extract) ref_extract
LEFT JOIN LATERAL JSONB_ARRAY_ELEMENTS(gl.i->'jpath') WITH ORDINALITY p(i, rn) ON TRUE FROM
full_ex
GROUP BY
id
,gl_line
,gl_row
,gl_ref;
RETURN NULL;
END;
$func$
CREATE TRIGGER log_insert
AFTER INSERT ON log
REFERENCING NEW TABLE AS ins
FOR EACH STATEMENT
EXECUTE PROCEDURE log_insert();