Python SQLAlchemy CTE查询引发内部错误,为什么?

Python SQLAlchemy CTE查询引发内部错误,为什么?,python,sql,postgresql,sqlalchemy,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 challeng

这是我试图作为使用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()
,然后才能执行更多查询