QueryTrace
Catch N+1 query loops (even when they hide behind helper functions), write loops, unbounded queries, and SQL injection risks in your ORM code while you type, before they reach production.
QueryTrace checks JavaScript, TypeScript, Python, and Ruby files for query patterns that work fine in development and break at scale. Examples: a loop of findUnique calls that turns into 10,001 round trips; a findMany with no take that returns the whole table; a raw SQL string built from user input.
Highlights
- Fewer false alarms. Queries inside comments, strings, and regex literals are ignored. Some calls look like queries but don't touch the database:
array.find(x => …), Map.get, stripe.customers.create, Playwright page.locator, and lazy ActiveRecord where chains. QueryTrace skips those too.
- Hidden N+1 detection.
for (const id of ids) await loadUser(id) is flagged when loadUser (or something it calls, up to three levels deep) queries the database. The hover shows the full call chain, for example loadUser → fetchProfile → prisma.profile.findFirst (users/repo.ts:12).
- One-click batch rewrite. A
findUnique / findById inside a for…of loop can be rewritten into one findMany / find before the loop, plus a Map lookup inside it.
- Branch review mode. Scan only the files your branch changed compared with
main / master / trunk. Then export a Markdown report to paste into a pull request.
- Covers more frameworks. Prisma, TypeORM, Sequelize, Mongoose, Knex, Drizzle, SQLAlchemy (1.x and 2.0), Django ORM, Flask-SQLAlchemy, and ActiveRecord.
How it works
- Files are scanned when you open them and again as you type (with a short delay). Findings appear as squiggles in the editor and in the Problems panel (source
QueryTrace, code = rule id).
- Hover a finding to see why it's slow or unsafe and a suggested rewrite. For N+1 loops the rewrite is generated from your actual code.
- The lightbulb offers quick fixes when a safe edit exists. It can also ignore the rule on that line or in that file, or disable the rule.
- The Query Issues view in the Explorer lists findings grouped by rule, then file, then finding. The most severe rules appear first. Toolbar buttons: Scan Changed Files, Scan Workspace, Export Report, Clear.
- The status bar shows the issue count for the active file. Click it to open the Query Issues view.
Rules
| Rule id |
Language |
Default |
Catches |
n1-query-in-loop |
JS/TS |
Error |
A read query (findUnique, findOne, findById, findByPk, …) awaited inside for / for…of / while / do / reduce |
write-in-loop |
JS/TS |
Warning |
create / update / delete / save / upsert awaited once per iteration; suggests createMany, updateMany, bulkWrite, or one transaction |
parallel-query-fanout |
JS/TS |
Warning |
One query per element through map / forEach / flatMap or promises.push(...), including Promise.all(ids.map(id => prisma.user.findUnique(...))) and Mongoose .then chains inside forEach |
aggregate-in-loop |
JS/TS |
Error |
count / aggregate / groupBy inside a loop |
n1-indirect-call |
All |
Warning |
A loop calls a helper function that queries the database, in the same file or another workspace file |
unbounded-query |
JS/TS |
Warning |
findMany / findAll / TypeORM find / Mongoose Model.find / Drizzle db.select().from() without take/limit, in API routes, controllers, routers, resolvers, tRPC, and server actions |
raw-sql-injection |
JS/TS |
Error |
$queryRawUnsafe, $executeRawUnsafe, .raw(), whereRaw and friends, sequelize.query, literal(), pool.query / connection.execute / sql.unsafe built from ${…} or + with non-constant values |
floating-query-promise |
JS/TS |
Warning |
A query statement that is never awaited, returned, or handled with .then / .catch |
py-query-in-loop |
Python |
Error |
session.query/get/execute/scalars, .objects.filter/all/…, Model.query… inside for/while loops and comprehensions |
py-objects-get-in-loop |
Python |
Error |
Model.objects.get, get_object_or_404, Model.query.get inside a loop or comprehension |
py-write-in-loop |
Python |
Warning |
.objects.create, get_or_create, .save(), .delete(), session.commit() inside a loop |
py-missing-eager-load |
Python |
Info |
Accessing a relationship while iterating a queryset, including querysets stored in a variable first, without select_related / prefetch_related / joinedload |
py-raw-sql-injection |
Python |
Error |
cursor.execute, session.execute(text(...)), Model.objects.raw built with f-strings, %, .format(), or + |
rb-query-in-block |
Ruby |
Error |
Model.find / find_by / exists? / where(...).first inside each / map / times / while blocks |
rb-association-in-loop |
Ruby |
Warning |
Association traversal on the block variable, e.g. post.comments.count. Skipped when the collection already uses .includes / .preload / .eager_load |
rb-write-in-block |
Ruby |
Warning |
Model.create! or record.save! / update! / update_column / destroy inside a block; suggests insert_all / update_all |
rb-raw-sql-injection |
Ruby |
Error |
#{…} or + inside where, order, having, joins, find_by_sql, execute, exec_query, … |
Paginated batch loops aren't flagged. That covers cursor / skip / offset reads, while loops that read with take/limit, and Django slices like [:500]. Writes wrapped in prisma.$transaction(items.map(...)) aren't flagged either.
Example
for (const order of orders) {
const user = await prisma.user.findUnique({ where: { id: order.userId }, include: { profile: true } });
console.log(user?.name);
}
The quick fix Batch into one findMany before the loop + Map lookup rewrites it to:
const userList = await prisma.user.findMany({ where: { id: { in: orders.map((order) => order.userId) } }, include: { profile: true } });
const userById = new Map(userList.map((row) => [row.id, row]));
for (const order of orders) {
const user = userById.get(order.userId) ?? null;
console.log(user?.name);
}
Mongoose works the same way: await User.findById(id).lean() inside a loop becomes one User.find({ _id: { $in: ids } }).lean() before the loop, keyed by String(row._id).
Hidden N+1 through a helper:
async function loadUser(id: string) {
return prisma.user.findUnique({ where: { id } });
}
for (const id of ids) {
await loadUser(id);
}
QueryTrace reports this with the chain loadUser → prisma.user.findUnique.
Quick fixes
- Batch rewrite for
findUnique / findFirst (Prisma) and findById / findOne (Mongoose) inside for…of loops when the lookup key comes from the loop variable
- Add
take: 100 / limit: 100, or append .limit(100) (before .exec(), at the end of Drizzle and Mongoose chains), to unbounded queries
- Add a missing
await to a floating query
- Convert
$queryRawUnsafe → $queryRaw (and $executeRawUnsafe → $executeRaw) tagged template
- Ignore the rule on this line: adds
// querytrace-ignore <rule-id>
- Ignore the rule in this file: adds
// querytrace-ignore-file <rule-id> at the top, after any shebang or encoding comment
- Disable the rule everywhere via
queryTrace.disabledRules
Suppressing findings
querytrace-ignore in a comment on the flagged line, or on the line above it, silences every rule there.
querytrace-ignore n1-query-in-loop, write-in-loop silences only the listed rules.
querytrace-ignore-file anywhere in a file silences the whole file. querytrace-ignore-file <rule-id> silences only those rules in that file.
Commands
All commands are in the Command Palette under the QueryTrace category.
- QueryTrace: Scan Workspace
- QueryTrace: Scan Changed Files (vs. main branch)
- QueryTrace: Scan Current File
- QueryTrace: Export Findings Report
- QueryTrace: Clear Findings
- QueryTrace: Show Query Issues View
- QueryTrace: Enable or Disable Scanning
- QueryTrace: Disable a Rule
- QueryTrace: Rate QueryTrace
- QueryTrace: Open Getting Started Walkthrough
Scan Changed Files compares your branch with where it split off the remote default branch. It tries origin/HEAD first, then main, master, trunk, or develop. Untracked files are included. Export Findings Report opens a Markdown summary: a count per rule plus a table of every finding with file and line, ready to paste into a pull request or ticket.
Settings
{
"queryTrace.enabled": true,
"queryTrace.disabledRules": ["py-missing-eager-load"],
"queryTrace.severityOverrides": {
"unbounded-query": "error",
"rb-association-in-loop": "information"
},
"queryTrace.crossFileAnalysis": true,
"queryTrace.skipTestAndSeedFiles": true,
"queryTrace.exclude": ["**/generated/**"]
}
queryTrace.enabled: turns all diagnostics on or off.
queryTrace.disabledRules: rule ids to skip.
queryTrace.severityOverrides: maps a rule id to error, warning, information, or hint.
queryTrace.crossFileAnalysis: follows helper functions into other workspace files to find hidden N+1 queries. Helpers in the same file are always followed. Across files, a helper only counts when it's imported, or when the receiver name matches the file (e.g. usersService.loadProfile → users.service.ts). Short or generic names like get and find are never matched across files.
queryTrace.skipTestAndSeedFiles: skips loop rules in tests, seed scripts, fixtures, factories, and migrations, where per-row queries are expected. Raw SQL and floating-promise checks still run there.
queryTrace.exclude: extra globs to skip during workspace scans and helper indexing. node_modules, dist, build, out, vendor, and virtualenvs are always skipped.
Enjoying QueryTrace?
If QueryTrace caught a slow or risky query for you, a quick rating helps other developers find it. After you've used it for a while, it shows a small prompt with Rate QueryTrace, Remind me later, and No thanks. Your choice is remembered. You can also run QueryTrace: Rate QueryTrace at any time.
Getting started
To open the "Get Started with QueryTrace" walkthrough, go to Help → Get Started, or run QueryTrace: Open Getting Started Walkthrough.
Requirements
- VS Code 1.85.0 or higher
- Git on your PATH (only for Scan Changed Files)
Author
Kanaihya Kumar - kanaihyakmr@gmail.com
License
MIT
| |