Static check (experimental)#

Since 0.8.0.

The pytest plugin finds an N+1 query when a test runs it. The static check reads your source code instead, without a database and without running your tests, and reports the most common shape of an N+1: a loop over the objects of an ORM query that reads a lazy relationship of each one.

def list_orders(session: Session) -> list[dict[str, object]]:
    rows = []
    for order in session.scalars(select(Order)).all():
        rows.append({"id": order.id, "customer": order.customer.name})
    return rows
$ python -m pytest_queryguard.lint --models app.models app/
app/orders.py:10:56: Order.customer is lazy-loaded once per row (N+1)
  in the loop at line 9 over the query at line 9 in list_orders
  rule: queryguard/static-relationship-load  label: Order.customer
  fix: load it with the parent query, e.g.
       select(Order).options(joinedload(Order.customer))

queryguard lint (experimental): 1 finding in 6 files

It is experimental (see Stability): the command, its options and its output may change in a minor release. It is deliberately conservative: it reports only what it can follow from start to end inside one function, so it misses many N+1 queries that the pytest plugin finds. Use it as an early warning, in an editor, a pre-commit hook or pull-request annotations, next to the plugin, not instead of it.

Running it#

python -m pytest_queryguard.lint --models MODULE [--models MODULE ...]
    [--format text|json|sarif|github] [--output FILE] PATHS...

The exit status is 1 when anything is reported, 0 when nothing is, and 2 when a model module cannot be imported, the mappers cannot be configured, a path does not exist, the --output file cannot be written or an argument is wrong.

What it reports#

A finding needs all of these:

  1. A for loop, an async for loop or a comprehension over the objects of one query of one mapped class: - session.scalars(select(C)...), session.execute(select(C)...).scalars(), await session.scalars(...), await session.stream_scalars(...), with or without .all(), .unique() or .fetchall(), or inside list(), tuple() or sorted(); - session.query(C)... and Flask-SQLAlchemy's C.query...; - SQLModel's session.exec(select(C)...), in a file that imports SQLModel; - select(C) followed by where, order_by, join, options, limit and the other methods that keep it a select of C. select has to be SQLAlchemy's (or SQLModel's) by the file's imports: from sqlalchemy import select, sa.select after import sqlalchemy as sa, or db.select where the module has db = SQLAlchemy(...) from Flask-SQLAlchemy.

The statement, the result or the list of rows may be assigned to a variable first, in the same function, as long as that variable is assigned exactly once there. A statement may also be built in steps, stmt = select(C) and then only stmt = stmt.where(...), stmt = stmt.options(...) and the like, all above the loop: an option added in any of the steps, also in an if, counts. C may be an aliased(C) or with_polymorphic(C, ...) of the class, written in the select() or assigned once in the same function (then only the relationships of C itself are checked). 2. In the loop body, obj.rel where rel is a relationship of C with the default lazy="select" (or lazy=True), or with lazy="immediate", which runs the same query per object when the objects load. Relationships with joined, selectin, subquery, raise, raise_on_sql, noload, write_only or dynamic are not reported. Reading an association_proxy reads the relationship it goes through. 3. The query has no loader option for that relationship: joinedload, selectinload, subqueryload, immediateload, raiseload, noload or contains_eager, on that path or with "*". lazyload() and defaultload() keep it lazy, so they do not count, and lazyload() of the relationship wins over a "*" option. The options are functions imported from SQLAlchemy (selectinload(...), orm.selectinload(...)) and the methods chained on them.

It follows chains: in order.customer.address, both Order.customer and Customer.address are checked, and in a nested loop for item in order.items: item.product, both Order.items and Item.product. obj.awaitable_attrs.rel counts as reading rel. The fix line is the same as the plugin's: joinedload for a many-to-one or one-to-one step, selectinload for a collection, chained along the path.

Each relationship is reported once per loop, at its first read.

What it does not report#

These are left out on purpose, to keep false positives rare:

It cannot know how many rows a query returns, whether the objects were already in the Session, or whether a branch runs: a finding means "likely N+1", not a measured one. The pytest plugin measures.

Accuracy#

Measured on the accuracy corpus, the same scenarios that measure the plugin, without running them: each scenario module is linted with its own models (the domain modules it imports and the module itself, as --models). A relationship-load BUG scenario is a positive; every other scenario, CLEAN or a BUG of another kind, is a negative; a scenario counts as reported when the check has any finding in it. Findings in a scenario's setup (its seeding code, which the corpus does not measure) are left out. uv run python scripts/lint_accuracy_report.py prints the numbers and every disagreement, and tests/corpus/test_lint_accuracy.py fails when they change.

On 2026-11-07, 266 scenarios (SQLModel not installed), 51 of them positives:

TP FP FN precision recall
before 30 5 21 86% 59%
after 35 0 16 100% 69%

