Skip to content

loop-db-query (EFF103)

Family: Execution Effects (EFF) · Exact · Enabled by default · Severity warning (slower code) · No automatic fix

A loop over data whose every iteration sends a database statement; its heuristic reports, a loop that can run a database query on every iteration.

What it does

Checks loops that run a database query on every iteration: cursor.execute(...), session.execute(...) (awaited ones on async sessions and connections too), the SQLAlchemy Query methods that run the query (all, first, one, count, ...) and iterating a Query (for row in session.query(User): in an outer loop, a comprehension, list(query)), the Django QuerySet methods that run the query (get, first, count, ... and their a* variants), pymongo, redis, and DynamoDB commands, pandas.read_sql, and project functions that reach them, also when an offloading API runs them on a worker thread per item (await asyncio.to_thread(load, i), a function decorated with @sync_to_async), including the getter of a property read in the loop and a generator iterated in the loop (its body runs where it is iterated, as for EFF101). A function a builtin calls once per item runs in a loop as long as the items (sorted(users, key=lambda u: score(conn, u)), list(map(load, ids)); see EFF102 for the builtins and the items whose number the code fixes).

It does not report reading the rows of a statement already executed (cursor.fetchone()), calls that only build a query (session.query(User).filter(...), QuerySet.filter(...), Redis.pipeline()), the bulk APIs, which send many rows in one statement and are called per batch by design (QuerySet.bulk_create, in_bulk, pymongo's insert_many, bulk_write), DDL statements (SQL starting with CREATE, ALTER, DROP, or PRAGMA run by a DB-API execute / executemany / executescript or SQLAlchemy's exec_driver_sql, also inside a helper the loop calls: a literal, an f-string, %, or .format() whose literal start is one, SQLAlchemy's text() of one, and the statements of a module's string constants: the items of a tuple, the pieces .split(";") / .splitlines() cut a schema into), migration code (upgrade / downgrade functions, files under migrations/ or alembic/), the ORM packages' own implementation, or loops whose size the code fixes when no data-sized loop is around them (for ident in enumerate((1, 2), 1), zip(order, ["m1", "m2"]), a name bound to a small display; see EFF102).

As for EFF102, a query that only runs while an attribute is unset, which the code then sets (if self._columns is None: self._columns = cursor.execute(...)), runs once per object and is not reported when the loop does not construct the object; so does one in a functools.cached_property getter, and one behind a module global runs once per process. A query that only runs while a local variable the loop carries is unset or a first-iteration flag holds (if first: cursor.execute(...); first = False), or that every way on from leaves the loop (cursor.execute(...) followed by return, break, or raise), runs once per run of the loop. A call whose arguments switch off the branch with the query (a constant, a literal default, a test the caller has made) is not followed into it.

A report is exact when the loop sends a database statement on every iteration that completes, over items whose number the data decides: a parameter (or an attribute or element of one), the rows of a query, the lines of a file, or the entries of a directory. The statement is sent by the call in the loop itself, or at the end of a chain of functions each of which makes the next call on every path on which it returns.

Each step is established, not assumed:

  • the loop steps through items of such an origin, through wrappers that keep them (sorted, list, filter, slices, dict views, the components of enumerate and zip); through map or a comprehension's element only their number carries. The items a project function returns are those every return of it gives, read from its module's own code: the rows of a query it runs (also on a parameter annotated with the connection's class) or of another function of the module it returns, whether the loop calls it directly, awaits it, calls it through a functools.partial object, or awaits an API that hands back what it returns (await asyncio.to_thread(load_rows, conn)). A loop whose number of iterations the code fixes gives no exact report, whatever the number: a constant range, a display, or rows whose number the query fixes (a LIMIT with a literal count at the end of its text, fetchmany of a constant, a SELECT of aggregates only without GROUP BY), in the loop or in the function returning them;
  • the call runs on every iteration that completes, exception edges included: an except handler that continues before it is an iteration without it;
  • every implementation each call on the chain can run is followed and makes the next call on every path on which it returns, as for EFF101;
  • the last call sends a statement on every call, as the ecosystem catalog describes it: not a Session.get the identity map may answer, a flush() / commit() that sends only pending changes, or a Django query set's count() that may read its cache; DDL, bulk APIs, and calls that only build a query are left out.

Every other report the rule finds is heuristic: items whose origin heki does not establish, a path heki cannot decide, a call it cannot resolve to every implementation, a database call that sends a statement only in some state.

What a report states

A report states that every iteration of the loop that completes sends a database statement: the one named, or, when the implementations a call can run reach different ones, each with its implementation. A heuristic report states that every iteration of the loop can run a database query (or a command of a database client) through the call shown: some premise below may be open.

Its premises:

  • Origin: the loop steps through items of a parameter, the rows of a query, the lines of a file, or the entries of a directory, also as a project function returns them, and the code does not fix their number. Open in a heuristic report: a loop whose size the code does not fix at 16 or fewer counts, and a size heki cannot bound counts as data-sized. Not followed, so open: the rows a module global holds (ROWS = conn.execute(...).fetchall()), the rows a function returns of a value another module gives it or of a parameter without an annotation, a function calling itself, and a chain of more than eight functions each returning what the next returns.
  • Every iteration: the call runs on every iteration that completes, exception edges into handlers included. Open in a heuristic report: the call counts as running on every iteration unless heki shows that it runs once per object, per process, or per run of the loop (the cases above).
  • Every return: each function on the chain has made the next call on every path on which it returns normally. Open in a heuristic report: one path that reaches the next call is enough, and a branch heki cannot decide counts as taken; only the branches the caller's arguments switch off, and the cases listed above, are left out.
  • Every implementation: each call on the chain has as its targets every implementation it can run (assumptions R1, R2, and R5), each with the fact. Open in a heuristic report: through a method call, one candidate implementation that leads on is enough.
  • Sends: the last call sends a statement on every call, as the ecosystem catalog describes it (R3). Open in a heuristic report: a call that sends one only in some state of its session (emits in the catalog: Session.get answered by the identity map, Session.flush without pending changes).

Not part of the claim: how many items the loop has, how slow the statement is, and whether the statements could be batched.

Why is this bad?

One round trip per item makes the run time grow with the number of rows and with the network latency to the database. A single batched query is usually orders of magnitude faster.

Example

import sqlite3


def names(cursor: sqlite3.Cursor, ids: list[int]) -> list[str]:
    out = []
    for i in ids:
        cursor.execute("SELECT name FROM users WHERE id = ?", (i,))  # EFF103
        out.append(cursor.fetchone()[0])
    return out

The same query under if i > 0: is a heuristic report: it runs on some iterations only.

Use instead:

import sqlite3


def names(cursor: sqlite3.Cursor, ids: list[int]) -> list[str]:
    if not ids:
        return []
    marks = ",".join("?" * len(ids))
    cursor.execute(f"SELECT id, name FROM users WHERE id IN ({marks})", ids)
    name_of = dict(cursor.fetchall())
    return [name_of[i] for i in ids]  # `KeyError` for an unknown ID (the loop: `TypeError`)

The query returns each matching row once and in no particular order, so the result is rebuilt from the IDs: in their order, with repeated IDs repeated. A database caps the number of parameters in one statement; split a long list of IDs into chunks.

Known limitations

A call through a name the project binds to another object in a way EFF101 lists among its known limitations (mock.patch outside tests, sys.modules) still counts as running its definition here too.

Fix safety

No automatic fix.