ExplainVisualizer.ai.ts45 lines · main
1import type { QueryPlanRow } from './ExplainVisualizer.types'
2
3export interface ExplainPromptInput {
4 sql: string
5 explainPlanRows: QueryPlanRow[]
6}
7
8export interface ExplainPromptOutput {
9 query: string
10 prompt: string
11}
12
13export function buildExplainPrompt({
14 sql,
15 explainPlanRows,
16}: ExplainPromptInput): ExplainPromptOutput {
17 const explainPlan = explainPlanRows.map((row) => row['QUERY PLAN']).join('\n')
18
19 const prompt = `Explain this PostgreSQL EXPLAIN ANALYZE output in simple terms:
20
21\`\`\`sql
22${sql}
23\`\`\`
24
25\`\`\`
26${explainPlan}
27\`\`\`
28
29Format your response with:
30
31**What it does** - 1-2 sentences.
32
33**How it runs** - Briefly explain the plan from bottom to top in plain English. Mention key operations (scans, joins, sorts) and why PostgreSQL chose them.
34
35**Issues** - Identify bottlenecks: slowest steps, sequential scans on large tables, inefficient joins, missing indexes. Be specific with timings from the plan.
36
37**Fixes** - 2-3 specific suggestions with CREATE INDEX statements if applicable.
38
39Keep it concise. Focus on actionable insights.`
40
41 return {
42 query: sql,
43 prompt,
44 }
45}