python runtime_error ai_generated true

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

ID: python/sqlalchemy-missing-session-rollback-after-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.4.x active
2.0.x active

Root Cause

After a failed commit, the session enters a 'prepared' state (two-phase commit) and requires rollback before further operations.

generic

中文

提交失败后,会话进入 'prepared' 状态(两阶段提交),需要回滚后才能进行后续操作。

Workarounds

  1. 95% success
    Call session.rollback() after catching any commit exception: try: session.commit() except: session.rollback() raise
  2. 90% success
    Use session.begin() context manager which auto-rolls-back on exception.

Dead Ends

Common approaches that don't work:

  1. 100% fail

    The session is stuck; a rollback is required first.

  2. 70% fail

    May leave database locks or transactions hanging.