Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: update pretty explain to match the Figma designs a bit better (#41540)

Ali Waseemf867ddbe1283
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsx
deleted file mode 100644
index 54b19f74a49..00000000000
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.CostIndicator.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-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.tsx
index 4bf26e799cc..d90a1305ac2 100644
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx
@@ -22,9 +22,22 @@ export function ExplainHeader({ mode, onToggleMode, summary }: ExplainHeaderProp
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>
+ <div className="flex items-center gap-2 text-sm">
+ <h3 className="font-medium text-foreground">Query Execution Plan</h3>
+ {/* 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">
+ <span className="text-foreground-light">/</span>
+ <span className="text-foreground-light">Total time</span>
+ <span className="font-mono font-medium text-foreground">
+ {summary.totalTime.toFixed(2)}ms
+ </span>
+ </div>
+ )}
+ </div>
+ )}
<button
type="button"
onClick={onToggleMode}
@@ -45,45 +58,16 @@ export function ExplainHeader({ mode, onToggleMode, summary }: ExplainHeaderProp
</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>
+ <span className="inline-block w-2 h-2 rounded-full bg-warning" />
+ <span>Seq Scan (slow)</span>
</div>
<div className="flex items-center gap-1.5">
- <Hash size={12} className="text-foreground-light" />
- <span>Hash (lookup table)</span>
+ <span className="inline-block w-2 h-2 rounded-full bg-brand" />
+ <span>Index Scan (fast)</span>
</div>
</div>
)}
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsx
deleted file mode 100644
index 101fd1d3516..00000000000
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRenderer.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-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.NodeRow.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx
new file mode 100644
index 00000000000..2539a6e7dad
--- /dev/null
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx
@@ -0,0 +1,144 @@
+import { useState } from 'react'
+import { ChevronRight, ChevronDown } from 'lucide-react'
+import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { RowCountIndicator } from './ExplainVisualizer.RowCountIndicator'
+import type { ExplainNode } from './ExplainVisualizer.types'
+import { parseDetailLines } from './ExplainVisualizer.parser'
+import { formatNodeDuration, getScanBarColor, getScanBorderColor } from './ExplainVisualizer.utils'
+
+interface ExplainNodeRowProps {
+ node: ExplainNode
+ depth: number
+ /** Maximum duration across all nodes, used to calculate bar width as % */
+ maxDuration: number
+}
+
+export function ExplainNodeRow({ node, depth, maxDuration }: ExplainNodeRowProps) {
+ const [isExpanded, setIsExpanded] = useState(false)
+ const hasChildren = node.children.length > 0
+ const hasDetails = Boolean(node.details?.trim())
+ const canExpand = hasDetails
+
+ const detailLines = parseDetailLines(node.details)
+ const indentPx = depth * 24
+
+ // Calculate duration and bar width as % of max duration
+ const duration = node.actualTime ? node.actualTime.end - node.actualTime.start : 0
+ const hasTimingData = node.actualTime && duration > 0
+ const barWidthPercent = maxDuration > 0 ? (duration / maxDuration) * 100 : 0
+ const barColorClass = getScanBarColor(node.operation)
+ const borderColorClass = getScanBorderColor(node.operation)
+
+ return (
+ <>
+ {/* Wrapper for group hover */}
+ <div className="group">
+ {/* Main row */}
+ <div
+ className={cn(
+ 'flex items-stretch border-b-border-muted border-b border-l-4 transition-colors bg-studio group-hover:bg-surface-100/50',
+ borderColorClass
+ )}
+ >
+ {/* Left section: expand button + operation info */}
+ <div
+ className="flex items-center gap-3 px-4 py-3 shrink-0 min-w-[400px]"
+ style={{ paddingLeft: `${16 + indentPx}px` }}
+ >
+ {/* Expand/collapse button */}
+ <button
+ type="button"
+ onClick={() => canExpand && setIsExpanded(!isExpanded)}
+ disabled={!canExpand}
+ className={cn(
+ 'flex items-center justify-center w-5 h-5 rounded border border-border-muted shrink-0',
+ canExpand ? 'hover:bg-surface-200 cursor-pointer' : 'opacity-30 cursor-default'
+ )}
+ aria-label={isExpanded ? 'Collapse details' : 'Expand details'}
+ >
+ {isExpanded ? (
+ <ChevronDown size={12} className="text-foreground-light" />
+ ) : (
+ <ChevronRight size={12} className="text-foreground-light" />
+ )}
+ </button>
+
+ {/* Operation name and cost info */}
+ <div className="flex items-center gap-2 font-mono text-xs min-w-0">
+ <span className="text-foreground uppercase font-medium whitespace-nowrap">
+ {node.operation}
+ </span>
+ <span className="text-foreground-muted whitespace-nowrap">
+ (cost {node.cost?.end?.toFixed(1) ?? '-'}, estimated{' '}
+ {node.rows?.toLocaleString() ?? '?'} {node.rows === 1 ? 'row' : 'rows'})
+ </span>
+ </div>
+ </div>
+
+ {/* Right section: duration bar visualization */}
+ <div className="flex-1 relative min-h-[43px] flex items-center">
+ {hasTimingData && (
+ <>
+ {/* Duration bar - width represents % of slowest operation */}
+ <div
+ className={cn('absolute left-0 top-0 h-full', barColorClass)}
+ style={{ width: `${barWidthPercent}%` }}
+ />
+ {/* Duration and row count info */}
+ <div className="relative flex items-center gap-2 font-mono text-xs whitespace-nowrap px-3">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-foreground-light cursor-help">
+ {formatNodeDuration(duration)}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-xs font-sans">
+ <p className="font-medium">Execution time: {formatNodeDuration(duration)}</p>
+ <p className="text-foreground-lighter text-xs mt-1">
+ This is how long this operation took to execute. The bar width shows this as
+ a percentage of the slowest operation ({Math.round(barWidthPercent)}%) —
+ wider bars indicate where more time is spent.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ <span className="text-foreground-muted">/</span>
+ <RowCountIndicator
+ actualRows={node.actualRows}
+ estimatedRows={node.rows}
+ rowsRemovedByFilter={node.rowsRemovedByFilter}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Expanded details section */}
+ {isExpanded && detailLines.length > 0 && (
+ <div
+ className={cn(
+ 'border-b-border-muted border-b border-l-4 bg-studio group-hover:bg-surface-100/50',
+ borderColorClass
+ )}
+ style={{ paddingLeft: `${16 + indentPx + 32}px` }}
+ >
+ <div className="px-4 py-3 space-y-2 font-mono text-xs">
+ {detailLines.map((line, idx) => (
+ <div key={idx} className="flex items-start gap-1">
+ {line.label && <span className="text-foreground-muted">{line.label}</span>}
+ <span className="text-foreground-light break-all">{line.value}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Render children recursively */}
+ {hasChildren &&
+ node.children.map((child, idx) => (
+ <ExplainNodeRow key={idx} node={child} depth={depth + 1} maxDuration={maxDuration} />
+ ))}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx
index f3d56f240e6..166d726427d 100644
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx
@@ -7,151 +7,9 @@ interface RowCountIndicatorProps {
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.`
+function formatRowCount(rows: number | undefined): string {
+ if (rows === undefined) return '-'
+ return rows.toLocaleString()
}
export function RowCountIndicator({
@@ -159,31 +17,78 @@ export function RowCountIndicator({
estimatedRows,
rowsRemovedByFilter,
}: RowCountIndicatorProps) {
- const hasData = actualRows !== undefined || estimatedRows !== undefined
- if (!hasData) return undefined
-
- const hasFilterData = rowsRemovedByFilter !== undefined && actualRows !== undefined
+ const hasActualRows = actualRows !== undefined
+ const hasEstimatedRows = estimatedRows !== undefined
+ const hasFilterData = rowsRemovedByFilter !== undefined && hasActualRows
const totalRowsScanned = hasFilterData ? actualRows + rowsRemovedByFilter : undefined
- // Priority 1: Show filter flow if we have filter data
+ // Show filter flow: scanned → filtered out → remaining
if (hasFilterData && totalRowsScanned !== undefined) {
return (
- <FilterFlowIndicator
- totalRowsScanned={totalRowsScanned}
- rowsRemovedByFilter={rowsRemovedByFilter}
- actualRows={actualRows}
- />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center gap-1.5 cursor-help">
+ <span className="text-foreground-light">{formatRowCount(totalRowsScanned)}</span>
+ <ArrowRight size={10} className="text-foreground-muted" />
+ <span className="text-destructive-600 font-medium">
+ -{formatRowCount(rowsRemovedByFilter)}
+ </span>
+ <ArrowRight size={10} className="text-foreground-muted" />
+ <span className="text-brand font-medium">
+ {formatRowCount(actualRows)} {actualRows === 1 ? 'row' : 'rows'}
+ </span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-xs font-sans">
+ <p className="font-medium">Filter applied</p>
+ <p className="text-foreground-lighter text-xs mt-1">
+ {formatRowCount(totalRowsScanned)} rows were scanned,{' '}
+ {formatRowCount(rowsRemovedByFilter)} were filtered out, leaving{' '}
+ {formatRowCount(actualRows)} rows. Consider adding an index to reduce rows scanned.
+ </p>
+ </TooltipContent>
+ </Tooltip>
)
}
- // Priority 2: Show simple count if estimate matches actual exactly
- const estimateMatchesActual =
- actualRows !== undefined && estimatedRows !== undefined && actualRows === estimatedRows
+ // Simple row count with actual rows
+ if (hasActualRows) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-foreground-light cursor-help">
+ {formatRowCount(actualRows)} {actualRows === 1 ? 'row' : 'rows'}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-xs font-sans">
+ <p className="font-medium">Rows returned</p>
+ <p className="text-foreground-lighter text-xs mt-1">
+ This operation processed and returned {formatRowCount(actualRows)} rows.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ )
+ }
- if (estimateMatchesActual) {
- return <SimpleCountIndicator rows={actualRows} />
+ // Only estimated rows available (EXPLAIN without ANALYZE)
+ if (hasEstimatedRows) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="text-foreground-muted cursor-help">
+ est. {formatRowCount(estimatedRows)} {estimatedRows === 1 ? 'row' : 'rows'}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-xs font-sans">
+ <p className="font-medium">Estimated rows</p>
+ <p className="text-foreground-lighter text-xs mt-1">
+ The planner estimates this operation will return {formatRowCount(estimatedRows)} rows.
+ Run with EXPLAIN ANALYZE to see actual row counts.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ )
}
- // Priority 3: Show comparison view
- return <ComparisonIndicator actualRows={actualRows} estimatedRows={estimatedRows} />
+ return <span className="text-foreground-muted">-</span>
}
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts
index 155c8c12697..35c5d4bea66 100644
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.parser.ts
@@ -217,14 +217,28 @@ function addNodeToTree(
}
// Calculate max cost for scaling the visualization bars
-function getNodeMax(node: ExplainNode): number {
+function getNodeMaxCost(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)
+ const childrenMax = node.children.reduce((max, child) => Math.max(max, getNodeMaxCost(child)), 0)
return Math.max(nodeCost, childrenMax)
}
export function calculateMaxCost(tree: ExplainNode[]): number {
- return tree.reduce((max, node) => Math.max(max, getNodeMax(node)), 0)
+ return tree.reduce((max, node) => Math.max(max, getNodeMaxCost(node)), 0)
+}
+
+// Calculate max duration across all nodes for scaling the visualization bars
+function getNodeMaxDuration(node: ExplainNode): number {
+ const nodeDuration = node.actualTime ? node.actualTime.end - node.actualTime.start : 0
+ const childrenMax = node.children.reduce(
+ (max, child) => Math.max(max, getNodeMaxDuration(child)),
+ 0
+ )
+ return Math.max(nodeDuration, childrenMax)
+}
+
+export function calculateMaxDuration(tree: ExplainNode[]): number {
+ return tree.reduce((max, node) => Math.max(max, getNodeMaxDuration(node)), 0)
}
// Calculate summary stats
@@ -266,3 +280,25 @@ export function createNodeTree(rows: readonly QueryPlanRow[]): ExplainNode[] {
tree.forEach(parseNodeDetails)
return tree
}
+
+export function parseDetailLines(details: string): { label: string; value: string }[] {
+ if (!details) return []
+
+ const lines = details.split('\n').filter(Boolean)
+ const result: { label: string; value: string }[] = []
+
+ for (const line of lines) {
+ const colonIndex = line.indexOf(':')
+ if (colonIndex > 0) {
+ result.push({
+ label: line.substring(0, colonIndex + 1),
+ value: line.substring(colonIndex + 1).trim(),
+ })
+ } else if (line.trim()) {
+ // Lines without colons (like table names)
+ result.push({ label: '', value: line.trim() })
+ }
+ }
+
+ return result
+}
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx
index 28642532e61..df339cd52dc 100644
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx
@@ -1,7 +1,7 @@
import { useMemo } from 'react'
import { ExplainHeader } from './ExplainVisualizer.Header'
-import { ExplainNodeRenderer } from './ExplainVisualizer.NodeRenderer'
-import { calculateMaxCost, calculateSummary, createNodeTree } from './ExplainVisualizer.parser'
+import { ExplainNodeRow } from './ExplainVisualizer.NodeRow'
+import { calculateMaxDuration, calculateSummary, createNodeTree } from './ExplainVisualizer.parser'
import type { QueryPlanRow } from './ExplainVisualizer.types'
export interface ExplainVisualizerProps {
@@ -11,12 +11,12 @@ export interface ExplainVisualizerProps {
export function ExplainVisualizer({ rows, onShowRaw }: ExplainVisualizerProps) {
const parsedTree = useMemo(() => createNodeTree(rows), [rows])
- const maxCost = useMemo(() => calculateMaxCost(parsedTree), [parsedTree])
+ const maxDuration = useMemo(() => calculateMaxDuration(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">
+ <div className="bg-studio border-t">
<p className="m-0 border-0 px-4 py-3 font-mono text-sm text-foreground-light">
No execution plan data available
</p>
@@ -25,14 +25,16 @@ export function ExplainVisualizer({ rows, onShowRaw }: ExplainVisualizerProps) {
}
return (
- <div className="bg-studio border-t h-full flex flex-col">
+ <div className="bg-studio border-t h-full flex flex-col min-h-0">
{onShowRaw && <ExplainHeader mode="visual" onToggleMode={onShowRaw} summary={summary} />}
- {/* Tree visualization */}
- <div className="p-4 pb-10 overflow-auto flex-1">
- {parsedTree.map((node, idx) => (
- <ExplainNodeRenderer key={idx} node={node} depth={0} maxCost={maxCost} isRoot={true} />
- ))}
+ {/* Plan nodes */}
+ <div className="flex-1 overflow-auto min-h-0">
+ <div className="flex flex-col min-w-max pb-4">
+ {parsedTree.map((node, idx) => (
+ <ExplainNodeRow key={idx} node={node} depth={0} maxDuration={maxDuration} />
+ ))}
+ </div>
</div>
</div>
)
diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts
index f1a731f095c..b44e2797a8b 100644
--- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts
+++ b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils.ts
@@ -131,3 +131,57 @@ export function isExplainQuery(rows: readonly any[]): boolean {
rows.length > 0 && rows[0].hasOwnProperty('QUERY PLAN') && Object.keys(rows[0]).length === 1
)
}
+
+export function formatNodeDuration(ms: number | undefined): string {
+ if (ms === undefined) return '-'
+ if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`
+ if (ms >= 1) return `${ms.toFixed(2)}ms`
+ if (ms >= 0.01) return `${ms.toFixed(2)}ms`
+ if (ms >= 0.001) return `${ms.toFixed(3)}ms`
+
+ const us = ms * 1000
+ if (us >= 0.1) return `${us.toFixed(1)}µs`
+ return `${us.toFixed(2)}µs`
+}
+
+export function getScanBarColor(operation: string): string {
+ const op = operation.toLowerCase()
+
+ // Index scans are green
+ if (
+ op.includes('index scan') ||
+ op.includes('index only scan') ||
+ op.includes('bitmap index scan')
+ ) {
+ return 'bg-brand/20'
+ }
+
+ // Sequential scans are yellow
+ if (op.includes('seq scan') || op.includes('sequential scan')) {
+ return 'bg-warning/20'
+ }
+
+ // Default neutral color for other operations
+ return 'bg-foreground/[0.06]'
+}
+
+export function getScanBorderColor(operation: string): string {
+ const op = operation.toLowerCase()
+
+ // Index scans are green
+ if (
+ op.includes('index scan') ||
+ op.includes('index only scan') ||
+ op.includes('bitmap index scan')
+ ) {
+ return 'border-l-brand'
+ }
+
+ // Sequential scans are yellow
+ if (op.includes('seq scan') || op.includes('sequential scan')) {
+ return 'border-l-warning'
+ }
+
+ // Default neutral color for other operations
+ return 'border-l-border-muted'
+}