在 Pony ORM 中使用 Common Table 表达式

Use Common Table Expression with Pony ORM

我有以下查询,其中包含一个常见的 table 表达式:

WITH example AS (
    SELECT unnest(ARRAY['foo', 'bar', 'baz']) as col
)
SELECT *
FROM example

尝试在 database.select(query) 中使用它会抛出 pony.orm.dbapiprovider.ProgrammingError: syntax error at or near "WITH",而 database.select(raw_sql(query)) 会抛出 TypeError: expected string or bytes-like object

如何使用带 ponyorm 的 CTE select 数据?

要使用包含 CTE 的查询,请在数据库上调用 execute 函数并使用返回的游标获取行:

cursor = database.execute("""
    WITH example AS (
        SELECT unnest(ARRAY['foo', 'bar', 'baz']) as col
    )
    SELECT *
    FROM example
""")
rows = cursor.fetchall()

注意:游标是来自 psycopg2 的 class,因此虽然此解决方案确实使用了 pony 库,但解决方案可能因所使用的数据库而异。