PY-SQLA0002 · session_commit_inside_loop
Find SQLAlchemy session commits nested inside loops.
This is a deterministic rule for python. Read its implementation.
Definition
Section titled “Definition”Resolve SQLAlchemy and SQLModel Session or AsyncSession parameters, annotated variables,
direct constructors, and context managers created by known session factories. Report a
commit call on one of those sessions when it is lexically nested in for, async for, or
while. Committing each item adds transaction overhead and leaves partial durable progress
when a later item fails.
Evidence
Section titled “Evidence”Each finding points to the inner commit. The count is the number of commits with a resolved session owner. The value is the number of commits with a resolved session owner inside a loop.
Exceptions
Section titled “Exceptions”Some ingestion workflows intentionally checkpoint durable progress per batch. Configure that boundary as an explicit batch loop rather than one transaction per row. Dynamic dependency injection and custom session wrappers are not guessed.
Examples
Section titled “Examples”Bad
`for row in rows` followed by `session.add(row)` and `session.commit()` is reported.
GoodAdd all rows inside with session.begin() and let the context commit once. For bounded
checkpointing, commit once after each explicitly sized batch.
References
Section titled “References”- Cites “SQLAlchemy documentation”, session transaction. Open reference
- Cites “SQLAlchemy documentation”, session lifecycle guidance. Open reference