Skip to content

Bug: SQLAlchemy's StatementError (or OperationalError) is incorrectly wrapped as IntegrityError #606

@linozen

Description

@linozen

Description

Running wrap_sqlalchemy_exception on a connection that triggers sqlalchemy.exc.StatementError (e.g., because the DB closed an idle session) or other errors which definitely aren't IntegrityErrros produces Advanced Alchemy’s IntegrityError, so transient connection failures are misreported as data-integrity faults.

This just sent us an debugging journey looking for invalid unique constraints and the like when the actual issue was that the DB closed idle sessions too aggressively.

URL to code causing the issue

No response

MCVE

from sqlalchemy import create_engine, text
from advanced_alchemy.exceptions import wrap_sqlalchemy_exception

engine = create_engine("sqlite:///:memory:")

with engine.connect() as connection:
    try:
        with wrap_sqlalchemy_exception(dialect_name=connection.dialect.name):
            # Raises StatementError -> OperationalError because table is missing
            connection.execute(text("SELECT * FROM missing_table"))
    except Exception as exc:  # noqa: BLE001
        print(
            f"raised: {type(exc).__name__}; "
            f"original: {type(exc.__context__).__name__}; "
            f"message: {exc}"
        )

Steps to reproduce

- Create an empty directory and inside it run `python3 -m venv .venv`.
- Activate the venv (`source .venv/bin/activate`) and install the affected versions: `pip install advanced-alchemy==1.4.5 sqlalchemy==2.0.41`.
- Save the script above as `reproduce_statement_misclassification.py`.
- Execute `python reproduce_statement_misclassification.py`.
- Observe the output: `raised: IntegrityError; original: OperationalError; message: There was an issue processing the statement.` This shows `StatementError` is being surfaced as `IntegrityError`.

Screenshots

No response

Logs

Package Version

1.4.5

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions