SQLAlchemy如何在大查询中添加注释?

时间:2017-10-01 20:31:17

标签: python sql python-2.7 sqlalchemy comments

我使用SQLAlchemy创建SQL语句,后来使用sqlparse格式化。

某些查询具有复杂性,可以从评论中受益。有没有办法让SQLAlchemy输出如下所示的查询:

SELECT foo,
 -- comment explaining the convoluted case statement
 CASE WHEN .. END as complicated_case
FROM bar
WHERE 1=1
   -- comment explaining the purpose of the EXISTS clause
   AND EXISTS (SELECT ...)

1 个答案:

答案 0 :(得分:0)

Mike Bayer在wiki中添加了一个POC,它为所有子句元素添加了一个.comment()方法,以便可以将SQL注释添加到单个元素中。 https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/CompiledComments

```

from sqlalchemy import Table, Column, MetaData, Integer
from sqlalchemy import select, case, func, exists

m = MetaData()

foo = Table(
    'foo', m,
    Column('a', Integer),
    Column('b', Integer)
)

bar = Table(
    'bar', m,
    Column('x', Integer),
    Column('y', Integer),
    Column('z', Integer)
)

subq = select([foo.c.a]).where(foo.c.b > 10).alias()
stmt = select([
    bar.c.x,
    case([
        (bar.c.y == 5, "A"),
        (bar.c.y == 10, "B")
    ], else_="C").label("complicated_case").
    comment("comment explaining the convoluted case statement"),
    func.row_number().over(order_by=bar.c.z).label("complicated_row_num").
    comment("comment exaplaining the convoluted window function")
]).select_from(
    bar.join(
        subq.comment("Comment explaining subquery and join"),
        bar.c.x == subq.c.a
    )
).where(
    exists([foo.c.b]).where(foo.c.a == bar.c.y).
    comment("comment explaining the purpose of the EXISTS clause")
)

print stmt

"""

output:

SELECT bar.x,
-- comment explaining the convoluted case statement
CASE WHEN (bar.y = :y_1) THEN :param_1 WHEN (bar.y = :y_2) THEN :param_2 ELSE :param_3 END AS complicated_case,
-- comment exaplaining the convoluted window function
row_number() OVER (ORDER BY bar.z) AS complicated_row_num
FROM bar JOIN
-- Comment explaining subquery and join
(SELECT foo.a AS a
FROM foo
WHERE foo.b > :b_1) AS anon_1 ON bar.x = anon_1.a
WHERE
-- comment explaining the purpose of the EXISTS clause
EXISTS (SELECT foo.b
FROM foo
WHERE foo.a = bar.y)

"""

```