N+1 and nested queries
A query inside a loop, a .map() or a list comprehension. When the loop walks the results of another query, it's flagged as N² and critical.
One command grades your codebase from A to F and lists every N+1 query, write in a loop, unbounded read and index-hostile filter in your MongoDB and SQL code, ranked from critical to low, with the fix.
❯ npx querydig --uri $REPLICA_URI querydig v0.2.0 — slow-query scan of ~/api 412 files in 0.31s live: mongodb shop · 18 collections · 64 query plans · 3 slow queries CRITICAL QD001 Query inside a loop (N+1) [mongodb] src/orders/orders.service.ts:42:20 │ const items = await Order.find({ userId: u._id }); `Order.find()` is called inside a loop (line 41), one round-trip per user. live: Each iteration does a full scan of orders (4.2M docs). (high → critical) fix: One Order.find({ userId: { $in: ids } }); until then db.orders.createIndex({ userId: 1 }). MEDIUM MQ005 sort() without limit() [mongodb] src/search/search.ts:18:10 │ return Product.find({ status }).sort({ createdAt: -1 }).lean(); fix: Add .limit(n) and createIndex({ status: 1, createdAt: -1 }). Summary CRITICAL 2 HIGH 7 MEDIUM 5 LOW 9 Query health: C (71/100) ❯
Understands the ORMs and drivers you already use
They pass code review, work fine on a laptop with 50 rows, and fall over at 5 million. querydig catches them from the source code, before they ship.
A query inside a loop, a .map() or a list comprehension. When the loop walks the results of another query, it's flagged as N² and critical.
One updateOne, save() or INSERT per item means one round-trip and one index update per item. querydig points you to the bulk API.
find({}), findMany(), objects.all() or db.Find(&rows) with no filter and no limit read the whole table, and get slower every day.
Unanchored or case-insensitive $regex, LIKE '%term', LOWER(col) = ?, $where and ORDER BY RAND(). None of them can use an index.
$lookup before $match, sort() without limit(), deep skip() and OFFSET pages. Each one comes with a suggested index or keyset rewrite.
arr.find(x => …), Python str.find(), polling while loops, batch jobs and loops over collections are left alone. Tests and migrations are skipped by default.
querydig explains the cost in plain words and shows the rewrite. Here's the most common one it finds: a query per row.
// 1 query for orders, then 1 per order const orders = await Order.find({ status: 'open' }); for (const o of orders) { o.user = await User.findById(o.userId); }
const orders = await Order.find({ status: 'open' }).lean(); const ids = orders.map((o) => o.userId); const users = await User.find({ _id: { $in: ids } }).lean(); const byId = new Map(users.map((u) => [String(u._id), u])); for (const o of orders) o.user = byId.get(String(o.userId));
Every finding gets a severity from what it costs at scale, not a style preference. Loop depth and data flow raise it automatically.
LIKE '%x'skip() and OFFSET paging$match, non-sargable WHERESELECT *.lean()count used as an exists checkA score from 0 to 100, adjusted for repo size, so you can track whether things are improving.
No agents, no proxies, no query logs. Just your repository.
Every JS, TS, Python, Go, Java, Ruby and PHP file is parsed with tree-sitter in a pool of worker threads. Your .gitignore is respected.
Calls to Mongoose, Prisma, Django, GORM and a dozen other ORMs and drivers become query records, along with their filters, limits and chained calls.
Loop depth, iterating callbacks and variables that hold query results are tracked to tell a real N+1 from a batch job.
Findings are ranked by severity, each with the code, why it's slow and how to fix it, in the format your team reads.
Add --format html and you get one self-contained file to share or attach to a ticket. It has filters by severity, rule, database and file, and a before/after example on every finding.
Add one step to any pipeline. Existing issues go into a baseline, so only new ones fail the build and the team can fix the backlog at its own pace.
--fail-on high exits with code 1 on high or critical findings.--baseline lets known issues through, so you only gate on new ones.--diff origin/main scans only the files a PR changed.# .github/workflows/querydig.yml name: querydig on: [pull_request] jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: { fetch-depth: 0 } - uses: actions/setup-node@v7 with: { node-version: 22 } - run: npx -y querydig --diff origin/${{ github.base_ref }} --fail-on high
# .gitlab-ci.yml querydig: image: node:22 script: - npx -y querydig --format md > querydig.md || true - npx -y querydig --fail-on high artifacts: when: always paths: [querydig.md]
# record today's issues once npx querydig --update-baseline # then, in any pipeline or pre-push hook npx -y querydig --baseline .querydig-baseline.json --fail-on high # shareable report as a build artifact npx -y querydig --format html -o querydig-report.html
querydig mcp is a Model Context Protocol server. querydig does the detection and verification; your assistant does the rewrite. No API key, and your code never leaves your machine.
1 · Pick your assistant
2 · Add querydig
# add querydig to Claude Code claude mcp add querydig -- npx -y querydig mcp # optional: live evidence from a read-only replica claude mcp add querydig \ -e QUERYDIG_DB_URI=postgres://reader:***@replica/shop \ -- npx -y querydig mcp
Then type /mcp__querydig__optimize_queries to run the full loop.
# one command codex mcp add querydig -- npx -y querydig mcp # or in ~/.codex/config.toml [mcp_servers.querydig] command = "npx" args = ["-y", "querydig", "mcp"]
Works in the Codex CLI and the Codex IDE extension, which share the same config.
{
"mcpServers": {
"querydig": {
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Use ~/.cursor/mcp.json to enable it in every project.
{
"servers": {
"querydig": {
"type": "stdio",
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Open Copilot Chat in Agent mode and the querydig tools are ready to use.
Install in VS Code{
"mcpServers": {
"querydig": {
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Save, then press refresh in the Cascade MCP panel.
{
"mcpServers": {
"querydig": {
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Settings → Developer → Edit Config. Restart Claude Desktop after saving.
{
"mcpServers": {
"querydig": {
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Run /mcp inside Gemini CLI to confirm querydig is connected.
{
"context_servers": {
"querydig": {
"source": "custom",
"command": "npx",
"args": ["-y", "querydig", "mcp"]
}
}
}
Open the Agent Panel; querydig shows up under context servers.
Optional: set QUERYDIG_DB_URI to a read-only replica in the server's env. The assistant then gets row counts, query plans and missing indexes, and the password never enters the chat.
Scans the repo and ranks every slow query by severity, then reads the code around each one.
scan_queriesget_finding_contextTests a proposed rewrite in memory, before a single line is written to disk.
analyze_snippetApplies the safe, mechanical fixes. Dry run unless the assistant asks to write.
apply_safe_fixesRescans the edited files and plans missing indexes from live query plans.
scan_queriessuggest_indexesThe built-in optimize_queries prompt scans, applies safe fixes, rewrites the worst findings one at a time, verifies each with querydig, and ends with a before/after table. Every claim is checked by the analyser, not taken on the model's word.
Order.find() runs once per user, an N+1. I'll batch it into a single $in query.querydig is a static analyser that runs locally. It makes no network calls of its own, and database access is strictly opt-in.
No telemetry, no account, no API key. It works the same on a plane as in CI.
Findings come from your source code. Point --uri at a replica for live evidence: plans and stats only, in read-only sessions, with passwords redacted.
MIT licensed. Every rule is plain TypeScript you can read, change or switch off.
Live rules (LV) need --uri. Run npx querydig explain <RULE> for a before/after example. Change a rule's severity or switch it off in querydig.config.json.
Can't find what you need? Open an issue. Feature requests for new ORMs and languages are very welcome.
No. By default querydig reads source code only. If you want proof, add --uri with a read-only MongoDB or Postgres connection. It then reads collection sizes, indexes, query plans and slow-query stats to confirm full scans and missing indexes. Queries are planned, never executed, unless you pass --explain-execute.
JavaScript and TypeScript (Mongoose, the MongoDB driver, Prisma, TypeORM, Sequelize, pg, mysql2, knex raw), Python (PyMongo, Motor, Django ORM, SQLAlchemy, DB-API cursors) Go (mongo-go-driver, GORM, xorm, database/sql), Java (Spring Data JPA/MongoDB, Hibernate, JDBC, jOOQ), Ruby (ActiveRecord, Mongoid, Sequel) and PHP (Laravel Eloquent, Doctrine, PDO, mysqli). Raw SQL strings are checked in every language.
Tests, specs, fixtures, migrations, seeds and benchmarks are skipped by default. Polling and batching loops, loops over collections, and array or string helpers aren't treated as queries. On Gitea (about 2,200 Go files) it reports 16 findings in under a second. To silence one, add // querydig-ignore QD001.
Partly, and only where it's safe. npx querydig --fix adds .lean() to read-only Mongoose queries, turns count() > 0 existence checks into exists() (Django, Rails, Laravel, Spring Data) or a limited count (MongoDB), and switches whole-table loops to find_each / lazy() in Rails and Laravel (preview with --dry-run). With --uri, --emit-indexes writes every missing index to one script for you to review and run. N+1 rewrites and limits change behaviour, so those stay as suggested fixes.
Yes. querydig mcp starts an MCP server for Claude Code, Codex, Cursor, VS Code (Copilot), Windsurf, Claude Desktop, Gemini CLI, Zed and any other MCP client. In Claude Code it is one command: claude mcp add querydig -- npx -y querydig mcp. The assistant can scan, read the code around a finding, check a rewrite before writing it, apply safe fixes and rescan to verify. It runs locally and needs no API key. See AI assistants.
Run npx querydig --update-baseline once and commit .querydig-baseline.json. Then run --baseline .querydig-baseline.json --fail-on high in CI, so only newly introduced issues fail the build.
Node.js 22.12 or newer. Run it with npx querydig, or add it as a dev dependency with npm i -D querydig and an npm script.
Yes. It's MIT licensed open source, and there's nothing paid. Issues and pull requests are welcome on GitHub.
Open a terminal in any repo. You get a ranked list of slow queries, and an HTML report you can share with the team.