Skip to content

Instantly share code, notes, and snippets.

@nurettin
Created April 4, 2020 11:15
Show Gist options
  • Save nurettin/cf5176957cbf08796316c73c3d593ce4 to your computer and use it in GitHub Desktop.
Save nurettin/cf5176957cbf08796316c73c3d593ce4 to your computer and use it in GitHub Desktop.
declarative json postgresql
select row_to_json(q) from (
select
row_to_json(a) account
, json_agg(t) trades
from pm_account a
left join lateral (
select
row_to_json(t) trade
, json_agg(d) dailies
, json_agg(sf) smartorders
from pm_trade t
left join pm_tradedaily d
on d.trade_id = t.id
left join lateral (
select
row_to_json(pts) smartorder
, json_agg(ptf) fills
from pm_tradesmartorder pts
left join pm_tradefill ptf
on ptf.trade_smartorder_id = pts.id
where pts.trade_id = t.id
group by pts.*
) sf on 1 = 1
where t.account_id = a.id
group by t.*
) t on 1 = 1
group by a.*
) q
@nurettin
Copy link
Author

nurettin commented Apr 4, 2020

one can convert the following schema into the above sql (tree leaves are left join, tree branches are left join lateral)

pm_account
        |__ pm_trade (account_id)
                     |__ pm_tradedaily (trade_id)
                     |__ pm_tradesmartorder (trade_id)
                                    |__ pm_tradefill (trade_smartorder_id)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment