我有一个系统,用户可以将查询和CTE作为文本配置提供。一种可能的配置类似于以下内容:
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)')])
实际上,此查询在呈现时不会包含CTE前导码:
>>> print q
SELECT * from (select * from foo_cte)
但是,如果我将所有可能的CTE添加到选择列表中:
q = q.select_from(cte)
...然后他们在渲染时有SQLAlchemy添加的额外且超常的FROM子句,使语法无效:
>>> print q
WITH foo_cte AS
(SELECT * from foo)
SELECT * from (select * from foo_cte)
FROM foo_cte
是否可以同时使用它 - 打印CTE前导码而不将其添加到生成的FROM子句中?
答案 0 :(得分:4)
如果您将q
定义为
q = sa.select(['*']).select_from(cte)
然后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