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

时间:2014-05-27 23:59:35

标签: python sql postgresql sqlalchemy

这是我试图在使用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' {}

查询看起来和我一样。这里发生了什么?我怎样才能知道我做错了什么?

1 个答案:

答案 0 :(得分:1)

错误(可能)与您的查询无关。看起来你在此之前在shell中进行了实验并且查询失败了。现在,您需要先执行session.rollback()才能进行更多查询。