/** * Statement shapes, for spotting repeats. * * Two statements have the same shape when they differ only in their values: * `where id = 1` and `where id = 2`. The same shape many times in one request * is the signature of an N+1, a relation loaded once per row instead of once. */ import type { QueriesSection, QueryEntry } from './types' export function normalizeSql(sql: string): string { return sql .replace(/'(?:[^']|'')*'/g, '?') .replace(/\$\d+/g, '?') .replace(/\b\d+(?:\.\d+)?\b/g, '?') .replace(/\bIN\s*\([^)]*\)/gi, 'IN (?)') .replace(/\s+/g, ' ') .trim() .toLowerCase() } function isRead(shape: string): boolean { return shape.startsWith('select') || shape.startsWith('with') } /** * Statements the framework runs about other statements, never the app's: * connection pragmas, plans, and everything that touches its own query log * (the write per logged statement, and the prune that follows). */ export function isBookkeepingSql(sql: string): boolean { return /^\s*(?:explain\b|pragma\b)/i.test(sql) || /\b(?:from|into|update|join)\s+[`"']?query_logs\b/i.test(sql) } export interface QueryAnalysisOptions { slowThresholdMs: number nPlusOneThreshold: number dropped?: number } /** Mark duplicates, repeated shapes and slow statements, and total them. */ export function analyzeQueries(statements: QueryEntry[], options: QueryAnalysisOptions): QueriesSection { const exact = new Map() const shapes = new Map() const keys: Array<{ exact: string, shape: string }> = [] for (const statement of statements) { const shape = normalizeSql(statement.sql) const key = `${statement.sql}\u0000${safeJson(statement.params)}` keys.push({ exact: key, shape }) exact.set(key, (exact.get(key) ?? 0) + 1) const seen = shapes.get(shape) if (seen) seen.count++ else shapes.set(shape, { count: 1, sample: statement.sql, source: statement.source }) } let duration = 0 let duplicates = 0 let slow = 0 let failed = 0 statements.forEach((statement, index) => { const { exact: key, shape } = keys[index]! const identical = exact.get(key) ?? 1 const similar = shapes.get(shape)?.count ?? 1 duration += statement.duration if (identical > 1) statement.duplicates = identical if (similar > 1) statement.similar = similar if (statement.duration >= options.slowThresholdMs) { statement.slow = true slow++ } if (statement.error) failed++ }) for (const count of exact.values()) duplicates += count - 1 const nPlusOne = [...shapes.entries()] .filter(([shape, group]) => group.count >= options.nPlusOneThreshold && isRead(shape)) .map(([shape, group]) => ({ shape, count: group.count, sample: group.sample, source: group.source })) .sort((a, b) => b.count - a.count) return { count: statements.length + (options.dropped ?? 0), duration, dropped: options.dropped ?? 0, duplicates, slow, failed, slowThresholdMs: options.slowThresholdMs, nPlusOne, statements, } } function safeJson(value: unknown): string { try { return JSON.stringify(value) ?? '' } catch { return '' } }