简体   繁体   中英

SQLAlchemy CTE query raises InternalError, why?

This is a query I am trying to get to run as part of an application that uses 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;

(I need the unused fields in the CTE for filtering later.)

This query runs fine when executed directly on my PostgreSQL database.

I modeled this as follows using SQLAlchemy constructs:

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)

Now when I perform:

tasks_query.all()

I get an error message ending in:

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' {}

The query looks the same to me. What is going on here? How can I find out what I am doing wrong?

The error is (probably) unrelated to your query. It looks like you were experimenting in the shell before this and made a failed query. Now you need to do session.rollback() before you can do more queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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