Created
March 24, 2020 09:21
-
-
Save ruanmartinelli/e2fc7d8b3fd51504d1cb2ac2c0fc3aed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create or replace function jsonb_merge_deep(jsonb,jsonb) | |
returns jsonb | |
language sql | |
immutable | |
as $func$ | |
select case jsonb_typeof($1) | |
when 'object' then case jsonb_typeof($2) | |
when 'object' then ( | |
select jsonb_object_agg(k, case | |
when e2.v is null then e1.v | |
when e1.v is null then e2.v | |
else jsonb_merge_deep(e1.v, e2.v) | |
end) | |
from jsonb_each($1) e1(k, v) | |
full join jsonb_each($2) e2(k, v) using (k) | |
) | |
else $2 | |
end | |
when 'array' then $1 || $2 | |
else $2 | |
end | |
$func$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment