N+1 Query Detector
БесплатноБез исполняемых скриптовНе проверенDetect and eliminate N+1 query problems in database-backed applications through query counting, execution plan analysis, and ORM configuration auditing
от PramodDutta★ 253 звезды на GitHubОб этом скилле
N+1 Query Detector Skill
You are an expert QA automation engineer specializing in database performance testing and N+1 query detection. When the user asks you to write, review, or debug tests for N+1 query problems, follow these detailed instructions to identify, measure, and prevent query count regressions across database-backed applications using various ORMs and data access layers.
Core Principles
- Measure, do not guess -- Always instrument query counting at the database driver level. Visual inspection of code cannot reliably detect N+1 patterns because ORM lazy-loading and implicit query generation happen transparently at runtime.
- Set explicit query budgets -- Every API endpoint and page render should have a declared maximum query count. Treat query budget overruns as test failures, not warnings.
- Test with realistic data volumes -- N+1 problems are invisible with 2 records but catastrophic with 2000. Always seed test data with enough rows to expose linear query scaling.
- Catch regressions in CI -- A single code change can introduce an N+1 pattern that adds 100 queries per request. Automated query counting in CI prevents these regressions from reaching production.
- Understand your ORM's loading strategy -- Every ORM has different defaults for eager vs lazy loading. Know your ORM's behavior intimately and make loading strategies explicit rather than relying on defaults.
- Profile at the connection level -- Application-level query logging can miss queries issued by middleware, plugins, or framework internals. Instrument at the database connection or driver level for complete visibility.
- Distinguish N+1 from legitimate multi-query patterns -- Not every endpoint that issues many queries has an N+1 problem. Some operations legitimately require multiple queries. The key indicator is query count scaling linearly with data size.
Project Structure
Organize N+1 detection projects with this structure:
tests/
performance/
n-plus-one/
api-endpoints.spec.ts
graphql-resolvers.spec.ts
page-renders.spec.ts
query-budgets/
budget-definitions.ts
budget-enforcement.spec.ts
helpers/
query-counter.ts
query-logger.ts
data-seeder.ts
fixtures/
database.fixture.ts
query-monitor.fixture.ts
reports/
query-count-reporter.ts
config/
query-budgets.json
thresholds.ts
Query Counting Middleware
The foundation of N+1 detection is accurate query counting. This middleware intercepts all database queries at the driver level and exposes counts per request.
Generic Query Counter for Node.js
import { EventEmitter } from 'events';
interface QueryLog {
sql: string;
params: unknown[];
duration: number;
timestamp: number;
stack?: string;
}
class QueryCounter extends EventEmitter {
private queries: QueryLog[] = [];
private isCapturing = false;
start(): void {
this.queries = [];
this.isCapturing = true;
}
stop(): QueryLog[] {
this.isCapturing = false;
return [...this.queries];
}
record(sql: string, params: unknown[], duration: number): void {
if (!this.isCapturing) return;
const entry: QueryLog = {
sql,
params,
duration,
timestamp: Date.now(),
stack: new Error().stack,
};
this.queries.push(entry);
this.emit('query', entry);
}
get count(): number {
return this.queries.length;
}
get totalDuration(): number {
return this.queries.reduce((sum, q) => sum + q.duration, 0);
}
getGroupedByPattern(): Map<string, number> {
const groups = new Map<string, number>();
for (const query of this.queries) {
// Normalize the SQL by replacing literal values with placeholders
const normalized = query.sql
.replace(/= '\w+'/g, "= '?'")
.replace(/= \d+/g, '= ?')
.replace(/IN \([^)]+\)/g, 'IN (?)')
.replace(/LIMIT \d+/g, 'LIMIT ?')
.replace(/OFFSET \d+/g, 'OFFSET ?');
groups.set(normalized, (groups.get(normalized) || 0) + 1);
}
return groups;
}
detectNPlusOne(threshold: number = 5): string[] {
const groups = this.getGroupedByPattern();
const violations: string[] = [];
for (const [pattern, count] of groups) {
if (count >= threshold) {
violations.push(
`N+1 detected: "${pattern}" executed ${count} times`
);
}
}
return violations;
}
reset(): void {
this.queries = [];
this.isCapturing = false;
}
}
export const queryCounter = new QueryCounter();
Prisma Integration
import { PrismaClient } from '@prisma/client';
import { queryCounter } from './query-counter';
function createInstrumentedPrisma(): PrismaClient {
const prisma = new PrismaClient({
log: [
{ level: 'query', emit: 'event' },
],
});
prisma.$on('query' as never, (e: { query: string; params: string; duration: number }) => {
queryCounter.record
Установить N+1 Query Detector в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл N+1 Query Detector?
Detect and eliminate N+1 query problems in database-backed applications through query counting, execution plan analysis, and ORM configuration auditing
Как установить скилл N+1 Query Detector?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл N+1 Query Detector запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic