New: MCP server for AI assistants · Open source · MIT

What's your query health grade?

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.

View on GitHub

No account · No config · No database connection needed

27performance rules
7languages: JS, TS, Python, Go, Java, Ruby, PHP
<1sfor 2,200+ files
0lines of code uploaded

Understands the ORMs and drivers you already use

What it finds

The query patterns that quietly melt databases.

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.

critical

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.

for (const o of orders) { await User.findById(o.userId) }
high

Writes in loops

One updateOne, save() or INSERT per item means one round-trip and one index update per item. querydig points you to the bulk API.

for item in items: db.items.update_one(...)
high

Unbounded reads

find({}), findMany(), objects.all() or db.Find(&rows) with no filter and no limit read the whole table, and get slower every day.

const all = await prisma.user.findMany()
high

Index-hostile filters

Unanchored or case-insensitive $regex, LIKE '%term', LOWER(col) = ?, $where and ORDER BY RAND(). None of them can use an index.

{ name: { $regex: q, $options: 'i' } }
medium

Pipelines and pagination

$lookup before $match, sort() without limit(), deep skip() and OFFSET pages. Each one comes with a suggested index or keyset rewrite.

.find(q).skip(page * 50).limit(50)
low noise

Knows what's not a query

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.

ids.find((id) => id === x) // ok
Every finding comes with a fix

Not just what is slow. How to make it fast.

querydig explains the cost in plain words and shows the rewrite. Here's the most common one it finds: a query per row.

before1 + N queries · grows with data
// 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);
}
after2 queries · constant
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));
1,001queries for 1,000 orders, before
2queries for 1,000 orders, after
Sameresult, no schema change
Severity

Fix the right thing first.

Every finding gets a severity from what it costs at scale, not a style preference. Loop depth and data flow raise it automatically.

Criticalfix now

  • A query per row of another query's results
  • N+1 nested two or more loops deep

Highthis sprint

  • Queries and writes inside loops
  • Full collection or table reads
  • Unanchored regex, LIKE '%x'

Mediumplan it

  • skip() and OFFSET paging
  • Sort without limit
  • Late $match, non-sargable WHERE

Lowwhen touching it

  • Missing projection, SELECT *
  • Missing .lean()
  • count used as an exists check

One query-health grade per repo

A score from 0 to 100, adjusted for repo size, so you can track whether things are improving.

ABCDF
How it works

From source code to a fix list in four steps.

No agents, no proxies, no query logs. Just your repository.

01

Parse

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.

02

Recognise

Calls to Mongoose, Prisma, Django, GORM and a dozen other ORMs and drivers become query records, along with their filters, limits and chained calls.

03

Trace

Loop depth, iterating callbacks and variables that hold query results are tracked to tell a real N+1 from a batch job.

04

Report

Findings are ranked by severity, each with the code, why it's slow and how to fix it, in the format your team reads.

Reports

A report your team will actually open.

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.

  • Exact location: file, line and the code itself.
  • Why it's slow, in plain words, for reviewers who aren't DB experts.
  • A concrete fix, including suggested compound indexes in ESR order.
terminalhtmlsarifmarkdownjson
querydig-report.html
The querydig HTML report: health grade F, 6 critical, 16 high, 7 medium and 12 low findings, with filters and a list of nested-query findings The querydig HTML report in light mode
The actual report for the sample app in the repo.
CI / CD

Stop slow queries at the pull request.

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.
  • SARIF output shows findings inline in GitHub code scanning.
# .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
AI assistants · MCP New in 0.5

Your AI assistant finds slow queries, fixes them, and proves it.

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.

Claude CodeCodexCursorVS CodeWindsurfGemini CLIZed

1 · Pick your assistant

2 · Add querydig

Terminal
# 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.

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.

  1. 01

    Find

    Scans the repo and ranks every slow query by severity, then reads the code around each one.

    scan_queriesget_finding_context
  2. 02

    Check

    Tests a proposed rewrite in memory, before a single line is written to disk.

    analyze_snippet
  3. 03

    Fix

    Applies the safe, mechanical fixes. Dry run unless the assistant asks to write.

    apply_safe_fixes
  4. 04

    Verify

    Rescans the edited files and plans missing indexes from live query plans.

    scan_queriessuggest_indexes
One prompt

The whole loop, on autopilot.

The 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.

Local-first

Your code never leaves your machine.

querydig is a static analyser that runs locally. It makes no network calls of its own, and database access is strictly opt-in.

Nothing uploaded

No telemetry, no account, no API key. It works the same on a plane as in CI.

Database optional, read-only

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.

Fully open source

MIT licensed. Every rule is plain TypeScript you can read, change or switch off.

Rules

27 rules, each with a why and a fix.

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.

FAQ

Questions, answered.

Can't find what you need? Open an issue. Feature requests for new ORMs and languages are very welcome.

Does it need access to my database?

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.

Which languages and libraries are supported?

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.

How noisy is it on a real codebase?

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.

Can it fix issues automatically?

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.

Can my AI assistant use it?

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.

How do I add it to a project that already has hundreds of issues?

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.

What do I need installed?

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.

Is it free?

Yes. It's MIT licensed open source, and there's nothing paid. Issues and pull requests are welcome on GitHub.

Takes about thirty seconds

Run your first scan now.

Open a terminal in any repo. You get a ranked list of slow queries, and an HTML report you can share with the team.

View on npm

Node.js 22.12+ · macOS, Linux, Windows