The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feature: Pretty explain in SQL Editor (#41289)
Ali Waseem3a41846044f3
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsxnew file mode 100644index 00000000000..54b19f74a49--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsx@@ -0,0 +1,77 @@+import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'++interface CostIndicatorProps {+ cost: number+ /** The maximum cost in the query plan, used to calculate bar width */+ maxCost: number+}++type CostLevel = 'low' | 'moderate' | 'high'++function getCostLevel(cost: number): CostLevel {+ if (cost < 100) return 'low'+ if (cost < 1000) return 'moderate'+ return 'high'+}++function getCostColorClass(level: CostLevel): string {+ switch (level) {+ case 'low':+ return 'bg-brand'+ case 'moderate':+ return 'bg-warning'+ case 'high':+ return 'bg-destructive'+ }+}++function getCostDescription(level: CostLevel): { label: string; description: string } {+ switch (level) {+ case 'low':+ return {+ label: 'Low cost',+ description: 'This operation is efficient and performs well.',+ }+ case 'moderate':+ return {+ label: 'Moderate cost',+ description: 'This operation may benefit from optimization, such as adding an index.',+ }+ case 'high':+ return {+ label: 'High cost',+ description:+ 'This operation is expensive and likely needs optimization. Consider adding indexes or restructuring the query.',+ }+ }+}++export function CostIndicator({ cost, maxCost }: CostIndicatorProps) {+ const rawWidth = maxCost > 0 ? (cost / maxCost) * 100 : 0+ const costWidth = Math.min(Math.max(rawWidth, 0), 100)+ const costLevel = getCostLevel(cost)+ const colorClass = getCostColorClass(costLevel)+ const { label, description } = getCostDescription(costLevel)++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-2 cursor-help">+ <div className="w-16 h-1.5 bg-surface-300 rounded-full overflow-hidden">+ <div+ className={cn('h-full rounded-full transition-all', colorClass)}+ style={{ width: `${costWidth}%` }}+ />+ </div>+ <span className="text-xs text-foreground-lighter">+ cost <span className="font-mono font-medium">{cost.toFixed(1)}</span>+ </span>+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-xs">+ <p className="font-medium">{label}</p>+ <p className="text-foreground-lighter text-xs mt-1">{description}</p>+ </TooltipContent>+ </Tooltip>+ )+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsxnew file mode 100644index 00000000000..4bf26e799cc--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx@@ -0,0 +1,92 @@+import { Activity, ArrowUp, Clock, Database, GitMerge, Hash, Zap } from 'lucide-react'+import { Badge } from 'ui'++export interface ExplainSummary {+ totalTime: number+ hasSeqScan: boolean+ hasIndexScan: boolean+}++export interface ExplainHeaderProps {+ mode: 'visual' | 'raw'+ onToggleMode: () => void+ summary?: ExplainSummary+}++export function ExplainHeader({ mode, onToggleMode, summary }: ExplainHeaderProps) {+ const isVisual = mode === 'visual'++ const hasSummaryStats =+ isVisual && summary && (summary.totalTime > 0 || (summary.hasSeqScan && !summary.hasIndexScan))++ return (+ <div className="bg-surface-100 border-b px-4 py-3 flex flex-col gap-3 text-xs">+ {/* Title row */}+ <div className="flex items-center gap-2">+ <Activity size={16} className="text-foreground-light" />+ <h3 className="text-sm font-medium text-foreground">Query Execution Plan</h3>+ <button+ type="button"+ onClick={onToggleMode}+ className="font-mono text-xs text-foreground-lighter hover:text-foreground transition-colors"+ aria-label={isVisual ? 'Switch to raw explain output' : 'Switch to visual explain output'}+ >+ {isVisual ? '[VISUAL]' : '[RAW]'}+ </button>+ </div>++ {/* How to read */}+ <div className="flex items-center gap-2 text-foreground-lighter">+ <ArrowUp size={12} className="text-foreground-light" />+ <span className="font-medium text-foreground-light">How to read:</span>+ <span>+ Start at the bottom where data is read from tables, then follow upward as each step+ processes the results.+ </span>+ </div>++ {/* Summary stats - only show in visual mode when we have the data */}+ {hasSummaryStats && (+ <div className="flex items-center gap-4 flex-wrap">+ {summary.totalTime > 0 && (+ <div className="flex items-center gap-1.5">+ <Clock size={12} className="text-foreground-muted" />+ <span className="text-foreground-light">Total:</span>+ <span className="font-mono font-medium text-foreground">+ {summary.totalTime.toFixed(2)}ms+ </span>+ </div>+ )}+ {summary.hasSeqScan && !summary.hasIndexScan && (+ <Badge variant="warning" className="text-xs gap-1">+ <Database size={10} />+ Sequential scan detected+ </Badge>+ )}+ </div>+ )}++ {/* Icon legend - only relevant in visual mode */}+ {isVisual && (+ <div className="flex items-center gap-4 flex-wrap text-foreground-lighter">+ <div className="flex items-center gap-1.5">+ <Database size={12} className="text-warning" />+ <span>Seq Scan (full table read)</span>+ </div>+ <div className="flex items-center gap-1.5">+ <Zap size={12} className="text-brand" />+ <span>Index Scan (fast lookup)</span>+ </div>+ <div className="flex items-center gap-1.5">+ <GitMerge size={12} className="text-foreground-light" />+ <span>Join</span>+ </div>+ <div className="flex items-center gap-1.5">+ <Hash size={12} className="text-foreground-light" />+ <span>Hash (lookup table)</span>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsxnew file mode 100644index 00000000000..101fd1d3516--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsx@@ -0,0 +1,143 @@+import { ArrowRight, ArrowUp, Clock } from 'lucide-react'+import { cn } from 'ui'+import { CostIndicator } from './ExplainVisualizer.CostIndicator'+import { RowCountIndicator } from './ExplainVisualizer.RowCountIndicator'+import {+ getOperationColor,+ getOperationDescription,+ getOperationIcon,+} from './ExplainVisualizer.utils'++import type { ExplainNode } from './ExplainVisualizer.types'+import { useMemo } from 'react'++export interface ExplainNodeRendererProps {+ node: ExplainNode+ depth: number+ maxCost: number+ isRoot?: boolean+}++export function ExplainNodeRenderer({+ node,+ depth,+ maxCost,+ isRoot = false,+}: ExplainNodeRendererProps) {+ const Icon = getOperationIcon(node.operation)+ const colorClass = getOperationColor(node.operation)+ const description = getOperationDescription(node.operation)+ const isLeaf = node.children.length === 0++ const detailLines = node.details ? node.details.split('\n').filter(Boolean) : []++ const hasNonColonPrefixedFirstLine = detailLines.length > 0 && !detailLines[0].includes(':')+ const targetName = hasNonColonPrefixedFirstLine ? detailLines[0] : null++ const pipelineIndicatorClass = useMemo(() => {+ if (isRoot) return 'bg-brand/20 text-brand'+ if (isLeaf) return 'bg-surface-300 text-foreground-light'+ return 'bg-surface-200 text-foreground-muted'+ }, [isRoot, isLeaf])++ return (+ <div className="relative">+ {/* Node content */}+ <div+ className={cn(+ 'flex items-start gap-3 py-3 px-3 rounded-lg border border-transparent hover:border-border hover:bg-surface-100 transition-all'+ )}+ style={{ marginLeft: `${depth * 32}px` }}+ >+ {/* Pipeline flow indicator */}+ <div+ className={cn(+ 'flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center',+ pipelineIndicatorClass+ )}+ >+ {isRoot ? (+ <ArrowRight size={14} className={'text-brand'} />+ ) : (+ <ArrowUp size={14} className={'text-foreground-light'} />+ )}+ </div>++ {/* Icon */}+ <div className={cn('flex-shrink-0 mt-0.5 rounded-lg px-1')}>+ <Icon size={18} strokeWidth={2} className={colorClass} />+ </div>++ {/* Content */}+ <div className="flex-1 min-w-0">+ {/* Operation name and target */}+ <div className="flex items-center gap-2 flex-wrap">+ <span className={cn('font-semibold text-sm', colorClass)}>{node.operation}</span>+ {targetName && (+ <code className="text-xs text-foreground-light bg-surface-200 px-2 py-0.5 rounded-md font-medium">+ {targetName}+ </code>+ )}+ </div>++ {/* Description */}+ {description && <p className="text-xs text-foreground-lighter mt-1">{description}</p>}++ {/* Metrics row */}+ <div className="flex items-center gap-3 mt-2 flex-wrap">+ {/* Cost visualization bar */}+ {node.cost && <CostIndicator cost={node.cost.end} maxCost={maxCost} />}++ {node.actualTime && (+ <>+ <span className="text-foreground-muted text-xs">|</span>+ <div className="flex items-center gap-1 text-xs text-foreground-lighter">+ <Clock size={12} />+ <span className="font-mono font-medium">{node.actualTime.end.toFixed(2)}ms</span>+ </div>+ </>+ )}++ {/* Row count */}+ {(node.actualRows !== undefined || node.rows !== undefined) && (+ <>+ <span className="text-foreground-muted text-xs">|</span>+ <RowCountIndicator+ actualRows={node.actualRows}+ estimatedRows={node.rows}+ rowsRemovedByFilter={node.rowsRemovedByFilter}+ />+ </>+ )}+ </div>++ {/* Detail lines (Filter, Hash Cond, etc.) */}+ {detailLines.length > 0 && (+ <div className="mt-2 space-y-0.5">+ {detailLines.map((detail, idx) => {+ // Skip the first line if it was already shown as the target+ if (idx === 0 && !detail.includes(':')) return null+ // Skip "Rows Removed" as we show it in the flow visualization+ if (detail.includes('Rows Removed by Filter')) return null+ return (+ <div key={idx} className="text-xs text-foreground font-mono py-1 rounded">+ {detail}+ </div>+ )+ })}+ </div>+ )}+ </div>+ </div>++ {/* Render children */}+ {node.children.length > 0 && (+ <div className="relative">+ {node.children.map((child, idx) => (+ <ExplainNodeRenderer key={idx} node={child} depth={depth + 1} maxCost={maxCost} />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsxnew file mode 100644index 00000000000..f3d56f240e6--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx@@ -0,0 +1,189 @@+import { ArrowRight } from 'lucide-react'+import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'++interface RowCountIndicatorProps {+ actualRows?: number+ estimatedRows?: number+ rowsRemovedByFilter?: number+}++const formatCount = (value?: number): string => value?.toLocaleString() ?? 'Unknown'++type EstimationAccuracy =+ | 'severely underestimated'+ | 'underestimated'+ | 'severely overestimated'+ | 'overestimated'+ | 'accurate'+ | 'unknown'++function getEstimationAccuracy(actualRows: number, estimatedRows: number): EstimationAccuracy {+ if (!estimatedRows || estimatedRows === 0) {+ // If estimatedRows is zero or falsy, we can't compute a ratio—treat as severely underestimated+ return 'unknown'+ }+ const ratio = actualRows / estimatedRows+ if (ratio > 10) return 'severely underestimated'+ if (ratio > 2) return 'underestimated'+ if (ratio < 0.1) return 'severely overestimated'+ if (ratio < 0.5) return 'overestimated'+ return 'accurate'+}++/** Shows: scanned → filtered out → remaining */+function FilterFlowIndicator({+ totalRowsScanned,+ rowsRemovedByFilter,+ actualRows,+}: {+ totalRowsScanned: number+ rowsRemovedByFilter: number+ actualRows: number+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-1.5 text-xs text-foreground-lighter cursor-help">+ <span>{formatCount(totalRowsScanned)} rows</span>+ <ArrowRight size={10} className="text-foreground-muted" />+ <span className="text-destructive-600 font-medium">+ -{formatCount(rowsRemovedByFilter)}+ </span>+ <ArrowRight size={10} className="text-foreground-muted" />+ <span className="text-brand font-medium">{formatCount(actualRows)} rows</span>+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-xs">+ <p className="font-medium">Filter applied</p>+ <p className="text-foreground-lighter text-xs mt-1">+ {formatCount(totalRowsScanned)} rows were scanned, {formatCount(rowsRemovedByFilter)} were+ filtered out, leaving {formatCount(actualRows)} rows. Consider adding an index to reduce+ rows scanned.+ </p>+ </TooltipContent>+ </Tooltip>+ )+}++/** Shows a simple count when estimated equals actual */+function SimpleCountIndicator({ rows }: { rows: number }) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="text-foreground-light font-medium text-xs cursor-help">+ {formatCount(rows)} rows+ </span>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-xs">+ <p className="font-medium">Row count</p>+ <p className="text-foreground-lighter text-xs mt-1">+ The planner's estimate matched the actual row count exactly.+ </p>+ </TooltipContent>+ </Tooltip>+ )+}++/** Shows comparison between estimated and actual rows */+function ComparisonIndicator({+ actualRows,+ estimatedRows,+}: {+ actualRows?: number+ estimatedRows?: number+}) {+ const hasBothValues = actualRows !== undefined && estimatedRows !== undefined+ const hasOnlyActual = actualRows !== undefined && estimatedRows === undefined++ const title = hasBothValues+ ? 'Estimated vs actual rows'+ : hasOnlyActual+ ? 'Actual rows'+ : 'Estimated rows'++ const description = getComparisonDescription({ actualRows, estimatedRows })++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="flex items-center gap-1.5 text-xs text-foreground-lighter cursor-help">+ {estimatedRows !== undefined && <span>est. {formatCount(estimatedRows)}</span>}+ {actualRows !== undefined && (+ <>+ {estimatedRows !== undefined && (+ <ArrowRight size={10} className="text-foreground-muted" />+ )}+ <span className="text-foreground-light font-medium">+ {formatCount(actualRows)} rows+ </span>+ </>+ )}+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-xs">+ <p className="font-medium">{title}</p>+ <p className="text-foreground-lighter text-xs mt-1">{description}</p>+ </TooltipContent>+ </Tooltip>+ )+}++function getComparisonDescription({+ actualRows,+ estimatedRows,+}: {+ actualRows?: number+ estimatedRows?: number+}): string {+ const hasBothValues = actualRows !== undefined && estimatedRows !== undefined++ if (!hasBothValues) {+ if (actualRows !== undefined) {+ return `The operation returned ${formatCount(actualRows)} rows.`+ }+ return `The planner estimates this operation will return ${formatCount(estimatedRows)} rows. Run with ANALYZE to see actual counts.`+ }++ const accuracy = getEstimationAccuracy(actualRows, estimatedRows)+ const hasEstimationIssue = accuracy !== 'accurate'++ if (hasEstimationIssue) {+ return `The planner ${accuracy} the row count (estimated ${formatCount(estimatedRows)}, got ${formatCount(actualRows)}). This may indicate outdated statistics — consider running ANALYZE on the table.`+ }++ return `The planner estimated ${formatCount(estimatedRows)} rows and ${formatCount(actualRows)} were returned. The estimate was reasonably accurate.`+}++export function RowCountIndicator({+ actualRows,+ estimatedRows,+ rowsRemovedByFilter,+}: RowCountIndicatorProps) {+ const hasData = actualRows !== undefined || estimatedRows !== undefined+ if (!hasData) return undefined++ const hasFilterData = rowsRemovedByFilter !== undefined && actualRows !== undefined+ const totalRowsScanned = hasFilterData ? actualRows + rowsRemovedByFilter : undefined++ // Priority 1: Show filter flow if we have filter data+ if (hasFilterData && totalRowsScanned !== undefined) {+ return (+ <FilterFlowIndicator+ totalRowsScanned={totalRowsScanned}+ rowsRemovedByFilter={rowsRemovedByFilter}+ actualRows={actualRows}+ />+ )+ }++ // Priority 2: Show simple count if estimate matches actual exactly+ const estimateMatchesActual =+ actualRows !== undefined && estimatedRows !== undefined && actualRows === estimatedRows++ if (estimateMatchesActual) {+ return <SimpleCountIndicator rows={actualRows} />+ }++ // Priority 3: Show comparison view+ return <ComparisonIndicator actualRows={actualRows} estimatedRows={estimatedRows} />+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.tsnew file mode 100644index 00000000000..155c8c12697--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts@@ -0,0 +1,268 @@+import type { ExplainNode, QueryPlanRow } from './ExplainVisualizer.types'++export interface ExplainSummary {+ totalTime: number+ totalCost: number+ hasSeqScan: boolean+ seqScanTables: string[]+ hasIndexScan: boolean+}++function parseFloatMetric(value: string): number | undefined {+ const parsed = parseFloat(value)+ return Number.isFinite(parsed) ? parsed : undefined+}++function parseIntMetric(value: string): number | undefined {+ const parsed = parseInt(value, 10)+ return Number.isNaN(parsed) ? undefined : parsed+}++// Parse the QUERY PLAN text into a tree structure+export function parseExplainOutput(rows: readonly QueryPlanRow[]): ExplainNode[] {+ const lines = rows.map((row) => row['QUERY PLAN'] || '').filter(Boolean)+ const root: ExplainNode[] = []+ const stack: { node: ExplainNode; indent: number }[] = []++ // Detail line patterns that should be attached to the previous node+ const detailPatterns =+ /^(Filter|Sort Key|Group Key|Hash Cond|Join Filter|Index Cond|Recheck Cond|Rows Removed by Filter|Rows Removed by Index Recheck|Output|Merge Cond|Sort Method|Worker \d+|Buffers|Planning Time|Execution Time|One-Time Filter|InitPlan|SubPlan):/++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]++ // Skip empty lines+ if (!line.trim()) continue++ // Calculate the indentation (number of leading spaces)+ const leadingMatch = line.match(/^(\s*)/)+ const leadingSpaces = leadingMatch ? leadingMatch[1].length : 0++ // Check if this line has an arrow (indicates a child operation node)+ const hasArrow = line.includes('->')++ // Extract the content after any arrow+ let content = line+ let effectiveIndent = leadingSpaces++ if (hasArrow) {+ // Find position of -> and use that for indent calculation+ const arrowIndex = line.indexOf('->')+ effectiveIndent = arrowIndex+ content = line.substring(arrowIndex + 2).trim()+ } else {+ content = line.trim()+ }++ // Skip Planning Time and Execution Time summary lines (at root level)+ if (+ content.startsWith('Planning Time:') ||+ content.startsWith('Execution Time:') ||+ content.startsWith('Planning:') ||+ content.startsWith('Execution:')+ ) {+ continue+ }++ // Check if this is a detail line (like Filter:, Sort Key:, etc.)+ if (detailPatterns.test(content) && stack.length > 0) {+ // Attach to the most recent node at or above this indentation+ const currentNode = stack[stack.length - 1].node+ currentNode.details += (currentNode.details ? '\n' : '') + content+ continue+ }++ // Check if this is a continuation of details (indented text without operation pattern)+ // These are typically wrapped condition expressions+ if (!hasArrow && stack.length > 0 && leadingSpaces > 0) {+ const lastItem = stack[stack.length - 1]+ // If it's more indented than the last node and doesn't look like an operation+ if (leadingSpaces > lastItem.indent && !content.match(/^\w+.*\(cost=/)) {+ lastItem.node.details += (lastItem.node.details ? '\n' : '') + content+ continue+ }+ }++ // Parse main operation line: "Operation on table (metrics)"+ // Match operation with optional metrics in parentheses+ // Handle multiple metric groups like (cost=...) (actual time=...)+ const metricsMatch = content.match(/^(.+?)\s*(\([^)]*cost=[^)]+\)(?:\s*\([^)]+\))*)?\s*$/)++ if (!metricsMatch) {+ continue+ }++ const [, operationPart, metricsStr] = metricsMatch+ const metrics = metricsStr+ ? metricsStr.replace(/^\(|\)$/g, '').replace(/\)\s*\(/g, ' ')+ : undefined++ // Split operation and object name (e.g., "Seq Scan on users" -> operation: "Seq Scan", details: "users")+ let operation = operationPart.trim()+ let details = ''++ // Check for "on tablename" or "using indexname" patterns+ const onMatch = operationPart.match(/^(.+?)\s+on\s+(.+)$/i)+ const usingMatch = operationPart.match(/^(.+?)\s+using\s+(.+)$/i)++ if (onMatch) {+ operation = onMatch[1].trim()+ details = 'on ' + onMatch[2].trim()+ } else if (usingMatch) {+ operation = usingMatch[1].trim()+ details = 'using ' + usingMatch[2].trim()+ }++ // Calculate the tree level based on indentation+ // PostgreSQL typically uses 6 spaces per level for -> nodes+ const level = hasArrow ? Math.floor(effectiveIndent / 6) + 1 : 0++ const node = createNode(operation, details, metrics, level, line)+ addNodeToTree(node, effectiveIndent, root, stack)+ }++ return root+}++function createNode(+ operation: string,+ details: string | undefined,+ metrics: string | undefined,+ level: number,+ raw: string+): ExplainNode {+ const node: ExplainNode = {+ operation: operation.trim(),+ details: details?.trim() || '',+ level,+ children: [],+ raw,+ }++ if (metrics) {+ // Parse cost=start..end+ const costMatch = metrics.match(/cost=([\d.]+)\.\.([\d.]+)/)+ if (costMatch) {+ const start = parseFloatMetric(costMatch[1])+ const end = parseFloatMetric(costMatch[2])+ // Only set cost if both values are valid numbers+ if (start !== undefined && end !== undefined) {+ node.cost = { start, end }+ }+ }++ // Parse rows=N (estimated rows, always the first occurrence)+ const rowsMatch = metrics.match(/rows=(\d+)/)+ if (rowsMatch) {+ node.rows = parseIntMetric(rowsMatch[1])+ }++ // Parse width=N+ const widthMatch = metrics.match(/width=(\d+)/)+ if (widthMatch) {+ node.width = parseIntMetric(widthMatch[1])+ }++ // Parse actual time=start..end+ const actualTimeMatch = metrics.match(/actual time=([\d.]+)\.\.([\d.]+)/)+ if (actualTimeMatch) {+ const start = parseFloatMetric(actualTimeMatch[1])+ const end = parseFloatMetric(actualTimeMatch[2])+ // Only set actualTime if both values are valid numbers+ if (start !== undefined && end !== undefined) {+ node.actualTime = { start, end }+ }++ // When EXPLAIN ANALYZE is used, the second rows= value (after actual time) is the actual rows+ const actualTimePart = metrics.substring(metrics.indexOf('actual time='))+ const actualRowsMatch = actualTimePart.match(/rows=(\d+)/)+ if (actualRowsMatch) {+ node.actualRows = parseIntMetric(actualRowsMatch[1])+ }+ }+ }++ return node+}++// After node creation, parse detail fields like "Rows Removed by Filter"+export function parseNodeDetails(node: ExplainNode): void {+ if (node.details) {+ const rowsRemovedMatch = node.details.match(/Rows Removed by Filter:\s*(\d+)/)+ if (rowsRemovedMatch) {+ node.rowsRemovedByFilter = parseIntMetric(rowsRemovedMatch[1])+ }+ }+ node.children.forEach(parseNodeDetails)+}++function addNodeToTree(+ node: ExplainNode,+ indent: number,+ root: ExplainNode[],+ stack: { node: ExplainNode; indent: number }[]+) {+ // Remove nodes from stack that are at the same or deeper indentation+ while (stack.length > 0 && stack[stack.length - 1].indent >= indent) {+ stack.pop()+ }++ if (stack.length === 0) {+ root.push(node)+ } else {+ stack[stack.length - 1].node.children.push(node)+ }++ stack.push({ node, indent })+}++// Calculate max cost for scaling the visualization bars+function getNodeMax(node: ExplainNode): number {+ const nodeCost = node.cost?.end || node.actualTime?.end || 0+ const childrenMax = node.children.reduce((max, child) => Math.max(max, getNodeMax(child)), 0)+ return Math.max(nodeCost, childrenMax)+}++export function calculateMaxCost(tree: ExplainNode[]): number {+ return tree.reduce((max, node) => Math.max(max, getNodeMax(node)), 0)+}++// Calculate summary stats+export function calculateSummary(tree: ExplainNode[]): ExplainSummary {+ const stats: ExplainSummary = {+ totalTime: 0,+ totalCost: 0,+ hasSeqScan: false,+ seqScanTables: [],+ hasIndexScan: false,+ }++ const traverse = (node: ExplainNode) => {+ if (node.actualTime) {+ stats.totalTime = Math.max(stats.totalTime, node.actualTime.end)+ }+ if (node.cost) {+ stats.totalCost = Math.max(stats.totalCost, node.cost.end)+ }+ const op = node.operation.toLowerCase()+ if (op.includes('seq scan')) {+ stats.hasSeqScan = true+ const tableMatch = node.details.match(/on\s+((?:"[^"]+"|[\w]+)(?:\.(?:"[^"]+"|[\w]+))*)/)+ if (tableMatch) stats.seqScanTables.push(tableMatch[1])+ }+ if (op.includes('index')) {+ stats.hasIndexScan = true+ }+ node.children.forEach(traverse)+ }+ tree.forEach(traverse)+ return stats+}++export function createNodeTree(rows: readonly QueryPlanRow[]): ExplainNode[] {+ const tree = parseExplainOutput(rows)++ // Parse additional details from each node+ tree.forEach(parseNodeDetails)+ return tree+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsxnew file mode 100644index 00000000000..aef5f50ee87--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx@@ -0,0 +1,39 @@+import { useMemo } from 'react'+import { ExplainHeader } from './ExplainVisualizer.Header'+import { ExplainNodeRenderer } from './ExplainVisualizer.NodeRenderer'+import { calculateMaxCost, calculateSummary, createNodeTree } from './ExplainVisualizer.parser'+import type { QueryPlanRow } from './ExplainVisualizer.types'++export interface ExplainVisualizerProps {+ rows: readonly QueryPlanRow[]+ onShowRaw?: () => void+}++export function ExplainVisualizer({ rows, onShowRaw }: ExplainVisualizerProps) {+ const parsedTree = useMemo(() => createNodeTree(rows), [rows])+ const maxCost = useMemo(() => calculateMaxCost(parsedTree), [parsedTree])+ const summary = useMemo(() => calculateSummary(parsedTree), [parsedTree])++ if (parsedTree.length === 0) {+ return (+ <div className="bg-table-header-light [[data-theme*=dark]_&]:bg-table-header-dark">+ <p className="m-0 border-0 px-4 py-3 font-mono text-sm text-foreground-light">+ No execution plan data available+ </p>+ </div>+ )+ }++ return (+ <div className="bg-studio border-t h-full flex flex-col">+ {onShowRaw && <ExplainHeader mode="visual" onToggleMode={onShowRaw} summary={summary} />}++ {/* Tree visualization */}+ <div className="p-4 mb-10 overflow-auto flex-1">+ {parsedTree.map((node, idx) => (+ <ExplainNodeRenderer key={idx} node={node} depth={0} maxCost={maxCost} isRoot={true} />+ ))}+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.types.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.types.tsnew file mode 100644index 00000000000..7a109bd0a0a--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.types.ts@@ -0,0 +1,18 @@+export interface ExplainNode {+ operation: string+ details: string+ cost?: { start: number; end: number }+ rows?: number+ width?: number+ actualTime?: { start: number; end: number }+ actualRows?: number+ level: number+ children: ExplainNode[]+ raw: string+ // Parsed detail fields+ rowsRemovedByFilter?: number+}++export interface QueryPlanRow {+ 'QUERY PLAN': string+}diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.tsnew file mode 100644index 00000000000..02421e0d211--- /dev/null+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts@@ -0,0 +1,128 @@+import {+ Activity,+ Database,+ GitMerge,+ Hash,+ ListFilter,+ SortAsc,+ Zap,+ Layers,+ type LucideIcon,+} from 'lucide-react'+import type { ExplainNode } from './ExplainVisualizer.types'++// Get human-readable description for an operation+export function getOperationDescription(operation: string): string {+ const op = operation.toLowerCase()++ if (op.includes('seq scan')) {+ return 'Reads entire table row by row'+ }+ if (op.includes('index only scan')) {+ return 'Reads data directly from index (fastest)'+ }+ if (op.includes('bitmap index scan')) {+ return 'Builds bitmap of matching rows from index'+ }+ if (op.includes('bitmap heap scan')) {+ return 'Fetches rows using bitmap'+ }+ if (op.includes('index scan')) {+ return 'Uses index to find matching rows'+ }+ if (op.includes('hash left join')) {+ return 'Returns all left rows with matching right rows via hash'+ }+ if (op.includes('hash right join')) {+ return 'Returns all right rows with matching left rows via hash'+ }+ if (op.includes('hash full join')) {+ return 'Returns all rows from both tables via hash'+ }+ if (op.includes('hash anti join')) {+ return 'Returns rows without matches via hash'+ }+ if (op.includes('hash semi join')) {+ return 'Returns rows with at least one match via hash'+ }+ if (op.includes('hash join')) {+ return 'Joins tables using hash lookup'+ }+ if (op.includes('merge left join')) {+ return 'Returns all left rows with matching right rows via merge'+ }+ if (op.includes('merge right join')) {+ return 'Returns all right rows with matching left rows via merge'+ }+ if (op.includes('merge full join')) {+ return 'Returns all rows from both tables via merge'+ }+ if (op.includes('merge anti join')) {+ return 'Returns rows without matches via merge'+ }+ if (op.includes('merge semi join')) {+ return 'Returns rows with at least one match via merge'+ }+ if (op.includes('merge join')) {+ return 'Joins pre-sorted tables'+ }+ if (op.includes('nested loop left join')) {+ return 'Returns all left rows with matching right rows via loop'+ }+ if (op.includes('nested loop anti join')) {+ return 'Returns rows without matches via loop'+ }+ if (op.includes('nested loop semi join')) {+ return 'Returns rows with at least one match via loop'+ }+ if (op.includes('nested loop')) {+ return 'Joins by looping through each row'+ }+ if (op === 'hash') {+ return 'Builds hash table for fast lookups'+ }+ if (op.includes('sort')) {+ return 'Sorts rows for output or join'+ }+ if (op.includes('aggregate') || op.includes('group')) {+ return 'Groups rows and calculates aggregates'+ }+ if (op.includes('limit')) {+ return 'Returns only first N rows'+ }+ if (op.includes('materialize')) {+ return 'Stores results in memory for reuse'+ }+ if (op.includes('gather')) {+ return 'Collects results from parallel workers'+ }++ return ''+}++// Get an icon for the operation type+export function getOperationIcon(operation: string): LucideIcon {+ const op = operation.toLowerCase()+ if (op === 'hash') return Hash+ if (op.includes('hash join')) return GitMerge+ if (op.includes('merge join')) return GitMerge+ if (op.includes('nested loop')) return GitMerge+ if (op.includes('join')) return Layers+ if (op.includes('index')) return Zap+ if (op.includes('seq scan')) return Database+ if (op.includes('scan')) return Database+ if (op.includes('filter')) return ListFilter+ if (op.includes('sort')) return SortAsc+ if (op.includes('aggregate') || op.includes('group')) return Activity+ return Database+}++// Get a color class for the operation type+export function getOperationColor(operation: string): string {+ const op = operation.toLowerCase()+ if (op.includes('seq scan')) return 'text-warning'+ if (op.includes('index')) return 'text-brand'+ if (op.includes('join')) return 'text-foreground-light'+ if (op.includes('sort') || op.includes('aggregate')) return 'text-foreground-light'+ return 'text-foreground-light'+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsxindex 222fb6ab931..14a034d51ea 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx@@ -12,6 +12,9 @@ import {copyToClipboard,} from 'ui'import { CellDetailPanel } from './CellDetailPanel'+import { ExplainHeader } from 'components/interfaces/ExplainVisualizer/ExplainVisualizer.Header'+import { ExplainVisualizer } from 'components/interfaces/ExplainVisualizer/ExplainVisualizer'+import { useFeatureFlags, useFlag } from 'common'function formatClipboardValue(value: any) {if (value === null) return ''@@ -24,6 +27,13 @@ function formatClipboardValue(value: any) {const Results = ({ rows }: { rows: readonly any[] }) => {const [expandCell, setExpandCell] = useState(false)const [cellPosition, setCellPosition] = useState<{ column: any; row: any; rowIdx: number }>()+ const [showRaw, setShowRaw] = useState(false)++ const showPrettyExplain = useFlag('ShowPrettyExplain')++ // Check if this is an EXPLAIN query result+ const isExplainQuery =+ rows.length > 0 && rows[0].hasOwnProperty('QUERY PLAN') && Object.keys(rows[0]).length === 1const formatter = (column: any, row: any) => {const cellValue = row[column]@@ -106,6 +116,39 @@ const Results = ({ rows }: { rows: readonly any[] }) => {}})+ // Show pretty explain query results as diagram+ if (showPrettyExplain && isExplainQuery) {+ if (showRaw) {+ return (+ <div className="bg-studio border-t h-full flex flex-col">+ <ExplainHeader mode="raw" onToggleMode={() => setShowRaw(false)} />+ <div className="flex-grow overflow-auto">+ <DataGrid+ columns={columns}+ rows={rows}+ className="h-full flex-grow border-t-0"+ rowClass={() => '[&>.rdg-cell]:items-center'}+ onSelectedCellChange={setCellPosition}+ onCellKeyDown={handleCopyCell}+ />+ <CellDetailPanel+ column={cellPosition?.column.name ?? ''}+ value={cellPosition?.row?.[cellPosition.column.name]}+ visible={expandCell}+ onClose={() => setExpandCell(false)}+ />+ </div>+ </div>+ )+ }++ return (+ <div className="h-full flex flex-col">+ <ExplainVisualizer rows={rows} onShowRaw={() => setShowRaw(true)} />+ </div>+ )+ }+return (<>{rows.length === 0 ? (diff --git a/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.ts b/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.tsnew file mode 100644index 00000000000..73cfe40d9b5--- /dev/null+++ b/apps/studio/tests/features/explain-visualizer/ExplainVisualizer.parser.test.ts@@ -0,0 +1,1099 @@+import { describe, test, expect } from 'vitest'+import {+ parseExplainOutput,+ parseNodeDetails,+ calculateMaxCost,+ calculateSummary,+ type ExplainSummary,+} from 'components/interfaces/ExplainVisualizer/ExplainVisualizer.parser'+import type {+ QueryPlanRow,+ ExplainNode,+} from 'components/interfaces/ExplainVisualizer/ExplainVisualizer.types'++// Helper to create QueryPlanRow array from strings+const toQueryPlanRows = (lines: string[]): QueryPlanRow[] =>+ lines.map((line) => ({ 'QUERY PLAN': line }))++describe('parseExplainOutput', () => {+ describe('simple operations', () => {+ test('parses a simple Seq Scan', () => {+ const input = toQueryPlanRows(['Seq Scan on users (cost=0.00..10.50 rows=100 width=36)'])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ expect(result[0].details).toBe('on users')+ expect(result[0].cost).toEqual({ start: 0, end: 10.5 })+ expect(result[0].rows).toBe(100)+ expect(result[0].width).toBe(36)+ expect(result[0].actualTime).toBeUndefined()+ expect(result[0].actualRows).toBeUndefined()+ expect(result[0].level).toBe(0)+ expect(result[0].children).toHaveLength(0)+ })++ test('parses an Index Scan', () => {+ const input = toQueryPlanRows([+ 'Index Scan using users_pkey on users (cost=0.29..8.30 rows=1 width=48)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ // Parser keeps "using indexname" as part of operation when "on tablename" is present+ expect(result[0].operation).toBe('Index Scan using users_pkey')+ expect(result[0].details).toBe('on users')+ expect(result[0].cost).toEqual({ start: 0.29, end: 8.3 })+ expect(result[0].rows).toBe(1)+ expect(result[0].width).toBe(48)+ })++ test('parses an Index Only Scan', () => {+ const input = toQueryPlanRows([+ 'Index Only Scan using idx_users_email on users (cost=0.15..4.17 rows=1 width=32)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ // Parser keeps "using indexname" as part of operation when "on tablename" is present+ expect(result[0].operation).toBe('Index Only Scan using idx_users_email')+ expect(result[0].details).toBe('on users')+ })++ test('parses Bitmap Index Scan and Bitmap Heap Scan', () => {+ const input = toQueryPlanRows([+ 'Bitmap Heap Scan on users (cost=4.18..13.65 rows=3 width=36)',+ ' -> Bitmap Index Scan on idx_users_status (cost=0.00..4.18 rows=3 width=0)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Bitmap Heap Scan')+ expect(result[0].children).toHaveLength(1)+ expect(result[0].children[0].operation).toBe('Bitmap Index Scan')+ expect(result[0].children[0].details).toBe('on idx_users_status')+ })+ })++ describe('EXPLAIN ANALYZE output', () => {+ test('parses actual time and actual rows from EXPLAIN ANALYZE', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=0.015..0.123 rows=85 loops=1)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].cost).toEqual({ start: 0, end: 10.5 })+ expect(result[0].rows).toBe(100) // estimated rows+ expect(result[0].actualTime).toEqual({ start: 0.015, end: 0.123 })+ expect(result[0].actualRows).toBe(85) // actual rows+ })++ test('skips Planning Time and Execution Time lines', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=0.015..0.123 rows=85 loops=1)',+ 'Planning Time: 0.089 ms',+ 'Execution Time: 0.156 ms',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ })+ })++ describe('nested operations', () => {+ test('parses nested Hash Join with children', () => {+ const input = toQueryPlanRows([+ 'Hash Join (cost=10.50..25.30 rows=50 width=72)',+ ' Hash Cond: (orders.user_id = users.id)',+ ' -> Seq Scan on orders (cost=0.00..12.00 rows=200 width=36)',+ ' -> Hash (cost=10.50..10.50 rows=100 width=36)',+ ' -> Seq Scan on users (cost=0.00..10.50 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Hash Join')+ expect(result[0].details).toContain('Hash Cond:')+ expect(result[0].children).toHaveLength(2)+ expect(result[0].children[0].operation).toBe('Seq Scan')+ expect(result[0].children[0].details).toBe('on orders')+ expect(result[0].children[1].operation).toBe('Hash')+ expect(result[0].children[1].children).toHaveLength(1)+ expect(result[0].children[1].children[0].operation).toBe('Seq Scan')+ })++ test('parses Merge Join', () => {+ const input = toQueryPlanRows([+ 'Merge Join (cost=200.00..350.00 rows=1000 width=80)',+ ' Merge Cond: (a.id = b.a_id)',+ ' -> Index Scan using a_pkey on a (cost=0.29..50.00 rows=500 width=40)',+ ' -> Sort (cost=150.00..155.00 rows=2000 width=40)',+ ' Sort Key: b.a_id',+ ' -> Seq Scan on b (cost=0.00..30.00 rows=2000 width=40)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Merge Join')+ expect(result[0].children).toHaveLength(2)+ expect(result[0].children[1].operation).toBe('Sort')+ expect(result[0].children[1].details).toContain('Sort Key:')+ })++ test('parses Nested Loop', () => {+ const input = toQueryPlanRows([+ 'Nested Loop (cost=0.29..16.60 rows=1 width=72)',+ ' -> Index Scan using users_pkey on users (cost=0.29..8.30 rows=1 width=36)',+ ' -> Index Scan using orders_user_id_idx on orders (cost=0.00..8.28 rows=1 width=36)',+ ' Index Cond: (user_id = users.id)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Nested Loop')+ expect(result[0].children).toHaveLength(2)+ expect(result[0].children[1].details).toContain('Index Cond:')+ })+ })++ describe('aggregate operations', () => {+ test('parses Aggregate operation', () => {+ const input = toQueryPlanRows([+ 'Aggregate (cost=12.50..12.51 rows=1 width=8)',+ ' -> Seq Scan on users (cost=0.00..10.50 rows=100 width=0)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Aggregate')+ expect(result[0].children).toHaveLength(1)+ })++ test('parses HashAggregate with Group Key', () => {+ const input = toQueryPlanRows([+ 'HashAggregate (cost=15.00..17.00 rows=10 width=12)',+ ' Group Key: status',+ ' -> Seq Scan on orders (cost=0.00..12.00 rows=200 width=4)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('HashAggregate')+ expect(result[0].details).toContain('Group Key: status')+ expect(result[0].children).toHaveLength(1)+ })++ test('parses GroupAggregate with Sort', () => {+ const input = toQueryPlanRows([+ 'GroupAggregate (cost=20.00..25.00 rows=10 width=12)',+ ' Group Key: category',+ ' -> Sort (cost=18.00..19.00 rows=200 width=8)',+ ' Sort Key: category',+ ' -> Seq Scan on products (cost=0.00..15.00 rows=200 width=8)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('GroupAggregate')+ expect(result[0].children).toHaveLength(1)+ expect(result[0].children[0].operation).toBe('Sort')+ expect(result[0].children[0].children).toHaveLength(1)+ })+ })++ describe('sorting and limiting', () => {+ test('parses Sort operation with Sort Key', () => {+ const input = toQueryPlanRows([+ 'Sort (cost=25.00..27.50 rows=100 width=36)',+ ' Sort Key: created_at DESC',+ ' -> Seq Scan on events (cost=0.00..20.00 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Sort')+ expect(result[0].details).toContain('Sort Key: created_at DESC')+ expect(result[0].children).toHaveLength(1)+ })++ test('parses Sort with Sort Method in EXPLAIN ANALYZE', () => {+ const input = toQueryPlanRows([+ 'Sort (cost=25.00..27.50 rows=100 width=36) (actual time=0.100..0.150 rows=100 loops=1)',+ ' Sort Key: created_at DESC',+ ' Sort Method: quicksort Memory: 32kB',+ ' -> Seq Scan on events (cost=0.00..20.00 rows=100 width=36) (actual time=0.010..0.050 rows=100 loops=1)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('Sort Key: created_at DESC')+ expect(result[0].details).toContain('Sort Method: quicksort Memory: 32kB')+ })++ test('parses Limit operation', () => {+ const input = toQueryPlanRows([+ 'Limit (cost=0.00..1.05 rows=10 width=36)',+ ' -> Seq Scan on users (cost=0.00..10.50 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Limit')+ expect(result[0].children).toHaveLength(1)+ })+ })++ describe('filter conditions', () => {+ test('parses Filter detail', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=50 width=36)',+ " Filter: (status = 'active'::text)",+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain("Filter: (status = 'active'::text)")+ })++ test('parses Rows Removed by Filter', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=50 width=36) (actual time=0.010..0.100 rows=50 loops=1)',+ " Filter: (status = 'active'::text)",+ ' Rows Removed by Filter: 50',+ ])++ const result = parseExplainOutput(input)+ parseNodeDetails(result[0])++ expect(result[0].details).toContain('Rows Removed by Filter: 50')+ expect(result[0].rowsRemovedByFilter).toBe(50)+ })++ test('parses Index Cond', () => {+ const input = toQueryPlanRows([+ 'Index Scan using users_pkey on users (cost=0.29..8.30 rows=1 width=48)',+ ' Index Cond: (id = 123)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('Index Cond: (id = 123)')+ })++ test('parses Recheck Cond for Bitmap scans', () => {+ const input = toQueryPlanRows([+ 'Bitmap Heap Scan on users (cost=4.18..13.65 rows=3 width=36)',+ " Recheck Cond: (status = 'active'::text)",+ ' -> Bitmap Index Scan on idx_users_status (cost=0.00..4.18 rows=3 width=0)',+ " Index Cond: (status = 'active'::text)",+ ])++ const result = parseExplainOutput(input)++ expect(result[0].details).toContain("Recheck Cond: (status = 'active'::text)")+ expect(result[0].children[0].details).toContain("Index Cond: (status = 'active'::text)")+ })+ })++ describe('subplans and CTEs', () => {+ test('parses CTE Scan', () => {+ const input = toQueryPlanRows([+ 'CTE Scan on recent_users (cost=10.50..12.50 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('CTE Scan')+ expect(result[0].details).toBe('on recent_users')+ })++ test('parses SubPlan reference', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on orders (cost=0.00..25.00 rows=100 width=36)',+ ' Filter: (total > (SubPlan 1))',+ ' SubPlan 1',+ ' -> Aggregate (cost=10.50..10.51 rows=1 width=8)',+ ' -> Seq Scan on orders orders_1 (cost=0.00..10.50 rows=100 width=4)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('Filter: (total > (SubPlan 1))')+ expect(result[0].details).toContain('SubPlan 1')+ })++ test('parses InitPlan', () => {+ const input = toQueryPlanRows([+ 'Result (cost=10.51..10.52 rows=1 width=8)',+ ' InitPlan 1 (returns $0)',+ ' -> Aggregate (cost=10.50..10.51 rows=1 width=8)',+ ' -> Seq Scan on users (cost=0.00..10.50 rows=100 width=0)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Result')+ expect(result[0].details).toContain('InitPlan 1 (returns $0)')+ })+ })++ describe('set operations', () => {+ test('parses Append for UNION ALL', () => {+ const input = toQueryPlanRows([+ 'Append (cost=0.00..21.00 rows=200 width=36)',+ ' -> Seq Scan on users_2023 (cost=0.00..10.50 rows=100 width=36)',+ ' -> Seq Scan on users_2024 (cost=0.00..10.50 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Append')+ expect(result[0].children).toHaveLength(2)+ })++ test('parses Unique for UNION (distinct)', () => {+ const input = toQueryPlanRows([+ 'Unique (cost=25.00..30.00 rows=150 width=36)',+ ' -> Sort (cost=25.00..26.00 rows=200 width=36)',+ ' Sort Key: id',+ ' -> Append (cost=0.00..21.00 rows=200 width=36)',+ ' -> Seq Scan on users_2023 (cost=0.00..10.50 rows=100 width=36)',+ ' -> Seq Scan on users_2024 (cost=0.00..10.50 rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Unique')+ expect(result[0].children).toHaveLength(1)+ expect(result[0].children[0].operation).toBe('Sort')+ })+ })++ describe('parallel queries', () => {+ test('parses Gather with parallel workers', () => {+ const input = toQueryPlanRows([+ 'Gather (cost=1000.00..15000.00 rows=100000 width=36)',+ ' Workers Planned: 2',+ ' -> Parallel Seq Scan on large_table (cost=0.00..14000.00 rows=41667 width=36)',+ " Filter: (status = 'active'::text)",+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Gather')+ expect(result[0].children).toHaveLength(1)+ expect(result[0].children[0].operation).toBe('Parallel Seq Scan')+ })++ test('parses Gather Merge', () => {+ const input = toQueryPlanRows([+ 'Gather Merge (cost=5000.00..10000.00 rows=50000 width=36)',+ ' Workers Planned: 2',+ ' -> Sort (cost=4000.00..4125.00 rows=25000 width=36)',+ ' Sort Key: created_at DESC',+ ' -> Parallel Seq Scan on events (cost=0.00..3000.00 rows=25000 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Gather Merge')+ })+ })++ describe('buffer information', () => {+ test('parses Buffers information in EXPLAIN (ANALYZE, BUFFERS)', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=0.010..0.100 rows=100 loops=1)',+ ' Buffers: shared hit=5',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('Buffers: shared hit=5')+ })+ })++ describe('edge cases', () => {+ test('handles empty input', () => {+ const result = parseExplainOutput([])+ expect(result).toHaveLength(0)+ })++ test('handles input with only empty strings', () => {+ const input = toQueryPlanRows(['', ' ', ''])+ const result = parseExplainOutput(input)+ expect(result).toHaveLength(0)+ })++ test('handles malformed metric strings gracefully', () => {+ const input = toQueryPlanRows(['Seq Scan on users (malformed metrics)'])+ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ expect(result[0].cost).toBeUndefined()+ })++ test('handles operation without metrics', () => {+ const input = toQueryPlanRows(['Seq Scan on users'])+ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ expect(result[0].details).toBe('on users')+ expect(result[0].cost).toBeUndefined()+ })++ test('handles deeply nested query plans', () => {+ const input = toQueryPlanRows([+ 'Limit (cost=100.00..100.10 rows=10 width=36)',+ ' -> Sort (cost=100.00..102.50 rows=1000 width=36)',+ ' Sort Key: total DESC',+ ' -> Hash Join (cost=50.00..80.00 rows=1000 width=36)',+ ' Hash Cond: (o.user_id = u.id)',+ ' -> Seq Scan on orders o (cost=0.00..20.00 rows=1000 width=20)',+ ' -> Hash (cost=40.00..40.00 rows=500 width=16)',+ ' -> Seq Scan on users u (cost=0.00..40.00 rows=500 width=16)',+ ' Filter: (active = true)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Limit')+ expect(result[0].children[0].operation).toBe('Sort')+ expect(result[0].children[0].children[0].operation).toBe('Hash Join')+ expect(result[0].children[0].children[0].children).toHaveLength(2)+ expect(result[0].children[0].children[0].children[1].children[0].operation).toBe('Seq Scan')+ })++ test('handles One-Time Filter', () => {+ const input = toQueryPlanRows([+ 'Result (cost=0.00..0.01 rows=1 width=0)',+ ' One-Time Filter: false',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('One-Time Filter: false')+ })++ test('handles Output detail line', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36)',+ ' Output: id, name, email',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].details).toContain('Output: id, name, email')+ })++ test('handles invalid cost values gracefully', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=invalid..notanumber rows=100 width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ // Should not parse invalid cost at all+ expect(result[0].cost).toBeUndefined()+ })++ test('handles invalid rows value gracefully', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=notanumber width=36)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Seq Scan')+ // Should not parse invalid rows at all (regex won't match)+ expect(result[0].rows).toBeUndefined()+ })++ test('handles invalid actual time values gracefully', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=invalid..notanumber rows=85 loops=1)',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ // Should not parse invalid actual time at all+ expect(result[0].actualTime).toBeUndefined()+ })++ test('handles invalid rowsRemovedByFilter value gracefully', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36)',+ " Filter: (status = 'active')",+ ' Rows Removed by Filter: notanumber',+ ])++ const result = parseExplainOutput(input)+ parseNodeDetails(result[0])++ expect(result).toHaveLength(1)+ // Should not parse invalid value at all (regex won't match)+ expect(result[0].rowsRemovedByFilter).toBeUndefined()+ })++ test('parsed numeric fields are finite for valid input', () => {+ const input = toQueryPlanRows([+ 'Seq Scan on users (cost=0.00..10.50 rows=100 width=36) (actual time=0.015..0.123 rows=85 loops=1)',+ " Filter: (status = 'active')",+ ' Rows Removed by Filter: 15',+ ])++ const result = parseExplainOutput(input)+ parseNodeDetails(result[0])++ expect(result).toHaveLength(1)+ const node = result[0]++ // Verify all numeric values are finite+ if (node.cost) {+ expect(Number.isFinite(node.cost.start)).toBe(true)+ expect(Number.isFinite(node.cost.end)).toBe(true)+ }+ if (node.actualTime) {+ expect(Number.isFinite(node.actualTime.start)).toBe(true)+ expect(Number.isFinite(node.actualTime.end)).toBe(true)+ }+ if (node.rows !== undefined) {+ expect(Number.isFinite(node.rows)).toBe(true)+ }+ if (node.actualRows !== undefined) {+ expect(Number.isFinite(node.actualRows)).toBe(true)+ }+ if (node.width !== undefined) {+ expect(Number.isFinite(node.width)).toBe(true)+ }+ if (node.rowsRemovedByFilter !== undefined) {+ expect(Number.isFinite(node.rowsRemovedByFilter)).toBe(true)+ }+ })+ })++ describe('complex real-world queries', () => {+ test('parses a complex analytical query', () => {+ const input = toQueryPlanRows([+ 'Limit (cost=1500.00..1500.05 rows=20 width=48) (actual time=15.234..15.240 rows=20 loops=1)',+ ' -> Sort (cost=1500.00..1525.00 rows=10000 width=48) (actual time=15.232..15.235 rows=20 loops=1)',+ ' Sort Key: (sum(o.total)) DESC',+ ' Sort Method: top-N heapsort Memory: 27kB',+ ' -> HashAggregate (cost=1200.00..1300.00 rows=10000 width=48) (actual time=12.456..14.789 rows=8543 loops=1)',+ ' Group Key: u.id',+ ' Batches: 1 Memory Usage: 1169kB',+ ' -> Hash Join (cost=125.00..950.00 rows=50000 width=20) (actual time=1.234..8.567 rows=50000 loops=1)',+ ' Hash Cond: (o.user_id = u.id)',+ ' -> Seq Scan on orders o (cost=0.00..750.00 rows=50000 width=12) (actual time=0.012..3.456 rows=50000 loops=1)',+ ' -> Hash (cost=100.00..100.00 rows=2000 width=8) (actual time=1.111..1.111 rows=2000 loops=1)',+ ' Buckets: 2048 Batches: 1 Memory Usage: 95kB',+ ' -> Seq Scan on users u (cost=0.00..100.00 rows=2000 width=8) (actual time=0.008..0.567 rows=2000 loops=1)',+ ' Filter: (active = true)',+ ' Rows Removed by Filter: 500',+ ])++ const result = parseExplainOutput(input)++ expect(result).toHaveLength(1)+ expect(result[0].operation).toBe('Limit')+ expect(result[0].actualTime).toEqual({ start: 15.234, end: 15.24 })+ expect(result[0].actualRows).toBe(20)++ // Navigate to the deepest Seq Scan on users+ const hashJoin = result[0].children[0].children[0].children[0]+ expect(hashJoin.operation).toBe('Hash Join')+ const hash = hashJoin.children[1]+ expect(hash.operation).toBe('Hash')+ const usersScan = hash.children[0]+ expect(usersScan.operation).toBe('Seq Scan')+ expect(usersScan.details).toContain('Filter: (active = true)')+ expect(usersScan.details).toContain('Rows Removed by Filter: 500')+ })+ })+})++describe('parseNodeDetails', () => {+ test('parses Rows Removed by Filter from node details', () => {+ const node: ExplainNode = {+ operation: 'Seq Scan',+ details: "on users\nFilter: (status = 'active')\nRows Removed by Filter: 150",+ cost: { start: 0, end: 10.5 },+ rows: 100,+ width: 36,++ level: 0,+ children: [],+ raw: '',+ }++ parseNodeDetails(node)++ expect(node.rowsRemovedByFilter).toBe(150)+ })++ test('handles node without Rows Removed by Filter', () => {+ const node: ExplainNode = {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 10.5 },+ rows: 100,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ }++ parseNodeDetails(node)++ expect(node.rowsRemovedByFilter).toBeUndefined()+ })++ test('recursively parses details for children', () => {+ const node: ExplainNode = {+ operation: 'Hash Join',+ details: '',+ cost: { start: 0, end: 50 },+ rows: 100,+ width: 72,+ level: 0,+ children: [+ {+ operation: 'Seq Scan',+ details: 'on orders\nRows Removed by Filter: 200',+ cost: { start: 0, end: 20 },+ rows: 50,+ width: 36,++ level: 1,+ children: [],+ raw: '',+ },+ {+ operation: 'Seq Scan',+ details: 'on users\nRows Removed by Filter: 75',+ cost: { start: 0, end: 15 },+ rows: 25,+ width: 36,++ level: 1,+ children: [],+ raw: '',+ },+ ],+ raw: '',+ }++ parseNodeDetails(node)++ expect(node.children[0].rowsRemovedByFilter).toBe(200)+ expect(node.children[1].rowsRemovedByFilter).toBe(75)+ })+})++describe('calculateMaxCost', () => {+ test('returns 0 for empty tree', () => {+ const result = calculateMaxCost([])+ expect(result).toBe(0)+ })++ test('returns cost.end for single node', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 25.5 },+ rows: 100,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateMaxCost(tree)+ expect(result).toBe(25.5)+ })++ test('prefers cost.end over actualTime.end (uses actualTime as fallback)', () => {+ // When both cost and actualTime are present, cost takes precedence+ const treeWithBoth: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 10.5 },+ rows: 100,+ width: 36,+ actualTime: { start: 0.01, end: 50.123 },+ actualRows: 100,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ expect(calculateMaxCost(treeWithBoth)).toBe(10.5)++ // When only actualTime is present, it's used as fallback+ const treeOnlyActualTime: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',++ rows: 100,+ width: 36,+ actualTime: { start: 0.01, end: 50.123 },+ actualRows: 100,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ expect(calculateMaxCost(treeOnlyActualTime)).toBe(50.123)+ })++ test('finds maximum across nested children', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Limit',+ details: '',+ cost: { start: 0, end: 100 },+ rows: 10,+ width: 36,+ level: 0,+ children: [+ {+ operation: 'Sort',+ details: '',+ cost: { start: 0, end: 250 }, // This is the maximum+ rows: 1000,+ width: 36,+ level: 1,+ children: [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 150 },+ rows: 1000,+ width: 36,+ level: 2,+ children: [],+ raw: '',+ },+ ],+ raw: '',+ },+ ],+ raw: '',+ },+ ]++ const result = calculateMaxCost(tree)+ expect(result).toBe(250)+ })++ test('handles multiple root nodes', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 30 },+ rows: 100,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ },+ {+ operation: 'Seq Scan',+ details: 'on orders',+ cost: { start: 0, end: 75 },+ rows: 200,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateMaxCost(tree)+ expect(result).toBe(75)+ })++ test('handles nodes without cost or actualTime', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Result',+ details: '',+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateMaxCost(tree)+ expect(result).toBe(0)+ })+})++describe('calculateSummary', () => {+ test('returns default values for empty tree', () => {+ const result = calculateSummary([])++ expect(result).toEqual({+ totalTime: 0,+ totalCost: 0,+ hasSeqScan: false,+ seqScanTables: [],+ hasIndexScan: false,+ })+ })++ test('calculates totalCost from cost.end', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 45.5 },+ rows: 100,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.totalCost).toBe(45.5)+ })++ test('calculates totalTime from actualTime.end', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 10.5 },+ rows: 100,+ width: 36,+ actualTime: { start: 0.01, end: 123.456 },+ actualRows: 100,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.totalTime).toBe(123.456)+ })++ test('detects Seq Scan and extracts table name', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 10.5 },+ rows: 100,+ width: 36,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.hasSeqScan).toBe(true)+ expect(result.seqScanTables).toEqual(['users'])+ })++ test('detects multiple Seq Scans on different tables', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Hash Join',+ details: '',+ cost: { start: 0, end: 50 },+ rows: 100,+ width: 72,+ level: 0,+ children: [+ {+ operation: 'Seq Scan',+ details: 'on orders',+ cost: { start: 0, end: 20 },+ rows: 100,+ width: 36,+ level: 1,+ children: [],+ raw: '',+ },+ {+ operation: 'Seq Scan',+ details: 'on users',+ cost: { start: 0, end: 15 },+ rows: 50,+ width: 36,+ level: 1,+ children: [],+ raw: '',+ },+ ],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.hasSeqScan).toBe(true)+ expect(result.seqScanTables).toEqual(['orders', 'users'])+ })++ test('detects Index Scan', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Index Scan using users_pkey',+ details: 'on users',+ cost: { start: 0.29, end: 8.3 },+ rows: 1,+ width: 48,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.hasIndexScan).toBe(true)+ expect(result.hasSeqScan).toBe(false)+ })++ test('detects Index Only Scan', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Index Only Scan',+ details: 'using idx_users_email on users',+ cost: { start: 0.15, end: 4.17 },+ rows: 1,+ width: 32,+ level: 0,+ children: [],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.hasIndexScan).toBe(true)+ })++ test('detects Bitmap Index Scan', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Bitmap Heap Scan',+ details: 'on users',+ cost: { start: 4.18, end: 13.65 },+ rows: 3,+ width: 36,+ level: 0,+ children: [+ {+ operation: 'Bitmap Index Scan',+ details: 'on idx_users_status',+ cost: { start: 0, end: 4.18 },+ rows: 3,+ width: 0,+ level: 1,+ children: [],+ raw: '',+ },+ ],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.hasIndexScan).toBe(true)+ })++ test('handles complex query with both seq and index scans', () => {+ const tree: ExplainNode[] = [+ {+ operation: 'Hash Join',+ details: '',+ cost: { start: 10.5, end: 35.8 },+ rows: 50,+ width: 72,+ actualTime: { start: 0.5, end: 2.345 },+ actualRows: 48,+ level: 0,+ children: [+ {+ operation: 'Seq Scan',+ details: 'on orders',+ cost: { start: 0, end: 20 },+ rows: 100,+ width: 36,+ actualTime: { start: 0.01, end: 0.5 },+ actualRows: 95,+ level: 1,+ children: [],+ raw: '',+ },+ {+ operation: 'Index Scan using users_pkey',+ details: 'on users',+ cost: { start: 0.29, end: 8.3 },+ rows: 1,+ width: 36,+ actualTime: { start: 0.005, end: 0.015 },+ actualRows: 1,+ level: 1,+ children: [],+ raw: '',+ },+ ],+ raw: '',+ },+ ]++ const result = calculateSummary(tree)+ expect(result.totalCost).toBe(35.8)+ expect(result.totalTime).toBe(2.345)+ expect(result.hasSeqScan).toBe(true)+ expect(result.hasIndexScan).toBe(true)+ expect(result.seqScanTables).toEqual(['orders'])+ })+})