【问题标题】:SQLAlchemy how to add comments inside a big query?SQLAlchemy 如何在大查询中添加注释?
【发布时间】:2018-03-13 00:00:11
【问题描述】:

我正在使用SQLAlchemy 创建 SQL 语句,这些语句稍后会使用sqlparse 格式化。

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

选择富, -- 评论解释复杂的案例陈述 CASE WHEN .. END 为 complex_case 从栏 其中 1=1 -- 解释 EXISTS 子句用途的注释 并且存在(选择...)

【问题讨论】:

    标签: python sql python-2.7 sqlalchemy comments


    【解决方案1】:

    Mike Bayer 向 wiki 添加了一个 POC,该 POC 将 .comment() 方法添加到所有子句元素,以便可以将 SQL cmets 添加到单个元素。 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)
    
    """
    

    ```

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2019-07-07
    • 2023-02-02
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多