"Before" is the check before these changes, on the same 266 scenarios. The 14 scenarios added for it are shapes reported to other static checks (a nested loop covered by the outer query's option chain, orm-lens #146; loops over mapped classes and over objects read only through columns and properties, orm-lens

72 and #85) and common ones: a repository with a service, a FastAPI#

endpoint that builds its list, Pydantic model_validate of a dict per row, an HTML fragment built like a template loop, a statement built over several lines, an aliased() entity, a search loop with an early return, an if guard.

The five false positives were a read inside ignore(), a relationship refreshed or set per object before the loop (two), the same rows loaded with the option by an earlier query, and a loop in a scenario's setup (now left out of the count; the check is right that it is an N+1 there). The five misses that were fixed: aliased(), with_polymorphic(), a statement built over several lines, lazy="immediate" and an association_proxy. Of the 16 misses left, 14 cross a function (a serializer, Pydantic or FastAPI reading the objects, a property, __str__, __repr__, a hybrid, a recursive walk, a query in a repository or a fixture), one is a Jinja template and one a session.delete() whose cascade loads the children. The labels of the 35 true positives are the plugin's but one: for a concrete inheritance hierarchy the check names the base class (Payment.store), the plugin the subclass (CardPayment.store).

As for the plugin, the corpus is small and written by one person, and these shapes were written with the check in mind: read the numbers as a regression baseline, not as what the check finds in your code.

Release thresholds#

The release gate (scripts/release_gate.py lint-accuracy, see Releasing) lints the corpus and fails when the precision or the recall of the check is below the minimum recorded in scripts/lint_accuracy_thresholds.json, when fewer than 270 scenarios were linted, or when a disagreement with a verdict is not documented. The minimum precision is 100%: a check people run in CI must not report clean code. The minimum recall is the value measured on 2026-11-08 (278 scenarios, SQLModel not installed), rounded down to two decimals:

rule minimum precision minimum recall measured
relationship-load 100% 69% 36 TP, 0 FP, 16 FN (100% and 69.2%)

The one positive added since the table above, bug_135_app_loop_called_from_a_test_helper, is found, and none of the negatives added with it is reported.

Ignoring a finding#

Put # queryguard: ignore on the line of the read or on the for line (for a comprehension, its first line). On the for line it ignores every relationship of that loop.

for order in session.scalars(select(Order)):  # queryguard: ignore
    print(order.customer.name)

JSON output#

--format json prints one object. The keys are stable for format 1:

Key Value
format 1
tool {"name": "pytest-queryguard", "version": ...}
files number of files read
errors files that were skipped, as "path: reason"
findings list of findings, sorted by file, line and column

Each finding:

Key Value
rule "queryguard/static-relationship-load"
file path relative to the working directory, with . and .. taken out (../shared/q.py for a file above it)
line, column the read of the relationship (1-based)
loop_line the loop that reads it
query_line the call that runs the query
function the qualified name of the function (Repo.list_orders), or <module>
relationship the label, as in the plugin: "Order.customer"
path the relationships from the query's class to this one, ["Order.customer", "Customer.address"]
query_class the class the query loads
fix the suggested query, "select(Order).options(joinedload(Order.customer))"

pre-commit#

Since 0.10.0 the repository has a pre-commit hook, queryguard-lint, that runs the check on the Python files of a commit:

repos:
  - repo: https://github.com/MaciejZiel/pytest-queryguard
    rev: v1.0.0   # a release tag, 0.10.0 or newer
    hooks:
      - id: queryguard-lint
        args: [--models, app.models]
        additional_dependencies: []   # what app.models imports, see below

--models is required, in args: the hook stops with a usage error without it. pre-commit runs hooks from the root of the repository and adds the file names after args, so the command is python -m pytest_queryguard.lint --models app.models FILES.... The files of the commit are only parsed; the module of --models is imported, so it must be importable in the hook's environment:

yaml repos: - repo: local hooks: - id: queryguard-lint name: queryguard lint entry: python -m pytest_queryguard.lint --models app.models language: system types: [python] require_serial: true

language: system runs the python on PATH: activate the virtual environment before git commit (or write entry: uv run python -m pytest_queryguard.lint ..., entry: .venv/bin/python -m ...).

The hook is require_serial, so one process imports the models once and checks every file. It fails the commit when it reports anything (exit status 1) and when it cannot run (2); # queryguard: ignore leaves out a finding (see Ignoring a finding). The hook's id and what it runs are experimental, like the check.

GitHub annotations#

--format github (since 0.10.0) prints one GitHub Actions workflow command per finding, which a workflow step turns into a warning annotation on that line of the pull request:

$ python -m pytest_queryguard.lint --models app.models --format github app
::warning file=app/orders.py,line=10,col=56,title=N+1%3A Order.customer (queryguard)::Order.customer is lazy-loaded once per row (N+1) in the loop at line 9 over the query at line 9 in list_orders.%0AFix: load it with the parent query, e.g. select(Order).options(joinedload(Order.customer))%0ARule: queryguard/static-relationship-load
queryguard lint (experimental): 1 finding in 6 files

The paths are relative to the repository root: in GitHub Actions each file is made relative to GITHUB_WORKSPACE, also from a working directory below it or a path such as ../shared; a file outside it keeps its absolute path, and GitHub shows its annotation in the run's summary only. A file that is skipped (it does not parse) is a ::notice::. The messages are escaped as workflow commands need (%0A for a line break). The GitHub Action runs it with its lint input, also only on the files a pull request changed.

SARIF output#

--format sarif writes SARIF 2.1.0 with one rule, queryguard/static-relationship-load, at level warning, so it can be uploaded to GitHub code scanning like the plugin's file (see SARIF output). In GitHub Actions the paths are made relative to the repository root with GITHUB_WORKSPACE, as in the plugin; a file outside the repository (or, outside GitHub Actions, above the working directory) gets an absolute file:// URI. Its findings are separate from the plugin's relationship-load results: the rule id is different, and a baseline does not apply to it. A result's fingerprint is made of the file, the function and the relationship path (and its position, when one function has the same path in two loops), not the line, so it survives edits elsewhere in the file. The file is the file of the JSON output, so app, ./app and the absolute path of app give the same fingerprints.

      - run: python -m pytest_queryguard.lint --models app.models --format sarif --output lint.sarif app
        continue-on-error: true
      - uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: lint.sarif
          category: pytest-queryguard-static

Edit this page on GitHub