[英]SQLAlchemy: Using a CTE from a (sub)query w/ FROM clause specified as literal text
I have a system where queries and CTEs can be provided by the user as textual configuration. 我有一个系统,用户可以将查询和CTE作为文本配置提供。 One possible configuration is akin to the following:
一种可能的配置类似于以下内容:
import sqlalchemy as sa
cte = sa.select([sa.sql.text('* from foo')]).cte('foo_cte')
q = sa.select([sa.sql.text('* from (select * from foo_cte)')])
As it is, this query will not include the CTE preamble when rendered: 实际上,此查询在呈现时不包括CTE前导码:
>>> print q
SELECT * from (select * from foo_cte)
If, however, I add all possible CTEs to the select list: 但是,如果我将所有可能的CTE添加到选择列表中:
q = q.select_from(cte)
...then they have additional and extranous FROM clauses added by SQLAlchemy on render, making the syntax invalid: ...然后,他们在渲染时有SQLAlchemy添加的额外且超常的FROM子句,使语法无效:
>>> print q
WITH foo_cte AS
(SELECT * from foo)
SELECT * from (select * from foo_cte)
FROM foo_cte
Is it possible to have it both ways -- printing the CTE preamble without also adding it to the generated FROM clause? 是否有可能同时使用它 - 打印CTE前导码而不将其添加到生成的FROM子句中?
If you defined q
as 如果你将
q
定义为
q = sa.select(['*']).select_from(cte)
Then sqlalchemy is able to figure out the proper sql to emit: 然后sqlalchemy能够找出要发出的正确sql:
import sqlalchemy as sa
cte = sa.select([sa.text('* from foo')]).cte('foo_cte')
q = sa.select(['*']).select_from(cte)
print(q)
WITH foo_cte AS
(SELECT * FROM foo)
SELECT *
FROM foo_cte
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.