繁体   English   中英

SQLAlchemy CTE查询引发InternalError,为什么?

[英]SQLAlchemy CTE query raises InternalError, why?

这是我试图作为使用SQLAlchemy的应用程序的一部分运行的查询:

WITH latest AS (
SELECT DISTINCT ON (actions.task_id) 
    actions.id AS id, 
    actions.timestamp AS timestamp, 
    actions.user_id AS user_id, 
    actions.status AS status, 
    tasks.challenge_slug AS challenge_slug, 
    actions.task_id AS task_id
FROM actions
JOIN tasks ON tasks.id = actions.task_id
ORDER BY actions.task_id DESC)
SELECT count(latest.id), latest.status
FROM latest 
GROUP BY status;

(我需要CTE中未使用的字段,以便以后进行过滤。)

直接在我的PostgreSQL数据库上执行时,此查询运行良好。

我使用SQLAlchemy构造对此建模如下:

latest_cte = db.session.query(
    Action.id,
    Action.task_id,
    Action.timestamp,
    Action.user_id,
    Action.status,
    Task.challenge_slug).join(
    Task).distinct(
    Action.task_id).order_by(
    Action.task_id.desc()).cte(name='latest')
tasks_query = db.session.query(
    func.count(latest_cte.c.id),
    latest_cte.c.status)

现在,当我执行:

tasks_query.all()

我收到以下错误消息:

sqlalchemy.exc.InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block
'WITH latest AS \n(SELECT DISTINCT ON (actions.task_id) actions.id AS id, actions.task_id AS task_id, actions.timestamp AS timestamp, actions.user_id AS user_id, actions.status AS status, tasks.challenge_slug AS challenge_slug \nFROM actions JOIN tasks ON tasks.id = actions.task_id ORDER BY actions.task_id DESC)\n SELECT count(latest.id) AS count_1, latest.status AS latest_status \nFROM latest GROUP BY latest.status' {}

该查询对我来说看起来相同。 这里发生了什么? 如何找出我做错了什么?

该错误(可能)与您的查询无关。 看来您在此之前已经在Shell中进行了尝试,并且查询失败。 现在,您需要执行session.rollback()才能进行更多查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM