Skip to content

PY-SQLA0002 · session_commit_inside_loop

Find SQLAlchemy session commits nested inside loops.

This is a deterministic rule for python. Read its implementation.

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.

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.

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.

Bad

`for row in rows` followed by `session.add(row)` and `session.commit()` is reported.
Good

Add all rows inside with session.begin() and let the context commit once. For bounded checkpointing, commit once after each explicitly sized batch.

  • Cites “SQLAlchemy documentation”, session transaction. Open reference
  • Cites “SQLAlchemy documentation”, session lifecycle guidance. Open reference