简体   繁体   中英

SQLAlchemy Nested CTE Query

The sqlalchemy core query builder appears to unnest and relocate CTE queries to the "top" of the compiled sql.

I'm converting an existing Postgres query that selects deeply joined data as a single JSON object. The syntax is pretty contrived but it significantly reduces network overhead for large queries. The goal is to build the query dynamically using the sqlalchemy core query builder.

Here's a minimal working example of a nested CTE

with res_cte as (
    select
        account_0.name acct_name,
        (
            with offer_cte as (
                select
                    offer_0.id
                from
                    offer offer_0
                where
                    offer_0.account_id = account_0.id
            )
            select
                array_agg(offer_cte.id)
            from
                offer_cte
        ) as offer_arr
    from
        account account_0
)
select 
    acct_name::text, offer_arr::text
from res_cte

Result

acct_name,  offer_arr
---------------------
oliver,     null
rachel,     {3}
buddy,      {4,5}

(my incorrect use of) the core query builder attempts to unnest offer_cte and results in every offer.id being associated with every account_name in the result.

There's no need to re-implement this exact query in an answer, any example that results in a similarly nested CTE would be perfect.

Received confirmation from the sqla team that it is not currently possible or on any roadmap https://github.com/sqlalchemy/sqlalchemy/issues/5335#issuecomment-630838687

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM