Skip to main content

pytest-queryguard

CI PyPI Python License Docs

A pytest plugin that fails a test when the SQLAlchemy 2 code it runs sends one query per row (N+1), and enforces query budgets. Sync, async and FastAPI code; nothing to import or configure. A test database holds a handful of rows, so such code passes its tests and sends hundreds of queries in production. This test passes without the plugin:

def test_list_orders(session):
    assert len(list_orders(session)) == 50

With the plugin installed it fails, and points to the line to fix:

queryguard: N+1 detected

  Order.customer was lazy-loaded 50 times
  first at app/orders.py:10 in list_orders
    called from tests/test_orders.py:7 in test_list_orders
  parents loaded at app/orders.py:9 in list_orders
  kind: relationship-load  label: Order.customer
  docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#relationship-load
  sql: SELECT customer.id, customer.name FROM customer WHERE customer.id = ?
  fix: load it with the parent query, e.g.
       select(Order).options(joinedload(Order.customer))

Python 3.10+, pytest 8+, SQLAlchemy 2.0.13+; tested on SQLite, PostgreSQL 14 to 18, MySQL 8.4 and MariaDB 11.8. Django ORM support is experimental: Django.

What it catches

Check Default Fails a test when
N+1 on a relationship on one relationship is lazy-loaded for 2 or more parent objects
Repeated statement on one SELECT runs 5 or more times: ORM, Core or text()
Column reloads on 5 or more objects reload a deferred or expired column one by one
Cartesian joins on, warns one query joinedloads two collections side by side, so its rows grow as their product (fail makes it fail)
Query and time budgets per test @pytest.mark.max_queries(n) or max_db_time(seconds) is exceeded
Row-by-row writes opt-in one INSERT, UPDATE or DELETE runs once per row from one line
Missing index, with the CREATE INDEX opt-in no index can serve a filter (PostgreSQL 16+, SQLite, MySQL, MariaDB)
Unused eager loads experimental, off a relationship is eager-loaded and never read
Unused columns experimental, off a query loads a wide row and the test reads few of its columns

Every test body is checked. The checks look at the application's statements: an N+1 in the test's own code (the test function, conftest.py, factories, helpers under tests/) never runs in production, so it is counted at the end of the run instead of failing the test (see Test code). How detection works explains each rule and its threshold.

How it compares

The comparison page has a dated feature matrix and the method; the numbers below are from it. On 2026-11-07 a head-to-head run in GitHub Actions ran 252 scenarios of the accuracy corpus (123 with an N+1 or a similar problem, 129 without) under each pytest tool that supports SQLAlchemy 2, each set up the way its own documentation says to fail a test:

Tool Scenarios with a problem flagged Scenarios without one flagged 300-test suite, added time (median)
pytest-queryguard 0.8.0, defaults 106 of 123 2 of 129 +1.7%
queryspy 0.6.0, --queryspy-strict 98 of 123 27 of 129 +28.8%
pytest-querycount 0.4.0, a marker on every test 103 of 123 27 of 129 +18.5%
n-plus-one-sniffer d4790f8, a marker on every test 103 of 123 25 of 129 +29.0%
nplusone 1.0.0 does not import on SQLAlchemy 2.1; 1 of 123 on 2.0

The corpus was written by the author of pytest-queryguard, and its scenarios without a problem include the shapes this plugin was taught to leave alone, so read the table with that bias. What it does show: pytest-queryguard fails tests with no marker, option or fixture; it reports loops of Core select() and text() statements as well as lazy loads; and it rarely flags fixed code. The accuracy page has the corpus measured again with the current code and its defaults: 117 of the 121 scenarios with a problem the default rules can report are flagged, and 2 of the 157 without one. Where the others are ahead (Django support, runs of 2 to 4 identical statements by default, exact SQL snapshots) is on the same page.

Quick start

In a project that has pytest tests for its SQLAlchemy code:

pip install pytest-queryguard
pytest

There is nothing else to set up. To see a failure first, run the example project, which has an N+1, a session.get() loop and a budget:

git clone --depth 1 https://github.com/MaciejZiel/pytest-queryguard
cd pytest-queryguard/examples/sync-n-plus-one
python -m venv .venv && . .venv/bin/activate
pip install pytest-queryguard
pytest tests/test_orders.py

Three tests fail; tests/test_orders_fixed.py has the same tests against the fixed code and passes. The code behind the failure above is app/orders.py:

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models import Order


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

With joinedload(Order.customer) in the query the same test passes. When you try it on code of your own, put the loop in a module of the application and call it from the test: a loop written in the test function is test code, and the run then ends with a queryguard: test code section that counts it and says how to see it (pytest -o queryguard_test_code=warn). For async code on SQLAlchemy 2.1 and newer, also install sqlalchemy[asyncio]. Getting started walks through the example, async code and FastAPI.

Coming from nplusone?

nplusone has had no release since 1.0.0 (2018-05-21). It patches Query.__iter__, so on SQLAlchemy 2.0 it misses the parents loaded by a select()-style query (session.scalars(select(Order))), and on SQLAlchemy 2.1 import nplusone.ext.sqlalchemy fails. The migration guide has a find-and-replace table: delete the profiler fixture and the imports, NPLUSONE_WHITELIST becomes queryguard_ignore, NPLUSONE_RAISE = False becomes queryguard_mode = "warn", signals.ignore() becomes pytest_queryguard.ignore(), and a before and after of one project.

Coming from queryspy?

queryspy reports N+1s but fails a test only with --queryspy-strict or queryspy_fail_on; pytest-queryguard fails by default, so start with queryguard_mode = "warn" if you ran queryspy without them. Its markers and helpers have equivalents (@pytest.mark.queryspy(max_queries=3) is @pytest.mark.max_queries(3), assert_max_queries() is max_queries(), no_n_plus_one() is record_queries() with assert_no_nplusone()), and two defaults differ: repeats and column reloads need 5 runs here, not 2, and loops in test code are counted, not reported. The migration guide has the full find-and-replace table.

Missing indexes

A test database holds a few rows, so a query that reads the whole table is as fast in CI as one that uses an index. pytest --queryguard-index-check plans every SELECT of a test again with sequential scans switched off (PostgreSQL 16 and newer), or reads EXPLAIN QUERY PLAN (SQLite) or EXPLAIN (MySQL and MariaDB). If the plan still reads a whole table to apply a filter, no index can serve it:

queryguard: missing index

  orders is read in full: Seq Scan with filter (orders.customer_id = $1)
  first at app/orders.py:11 in orders_of
  kind: missing-index  label: orders
  docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#missing-index
  sql: SELECT orders.id, orders.customer_id FROM orders WHERE orders.customer_id = %s::INTEGER
  fix: CREATE INDEX ON orders (customer_id)
  alembic: op.create_index("ix_orders_customer_id", "orders", ["customer_id"])

  a sequential scan is fine on a small lookup table:
  list it in queryguard_index_ignore_tables

The check is off by default. See PostgreSQL, SQLite, MySQL and MariaDB and the index advisor, which can verify a suggested index with hypopg.

Adopting it on an existing project

  • Record today's findings once, and only new ones fail: pytest --queryguard-baseline=queryguard-baseline.json --queryguard-update-baseline. See Baseline.
  • pytest --queryguard-sarif=queryguard.sarif writes the findings as SARIF for GitHub code scanning, and the GitHub Action runs pytest and uploads it. See CI and GitHub Action.
  • Leave out single findings with @pytest.mark.queryguard_ignore("Order.customer") or the queryguard_ignore option; make kinds warn with queryguard_fail_on or queryguard_mode = warn. See Ignoring findings.
  • Read the statements of a block in a test with record_queries(). See Reading the queries.
  • The same rules run per request in a FastAPI, Starlette or Flask app during development: in-application mode.
[tool.pytest.ini_options]
queryguard_mode = "warn"                  # fail (default), warn or off
queryguard_repeat_threshold = 10
# the file must exist: create it first with --queryguard-update-baseline
queryguard_baseline = "queryguard-baseline.json"
queryguard_index_check = true
queryguard_index_ignore_tables = ["countries", "lookup_*"]

Every option, flag and marker is in the configuration reference.

Overhead

On the 300-test suite of the comparison, pytest-queryguard 0.8.0 added 0.8 to 1.7 % to the run time. Per statement, on in-memory SQLite, the current code adds about 16 us to a Core statement and 34 to 36 us to an ORM one, which is a large share of a statement that costs almost nothing; against a database on disk or over the network the share is smaller. Method and numbers: Performance and the FAQ.

Limitations

  • SQLAlchemy, and Django experimentally; raw DB-API connections (sqlite3 and the like) and other ORMs (Peewee) are not seen, and nothing says so.
  • Only the test function body is measured, not fixtures. One measurement is active per process; under pytest-xdist each worker measures its own tests.
  • Test code is told from the application by file: application code kept in a test module or under tests/ is taken for test code.
  • The PostgreSQL index check needs PostgreSQL 16 or newer and a sync engine or asyncpg; the SQLite, MySQL and MariaDB checks judge less precisely. It says that no index can serve a filter, not that an existing index is a good one.
  • A finding says that a pattern happened, not that production is slow.

The full list is on the Limitations page.

Documentation

https://maciejziel.github.io/pytest-queryguard/, starting with Getting started and A test failed: now what.

Page What is in it
How detection works The rules, the thresholds and why
Configuration reference Ini options, flags, markers
Budgets and timing max_queries, max_db_time, a budget file
Baseline, CI and Action, SARIF Adoption and code scanning
Recipes FastAPI, Flask-SQLAlchemy, SQLModel, Litestar, pytest-asyncio, Factory Boy, query counts that must not grow, Sentry N+1 issues, legacy projects, CI
In-application mode The same rules per request in a running app; a development panel
FAQ, Limitations raiseload, false positives, xdist, drivers
Comparison, accuracy Other tools, precision and recall
Stability and versioning What is public API, deprecations
Changelog, examples

Development

The project uses uv.

uv sync
uv run coverage run -m pytest
uv run coverage report
uv run ruff check .
uv run ruff format --check .
uv run mypy src
uv run --group docs python scripts/build_docs.py --strict   # the docs site, into site/

The PostgreSQL tests run when QUERYGUARD_PG_URL points to a server, and are skipped otherwise:

docker run -d --rm --name qg-postgres -p 55432:5432 -e POSTGRES_PASSWORD=pg postgres:17
QUERYGUARD_PG_URL=postgresql+pg8000://postgres:pg@localhost:55432/postgres uv run pytest
docker stop qg-postgres

Coverage is measured with coverage run rather than pytest --cov, because --cov starts after pytest has imported the plugin and misses its import-time lines. Third-party licenses are listed in 3rdparty_licenses.md.

License

MIT, see the LICENSE file.

Metadata

Release files for pytest-queryguard 0.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-queryguard 0.10.0
File Size Uploaded Provenance Actions
pytest_queryguard-0.10.0.tar.gz 1.3 MB With provenance Details for pytest_queryguard-0.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-queryguard 0.10.0
File Interpreter ABI Platform Actions
pytest_queryguard-0.10.0-py3-none-any.whl Python 3 none any Details for pytest_queryguard-0.10.0-py3-none-any.whl

Total release size: 1.6 MB

Release files / pytest_queryguard-0.10.0.tar.gz

Download URL pytest_queryguard-0.10.0.tar.gz
Size 1.3 MB
Tags Source
SHA-256 checksum
How to use checksums
b6366c3d09ca8f476325d68c16e1e133ccb5d47db9b30f0cf5d1786bf5c9c139
BLAKE2b-256 checksum
How to use checksums
e07036ae783f25bf91049b4f7f023066bb1a6b0fa8c09d6c70651651d4b80f92
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Release files / pytest_queryguard-0.10.0-py3-none-any.whl

Download URL pytest_queryguard-0.10.0-py3-none-any.whl
Size 305.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1e5fabcece89a1fcc762833431457da8e6c8ddeab47205542ac5419ca4a70ea9
BLAKE2b-256 checksum
How to use checksums
6b27586dadda9024b0db0f5d4d83ec555e0ce0bb0b117baf17304297e94e24b4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Security for pytest-queryguard 0.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_queryguard-0.10.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page