python runtime_error ai_generated true

sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.

ID: python/sqlalchemy-invalid-request-state

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Attempting to execute SQL queries after committing the session, which closes the transaction.

generic

中文

在提交会话后尝试执行 SQL 查询,事务已关闭。

Workarounds

  1. 100% success Create a new session for subsequent operations
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind=engine)
    new_session = Session()
    new_session.query(User).all()
  2. 95% success Use session.begin_nested() for savepoints
    with session.begin_nested():
        session.add(new_user)
    session.commit()

Dead Ends

Common approaches that don't work:

  1. Calling session.rollback() after commit 90% fail

    Rollback is not allowed after commit; the transaction is already finalized.

  2. Using session.begin() again without a new session 85% fail

    The session is in a committed state; you need to create a new session or use begin_nested.