ExplainVisualizer.ai.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import type { QueryPlanRow } from './ExplainVisualizer.types'
  2. export interface ExplainPromptInput {
  3. sql: string
  4. explainPlanRows: QueryPlanRow[]
  5. }
  6. export interface ExplainPromptOutput {
  7. query: string
  8. prompt: string
  9. }
  10. export function buildExplainPrompt({
  11. sql,
  12. explainPlanRows,
  13. }: ExplainPromptInput): ExplainPromptOutput {
  14. const explainPlan = explainPlanRows.map((row) => row['QUERY PLAN']).join('\n')
  15. const prompt = `Explain this PostgreSQL EXPLAIN ANALYZE output in simple terms:
  16. \`\`\`sql
  17. ${sql}
  18. \`\`\`
  19. \`\`\`
  20. ${explainPlan}
  21. \`\`\`
  22. Format your response with:
  23. **What it does** - 1-2 sentences.
  24. **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.
  25. **Issues** - Identify bottlenecks: slowest steps, sequential scans on large tables, inefficient joins, missing indexes. Be specific with timings from the plan.
  26. **Fixes** - 2-3 specific suggestions with CREATE INDEX statements if applicable.
  27. Keep it concise. Focus on actionable insights.`
  28. return {
  29. query: sql,
  30. prompt,
  31. }
  32. }