mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 16:09:06 +00:00
Deprecate query insights UI (#54522)
## Context Just reviving this [PR here](https://github.com/supabase/supabase/pull/48794?from=linear) which deprecates the Query Insights UI - there's a lot of conflicts on that one so just making a new one instead. No visible changes from a user's POV on the dashboard
This commit is contained in:
1 parent
6d14282357
commit
6de989cc78
51 files changed
+224
-4063
No files matched your search
@@ -249,7 +249,6 @@
|
||||
"components/interfaces/ProjectAPIDocs/ProjectAPIDocs.constants.ts": 2,
|
||||
"components/interfaces/ProjectAPIDocs/ResourceContent.tsx": 1,
|
||||
"components/interfaces/ProjectCreation/PostgresVersionSelector.tsx": 2,
|
||||
"components/interfaces/QueryInsights/QueryInsights.types.ts": 1,
|
||||
"components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/IndexAdvisor/IndexAdvisorDisabledState.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils.ts": 2,
|
||||
@@ -736,8 +735,6 @@
|
||||
"components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.tsx": 1,
|
||||
"components/interfaces/Platform/Webhooks/PlatformWebhooksPage.tsx": 1,
|
||||
"components/interfaces/ProjectAPIDocs/SecondLevelNav.Layout.tsx": 1,
|
||||
"components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx": 1,
|
||||
"components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/components/FilterInput.tsx": 1,
|
||||
"components/interfaces/Realtime/Inspector/ChooseChannelPopover.tsx": 1,
|
||||
@@ -873,8 +870,6 @@
|
||||
"components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails.tsx": 1,
|
||||
"components/interfaces/ProjectHome/HighAvailabilityBadge.tsx": 5,
|
||||
"components/interfaces/ProjectHome/ServerLightGrid.tsx": 1,
|
||||
"components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.tsx": 2,
|
||||
"components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx": 2,
|
||||
"components/interfaces/Realtime/Inspector/RealtimeFilterPopover/index.tsx": 1,
|
||||
"components/interfaces/Reports/ReportBlock/ChartBlock.tsx": 2,
|
||||
"components/interfaces/Reports/ReportFilterBar.tsx": 3,
|
||||
@@ -1072,7 +1067,6 @@
|
||||
"components/interfaces/Integrations/CronJobs/CronJobsTab.useCleanupActions.ts": 2,
|
||||
"components/interfaces/Integrations/GraphQL/useSetIntrospection.ts": 1,
|
||||
"components/interfaces/Linter/GraphqlExposureLintCTA.tsx": 1,
|
||||
"components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils.ts": 1,
|
||||
"components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx": 1,
|
||||
"components/interfaces/QueryPerformance/useQueryPerformanceQuery.ts": 1,
|
||||
@@ -1203,7 +1197,6 @@
|
||||
"data/database/retrieve-index-from-select-query.ts": 2,
|
||||
"data/database/schema-create-mutation.ts": 1,
|
||||
"data/database/schemas-query.ts": 1,
|
||||
"data/database/supamonitor-enabled-query.ts": 1,
|
||||
"data/database/table-columns-query.ts": 1,
|
||||
"data/database/table-definition-query.ts": 1,
|
||||
"data/database/table-index-advisor-query.ts": 1,
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
import { CodeIcon, EyeIcon, HelpCircleIcon } from 'lucide-react'
|
||||
import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
|
||||
|
||||
import { buildExplainPrompt } from './ExplainVisualizer.ai'
|
||||
import type { QueryPlanRow } from './ExplainVisualizer.types'
|
||||
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
|
||||
import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
|
||||
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
|
||||
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
|
||||
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
|
||||
|
||||
export interface ExplainSummary {
|
||||
totalTime: number
|
||||
hasSeqScan: boolean
|
||||
hasIndexScan: boolean
|
||||
}
|
||||
|
||||
export interface ExplainHeaderProps {
|
||||
mode: 'visual' | 'raw'
|
||||
onToggleMode: () => void
|
||||
summary?: ExplainSummary
|
||||
id?: string
|
||||
rows?: readonly QueryPlanRow[]
|
||||
}
|
||||
|
||||
export function ExplainHeader({ mode, onToggleMode, summary, id, rows }: ExplainHeaderProps) {
|
||||
const isVisual = mode === 'visual'
|
||||
|
||||
const snapV2 = useSqlEditorV2StateSnapshot()
|
||||
const { openSidebar } = useSidebarManagerSnapshot()
|
||||
const aiSnap = useAiAssistantStateSnapshot()
|
||||
|
||||
const getPromptData = () => {
|
||||
if (!id) return null
|
||||
const snippet = snapV2.snippets[id]?.snippet
|
||||
if (!snippet?.content?.unchecked_sql) return null
|
||||
|
||||
return buildExplainPrompt({
|
||||
sql: snippet.content.unchecked_sql,
|
||||
explainPlanRows: (rows as QueryPlanRow[]) ?? [],
|
||||
})
|
||||
}
|
||||
|
||||
const handleExplainWithAI = () => {
|
||||
const promptData = getPromptData()
|
||||
if (!promptData) return
|
||||
|
||||
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
|
||||
aiSnap.newChat({
|
||||
sqlSnippets: [
|
||||
{
|
||||
label: 'Query',
|
||||
content: promptData.query,
|
||||
},
|
||||
],
|
||||
initialMessage: promptData.prompt,
|
||||
})
|
||||
}
|
||||
|
||||
const buildPromptForCopy = () => {
|
||||
const promptData = getPromptData()
|
||||
if (!promptData) return ''
|
||||
|
||||
// Combine SQL and prompt into a single copyable text
|
||||
return `${promptData.prompt}\n\nSQL Query:\n\`\`\`sql\n${promptData.query}\n\`\`\``
|
||||
}
|
||||
|
||||
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 justify-between text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="font-medium text-foreground">Query Execution Plan</h3>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<HelpCircleIcon
|
||||
size="14"
|
||||
strokeWidth={2}
|
||||
className="text-foreground-lighter hover:text-foreground-light transition-colors cursor-help"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" className="max-w-xs p-4">
|
||||
<h3 className="text-xs font-medium mb-2">How to read</h3>
|
||||
<p className="text-foreground-light text-xs">
|
||||
Start at the bottom where data is read from tables, then follow upward as each step
|
||||
processes the results.
|
||||
</p>
|
||||
|
||||
{isVisual && (
|
||||
<>
|
||||
<h3 className="text-xs font-medium mt-4 mb-2">Key</h3>
|
||||
<div className="flex flex-col gap-1 text-foreground-light">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="inline-block w-1.5 h-1.5 rounded-full bg-warning" />
|
||||
<span>Seq Scan (slow)</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="inline-block w-1.5 h-1.5 rounded-full bg-primary-bright" />
|
||||
<span>Index Scan (fast)</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
{/* 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-2">
|
||||
<span className="text-foreground-muted">/</span>
|
||||
<span className="text-foreground-light">Total time</span>
|
||||
<span className="font-medium text-foreground">
|
||||
{summary.totalTime.toFixed(2)}ms
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{id && rows && (
|
||||
<AiAssistantDropdown
|
||||
label="Explain with AI"
|
||||
buildPrompt={buildPromptForCopy}
|
||||
onOpenAssistant={handleExplainWithAI}
|
||||
telemetrySource="explain_visualizer"
|
||||
size="tiny"
|
||||
variant="default"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
size="tiny"
|
||||
icon={isVisual ? <CodeIcon size={14} /> : <EyeIcon size={14} />}
|
||||
onClick={onToggleMode}
|
||||
>
|
||||
{isVisual ? 'Raw' : 'Visual'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
|
||||
|
||||
import { parseDetailLines } from './ExplainVisualizer.parser'
|
||||
import { RowCountIndicator } from './ExplainVisualizer.RowCountIndicator'
|
||||
import type { ExplainNode } from './ExplainVisualizer.types'
|
||||
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-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"
|
||||
tabIndex={canExpand ? 0 : -1}
|
||||
onClick={() => canExpand && setIsExpanded(!isExpanded)}
|
||||
disabled={!canExpand}
|
||||
className={cn(
|
||||
'flex items-center justify-center w-5 h-5 rounded-sm 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 ? (
|
||||
<ChevronDownIcon size={12} className="text-foreground-light" />
|
||||
) : (
|
||||
<ChevronRightIcon 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) ?? <span>-</span>}
|
||||
<span>, estimated</span> {node.rows?.toLocaleString() ?? <span>?</span>}{' '}
|
||||
{node.rows === 1 ? <span>row</span> : <span>rows</span>}
|
||||
<span>)</span>
|
||||
</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-t-border-muted border-t border-l-4 bg-studio group-hover:bg-surface-100/50',
|
||||
borderColorClass
|
||||
)}
|
||||
style={{ paddingLeft: `${16 + indentPx + 32}px` }}
|
||||
>
|
||||
<div className="px-0 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} />
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
import { ArrowRightIcon } from 'lucide-react'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
|
||||
|
||||
interface RowCountIndicatorProps {
|
||||
actualRows?: number
|
||||
estimatedRows?: number
|
||||
rowsRemovedByFilter?: number
|
||||
}
|
||||
|
||||
function formatRowCount(rows: number | undefined): string {
|
||||
if (rows === undefined) return '-'
|
||||
return rows.toLocaleString()
|
||||
}
|
||||
|
||||
export function RowCountIndicator({
|
||||
actualRows,
|
||||
estimatedRows,
|
||||
rowsRemovedByFilter,
|
||||
}: RowCountIndicatorProps) {
|
||||
const hasActualRows = actualRows !== undefined
|
||||
const hasEstimatedRows = estimatedRows !== undefined
|
||||
const hasFilterData = rowsRemovedByFilter !== undefined && hasActualRows
|
||||
const totalRowsScanned = hasFilterData ? actualRows + rowsRemovedByFilter : undefined
|
||||
|
||||
// Show filter flow: scanned → filtered out → remaining
|
||||
if (hasFilterData && totalRowsScanned !== undefined) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex items-center gap-1.5 cursor-help">
|
||||
<span className="text-foreground-light">{formatRowCount(totalRowsScanned)}</span>
|
||||
<ArrowRightIcon size={10} className="text-foreground-muted" />
|
||||
<span className="text-destructive-600 font-medium">
|
||||
-{formatRowCount(rowsRemovedByFilter)}
|
||||
</span>
|
||||
<ArrowRightIcon size={10} className="text-foreground-muted" />
|
||||
<span className="text-primary font-medium">
|
||||
{formatRowCount(actualRows)} {actualRows === 1 ? <span>row</span> : <span>rows</span>}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
// Simple row count with actual rows
|
||||
if (hasActualRows) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="text-foreground-light cursor-help">
|
||||
{formatRowCount(actualRows)} {actualRows === 1 ? <span>row</span> : <span>rows</span>}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 ? <span>row</span> : <span>rows</span>}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
return <span className="text-foreground-muted">-</span>
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import type { QueryPlanRow } from './ExplainVisualizer.types'
|
||||
|
||||
export interface ExplainPromptInput {
|
||||
sql: string
|
||||
explainPlanRows: QueryPlanRow[]
|
||||
}
|
||||
|
||||
export interface ExplainPromptOutput {
|
||||
query: string
|
||||
prompt: string
|
||||
}
|
||||
|
||||
export function buildExplainPrompt({
|
||||
sql,
|
||||
explainPlanRows,
|
||||
}: ExplainPromptInput): ExplainPromptOutput {
|
||||
const explainPlan = explainPlanRows.map((row) => row['QUERY PLAN']).join('\n')
|
||||
|
||||
const prompt = `Explain this PostgreSQL EXPLAIN ANALYZE output in simple terms:
|
||||
|
||||
\`\`\`sql
|
||||
${sql}
|
||||
\`\`\`
|
||||
|
||||
\`\`\`
|
||||
${explainPlan}
|
||||
\`\`\`
|
||||
|
||||
Format your response with:
|
||||
|
||||
**What it does** - 1-2 sentences.
|
||||
|
||||
**How it runs** - Briefly explain the plan from bottom to top in plain English. Mention key operations (scans, joins, sorts) and why PostgreSQL chose them.
|
||||
|
||||
**Issues** - Identify bottlenecks: slowest steps, sequential scans on large tables, inefficient joins, missing indexes. Be specific with timings from the plan.
|
||||
|
||||
**Fixes** - 2-3 specific suggestions with CREATE INDEX statements if applicable.
|
||||
|
||||
Keep it concise. Focus on actionable insights.`
|
||||
|
||||
return {
|
||||
query: sql,
|
||||
prompt,
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import { ExplainHeader } from './ExplainVisualizer.Header'
|
||||
import { ExplainNodeRow } from './ExplainVisualizer.NodeRow'
|
||||
import { calculateMaxDuration, calculateSummary, createNodeTree } from './ExplainVisualizer.parser'
|
||||
import type { QueryPlanRow } from './ExplainVisualizer.types'
|
||||
|
||||
export interface ExplainVisualizerProps {
|
||||
rows: readonly QueryPlanRow[]
|
||||
onShowRaw?: () => void
|
||||
id?: string
|
||||
}
|
||||
|
||||
export function ExplainVisualizer({ rows, onShowRaw, id }: ExplainVisualizerProps) {
|
||||
const parsedTree = useMemo(() => createNodeTree(rows), [rows])
|
||||
const maxDuration = useMemo(() => calculateMaxDuration(parsedTree), [parsedTree])
|
||||
const summary = useMemo(() => calculateSummary(parsedTree), [parsedTree])
|
||||
|
||||
if (parsedTree.length === 0) {
|
||||
return (
|
||||
<div className="bg-studio">
|
||||
<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 h-full flex flex-col min-h-0">
|
||||
{onShowRaw && (
|
||||
<ExplainHeader
|
||||
mode="visual"
|
||||
onToggleMode={onShowRaw}
|
||||
summary={summary}
|
||||
id={id}
|
||||
rows={rows}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Plan nodes */}
|
||||
<div className="flex-1 overflow-auto min-h-0">
|
||||
<div className="flex flex-col min-w-max pb-1 divide-y divide-border-muted">
|
||||
{parsedTree.map((node, idx) => (
|
||||
<ExplainNodeRow key={idx} node={node} depth={0} maxDuration={maxDuration} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { DOCS_URL } from '@/lib/constants'
|
||||
export const OBSERVABILITY_DOCS_HREFS = {
|
||||
overview: `${DOCS_URL}/guides/telemetry/reports`,
|
||||
queryPerformance: `${DOCS_URL}/guides/platform/performance#examining-query-performance`,
|
||||
queryInsights: `${DOCS_URL}/guides/platform/performance#examining-query-performance`,
|
||||
apiGateway: `${DOCS_URL}/guides/telemetry/reports#api-gateway`,
|
||||
database: `${DOCS_URL}/guides/telemetry/reports#database`,
|
||||
dataApi: `${DOCS_URL}/guides/telemetry/reports#postgrest`,
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
export const SUPAMONITOR_EXCLUDED_ROLES = [
|
||||
'supabase_admin',
|
||||
'supabase_auth_admin',
|
||||
'supabase_storage_admin',
|
||||
'supabase_realtime_admin',
|
||||
'pgbouncer',
|
||||
'dashboard_user',
|
||||
] as const
|
||||
|
||||
export const SUPAMONITOR_EXCLUDED_APP_NAMES = ['supabase-dashboard', 'mgmt-api'] as const
|
||||
|
||||
export const TRANSACTION_CONTROL_REGEX =
|
||||
/^\s*(BEGIN|COMMIT|ROLLBACK|SET\s|RESET\s|DISCARD|DEALLOCATE|SHOW\s)/i
|
||||
|
||||
export const SCHEMA_INTROSPECTION_REGEX =
|
||||
/\bFROM\s+(?:pg_catalog\.|information_schema\.|pg_class\b|pg_attribute\b|pg_type\b|pg_namespace\b)/i
|
||||
|
||||
export const getSupamonitorLogsQuery = (startTime: string, endTime: string) => {
|
||||
// Validate and canonicalize to ISO 8601 UTC before embedding in SQL.
|
||||
// new Date().toISOString() throws RangeError on invalid input and always
|
||||
// produces "YYYY-MM-DDTHH:mm:ss.mmmZ" which contains no SQL special characters.
|
||||
const safeStart = new Date(startTime).toISOString()
|
||||
const safeEnd = new Date(endTime).toISOString()
|
||||
|
||||
return `
|
||||
-- This query is run by Supabase Query Insights to aggregate pg_stat_statements
|
||||
-- data collected by the supamonitor extension. It reads from Logflare and groups
|
||||
-- execution metrics (timing, call counts, percentiles) by query and minute so
|
||||
-- the dashboard can surface slow queries, high-call patterns, and planning overhead.
|
||||
-- If you see this query in your logs, it is a read-only analytics query and safe to ignore.
|
||||
select
|
||||
TIMESTAMP_TRUNC(sml.timestamp, MINUTE) as timestamp,
|
||||
CAST(sml_parsed.application_name AS STRING) as application_name,
|
||||
SUM(sml_parsed.calls) as calls,
|
||||
CAST(sml_parsed.database_name AS STRING) as database_name,
|
||||
CAST(sml_parsed.query AS STRING) as query,
|
||||
sml_parsed.query_id as query_id,
|
||||
SUM(sml_parsed.total_exec_time) as total_exec_time,
|
||||
SUM(sml_parsed.total_plan_time) as total_plan_time,
|
||||
CAST(sml_parsed.user_name AS STRING) as user_name,
|
||||
CASE WHEN SUM(sml_parsed.calls) > 0
|
||||
THEN SUM(sml_parsed.total_exec_time) / SUM(sml_parsed.calls)
|
||||
ELSE 0
|
||||
END as mean_exec_time,
|
||||
MIN(NULLIF(sml_parsed.total_exec_time, 0)) as min_exec_time,
|
||||
MAX(sml_parsed.total_exec_time) as max_exec_time,
|
||||
CASE WHEN SUM(sml_parsed.calls) > 0
|
||||
THEN SUM(sml_parsed.total_plan_time) / SUM(sml_parsed.calls)
|
||||
ELSE 0
|
||||
END as mean_plan_time,
|
||||
MIN(NULLIF(sml_parsed.total_plan_time, 0)) as min_plan_time,
|
||||
MAX(sml_parsed.total_plan_time) as max_plan_time,
|
||||
APPROX_QUANTILES(sml_parsed.total_exec_time, 100)[OFFSET(50)] as p50_exec_time,
|
||||
APPROX_QUANTILES(sml_parsed.total_exec_time, 100)[OFFSET(95)] as p95_exec_time,
|
||||
APPROX_QUANTILES(sml_parsed.total_plan_time, 100)[OFFSET(50)] as p50_plan_time,
|
||||
APPROX_QUANTILES(sml_parsed.total_plan_time, 100)[OFFSET(95)] as p95_plan_time
|
||||
from supamonitor_logs as sml
|
||||
cross join unnest(sml.metadata) as sml_metadata
|
||||
cross join unnest(sml_metadata.supamonitor) as sml_parsed
|
||||
WHERE sml.event_message = 'log'
|
||||
AND sml.timestamp >= CAST('${safeStart}' AS TIMESTAMP)
|
||||
AND sml.timestamp <= CAST('${safeEnd}' AS TIMESTAMP)
|
||||
GROUP BY timestamp, user_name, database_name, application_name, query_id, query
|
||||
ORDER BY timestamp DESC
|
||||
`.trim()
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import { useParams } from 'common'
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import { useMemo, useState } from 'react'
|
||||
|
||||
import { useSupamonitorIndexAdvisor } from './hooks/useSupamonitorIndexAdvisor'
|
||||
import { getSupamonitorLogsQuery } from './QueryInsights.constants'
|
||||
import { QueryInsightsChart } from './QueryInsightsChart/QueryInsightsChart'
|
||||
import { QueryInsightsHealth } from './QueryInsightsHealth/QueryInsightsHealth'
|
||||
import { QueryInsightsTable } from './QueryInsightsTable/QueryInsightsTable'
|
||||
import {
|
||||
aggregateLogsByQuery,
|
||||
filterSystemLogs,
|
||||
parseSupamonitorLogs,
|
||||
transformLogsToChartData,
|
||||
} from './utils/supamonitor.utils'
|
||||
import { useLogsQuery } from '@/hooks/analytics/useLogsQuery'
|
||||
|
||||
dayjs.extend(utc)
|
||||
|
||||
interface QueryInsightsProps {
|
||||
dateRange?: {
|
||||
period_start: { date: string; time_period: string }
|
||||
period_end: { date: string; time_period: string }
|
||||
interval: string
|
||||
}
|
||||
}
|
||||
|
||||
export const QueryInsights = ({ dateRange }: QueryInsightsProps) => {
|
||||
const { ref } = useParams()
|
||||
|
||||
const effectiveDateRange = useMemo(() => {
|
||||
if (dateRange) {
|
||||
return {
|
||||
iso_timestamp_start: dateRange.period_start.date,
|
||||
iso_timestamp_end: dateRange.period_end.date,
|
||||
}
|
||||
}
|
||||
const end = dayjs.utc()
|
||||
const start = end.subtract(1, 'hour')
|
||||
return {
|
||||
iso_timestamp_start: start.toISOString(),
|
||||
iso_timestamp_end: end.toISOString(),
|
||||
}
|
||||
}, [dateRange])
|
||||
|
||||
const sql = useMemo(
|
||||
() =>
|
||||
getSupamonitorLogsQuery(
|
||||
effectiveDateRange.iso_timestamp_start,
|
||||
effectiveDateRange.iso_timestamp_end
|
||||
),
|
||||
[effectiveDateRange]
|
||||
)
|
||||
|
||||
const { logData, isLoading } = useLogsQuery({
|
||||
projectRef: ref as string,
|
||||
initialParams: {
|
||||
sql,
|
||||
iso_timestamp_start: effectiveDateRange.iso_timestamp_start,
|
||||
iso_timestamp_end: effectiveDateRange.iso_timestamp_end,
|
||||
},
|
||||
})
|
||||
|
||||
const [selectedQuery, setSelectedQuery] = useState<string | null>(null)
|
||||
|
||||
const parsedLogs = useMemo(() => parseSupamonitorLogs(logData || []), [logData])
|
||||
const filteredLogs = useMemo(() => filterSystemLogs(parsedLogs), [parsedLogs])
|
||||
const chartData = useMemo(() => transformLogsToChartData(filteredLogs), [filteredLogs])
|
||||
const selectedChartData = useMemo(
|
||||
() =>
|
||||
selectedQuery
|
||||
? transformLogsToChartData(
|
||||
filteredLogs.filter((log) => log.query?.replace(/\s+/g, ' ').trim() === selectedQuery)
|
||||
)
|
||||
: undefined,
|
||||
[filteredLogs, selectedQuery]
|
||||
)
|
||||
const aggregatedData = useMemo(() => aggregateLogsByQuery(filteredLogs), [filteredLogs])
|
||||
const enrichedData = useSupamonitorIndexAdvisor(aggregatedData)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<QueryInsightsHealth data={enrichedData} isLoading={isLoading} />
|
||||
<QueryInsightsChart
|
||||
chartData={chartData}
|
||||
selectedChartData={selectedChartData}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<QueryInsightsTable
|
||||
data={enrichedData}
|
||||
isLoading={isLoading}
|
||||
currentSelectedQuery={selectedQuery}
|
||||
onCurrentSelectQuery={setSelectedQuery}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import type { SafeSqlFragment } from '@supabase/pg-meta'
|
||||
|
||||
export interface ChartDataPoint {
|
||||
period_start: number
|
||||
timestamp: string
|
||||
query_latency: number
|
||||
mean_time: number
|
||||
min_time: number
|
||||
max_time: number
|
||||
stddev_time: number
|
||||
p50_time: number
|
||||
p95_time: number
|
||||
rows_read: number
|
||||
calls: number
|
||||
cache_hits: number
|
||||
cache_misses: number
|
||||
}
|
||||
|
||||
export interface ParsedLogEntry {
|
||||
timestamp?: string
|
||||
application_name?: string
|
||||
calls?: number
|
||||
database_name?: string
|
||||
query?: SafeSqlFragment
|
||||
query_id?: number
|
||||
total_exec_time?: number
|
||||
total_plan_time?: number
|
||||
user_name?: string
|
||||
mean_exec_time?: number
|
||||
mean_plan_time?: number
|
||||
min_exec_time?: number
|
||||
max_exec_time?: number
|
||||
min_plan_time?: number
|
||||
max_plan_time?: number
|
||||
p50_exec_time?: number
|
||||
p95_exec_time?: number
|
||||
p50_plan_time?: number
|
||||
p95_plan_time?: number
|
||||
[key: string]: any
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
import { CHART_COLORS } from '@/components/ui/Charts/Charts.constants'
|
||||
|
||||
export const CHART_TABS = [
|
||||
{ id: 'query_latency', label: 'Query latency' },
|
||||
{ id: 'rows_read', label: 'Rows read' },
|
||||
{ id: 'calls', label: 'Calls' },
|
||||
{ id: 'cache_hits', label: 'Cache hits' },
|
||||
]
|
||||
|
||||
export const LEGEND_ITEMS: Record<string, { label: string; color: string; dataKey: string }[]> = {
|
||||
query_latency: [
|
||||
{ label: 'P50', color: 'var(--chart-4)', dataKey: 'p50' },
|
||||
{ label: 'P95', color: CHART_COLORS.GREEN_1, dataKey: 'p95' },
|
||||
],
|
||||
rows_read: [{ label: 'Rows Read', color: CHART_COLORS.GREEN_1, dataKey: 'rows_read' }],
|
||||
calls: [{ label: 'Calls', color: CHART_COLORS.GREEN_1, dataKey: 'calls' }],
|
||||
cache_hits: [{ label: 'Cache Hits', color: '#10B981', dataKey: 'cache_hits' }],
|
||||
}
|
||||
|
||||
export const CHART_TYPE = 'linear'
|
||||
|
||||
export const SEL_COLOR = 'var(--chart-2)'
|
||||
-262
@@ -1,262 +0,0 @@
|
||||
import { Loader2Icon } from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { useMemo, useState } from 'react'
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
CartesianGrid,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts'
|
||||
import { cn, Tabs, TabsContent, TabsList, TabsTrigger } from 'ui'
|
||||
|
||||
import type { ChartDataPoint } from '../QueryInsights.types'
|
||||
import { CHART_TABS, CHART_TYPE, LEGEND_ITEMS, SEL_COLOR } from './QueryInsightsChart.constants'
|
||||
import { formatTime } from './QueryInsightsChart.utils'
|
||||
import { QueryInsightsChartTooltip } from './QueryInsightsChartTooltip'
|
||||
|
||||
interface QueryInsightsChartProps {
|
||||
chartData: ChartDataPoint[]
|
||||
selectedChartData?: ChartDataPoint[]
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export const QueryInsightsChart = ({
|
||||
chartData,
|
||||
selectedChartData,
|
||||
isLoading,
|
||||
}: QueryInsightsChartProps) => {
|
||||
const [selectedMetric, setSelectedMetric] = useState('query_latency')
|
||||
const [hiddenSeries, setHiddenSeries] = useState<Set<string>>(new Set())
|
||||
const { resolvedTheme } = useTheme()
|
||||
const isDarkMode = resolvedTheme?.includes('dark')
|
||||
|
||||
const data = useMemo(() => {
|
||||
const normalize = (ts: number) => (ts > 1e13 ? Math.floor(ts / 1000) : ts)
|
||||
const selByTime = new Map((selectedChartData ?? []).map((d) => [normalize(d.period_start), d]))
|
||||
|
||||
return chartData.map((d) => {
|
||||
const t = normalize(d.period_start)
|
||||
const sel = selByTime.get(t)
|
||||
return {
|
||||
time: t,
|
||||
p50: d.p50_time,
|
||||
p95: d.p95_time,
|
||||
rows_read: d.rows_read,
|
||||
calls: d.calls,
|
||||
cache_hits: d.cache_hits,
|
||||
sel_p50: sel?.p50_time,
|
||||
sel_rows_read: sel?.rows_read,
|
||||
sel_calls: sel?.calls,
|
||||
sel_cache_hits: sel?.cache_hits,
|
||||
}
|
||||
})
|
||||
}, [chartData, selectedChartData])
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (hiddenSeries.size === 0) return data
|
||||
return data.map((point) => {
|
||||
const filtered = { ...point } as Record<string, number | undefined>
|
||||
hiddenSeries.forEach((key) => {
|
||||
filtered[key] = undefined
|
||||
})
|
||||
return filtered
|
||||
})
|
||||
}, [data, hiddenSeries])
|
||||
|
||||
const toggleSeries = (dataKey: string) => {
|
||||
setHiddenSeries((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(dataKey)) {
|
||||
next.delete(dataKey)
|
||||
} else {
|
||||
next.add(dataKey)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const hasSelection = !!selectedChartData && selectedChartData.length > 0
|
||||
const selDataKey = selectedMetric === 'query_latency' ? 'sel_p50' : `sel_${selectedMetric}`
|
||||
const legendItems = LEGEND_ITEMS[selectedMetric] ?? []
|
||||
|
||||
return (
|
||||
<div className="bg-surface-100 border-b min-h-[320px]">
|
||||
<Tabs value={selectedMetric} onValueChange={setSelectedMetric} className="w-full">
|
||||
<TabsList className="flex justify-start rounded-none gap-x-4 border-b mt-0! pt-0 px-6">
|
||||
{CHART_TABS.map((tab) => (
|
||||
<TabsTrigger
|
||||
key={tab.id}
|
||||
value={tab.id}
|
||||
className="flex items-center gap-2 text-xs py-3 border-b font-mono uppercase"
|
||||
>
|
||||
{tab.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value={selectedMetric} className="bg-surface-100 mt-0">
|
||||
<div className="w-full gap-4 mt-4 px-6 flex items-center justify-end">
|
||||
{legendItems.map((item: { dataKey: string; label: string; color: string }) => (
|
||||
<button
|
||||
key={item.dataKey}
|
||||
type="button"
|
||||
tabIndex={0}
|
||||
onClick={() => toggleSeries(item.dataKey)}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 text-[11px] transition-colors cursor-pointer',
|
||||
!hiddenSeries.has(item.dataKey)
|
||||
? 'text-foreground hover:text-foreground-light'
|
||||
: 'text-foreground-muted'
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'h-1.5 w-1.5 rounded-full transition-opacity',
|
||||
hiddenSeries.has(item.dataKey) && 'opacity-30'
|
||||
)}
|
||||
style={{ backgroundColor: item.color }}
|
||||
/>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
{hasSelection && (
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={0}
|
||||
onClick={() => toggleSeries(selDataKey)}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 text-[11px] transition-colors cursor-pointer',
|
||||
!hiddenSeries.has(selDataKey)
|
||||
? 'text-foreground hover:text-foreground-light'
|
||||
: 'text-foreground-muted'
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'h-1.5 w-1.5 rounded-xs transition-opacity',
|
||||
hiddenSeries.has(selDataKey) && 'opacity-30'
|
||||
)}
|
||||
style={{ backgroundColor: SEL_COLOR }}
|
||||
/>
|
||||
Selected query
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-full py-4 flex flex-col">
|
||||
<div className="w-full h-[180px] px-0">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<Loader2Icon size={20} className="animate-spin text-foreground-lighter" />
|
||||
</div>
|
||||
) : data.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<p className="text-sm text-foreground-lighter">No data available</p>
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={filteredData} margin={{ top: 4, left: 0, right: 0, bottom: 4 }}>
|
||||
<defs>
|
||||
{legendItems.map((item) => (
|
||||
<linearGradient
|
||||
key={`gradient-${item.dataKey}`}
|
||||
id={`gradient-${item.dataKey}`}
|
||||
x1="0"
|
||||
y1="0"
|
||||
x2="0"
|
||||
y2="1"
|
||||
>
|
||||
<stop offset="0%" stopColor={item.color} stopOpacity={0.15} />
|
||||
<stop offset="100%" stopColor={item.color} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
))}
|
||||
{hasSelection && (
|
||||
<linearGradient id={`gradient-${selDataKey}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={SEL_COLOR} stopOpacity={0.35} />
|
||||
<stop offset="100%" stopColor={SEL_COLOR} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
)}
|
||||
</defs>
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
tick={false}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: 'var(--border-default)' }}
|
||||
height={1}
|
||||
/>
|
||||
<YAxis
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fontSize: 10, fill: 'var(--foreground-muted)' }}
|
||||
tickCount={3}
|
||||
width={40}
|
||||
orientation="left"
|
||||
tickFormatter={(v) =>
|
||||
selectedMetric === 'query_latency'
|
||||
? `${Math.round(v)}ms`
|
||||
: `${Math.round(v)}`
|
||||
}
|
||||
mirror={true}
|
||||
/>
|
||||
<Tooltip
|
||||
content={<QueryInsightsChartTooltip />}
|
||||
cursor={{
|
||||
stroke: isDarkMode ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)',
|
||||
strokeWidth: 1,
|
||||
}}
|
||||
/>
|
||||
<CartesianGrid
|
||||
horizontal={true}
|
||||
vertical={false}
|
||||
stroke="var(--border-default)"
|
||||
strokeOpacity={0.5}
|
||||
/>
|
||||
{legendItems.map((item) => (
|
||||
<Area
|
||||
key={item.dataKey}
|
||||
type={CHART_TYPE}
|
||||
dataKey={item.dataKey}
|
||||
stroke={item.color}
|
||||
strokeWidth={1}
|
||||
fill={`url(#gradient-${item.dataKey})`}
|
||||
dot={false}
|
||||
name={item.label}
|
||||
strokeOpacity={
|
||||
!hiddenSeries.has(item.dataKey) ? (hasSelection ? 0.2 : 1) : 0
|
||||
}
|
||||
fillOpacity={!hiddenSeries.has(item.dataKey) ? (hasSelection ? 0.2 : 1) : 0}
|
||||
/>
|
||||
))}
|
||||
{hasSelection && (
|
||||
<Area
|
||||
type={CHART_TYPE}
|
||||
dataKey={selDataKey}
|
||||
stroke={SEL_COLOR}
|
||||
strokeWidth={1}
|
||||
fill={`url(#gradient-${selDataKey})`}
|
||||
dot={false}
|
||||
name="Selected query"
|
||||
connectNulls={false}
|
||||
strokeOpacity={!hiddenSeries.has(selDataKey) ? 1 : 0}
|
||||
fillOpacity={!hiddenSeries.has(selDataKey) ? 1 : 0}
|
||||
/>
|
||||
)}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.length > 0 && (
|
||||
<div className="flex justify-between text-xs text-foreground-lighter pt-2 px-6">
|
||||
<span>{formatTime(data[0].time)}</span>
|
||||
<span>{formatTime(data[data.length - 1].time)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { formatTime, isTimeMetric } from './QueryInsightsChart.utils'
|
||||
|
||||
describe('isTimeMetric', () => {
|
||||
it('returns true for p50 and p95', () => {
|
||||
expect(isTimeMetric('p50')).toBe(true)
|
||||
expect(isTimeMetric('p95')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for other keys', () => {
|
||||
expect(isTimeMetric('calls')).toBe(false)
|
||||
expect(isTimeMetric('count')).toBe(false)
|
||||
expect(isTimeMetric('')).toBe(false)
|
||||
expect(isTimeMetric('P50')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatTime', () => {
|
||||
it('formats a timestamp to include the month and day', () => {
|
||||
const ts = new Date('2024-06-01T10:00:00Z').getTime()
|
||||
const result = formatTime(ts)
|
||||
expect(result).toMatch(/Jun/)
|
||||
expect(result).toMatch(/1/)
|
||||
})
|
||||
})
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
export const isTimeMetric = (dataKey: string) => dataKey.endsWith('p50') || dataKey.endsWith('p95')
|
||||
|
||||
export const formatTime = (value: number) => {
|
||||
const d = new Date(value)
|
||||
return d.toLocaleString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
import dayjs from 'dayjs'
|
||||
import type { TooltipProps } from 'recharts'
|
||||
|
||||
import { formatDuration } from '../QueryInsightsTable/QueryInsightsTable.utils'
|
||||
import { isTimeMetric } from './QueryInsightsChart.utils'
|
||||
import { guessLocalTimezone } from '@/lib/dayjs'
|
||||
|
||||
export const QueryInsightsChartTooltip = ({ active, payload }: TooltipProps<number, string>) => {
|
||||
if (!active || !payload?.length) return null
|
||||
|
||||
const time = payload[0]?.payload?.time
|
||||
const localTimeZone = guessLocalTimezone()
|
||||
|
||||
return (
|
||||
<div className="grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg px-2.5 py-1.5 text-xs shadow-xl">
|
||||
<p className="text-foreground-light text-xs">{localTimeZone}</p>
|
||||
<p className="font-medium">{dayjs(time).format('MMM D, hh:mm:ssa')}</p>
|
||||
<div className="grid gap-0">
|
||||
{payload.map((entry, index) => (
|
||||
<div key={`${entry.name}-${index}`} className="flex items-center w-full">
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<circle cx="5" cy="5" r="3" fill={entry.color} />
|
||||
</svg>
|
||||
<span className="text-foreground-lighter ml-1 grow">{entry.name}</span>
|
||||
<span className="ml-3.5">
|
||||
{typeof entry.value === 'number'
|
||||
? isTimeMetric(typeof entry.dataKey === 'string' ? entry.dataKey : '')
|
||||
? formatDuration(entry.value)
|
||||
: entry.value.toLocaleString()
|
||||
: entry.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
import type { HealthLevel } from './QueryInsightsHealth.types'
|
||||
|
||||
export const SLOW_QUERY_THRESHOLD_MS = 200
|
||||
export const HIGH_CALL_THRESHOLD = 100
|
||||
|
||||
export const SCORE_DEDUCTIONS = {
|
||||
error: 20,
|
||||
indexHighCalls: 15,
|
||||
indexLowCalls: 8,
|
||||
slowHighCalls: 10,
|
||||
slowLowCalls: 5,
|
||||
} as const
|
||||
|
||||
export const HEALTH_LEVELS: Record<HealthLevel, { label: string; min: number }> = {
|
||||
healthy: { label: 'Healthy', min: 70 },
|
||||
warning: { label: 'Needs attention', min: 40 },
|
||||
critical: { label: 'Critical', min: 0 },
|
||||
}
|
||||
|
||||
export const HEALTH_COLORS: Record<HealthLevel, string> = {
|
||||
healthy: 'hsl(var(--brand-default))',
|
||||
warning: 'var(--warning)',
|
||||
critical: 'hsl(var(--destructive-default))',
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import { useQueryInsightsIssues } from '../hooks/useQueryInsightsIssues'
|
||||
import { useQueryInsightsMetrics } from '../hooks/useQueryInsightsMetrics'
|
||||
import { useQueryInsightsScore } from '../hooks/useQueryInsightsScore'
|
||||
import { HEALTH_COLORS, HEALTH_LEVELS } from './QueryInsightsHealth.constants'
|
||||
import { QueryInsightsHealthMetric } from './QueryInsightsHealthMetric'
|
||||
import { QueryInsightsHealthScore } from './QueryInsightsHealthScore'
|
||||
import { QueryInsightsHealthScoreSkeleton } from './QueryInsightsHealthScoreSkeleton'
|
||||
|
||||
interface QueryInsightsHealthProps {
|
||||
data: QueryPerformanceRow[]
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export const QueryInsightsHealth = ({ data, isLoading }: QueryInsightsHealthProps) => {
|
||||
const { errors, indexIssues, slowQueries } = useQueryInsightsIssues(data)
|
||||
const { score, level } = useQueryInsightsScore({ errors, indexIssues, slowQueries })
|
||||
const { avgP95, totalCalls, totalRowsRead, cacheHitRate } = useQueryInsightsMetrics(data)
|
||||
|
||||
const color = HEALTH_COLORS[level]
|
||||
const label = HEALTH_LEVELS[level].label
|
||||
|
||||
return (
|
||||
<div className="w-full border-b flex items-center">
|
||||
<div className="px-6 py-3 flex items-center gap-3">
|
||||
{isLoading ? (
|
||||
<QueryInsightsHealthScoreSkeleton />
|
||||
) : (
|
||||
<QueryInsightsHealthScore score={score} color={color} label={label} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 border-l h-full">
|
||||
<div className="grid grid-cols-2">
|
||||
<QueryInsightsHealthMetric
|
||||
label="Average P95"
|
||||
value={`${avgP95}ms`}
|
||||
className="border-b"
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<QueryInsightsHealthMetric
|
||||
label="Total Calls"
|
||||
value={totalCalls.toLocaleString()}
|
||||
className="border-l border-b"
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<QueryInsightsHealthMetric
|
||||
label="Total Rows Read"
|
||||
value={totalRowsRead.toLocaleString()}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<QueryInsightsHealthMetric
|
||||
label="Cache Hit Rate"
|
||||
value={cacheHitRate}
|
||||
className="border-l"
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
|
||||
export type IssueType = 'error' | 'index' | 'slow' | null
|
||||
|
||||
export type HealthLevel = 'healthy' | 'warning' | 'critical'
|
||||
|
||||
export interface ClassifiedQuery extends QueryPerformanceRow {
|
||||
issueType: IssueType
|
||||
hint: string
|
||||
queryType: string | null
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { getHealthLevel } from './QueryInsightsHealth.utils'
|
||||
|
||||
describe('getHealthLevel', () => {
|
||||
it('returns healthy for scores >= 70', () => {
|
||||
expect(getHealthLevel(100)).toBe('healthy')
|
||||
expect(getHealthLevel(70)).toBe('healthy')
|
||||
})
|
||||
|
||||
it('returns warning for scores between 40 and 69', () => {
|
||||
expect(getHealthLevel(69)).toBe('warning')
|
||||
expect(getHealthLevel(40)).toBe('warning')
|
||||
})
|
||||
|
||||
it('returns critical for scores below 40', () => {
|
||||
expect(getHealthLevel(39)).toBe('critical')
|
||||
expect(getHealthLevel(0)).toBe('critical')
|
||||
})
|
||||
})
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
import { HEALTH_LEVELS } from './QueryInsightsHealth.constants'
|
||||
import type { HealthLevel } from './QueryInsightsHealth.types'
|
||||
|
||||
export const getHealthLevel = (score: number): HealthLevel => {
|
||||
if (score >= HEALTH_LEVELS.healthy.min) return 'healthy'
|
||||
if (score >= HEALTH_LEVELS.warning.min) return 'warning'
|
||||
return 'critical'
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
import { cn } from 'ui'
|
||||
|
||||
interface QueryInsightsHealthMetricProps {
|
||||
label: string
|
||||
value: number | string | undefined
|
||||
className?: string
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
export const QueryInsightsHealthMetric = ({
|
||||
label,
|
||||
value,
|
||||
className,
|
||||
isLoading,
|
||||
}: QueryInsightsHealthMetricProps) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'font-mono text-xs flex items-center justify-between px-4 py-2 h-10',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className="text-foreground-lighter tracking-wider truncate uppercase">{label}</span>
|
||||
{isLoading ? (
|
||||
<div className="h-3 w-12 rounded-sm bg-surface-300 animate-pulse" />
|
||||
) : (
|
||||
<span className="text-foreground font-medium tabular-nums">{value}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
export const QueryInsightsHealthScore = ({
|
||||
score,
|
||||
color,
|
||||
label,
|
||||
}: {
|
||||
score: number
|
||||
color: string
|
||||
label: string
|
||||
}) => (
|
||||
<>
|
||||
<div
|
||||
className="h-12 w-12 rounded-full flex items-center justify-center"
|
||||
style={{
|
||||
background: `conic-gradient(${color} ${score * 3.6}deg, var(--border-default) ${score * 3.6}deg)`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="h-10 w-10 rounded-full bg-studio flex items-center justify-center text-base font-medium"
|
||||
style={{ color }}
|
||||
>
|
||||
{score}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-foreground-lighter uppercase font-mono tracking-wider">
|
||||
Health Score
|
||||
</span>
|
||||
<span className="text-xl text-foreground-light" style={{ color }}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
export const QueryInsightsHealthScoreSkeleton = () => (
|
||||
<>
|
||||
<div className="h-12 w-12 rounded-full bg-surface-300 animate-pulse" />
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="h-3 w-20 rounded-sm bg-surface-300 animate-pulse" />
|
||||
<div className="h-5 w-24 rounded-sm bg-surface-300 animate-pulse" />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
import { Loader2Icon } from 'lucide-react'
|
||||
import {
|
||||
AiIconAnimation,
|
||||
Button,
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetTitle,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from 'ui'
|
||||
|
||||
import { QueryDetail } from '../../QueryPerformance/QueryDetail'
|
||||
import { QueryIndexes } from '../../QueryPerformance/QueryIndexes'
|
||||
import { buildExplainOptimizationPrompt } from '../../QueryPerformance/QueryPerformance.ai'
|
||||
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import { ExplainVisualizer } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer'
|
||||
import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
|
||||
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
|
||||
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
|
||||
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
|
||||
|
||||
interface QueryInsightsDetailSheetProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
activeSheetRow: ClassifiedQuery | undefined
|
||||
sheetView: 'details' | 'indexes' | 'explain'
|
||||
onSheetViewChange: (view: 'details' | 'indexes' | 'explain') => void
|
||||
onClose: () => void
|
||||
dataGridContainerRef: React.RefObject<HTMLDivElement | null>
|
||||
triageContainerRef: React.RefObject<HTMLDivElement | null>
|
||||
explainLoadingQuery: string | null
|
||||
explainResults: Record<string, QueryPlanRow[]>
|
||||
}
|
||||
|
||||
export const QueryInsightsDetailSheet = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
activeSheetRow,
|
||||
sheetView,
|
||||
onSheetViewChange,
|
||||
onClose,
|
||||
dataGridContainerRef,
|
||||
triageContainerRef,
|
||||
explainLoadingQuery,
|
||||
explainResults,
|
||||
}: QueryInsightsDetailSheetProps) => {
|
||||
const { openSidebar } = useSidebarManagerSnapshot()
|
||||
const aiSnap = useAiAssistantStateSnapshot()
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange} modal={false}>
|
||||
<SheetTitle className="sr-only">Query details</SheetTitle>
|
||||
<SheetDescription className="sr-only">Query Insights Details & Indexes</SheetDescription>
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="flex flex-col h-full bg-studio border-l lg:w-[calc(100vw-802px)]! max-w-[700px] w-full"
|
||||
hasOverlay={false}
|
||||
onInteractOutside={(event) => {
|
||||
if (
|
||||
dataGridContainerRef.current?.contains(event.target as Node) ||
|
||||
triageContainerRef.current?.contains(event.target as Node)
|
||||
) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
value={sheetView}
|
||||
className="flex flex-col h-full"
|
||||
onValueChange={(v) => onSheetViewChange(v as 'details' | 'indexes' | 'explain')}
|
||||
>
|
||||
<div className="px-5 border-b">
|
||||
<TabsList className="px-0 flex gap-x-4 min-h-[46px] border-b-0 [&>button]:h-[47px]">
|
||||
<TabsTrigger
|
||||
value="details"
|
||||
className="px-0 pb-0 data-[state=active]:bg-transparent shadow-none!"
|
||||
>
|
||||
Query details
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="indexes"
|
||||
className="px-0 pb-0 data-[state=active]:bg-transparent shadow-none!"
|
||||
>
|
||||
Indexes
|
||||
</TabsTrigger>
|
||||
{activeSheetRow?.issueType !== 'error' && (
|
||||
<TabsTrigger
|
||||
value="explain"
|
||||
className="px-0 pb-0 data-[state=active]:bg-transparent shadow-none!"
|
||||
>
|
||||
Explain
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
</div>
|
||||
<TabsContent value="details" className="mt-0 grow min-h-0 overflow-y-auto">
|
||||
{activeSheetRow && (
|
||||
<QueryDetail
|
||||
selectedRow={activeSheetRow}
|
||||
onClickViewSuggestion={() => onSheetViewChange('indexes')}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="indexes" className="mt-0 grow min-h-0 overflow-y-auto">
|
||||
{activeSheetRow && <QueryIndexes selectedRow={activeSheetRow} />}
|
||||
</TabsContent>
|
||||
<TabsContent value="explain" className="mt-0 grow min-h-0 flex flex-col overflow-hidden">
|
||||
{explainLoadingQuery ? (
|
||||
<div className="px-6 py-4 flex items-center gap-2 text-sm text-foreground-light">
|
||||
<Loader2Icon size={14} className="animate-spin" /> Running EXPLAIN ANALYZE...
|
||||
</div>
|
||||
) : activeSheetRow && explainResults[activeSheetRow.query]?.length > 0 ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between px-5 py-2 border-b shrink-0">
|
||||
<p className="text-xs text-foreground-lighter">EXPLAIN ANALYZE output</p>
|
||||
<Button
|
||||
size="tiny"
|
||||
icon={<AiIconAnimation size={14} />}
|
||||
onClick={() => {
|
||||
const rows = explainResults[activeSheetRow.query]
|
||||
const { query, prompt } = buildExplainOptimizationPrompt(
|
||||
activeSheetRow.query,
|
||||
rows,
|
||||
{
|
||||
mean_time: activeSheetRow.mean_time,
|
||||
calls: activeSheetRow.calls,
|
||||
total_time: activeSheetRow.total_time,
|
||||
}
|
||||
)
|
||||
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
|
||||
aiSnap.newChat({
|
||||
sqlSnippets: [{ label: 'Query', content: query }],
|
||||
initialMessage: prompt,
|
||||
})
|
||||
}}
|
||||
>
|
||||
Optimize with AI
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
<ExplainVisualizer rows={explainResults[activeSheetRow.query]} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="px-6 py-4 text-sm text-foreground-lighter">
|
||||
No explain results available.
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
import { CircleAlertIcon, LightbulbIcon } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
|
||||
export const ISSUE_DOT_COLORS: Record<
|
||||
string,
|
||||
{ border: string; background: string; color: string }
|
||||
> = {
|
||||
error: {
|
||||
border: 'border-destructive-500',
|
||||
background: 'bg-destructive-200',
|
||||
color: 'text-destructive-600',
|
||||
},
|
||||
index: {
|
||||
border: 'border-warning-500',
|
||||
background: 'bg-warning-200',
|
||||
color: 'text-warning-600',
|
||||
},
|
||||
slow: {
|
||||
border: 'border-strong',
|
||||
background: 'bg-alternative dark:bg-muted',
|
||||
color: 'text-foreground-lighter',
|
||||
},
|
||||
}
|
||||
|
||||
export const ISSUE_ICONS: Record<string, LucideIcon> = {
|
||||
error: CircleAlertIcon,
|
||||
index: LightbulbIcon,
|
||||
slow: CircleAlertIcon,
|
||||
}
|
||||
|
||||
export const QUERY_INSIGHTS_EXPLORER_COLUMNS = [
|
||||
{ id: 'query', name: 'Query', description: undefined, minWidth: 500 },
|
||||
{ id: 'prop_total_time', name: 'Time consumed', description: undefined, minWidth: 150 },
|
||||
{ id: 'calls', name: 'Calls', description: undefined, minWidth: 100 },
|
||||
{ id: 'max_time', name: 'Max time', description: undefined, minWidth: 100 },
|
||||
{ id: 'mean_time', name: 'Mean time', description: undefined, minWidth: 100 },
|
||||
{ id: 'min_time', name: 'Min time', description: undefined, minWidth: 100 },
|
||||
{ id: 'rows_read', name: 'Rows processed', description: undefined, minWidth: 130 },
|
||||
{ id: 'cache_hit_rate', name: 'Cache hit rate', description: undefined, minWidth: 130 },
|
||||
{ id: 'rolname', name: 'Role', description: undefined, minWidth: 200 },
|
||||
{ id: 'application_name', name: 'Source', description: undefined, minWidth: 200 },
|
||||
] as const
|
||||
|
||||
export const NON_SORTABLE_COLUMNS = [] as const
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
import { createRootRoute, createRoute } from '@tanstack/react-router'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { QueryInsightsTable } from './QueryInsightsTable'
|
||||
import { NuqsAdapter } from '@/lib/nuqs-tanstack-adapter'
|
||||
import { createTestRouter, customRender } from '@/tests/lib/custom-render'
|
||||
import { addAPIMock } from '@/tests/lib/msw'
|
||||
|
||||
class MockIntersectionObserver implements IntersectionObserver {
|
||||
readonly root = null
|
||||
readonly rootMargin = ''
|
||||
readonly scrollMargin = ''
|
||||
readonly thresholds = []
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords(): IntersectionObserverEntry[] {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function createQueryInsightsRouter(initialEntry: string) {
|
||||
const rootRoute = createRootRoute()
|
||||
const queryInsightsRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/project/$ref/observability/query-insights',
|
||||
})
|
||||
const postgresLogsRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/project/$ref/logs/postgres-logs',
|
||||
})
|
||||
|
||||
return createTestRouter(
|
||||
initialEntry,
|
||||
rootRoute.addChildren([queryInsightsRoute, postgresLogsRoute])
|
||||
)
|
||||
}
|
||||
|
||||
function mockProjectEndpoint() {
|
||||
addAPIMock({
|
||||
method: 'get',
|
||||
path: '/platform/projects/:ref',
|
||||
response: {
|
||||
cloud_provider: 'AWS',
|
||||
db_host: 'db.default.supabase.co',
|
||||
high_availability: false,
|
||||
id: 1,
|
||||
inserted_at: '2026-01-01T00:00:00Z',
|
||||
integration_source: null,
|
||||
is_branch_enabled: false,
|
||||
is_physical_backups_enabled: false,
|
||||
name: 'Test project',
|
||||
organization_id: 1,
|
||||
ref: 'default',
|
||||
region: 'us-east-1',
|
||||
restUrl: 'https://default.supabase.co',
|
||||
status: 'ACTIVE_HEALTHY',
|
||||
subscription_id: 'subscription-1',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
connectionString: 'postgresql://postgres:password@localhost:5432/postgres',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('QueryInsightsTable route change handling', () => {
|
||||
it('clears selected query on pathname change without mutating destination or history search params', async () => {
|
||||
mockProjectEndpoint()
|
||||
const onCurrentSelectQuery = vi.fn()
|
||||
const router = createQueryInsightsRouter(
|
||||
'/project/default/observability/query-insights?search=select'
|
||||
)
|
||||
await router.load()
|
||||
|
||||
customRender(
|
||||
<NuqsAdapter>
|
||||
<QueryInsightsTable
|
||||
data={[]}
|
||||
isLoading={false}
|
||||
currentSelectedQuery="SELECT 1"
|
||||
onCurrentSelectQuery={onCurrentSelectQuery}
|
||||
/>
|
||||
</NuqsAdapter>,
|
||||
{ router }
|
||||
)
|
||||
|
||||
// Same pathname with updated search params should not reset selection
|
||||
await act(async () => {
|
||||
await router.navigate({
|
||||
to: '/project/$ref/observability/query-insights',
|
||||
params: { ref: 'default' },
|
||||
search: { search: 'select', sort: 'calls' } as never,
|
||||
})
|
||||
})
|
||||
|
||||
expect(onCurrentSelectQuery).not.toHaveBeenCalled()
|
||||
expect(router.state.location.search).toEqual({ search: 'select', sort: 'calls' })
|
||||
|
||||
// Navigating to a different pathname should clear selection without clobbering destination search params
|
||||
await act(async () => {
|
||||
await router.navigate({
|
||||
to: '/project/$ref/logs/postgres-logs',
|
||||
params: { ref: 'default' },
|
||||
search: { search: 'from-logs' } as never,
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => expect(onCurrentSelectQuery).toHaveBeenCalledWith(null))
|
||||
expect(router.state.location.search).toEqual({ search: 'from-logs' })
|
||||
|
||||
// Navigating back preserves the previous history entry's search params
|
||||
await act(async () => {
|
||||
router.history.back()
|
||||
await router.load()
|
||||
})
|
||||
|
||||
await waitFor(() =>
|
||||
expect(router.state.location.pathname).toBe('/project/default/observability/query-insights')
|
||||
)
|
||||
expect(router.state.location.search).toEqual({ search: 'select', sort: 'calls' })
|
||||
})
|
||||
})
|
||||
-577
@@ -1,577 +0,0 @@
|
||||
import { safeSql, type SafeSqlFragment } from '@supabase/pg-meta'
|
||||
import { wrapWithRollback } from '@supabase/pg-meta/src/query'
|
||||
import { useLocation, useNavigate } from '@tanstack/react-router'
|
||||
import { useParams } from 'common'
|
||||
import { SearchIcon, TextSearchIcon, XIcon } from 'lucide-react'
|
||||
import { parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import DataGrid, { DataGridHandle, Row } from 'react-data-grid'
|
||||
import { Button, cn, FloatingPlate, Tabs, TabsList, TabsTrigger } from 'ui'
|
||||
import { Input } from 'ui-patterns/DataInputs/Input'
|
||||
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
|
||||
|
||||
import { buildQueryInsightFixPrompt } from '../../QueryPerformance/QueryPerformance.ai'
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import { useQueryInsightsIssues } from '../hooks/useQueryInsightsIssues'
|
||||
import { useQueryInsightsTableColumns } from '../hooks/useQueryInsightsTableColumns'
|
||||
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import { QueryInsightsDetailSheet } from './QueryInsightsDetailSheet'
|
||||
import type { IssueFilter, Mode } from './QueryInsightsTable.types'
|
||||
import {
|
||||
formatDuration,
|
||||
getColumnName,
|
||||
getQueryType,
|
||||
getTableName,
|
||||
} from './QueryInsightsTable.utils'
|
||||
import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
|
||||
import { FilterPill } from '@/components/interfaces/QueryPerformance/components/FilterPill'
|
||||
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
|
||||
import { FilterPopover } from '@/components/ui/FilterPopover'
|
||||
import { TwoOptionToggle } from '@/components/ui/TwoOptionToggle'
|
||||
import { isUserFaultForStatsStatement } from '@/data/database/pg-stat-statements-sqlstate'
|
||||
import { unguarded } from '@/data/fetchers'
|
||||
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
|
||||
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
||||
import { navigateToUrl } from '@/lib/navigation'
|
||||
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
|
||||
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
|
||||
|
||||
interface QueryInsightsTableProps {
|
||||
data: QueryPerformanceRow[]
|
||||
isLoading: boolean
|
||||
currentSelectedQuery?: string | null
|
||||
onCurrentSelectQuery?: (query: string | null) => void
|
||||
}
|
||||
|
||||
export const QueryInsightsTable = ({
|
||||
data,
|
||||
isLoading,
|
||||
currentSelectedQuery,
|
||||
onCurrentSelectQuery,
|
||||
}: QueryInsightsTableProps) => {
|
||||
const [mode, setMode] = useState<Mode>('triage')
|
||||
const [filter, setFilter] = useState<IssueFilter>('all')
|
||||
const [
|
||||
{ search: urlSearch, sort: urlSortCol, order: urlSortOrder, source: urlSource },
|
||||
setQueryStates,
|
||||
] = useQueryStates({
|
||||
search: parseAsString.withDefault(''),
|
||||
sort: parseAsString,
|
||||
order: parseAsString,
|
||||
source: parseAsArrayOf(parseAsString).withDefault([]),
|
||||
})
|
||||
const searchQuery = urlSearch
|
||||
const setSearchQuery = useCallback(
|
||||
(value: string) => setQueryStates({ search: value || null }),
|
||||
[setQueryStates]
|
||||
)
|
||||
const appNameFilter = urlSource
|
||||
const setAppNameFilter = (names: string[]) =>
|
||||
setQueryStates({ source: names.length ? names : null })
|
||||
|
||||
const appNameOptions = useMemo(() => {
|
||||
const names = Array.from(
|
||||
new Set(data.map((r) => r.application_name).filter(Boolean))
|
||||
) as string[]
|
||||
return names.map((name) => ({ value: name, label: name }))
|
||||
}, [data])
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
if (appNameFilter.length === 0) return data
|
||||
return data.filter((r) => appNameFilter.includes(r.application_name ?? ''))
|
||||
}, [data, appNameFilter])
|
||||
|
||||
const { classified, errors, indexIssues, slowQueries } = useQueryInsightsIssues(filteredData)
|
||||
const [selectedRow, setSelectedRow] = useState<number>()
|
||||
const [selectedTriageRow, setSelectedTriageRow] = useState<number | undefined>()
|
||||
const [sheetView, setSheetView] = useState<'details' | 'indexes' | 'explain'>('details')
|
||||
const gridRef = useRef<DataGridHandle>(null)
|
||||
const triageGridRef = useRef<DataGridHandle>(null)
|
||||
const dataGridContainerRef = useRef<HTMLDivElement>(null)
|
||||
const triageContainerRef = useRef<HTMLDivElement>(null)
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||
const [triageContainerWidth, setTriageContainerWidth] = useState(0)
|
||||
const sort = useMemo<{ column: string; order: 'asc' | 'desc' }>(
|
||||
() =>
|
||||
urlSortCol && urlSortOrder && ['asc', 'desc'].includes(urlSortOrder)
|
||||
? { column: urlSortCol, order: urlSortOrder as 'asc' | 'desc' }
|
||||
: { column: 'prop_total_time', order: 'desc' },
|
||||
[urlSortCol, urlSortOrder]
|
||||
)
|
||||
const setSort = useCallback(
|
||||
(config: { column: string; order: 'asc' | 'desc' } | null) =>
|
||||
setQueryStates(
|
||||
config ? { sort: config.column, order: config.order } : { sort: null, order: null }
|
||||
),
|
||||
[setQueryStates]
|
||||
)
|
||||
|
||||
const [explainResults, setExplainResults] = useState<Record<string, QueryPlanRow[]>>({})
|
||||
const [explainLoadingQuery, setExplainLoadingQuery] = useState<string | null>(null)
|
||||
|
||||
const { ref } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const pathname = useLocation({ select: (location) => location.pathname })
|
||||
const { openSidebar } = useSidebarManagerSnapshot()
|
||||
const aiSnap = useAiAssistantStateSnapshot()
|
||||
|
||||
const { data: project } = useSelectedProjectQuery()
|
||||
|
||||
const { mutate: executeExplain } = useExecuteSqlMutation()
|
||||
|
||||
const triageItems = useMemo(() => classified.filter((q) => q.issueType !== null), [classified])
|
||||
|
||||
const filteredTriageItems = useMemo(() => {
|
||||
const filtered =
|
||||
filter === 'all' ? triageItems : triageItems.filter((q) => q.issueType === filter)
|
||||
return filtered.map((item) => ({
|
||||
...item,
|
||||
queryType: getQueryType(item.query),
|
||||
}))
|
||||
}, [triageItems, filter])
|
||||
|
||||
const explorerItems = useMemo(() => {
|
||||
let items = [...classified]
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
const searchLower = searchQuery.toLowerCase()
|
||||
items = items.filter((item) => {
|
||||
const queryType = getQueryType(item.query) ?? ''
|
||||
const tableName = getTableName(item.query) ?? ''
|
||||
const columnName = getColumnName(item.query) ?? ''
|
||||
const appName = item.application_name ?? ''
|
||||
const query = item.query ?? ''
|
||||
|
||||
return (
|
||||
queryType.toLowerCase().includes(searchLower) ||
|
||||
tableName.toLowerCase().includes(searchLower) ||
|
||||
columnName.toLowerCase().includes(searchLower) ||
|
||||
appName.toLowerCase().includes(searchLower) ||
|
||||
query.toLowerCase().includes(searchLower)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (sort) {
|
||||
items.sort((a, b) => {
|
||||
if (sort.column === 'query') {
|
||||
const aDate = a.first_seen ? new Date(a.first_seen).getTime() : 0
|
||||
const bDate = b.first_seen ? new Date(b.first_seen).getTime() : 0
|
||||
return sort.order === 'asc' ? aDate - bDate : bDate - aDate
|
||||
}
|
||||
|
||||
const aValue: unknown = a[sort.column as keyof typeof a]
|
||||
const bValue: unknown = b[sort.column as keyof typeof b]
|
||||
|
||||
if (typeof aValue === 'number' && typeof bValue === 'number') {
|
||||
return sort.order === 'asc' ? aValue - bValue : bValue - aValue
|
||||
}
|
||||
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
return items
|
||||
}, [classified, searchQuery, sort])
|
||||
|
||||
const activeSheetRow: ClassifiedQuery | undefined = useMemo(() => {
|
||||
if (mode === 'triage') {
|
||||
return selectedTriageRow !== undefined ? filteredTriageItems[selectedTriageRow] : undefined
|
||||
}
|
||||
return selectedRow !== undefined ? (explorerItems[selectedRow] as ClassifiedQuery) : undefined
|
||||
}, [mode, selectedTriageRow, selectedRow, filteredTriageItems, explorerItems])
|
||||
|
||||
const runExplain = useCallback(
|
||||
(query: SafeSqlFragment) => {
|
||||
if (explainResults[query]) return
|
||||
if (explainLoadingQuery) return
|
||||
const requestQuery = query
|
||||
setExplainLoadingQuery(requestQuery)
|
||||
executeExplain(
|
||||
{
|
||||
projectRef: project?.ref,
|
||||
connectionString: project?.connectionString,
|
||||
sql: wrapWithRollback(safeSql`EXPLAIN ANALYZE ${requestQuery}`),
|
||||
// The query text comes from pg_stat_statements, so the user wrote it
|
||||
sqlOrigin: 'studio',
|
||||
queryName: 'query-insights-explain',
|
||||
isUserFaultSqlState: isUserFaultForStatsStatement,
|
||||
grant: unguarded.migrating,
|
||||
},
|
||||
{
|
||||
onSuccess(data) {
|
||||
setExplainResults((prev) => ({ ...prev, [requestQuery]: data.result }))
|
||||
setExplainLoadingQuery(null)
|
||||
},
|
||||
onError() {
|
||||
setExplainLoadingQuery(null)
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
[explainResults, explainLoadingQuery, executeExplain, project]
|
||||
)
|
||||
|
||||
const handleGoToLogs = useCallback(() => {
|
||||
navigateToUrl(navigate, `/project/${ref}/logs/postgres-logs`)
|
||||
}, [navigate, ref])
|
||||
|
||||
const handleAiSuggestedFix = useCallback(
|
||||
(item: ClassifiedQuery) => {
|
||||
const { query, prompt } = buildQueryInsightFixPrompt(item)
|
||||
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
|
||||
aiSnap.newChat({
|
||||
sqlSnippets: [{ label: 'Query', content: query }],
|
||||
initialMessage: prompt,
|
||||
})
|
||||
},
|
||||
[openSidebar, aiSnap]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (sheetView === 'explain' && activeSheetRow?.query) {
|
||||
runExplain(activeSheetRow.query)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sheetView, activeSheetRow?.query])
|
||||
|
||||
const prevPathnameRef = useRef(pathname)
|
||||
useEffect(() => {
|
||||
if (prevPathnameRef.current !== pathname) {
|
||||
prevPathnameRef.current = pathname
|
||||
onCurrentSelectQuery?.(null)
|
||||
}
|
||||
}, [pathname, onCurrentSelectQuery])
|
||||
|
||||
const timeConsumedWidth = useMemo(() => {
|
||||
if (!explorerItems.length) return 150
|
||||
let maxWidth = 150
|
||||
explorerItems.forEach((row) => {
|
||||
const pct = row.prop_total_time || 0
|
||||
const total = row.total_time || 0
|
||||
if (pct && total) {
|
||||
const text = `${pct.toFixed(1)}% / ${formatDuration(total)}`
|
||||
maxWidth = Math.max(maxWidth, text.length * 8 + 40)
|
||||
}
|
||||
})
|
||||
return Math.min(maxWidth, 300)
|
||||
}, [explorerItems])
|
||||
|
||||
const triageQueryColWidth = useMemo(() => {
|
||||
if (!triageContainerWidth) return 380
|
||||
const fixed = timeConsumedWidth + 100 + 300 + 4
|
||||
return Math.max(380, triageContainerWidth - fixed - 120)
|
||||
}, [triageContainerWidth, timeConsumedWidth])
|
||||
|
||||
const { columns, triageColumns } = useQueryInsightsTableColumns({
|
||||
sort,
|
||||
setSort,
|
||||
timeConsumedWidth,
|
||||
triageQueryColWidth,
|
||||
gridRef,
|
||||
setSelectedRow,
|
||||
setSelectedTriageRow,
|
||||
setSheetView,
|
||||
handleGoToLogs,
|
||||
handleAiSuggestedFix,
|
||||
})
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (!explorerItems.length || selectedRow === undefined) return
|
||||
|
||||
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return
|
||||
|
||||
event.stopPropagation()
|
||||
|
||||
let nextIndex = selectedRow
|
||||
if (event.key === 'ArrowUp' && selectedRow > 0) {
|
||||
nextIndex = selectedRow - 1
|
||||
} else if (event.key === 'ArrowDown' && selectedRow < explorerItems.length - 1) {
|
||||
nextIndex = selectedRow + 1
|
||||
}
|
||||
|
||||
if (nextIndex !== selectedRow) {
|
||||
setSelectedRow(nextIndex)
|
||||
gridRef.current?.scrollToCell({ idx: 0, rowIdx: nextIndex })
|
||||
}
|
||||
},
|
||||
[explorerItems, selectedRow]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('keydown', handleKeyDown, true)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown, true)
|
||||
}
|
||||
}, [handleKeyDown])
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedRow(undefined)
|
||||
}, [searchQuery, sort])
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'triage') {
|
||||
triageGridRef.current?.scrollToCell({ idx: 0, rowIdx: 0 })
|
||||
} else {
|
||||
gridRef.current?.scrollToCell({ idx: 0, rowIdx: 0 })
|
||||
}
|
||||
}, [mode])
|
||||
|
||||
useEffect(() => {
|
||||
const el = triageContainerRef.current
|
||||
if (!el) return
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
setTriageContainerWidth(entry.contentRect.width)
|
||||
})
|
||||
observer.observe(el)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const errorCount = errors.length
|
||||
const indexCount = indexIssues.length
|
||||
const slowCount = slowQueries.length
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<div className="overflow-x-auto shrink-0 bg-surface-100 border-b">
|
||||
<div className="flex items-center justify-between px-6 h-10 min-w-max">
|
||||
<div className="flex items-center gap-x-1.5">
|
||||
<TwoOptionToggle
|
||||
width={75}
|
||||
options={['explorer', 'triage']}
|
||||
activeOption={mode}
|
||||
borderOverride="border"
|
||||
onClickOption={(mode) => setMode(mode as Mode)}
|
||||
/>
|
||||
{appNameFilter.length > 0 ? (
|
||||
<FilterPill
|
||||
label="Source"
|
||||
value={appNameFilter.join(', ')}
|
||||
onClear={() => setAppNameFilter([])}
|
||||
/>
|
||||
) : (
|
||||
<FilterPopover
|
||||
name="Source"
|
||||
options={appNameOptions}
|
||||
activeOptions={appNameFilter}
|
||||
valueKey="value"
|
||||
labelKey="label"
|
||||
onSaveFilters={setAppNameFilter}
|
||||
showOnlyButton={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
{mode === 'triage' ? (
|
||||
<Tabs value={filter} onValueChange={(v) => setFilter(v as IssueFilter)}>
|
||||
<TabsList className="flex gap-x-4 rounded-none mt-0! pt-0 border-none!">
|
||||
<TabsTrigger value="all" className="text-xs py-3 border-b font-mono uppercase">
|
||||
All{triageItems.length > 0 && <span>{` (${triageItems.length})`}</span>}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="error" className="text-xs py-3 border-b font-mono uppercase">
|
||||
Errors{errorCount > 0 && <span>{` (${errorCount})`}</span>}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="index" className="text-xs py-3 border-b font-mono uppercase">
|
||||
Index{indexCount > 0 && <span>{` (${indexCount})`}</span>}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="slow" className="text-xs py-3 border-b font-mono uppercase">
|
||||
Slow{slowCount > 0 && <span>{` (${slowCount})`}</span>}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
) : (
|
||||
<Input
|
||||
size="tiny"
|
||||
autoComplete="off"
|
||||
icon={<SearchIcon className="h-4 w-4" />}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
name="search"
|
||||
id="search"
|
||||
placeholder="Search queries..."
|
||||
className="w-64"
|
||||
actions={[
|
||||
searchQuery && (
|
||||
<Button
|
||||
key="clear"
|
||||
size="tiny"
|
||||
variant="text"
|
||||
icon={<XIcon className="h-4 w-4" />}
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="p-0 h-5 w-5"
|
||||
/>
|
||||
),
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
className="relative flex-1 min-h-0 flex flex-col overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className={[
|
||||
'absolute bottom-8 left-0 right-0 flex justify-center z-10 pointer-events-none',
|
||||
'transition-all duration-200',
|
||||
currentSelectedQuery
|
||||
? 'opacity-100 translate-y-0 pointer-events-auto'
|
||||
: 'opacity-0 translate-y-4 pointer-events-none',
|
||||
].join(' ')}
|
||||
>
|
||||
<FloatingPlate rounded="full">
|
||||
<Button
|
||||
size="tiny"
|
||||
className="rounded-full shadow-md"
|
||||
onClick={() => onCurrentSelectQuery?.(null)}
|
||||
>
|
||||
Clear query
|
||||
</Button>
|
||||
</FloatingPlate>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<div className="px-6 py-4">
|
||||
<GenericSkeletonLoader />
|
||||
</div>
|
||||
) : mode === 'triage' ? (
|
||||
<div ref={triageContainerRef} className="flex-1 min-h-0 min-w-0 overflow-x-auto">
|
||||
<DataGrid
|
||||
ref={triageGridRef}
|
||||
style={{ height: '100%' }}
|
||||
className="flex-1 grow h-full border-t-0! border-b-0!"
|
||||
rowHeight={60}
|
||||
headerRowHeight={36}
|
||||
columns={triageColumns}
|
||||
rows={filteredTriageItems}
|
||||
rowClass={(_, idx) => {
|
||||
const isSelected = idx === selectedTriageRow
|
||||
const query = filteredTriageItems[idx]?.query
|
||||
const isCharted = currentSelectedQuery ? currentSelectedQuery === query : false
|
||||
return [
|
||||
`${isSelected ? 'bg-surface-300 dark:bg-surface-300' : isCharted ? 'bg-surface-200 dark:bg-surface-200' : 'bg-200 hover:bg-surface-200'} cursor-pointer`,
|
||||
'[&>div:first-child]:border-l-4 [&>div:first-child]:pl-5 [&>div:last-child]:pr-6',
|
||||
`${isSelected || isCharted ? '[&>div:first-child]:border-l-foreground' : '[&>div:first-child]:border-l-transparent'}`,
|
||||
'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-hidden [&>.rdg-cell]:shadow-none [&>.rdg-cell]:py-3',
|
||||
'[&>.rdg-cell.column-prop_total_time]:relative',
|
||||
].join(' ')
|
||||
}}
|
||||
renderers={{
|
||||
renderRow(idx, props) {
|
||||
return (
|
||||
<Row
|
||||
{...props}
|
||||
key={`triage-row-${props.rowIdx}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
if (typeof idx === 'number' && idx >= 0) {
|
||||
const query = filteredTriageItems[idx]?.query
|
||||
if (query && onCurrentSelectQuery) {
|
||||
onCurrentSelectQuery(currentSelectedQuery === query ? null : query)
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
noRowsFallback: (
|
||||
<div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">
|
||||
<TextSearchIcon className="text-foreground-muted" strokeWidth={1} />
|
||||
<div className="text-center">
|
||||
<p className="text-foreground">No issues found</p>
|
||||
<p className="text-foreground-light">
|
||||
{data.length === 0
|
||||
? 'No query data available yet'
|
||||
: 'No issues detected for the selected filter'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div ref={dataGridContainerRef} className="flex-1 min-h-0 min-w-0 overflow-x-auto">
|
||||
<DataGrid
|
||||
ref={gridRef}
|
||||
style={{ height: '100%' }}
|
||||
className={cn('flex-1 grow h-full border-t-0! border-b-0!')}
|
||||
rowHeight={44}
|
||||
headerRowHeight={36}
|
||||
columns={columns}
|
||||
rows={explorerItems}
|
||||
rowClass={(_, idx) => {
|
||||
const isSelected = idx === selectedRow
|
||||
const query = explorerItems[idx]?.query
|
||||
const isCharted = currentSelectedQuery ? currentSelectedQuery === query : false
|
||||
return [
|
||||
`${isSelected ? 'bg-surface-300 dark:bg-surface-300' : isCharted ? 'bg-surface-200 dark:bg-surface-200' : 'bg-200 hover:bg-surface-200'} cursor-pointer`,
|
||||
'[&>div:first-child]:border-l-4 [&>div:first-child]:pl-5 [&>div:last-child]:pr-6',
|
||||
`${isSelected || isCharted ? '[&>div:first-child]:border-l-foreground' : '[&>div:first-child]:border-l-transparent'}`,
|
||||
'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-hidden [&>.rdg-cell]:shadow-none [&>.rdg-cell]:py-3',
|
||||
'[&>.rdg-cell.column-prop_total_time]:relative',
|
||||
].join(' ')
|
||||
}}
|
||||
renderers={{
|
||||
renderRow(idx, props) {
|
||||
return (
|
||||
<Row
|
||||
{...props}
|
||||
key={`explorer-row-${props.rowIdx}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
if (typeof idx === 'number' && idx >= 0) {
|
||||
const query = explorerItems[idx]?.query
|
||||
if (query && onCurrentSelectQuery) {
|
||||
onCurrentSelectQuery(currentSelectedQuery === query ? null : query)
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
noRowsFallback: (
|
||||
<div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">
|
||||
<TextSearchIcon className="text-foreground-muted" strokeWidth={1} />
|
||||
<div className="text-center">
|
||||
<p className="text-foreground">No queries found</p>
|
||||
<p className="text-foreground-light">
|
||||
{searchQuery.trim()
|
||||
? 'No queries match your search criteria'
|
||||
: 'No query data available yet'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<QueryInsightsDetailSheet
|
||||
open={activeSheetRow !== undefined}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setSelectedTriageRow(undefined)
|
||||
setSelectedRow(undefined)
|
||||
}
|
||||
}}
|
||||
activeSheetRow={activeSheetRow}
|
||||
sheetView={sheetView}
|
||||
onSheetViewChange={setSheetView}
|
||||
onClose={() => {
|
||||
setSelectedTriageRow(undefined)
|
||||
setSelectedRow(undefined)
|
||||
}}
|
||||
dataGridContainerRef={dataGridContainerRef}
|
||||
triageContainerRef={triageContainerRef}
|
||||
explainLoadingQuery={explainLoadingQuery}
|
||||
explainResults={explainResults}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
export type Mode = 'triage' | 'explorer'
|
||||
export type IssueFilter = 'all' | 'error' | 'index' | 'slow'
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
formatDuration,
|
||||
formatQueryDisplay,
|
||||
getColumnName,
|
||||
getQueryType,
|
||||
getTableName,
|
||||
} from './QueryInsightsTable.utils'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it('returns ms for values under 1000', () => {
|
||||
expect(formatDuration(0)).toBe('0ms')
|
||||
expect(formatDuration(500)).toBe('500ms')
|
||||
expect(formatDuration(999)).toBe('999ms')
|
||||
})
|
||||
|
||||
it('delegates to formatDurationLong for values >= 1000', () => {
|
||||
expect(formatDuration(1000)).toBe('1.00s')
|
||||
expect(formatDuration(60000)).toBe('1m')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getQueryType', () => {
|
||||
it('returns null for empty/null/undefined input', () => {
|
||||
expect(getQueryType(null)).toBeNull()
|
||||
expect(getQueryType(undefined)).toBeNull()
|
||||
expect(getQueryType('')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the SQL keyword for standard statement types', () => {
|
||||
expect(getQueryType('SELECT * FROM users')).toBe('SELECT')
|
||||
expect(getQueryType('INSERT INTO orders VALUES (1)')).toBe('INSERT')
|
||||
expect(getQueryType('UPDATE users SET name = $1')).toBe('UPDATE')
|
||||
expect(getQueryType('DELETE FROM logs')).toBe('DELETE')
|
||||
expect(getQueryType('CREATE TABLE foo (id int)')).toBe('CREATE')
|
||||
expect(getQueryType('DROP TABLE foo')).toBe('DROP')
|
||||
expect(getQueryType('ALTER TABLE foo ADD COLUMN bar text')).toBe('ALTER')
|
||||
expect(getQueryType('TRUNCATE foo')).toBe('TRUNCATE')
|
||||
})
|
||||
|
||||
it('returns WITH for simple CTEs', () => {
|
||||
expect(getQueryType('WITH cte AS (SELECT 1) SELECT * FROM cte')).toBe('WITH')
|
||||
})
|
||||
|
||||
it('is case-insensitive', () => {
|
||||
expect(getQueryType('select * from users')).toBe('SELECT')
|
||||
expect(getQueryType('insert into foo values (1)')).toBe('INSERT')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTableName', () => {
|
||||
it('returns null for empty/null/undefined input', () => {
|
||||
expect(getTableName(null)).toBeNull()
|
||||
expect(getTableName(undefined)).toBeNull()
|
||||
expect(getTableName('')).toBeNull()
|
||||
})
|
||||
|
||||
it('extracts table from SELECT FROM', () => {
|
||||
expect(getTableName('SELECT * FROM users')).toBe('users')
|
||||
expect(getTableName('SELECT id FROM public.orders WHERE id = 1')).toBe('orders')
|
||||
})
|
||||
|
||||
it('extracts table from INSERT INTO', () => {
|
||||
expect(getTableName('INSERT INTO orders (id) VALUES (1)')).toBe('orders')
|
||||
})
|
||||
|
||||
it('extracts table from UPDATE', () => {
|
||||
expect(getTableName('UPDATE users SET name = $1 WHERE id = 1')).toBe('users')
|
||||
})
|
||||
|
||||
it('extracts table from DELETE FROM', () => {
|
||||
expect(getTableName('DELETE FROM logs WHERE id = 1')).toBe('logs')
|
||||
})
|
||||
|
||||
it('extracts table from CREATE TABLE', () => {
|
||||
expect(getTableName('CREATE TABLE foo (id int)')).toBe('foo')
|
||||
expect(getTableName('CREATE TABLE IF NOT EXISTS bar (id int)')).toBe('bar')
|
||||
})
|
||||
|
||||
it('extracts table from ALTER TABLE', () => {
|
||||
expect(getTableName('ALTER TABLE users ADD COLUMN email text')).toBe('users')
|
||||
})
|
||||
|
||||
it('extracts table from DROP TABLE', () => {
|
||||
expect(getTableName('DROP TABLE IF EXISTS old_table')).toBe('old_table')
|
||||
})
|
||||
|
||||
it('extracts table from TRUNCATE', () => {
|
||||
expect(getTableName('TRUNCATE TABLE logs')).toBe('logs')
|
||||
expect(getTableName('TRUNCATE logs')).toBe('logs')
|
||||
})
|
||||
|
||||
it('strips quotes', () => {
|
||||
expect(getTableName('SELECT * FROM "my_table"')).toBe('my_table')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getColumnName', () => {
|
||||
it('returns null for empty/null/undefined input', () => {
|
||||
expect(getColumnName(null)).toBeNull()
|
||||
expect(getColumnName(undefined)).toBeNull()
|
||||
expect(getColumnName('')).toBeNull()
|
||||
})
|
||||
|
||||
it('extracts column from WHERE clause', () => {
|
||||
expect(getColumnName('SELECT * FROM users WHERE id = 1')).toBe('id')
|
||||
})
|
||||
|
||||
it('extracts column from ORDER BY when no WHERE clause', () => {
|
||||
expect(getColumnName('SELECT * FROM users ORDER BY created_at')).toBe('created_at')
|
||||
})
|
||||
|
||||
it('extracts column from GROUP BY', () => {
|
||||
expect(getColumnName('SELECT status, count(*) FROM orders GROUP BY status')).toBe('status')
|
||||
})
|
||||
|
||||
it('extracts column from UPDATE SET when no WHERE clause', () => {
|
||||
expect(getColumnName('UPDATE users SET email = $1')).toBe('email')
|
||||
})
|
||||
|
||||
it('extracts first column from INSERT INTO', () => {
|
||||
expect(getColumnName('INSERT INTO users (id, name) VALUES ($1, $2)')).toBe('id')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatQueryDisplay', () => {
|
||||
it('formats all three parts', () => {
|
||||
expect(formatQueryDisplay('SELECT', 'users', 'id')).toBe('SELECT in users, id')
|
||||
})
|
||||
|
||||
it('uses dash placeholders for null values', () => {
|
||||
expect(formatQueryDisplay(null, null, null)).toBe('– in –, –')
|
||||
expect(formatQueryDisplay('SELECT', null, null)).toBe('SELECT in –, –')
|
||||
})
|
||||
})
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
import { formatDuration as formatDurationLong } from '../../QueryPerformance/QueryPerformance.utils'
|
||||
|
||||
export const formatDuration = (ms: number) => {
|
||||
if (ms < 1000) {
|
||||
return `${Math.round(ms)}ms`
|
||||
}
|
||||
return formatDurationLong(ms)
|
||||
}
|
||||
|
||||
export const getQueryType = (query: string | undefined | null): string | null => {
|
||||
if (!query) return null
|
||||
const trimmed = query.trim()
|
||||
const firstWord = trimmed.split(/\s+/)[0]?.toUpperCase()
|
||||
|
||||
const sqlTypes = [
|
||||
'SELECT',
|
||||
'INSERT',
|
||||
'UPDATE',
|
||||
'DELETE',
|
||||
'CREATE',
|
||||
'DROP',
|
||||
'ALTER',
|
||||
'TRUNCATE',
|
||||
'WITH',
|
||||
]
|
||||
|
||||
if (firstWord && sqlTypes.includes(firstWord)) {
|
||||
return firstWord
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const cleanIdentifier = (identifier?: string): string | null => {
|
||||
if (!identifier) return null
|
||||
return (
|
||||
identifier
|
||||
.replace(/["`']/g, '')
|
||||
.replace(/^[\w]+\./, '')
|
||||
.trim() || null
|
||||
)
|
||||
}
|
||||
|
||||
export const getTableName = (query: string | undefined | null): string | null => {
|
||||
if (!query) return null
|
||||
const trimmed = query.trim()
|
||||
|
||||
let match = trimmed.match(
|
||||
/FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/INSERT\s+INTO\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(/UPDATE\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/DELETE\s+FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/CREATE\s+(?:TEMPORARY\s+|TEMP\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/ALTER\s+TABLE\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/TRUNCATE\s+(?:TABLE\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
if (trimmed.toUpperCase().startsWith('WITH')) {
|
||||
match = trimmed.match(
|
||||
/WITH\s+[\s\S]*?\s+FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const getColumnName = (query: string | undefined | null): string | null => {
|
||||
if (!query) return null
|
||||
const trimmed = query.trim()
|
||||
|
||||
let match = trimmed.match(
|
||||
/WHERE\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match?.groups?.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/SELECT\s+(?:\*\s+FROM|(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+))(?:\s*,\s*[\w.]+)*)\s+FROM)/i
|
||||
)
|
||||
if (match?.groups?.column && match.groups.column.toUpperCase() !== '*') {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/ORDER\s+BY\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/GROUP\s+BY\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/UPDATE\s+[\w.]+\s+SET\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(/INSERT\s+INTO\s+[\w.]+\s*\((?<column>(?:"[^"]+"|[\w]+))/i)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const formatQueryDisplay = (
|
||||
queryType: string | null,
|
||||
tableName: string | null,
|
||||
columnName: string | null
|
||||
): string => {
|
||||
const type = queryType ?? '–'
|
||||
const table = tableName ?? '–'
|
||||
const column = columnName ?? '–'
|
||||
return `${type} in ${table}, ${column}`
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import { getQueryType } from '../QueryInsightsTable/QueryInsightsTable.utils'
|
||||
import { classifyQuery } from './useQueryInsightsIssues.utils'
|
||||
|
||||
export function useQueryInsightsIssues(data: QueryPerformanceRow[]) {
|
||||
return useMemo(() => {
|
||||
const classified: ClassifiedQuery[] = data.map((row) => {
|
||||
const { issueType, hint } = classifyQuery(row)
|
||||
return { ...row, issueType, hint, queryType: getQueryType(row.query) }
|
||||
})
|
||||
|
||||
const errors = classified.filter((q) => q.issueType === 'error')
|
||||
const indexIssues = classified.filter((q) => q.issueType === 'index')
|
||||
const slowQueries = classified.filter((q) => q.issueType === 'slow')
|
||||
|
||||
return { classified, errors, indexIssues, slowQueries }
|
||||
}, [data])
|
||||
}
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
import { safeSql } from '@supabase/pg-meta'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { hasIndexRecommendations } from '../../QueryPerformance/IndexAdvisor/index-advisor.utils'
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import { classifyQuery } from './useQueryInsightsIssues.utils'
|
||||
|
||||
vi.mock('../../QueryPerformance/IndexAdvisor/index-advisor.utils', () => ({
|
||||
hasIndexRecommendations: vi.fn(),
|
||||
}))
|
||||
|
||||
const baseRow: QueryPerformanceRow = {
|
||||
query: safeSql`SELECT * FROM users`,
|
||||
calls: 10,
|
||||
mean_time: 50,
|
||||
min_time: 10,
|
||||
max_time: 200,
|
||||
total_time: 500,
|
||||
prop_total_time: 5,
|
||||
rows_read: 100,
|
||||
cache_hit_rate: 1,
|
||||
rolname: 'postgres',
|
||||
application_name: 'test',
|
||||
index_advisor_result: null,
|
||||
_total_cache_hits: 0,
|
||||
_total_cache_misses: 0,
|
||||
}
|
||||
|
||||
describe('classifyQuery', () => {
|
||||
it('returns error when index_advisor_result has errors', () => {
|
||||
const row = {
|
||||
...baseRow,
|
||||
index_advisor_result: {
|
||||
errors: ['some error'],
|
||||
index_statements: [],
|
||||
startup_cost_before: 0,
|
||||
startup_cost_after: 0,
|
||||
total_cost_before: 0,
|
||||
total_cost_after: 0,
|
||||
},
|
||||
}
|
||||
const result = classifyQuery(row)
|
||||
expect(result.issueType).toBe('error')
|
||||
expect(result.hint).toBe('some error')
|
||||
})
|
||||
|
||||
it('returns index when hasIndexRecommendations is true', () => {
|
||||
vi.mocked(hasIndexRecommendations).mockReturnValue(true)
|
||||
const row = {
|
||||
...baseRow,
|
||||
index_advisor_result: {
|
||||
errors: [],
|
||||
index_statements: [safeSql`CREATE INDEX ...`],
|
||||
startup_cost_before: 0,
|
||||
startup_cost_after: 0,
|
||||
total_cost_before: 0,
|
||||
total_cost_after: 0,
|
||||
},
|
||||
}
|
||||
const result = classifyQuery(row)
|
||||
expect(result.issueType).toBe('index')
|
||||
expect(result.hint).toContain('Missing index')
|
||||
vi.mocked(hasIndexRecommendations).mockReset()
|
||||
})
|
||||
|
||||
it('returns slow when mean_time exceeds threshold', () => {
|
||||
vi.mocked(hasIndexRecommendations).mockReturnValue(false)
|
||||
const row = { ...baseRow, mean_time: 300 }
|
||||
const result = classifyQuery(row)
|
||||
expect(result.issueType).toBe('slow')
|
||||
expect(result.hint).toBe('Abnormally slow query detected')
|
||||
vi.mocked(hasIndexRecommendations).mockReset()
|
||||
})
|
||||
|
||||
it('returns null issue for healthy queries', () => {
|
||||
vi.mocked(hasIndexRecommendations).mockReturnValue(false)
|
||||
const row = { ...baseRow, mean_time: 50 }
|
||||
const result = classifyQuery(row)
|
||||
expect(result.issueType).toBeNull()
|
||||
expect(result.hint).toBe('')
|
||||
vi.mocked(hasIndexRecommendations).mockReset()
|
||||
})
|
||||
|
||||
it('errors take priority over index recommendations', () => {
|
||||
vi.mocked(hasIndexRecommendations).mockReturnValue(true)
|
||||
const row = {
|
||||
...baseRow,
|
||||
index_advisor_result: {
|
||||
errors: ['critical error'],
|
||||
index_statements: [safeSql`CREATE INDEX ...`],
|
||||
startup_cost_before: 0,
|
||||
startup_cost_after: 0,
|
||||
total_cost_before: 0,
|
||||
total_cost_after: 0,
|
||||
},
|
||||
}
|
||||
const result = classifyQuery(row)
|
||||
expect(result.issueType).toBe('error')
|
||||
vi.mocked(hasIndexRecommendations).mockReset()
|
||||
})
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
import { hasIndexRecommendations } from '../../QueryPerformance/IndexAdvisor/index-advisor.utils'
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import { SLOW_QUERY_THRESHOLD_MS } from '../QueryInsightsHealth/QueryInsightsHealth.constants'
|
||||
import type { IssueType } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
|
||||
export function classifyQuery(row: QueryPerformanceRow): { issueType: IssueType; hint: string } {
|
||||
// undefined means index advisor is still loading — defer index classification only to avoid
|
||||
// flickering between 'slow' and 'index' as results arrive, but still classify slow queries
|
||||
if (row.index_advisor_result === undefined) {
|
||||
if (row.mean_time > SLOW_QUERY_THRESHOLD_MS) {
|
||||
return { issueType: 'slow', hint: 'Abnormally slow query detected' }
|
||||
}
|
||||
return { issueType: null, hint: '' }
|
||||
}
|
||||
|
||||
const advisorErrors = row.index_advisor_result?.errors
|
||||
if (advisorErrors && advisorErrors.length > 0) {
|
||||
return { issueType: 'error', hint: advisorErrors[0] }
|
||||
}
|
||||
|
||||
if (hasIndexRecommendations(row.index_advisor_result, true)) {
|
||||
const statements = row.index_advisor_result?.index_statements ?? []
|
||||
return {
|
||||
issueType: 'index',
|
||||
hint: `Missing index: ${statements[0] ?? 'Index suggestion available'}`,
|
||||
}
|
||||
}
|
||||
|
||||
if (row.mean_time > SLOW_QUERY_THRESHOLD_MS) {
|
||||
return {
|
||||
issueType: 'slow',
|
||||
hint: `Abnormally slow query detected`,
|
||||
}
|
||||
}
|
||||
|
||||
return { issueType: null, hint: '' }
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
|
||||
export const useQueryInsightsMetrics = (data: QueryPerformanceRow[]) => {
|
||||
const avgP95 = useMemo(() => {
|
||||
const rows = data.filter((r) => (r.p95_time ?? 0) > 0)
|
||||
if (rows.length === 0) return 0
|
||||
return Math.round(rows.reduce((sum, r) => sum + (r.p95_time ?? 0), 0) / rows.length)
|
||||
}, [data])
|
||||
|
||||
const totalCalls = useMemo(() => data.reduce((sum, r) => sum + r.calls, 0), [data])
|
||||
|
||||
const totalRowsRead = useMemo(() => data.reduce((sum, r) => sum + r.rows_read, 0), [data])
|
||||
|
||||
const cacheHitRate = useMemo(() => {
|
||||
const hits = data.reduce((sum, r) => sum + (r._total_cache_hits ?? 0), 0)
|
||||
const misses = data.reduce((sum, r) => sum + (r._total_cache_misses ?? 0), 0)
|
||||
const total = hits + misses
|
||||
return total > 0 ? ((hits / total) * 100).toFixed(2) + '%' : '–'
|
||||
}, [data])
|
||||
|
||||
return { avgP95, totalCalls, totalRowsRead, cacheHitRate }
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import {
|
||||
HIGH_CALL_THRESHOLD,
|
||||
SCORE_DEDUCTIONS,
|
||||
} from '../QueryInsightsHealth/QueryInsightsHealth.constants'
|
||||
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import { getHealthLevel } from '../QueryInsightsHealth/QueryInsightsHealth.utils'
|
||||
|
||||
export function useQueryInsightsScore({
|
||||
errors,
|
||||
indexIssues,
|
||||
slowQueries,
|
||||
}: {
|
||||
errors: ClassifiedQuery[]
|
||||
indexIssues: ClassifiedQuery[]
|
||||
slowQueries: ClassifiedQuery[]
|
||||
}) {
|
||||
return useMemo(() => {
|
||||
let score = 100
|
||||
|
||||
score -= errors.length * SCORE_DEDUCTIONS.error
|
||||
|
||||
score -= indexIssues.reduce(
|
||||
(acc, q) =>
|
||||
acc +
|
||||
(q.calls > HIGH_CALL_THRESHOLD
|
||||
? SCORE_DEDUCTIONS.indexHighCalls
|
||||
: SCORE_DEDUCTIONS.indexLowCalls),
|
||||
0
|
||||
)
|
||||
|
||||
score -= slowQueries.reduce(
|
||||
(acc, q) =>
|
||||
acc +
|
||||
(q.calls > HIGH_CALL_THRESHOLD / 2
|
||||
? SCORE_DEDUCTIONS.slowHighCalls
|
||||
: SCORE_DEDUCTIONS.slowLowCalls),
|
||||
0
|
||||
)
|
||||
|
||||
score = Math.max(0, Math.min(100, score))
|
||||
|
||||
return {
|
||||
score,
|
||||
level: getHealthLevel(score),
|
||||
}
|
||||
}, [errors, indexIssues, slowQueries])
|
||||
}
|
||||
-600
@@ -1,600 +0,0 @@
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowRightIcon,
|
||||
ArrowUpIcon,
|
||||
ChevronDownIcon,
|
||||
ExternalLinkIcon,
|
||||
ScanSearchIcon,
|
||||
} from 'lucide-react'
|
||||
import { useMemo, type RefObject } from 'react'
|
||||
import { type Column, type DataGridHandle } from 'react-data-grid'
|
||||
import {
|
||||
Button,
|
||||
cn,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from 'ui'
|
||||
import { CodeBlock } from 'ui-patterns/CodeBlock'
|
||||
import { InfoTooltip } from 'ui-patterns/info-tooltip'
|
||||
|
||||
import { buildQueryInsightFixPrompt } from '../../QueryPerformance/QueryPerformance.ai'
|
||||
import { QUERY_PERFORMANCE_ROLE_DESCRIPTION } from '../../QueryPerformance/QueryPerformance.constants'
|
||||
import type { ClassifiedQuery } from '../QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import {
|
||||
ISSUE_DOT_COLORS,
|
||||
ISSUE_ICONS,
|
||||
NON_SORTABLE_COLUMNS,
|
||||
QUERY_INSIGHTS_EXPLORER_COLUMNS,
|
||||
} from '../QueryInsightsTable/QueryInsightsTable.constants'
|
||||
import {
|
||||
formatDuration,
|
||||
getColumnName,
|
||||
getTableName,
|
||||
} from '../QueryInsightsTable/QueryInsightsTable.utils'
|
||||
import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
|
||||
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
||||
|
||||
interface UseQueryInsightsTableColumnsParams {
|
||||
sort: { column: string; order: 'asc' | 'desc' }
|
||||
setSort: (config: { column: string; order: 'asc' | 'desc' } | null) => void
|
||||
timeConsumedWidth: number
|
||||
triageQueryColWidth: number
|
||||
gridRef: RefObject<DataGridHandle | null>
|
||||
setSelectedRow: (idx: number) => void
|
||||
setSelectedTriageRow: (idx: number | undefined) => void
|
||||
setSheetView: (view: 'details' | 'indexes' | 'explain') => void
|
||||
handleGoToLogs: () => void
|
||||
handleAiSuggestedFix: (item: ClassifiedQuery) => void
|
||||
}
|
||||
|
||||
export function useQueryInsightsTableColumns({
|
||||
sort,
|
||||
setSort,
|
||||
timeConsumedWidth,
|
||||
triageQueryColWidth,
|
||||
gridRef,
|
||||
setSelectedRow,
|
||||
setSelectedTriageRow,
|
||||
setSheetView,
|
||||
handleGoToLogs,
|
||||
handleAiSuggestedFix,
|
||||
}: UseQueryInsightsTableColumnsParams): {
|
||||
columns: Column<ClassifiedQuery>[]
|
||||
triageColumns: Column<ClassifiedQuery>[]
|
||||
} {
|
||||
const columns = useMemo(() => {
|
||||
return QUERY_INSIGHTS_EXPLORER_COLUMNS.map((col) => {
|
||||
const isSortable = !NON_SORTABLE_COLUMNS.includes(col.id as never)
|
||||
|
||||
const result: Column<ClassifiedQuery> = {
|
||||
key: col.id,
|
||||
name: col.name,
|
||||
cellClass: `column-${col.id}`,
|
||||
resizable: true,
|
||||
minWidth: col.id === 'prop_total_time' ? timeConsumedWidth : (col.minWidth ?? 120),
|
||||
sortable: isSortable,
|
||||
headerCellClass: 'first:pl-6 cursor-pointer',
|
||||
renderHeaderCell: () => {
|
||||
return (
|
||||
<div className="flex items-center justify-between text-xs w-full">
|
||||
<div className="flex items-center gap-x-2">
|
||||
<p className="text-foreground! font-medium">{col.name}</p>
|
||||
{col.description && (
|
||||
<p className="text-foreground-lighter font-normal">{col.description}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSortable && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="text"
|
||||
size="tiny"
|
||||
className="p-1 h-5 w-5 shrink-0"
|
||||
icon={<ChevronDownIcon size={14} className="text-foreground-muted" />}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={() => setSort({ column: col.id, order: 'asc' })}
|
||||
className={cn(
|
||||
'flex gap-2',
|
||||
sort?.column === col.id && sort?.order === 'asc' && 'text-foreground'
|
||||
)}
|
||||
>
|
||||
<ArrowUpIcon size={14} />
|
||||
Sort Ascending
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setSort({ column: col.id, order: 'desc' })}
|
||||
className={cn(
|
||||
'flex gap-2',
|
||||
sort?.column === col.id && sort?.order === 'desc' && 'text-foreground'
|
||||
)}
|
||||
>
|
||||
<ArrowDownIcon size={14} />
|
||||
Sort Descending
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
renderCell: (props) => {
|
||||
const row = props.row
|
||||
const value = row[col.id]
|
||||
|
||||
if (col.id === 'query') {
|
||||
const IssueIcon = row.issueType ? ISSUE_ICONS[row.issueType] : null
|
||||
return (
|
||||
<div className="w-full flex items-center gap-x-3 group">
|
||||
<div className="shrink-0 w-6">
|
||||
{row.issueType && IssueIcon && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div
|
||||
className={cn(
|
||||
'h-6 w-6 rounded-full border flex items-center justify-center cursor-default',
|
||||
ISSUE_DOT_COLORS[row.issueType]?.border,
|
||||
ISSUE_DOT_COLORS[row.issueType]?.background
|
||||
)}
|
||||
>
|
||||
<IssueIcon size={14} className={ISSUE_DOT_COLORS[row.issueType].color} />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
{row.hint && (
|
||||
<TooltipContent side="top" className="max-w-[260px]">
|
||||
{row.hint}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<CodeBlock
|
||||
language="pgsql"
|
||||
className="bg-transparent! p-0! m-0! border-none! whitespace-nowrap! [&>code]:whitespace-nowrap! [&>code]:wrap-break-word overflow-visible! truncate! w-full! pr-20! pointer-events-none"
|
||||
wrapperClassName="max-w-full! flex-1"
|
||||
hideLineNumbers
|
||||
hideCopy
|
||||
value={typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : ''}
|
||||
wrapLines={false}
|
||||
/>
|
||||
<ButtonTooltip
|
||||
tooltip={{ content: { text: 'Query details' } }}
|
||||
icon={<ArrowRightIcon size={14} />}
|
||||
size="tiny"
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
setSelectedRow(props.rowIdx)
|
||||
setSheetView('details')
|
||||
gridRef.current?.scrollToCell({ idx: 0, rowIdx: props.rowIdx })
|
||||
}}
|
||||
className="p-1 shrink-0 -translate-x-2 group-hover:flex hidden"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'prop_total_time') {
|
||||
const percentage = row.prop_total_time || 0
|
||||
const totalTime = row.total_time || 0
|
||||
const fillWidth = Math.min(percentage, 100)
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
<div
|
||||
className="absolute inset-0 bg-foreground transition-all duration-200 z-0"
|
||||
style={{ width: `${fillWidth}%`, opacity: 0.04 }}
|
||||
/>
|
||||
{percentage && totalTime ? (
|
||||
<span className="flex items-center justify-end gap-x-1.5">
|
||||
<span
|
||||
className={cn(percentage.toFixed(1) === '0.0' && 'text-foreground-lighter')}
|
||||
>
|
||||
{percentage.toFixed(1)}%
|
||||
</span>
|
||||
<span className="text-muted">/</span>
|
||||
<span
|
||||
className={cn(
|
||||
formatDuration(totalTime) === '0ms' && 'text-foreground-lighter'
|
||||
)}
|
||||
>
|
||||
{formatDuration(totalTime)}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'calls') {
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
|
||||
<p className={cn(value === 0 && 'text-foreground-lighter')}>
|
||||
{value.toLocaleString()}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'max_time' || col.id === 'mean_time' || col.id === 'min_time') {
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
|
||||
<p className={cn(value.toFixed(0) === '0' && 'text-foreground-lighter')}>
|
||||
{Math.round(value).toLocaleString()}ms
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'rows_read') {
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
|
||||
<p className={cn(value === 0 && 'text-foreground-lighter')}>
|
||||
{value.toLocaleString()}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'cache_hit_rate') {
|
||||
const num = typeof value === 'number' ? value : parseFloat(value ?? '0')
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof num === 'number' && !isNaN(num) && isFinite(num) ? (
|
||||
<p className={cn(num.toFixed(2) === '0.00' && 'text-foreground-lighter')}>
|
||||
{num.toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}
|
||||
%
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'rolname') {
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center">
|
||||
{value ? (
|
||||
<span className="flex items-center gap-x-1">
|
||||
<p className="font-mono text-xs">{value}</p>
|
||||
<InfoTooltip align="end" alignOffset={-12} className="w-56">
|
||||
{
|
||||
QUERY_PERFORMANCE_ROLE_DESCRIPTION.find((r) => r.name === value)
|
||||
?.description
|
||||
}
|
||||
</InfoTooltip>
|
||||
</span>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (col.id === 'application_name') {
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center">
|
||||
{value ? (
|
||||
<p className="font-mono text-xs">{value}</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
}
|
||||
return result
|
||||
})
|
||||
}, [sort, setSort, timeConsumedWidth, gridRef, setSelectedRow, setSheetView])
|
||||
|
||||
const triageColumns = useMemo(
|
||||
(): Column<ClassifiedQuery>[] => [
|
||||
{
|
||||
key: 'query',
|
||||
name: 'Query',
|
||||
minWidth: triageQueryColWidth,
|
||||
width: triageQueryColWidth,
|
||||
resizable: true,
|
||||
headerCellClass: 'first:pl-6 cursor-default',
|
||||
renderHeaderCell: () => (
|
||||
<div className="flex items-center text-xs w-full">
|
||||
<p className="text-foreground! font-medium">Query</p>
|
||||
</div>
|
||||
),
|
||||
renderCell: (props) => {
|
||||
const row = props.row as ClassifiedQuery
|
||||
const IssueIcon = row.issueType ? ISSUE_ICONS[row.issueType] : null
|
||||
return (
|
||||
<div className="w-full flex items-center gap-x-3 group">
|
||||
<div className="shrink-0 w-6">
|
||||
{row.issueType && IssueIcon && (
|
||||
<div
|
||||
className={cn(
|
||||
'h-6 w-6 rounded-full border flex items-center justify-center',
|
||||
ISSUE_DOT_COLORS[row.issueType]?.border,
|
||||
ISSUE_DOT_COLORS[row.issueType]?.background
|
||||
)}
|
||||
>
|
||||
<IssueIcon size={14} className={ISSUE_DOT_COLORS[row.issueType].color} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-mono text-foreground truncate">
|
||||
{row.queryType ?? <span>–</span>}
|
||||
{getTableName(row.query) && (
|
||||
<>
|
||||
{' '}
|
||||
<span className="text-foreground-lighter">in</span> {getTableName(row.query)}
|
||||
</>
|
||||
)}
|
||||
{getColumnName(row.query) && (
|
||||
<>
|
||||
<span className="text-foreground-lighter">,</span> {getColumnName(row.query)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs mt-0.5 font-mono truncate',
|
||||
row.issueType === 'error' && 'text-destructive-600',
|
||||
row.issueType === 'index' && 'text-warning-600',
|
||||
row.issueType === 'slow' && 'text-foreground-lighter'
|
||||
)}
|
||||
>
|
||||
{row.hint}
|
||||
</p>
|
||||
</div>
|
||||
<ButtonTooltip
|
||||
tooltip={{ content: { text: 'Query details' } }}
|
||||
icon={<ArrowRightIcon size={14} />}
|
||||
size="tiny"
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
setSelectedTriageRow(props.rowIdx)
|
||||
setSheetView('details')
|
||||
}}
|
||||
className="p-1 shrink-0 group-hover:flex hidden"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'prop_total_time',
|
||||
name: 'Time consumed',
|
||||
minWidth: timeConsumedWidth,
|
||||
resizable: true,
|
||||
cellClass: 'column-prop_total_time',
|
||||
headerCellClass: 'cursor-default',
|
||||
renderHeaderCell: () => (
|
||||
<div className="flex items-center text-xs w-full">
|
||||
<p className="text-foreground! font-medium">Time consumed</p>
|
||||
</div>
|
||||
),
|
||||
renderCell: (props) => {
|
||||
const row = props.row as ClassifiedQuery
|
||||
const percentage = row.prop_total_time || 0
|
||||
const totalTime = row.total_time || 0
|
||||
const fillWidth = Math.min(percentage, 100)
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
<div
|
||||
className="absolute inset-0 bg-foreground transition-all duration-200 z-0"
|
||||
style={{ width: `${fillWidth}%`, opacity: 0.04 }}
|
||||
/>
|
||||
{percentage && totalTime ? (
|
||||
<span className="flex items-center justify-end gap-x-1.5">
|
||||
<span
|
||||
className={cn(percentage.toFixed(1) === '0.0' && 'text-foreground-lighter')}
|
||||
>
|
||||
{percentage.toFixed(1)}%
|
||||
</span>
|
||||
<span className="text-muted">/</span>
|
||||
<span
|
||||
className={cn(formatDuration(totalTime) === '0ms' && 'text-foreground-lighter')}
|
||||
>
|
||||
{formatDuration(totalTime)}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'calls',
|
||||
name: 'Calls',
|
||||
minWidth: 90,
|
||||
resizable: true,
|
||||
headerCellClass: 'cursor-default',
|
||||
renderHeaderCell: () => (
|
||||
<div className="flex items-center text-xs w-full">
|
||||
<p className="text-foreground! font-medium">Calls</p>
|
||||
</div>
|
||||
),
|
||||
renderCell: (props) => {
|
||||
const value = (props.row as ClassifiedQuery).calls
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
|
||||
<p className={cn(value === 0 && 'text-foreground-lighter')}>
|
||||
{value.toLocaleString()}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'mean_time',
|
||||
name: 'Mean time',
|
||||
minWidth: 90,
|
||||
resizable: true,
|
||||
headerCellClass: 'cursor-default',
|
||||
renderHeaderCell: () => (
|
||||
<div className="flex items-center text-xs w-full">
|
||||
<p className="text-foreground! font-medium">Mean time</p>
|
||||
</div>
|
||||
),
|
||||
renderCell: (props) => {
|
||||
const value = (props.row as ClassifiedQuery).mean_time
|
||||
return (
|
||||
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
|
||||
{typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
|
||||
<p className={cn(value === 0 && 'text-foreground-lighter')}>
|
||||
{formatDuration(value)}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-muted">–</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
name: 'Actions',
|
||||
minWidth: 200,
|
||||
resizable: false,
|
||||
headerCellClass: 'cursor-default',
|
||||
renderHeaderCell: () => (
|
||||
<div className="flex items-center text-xs w-full">
|
||||
<p className="text-foreground! font-medium">Actions</p>
|
||||
</div>
|
||||
),
|
||||
renderCell: (props) => {
|
||||
const row = props.row as ClassifiedQuery
|
||||
return (
|
||||
<div className="flex items-center gap-2 justify-end w-full h-full">
|
||||
{!row.issueType && (
|
||||
<Button
|
||||
size="tiny"
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
handleGoToLogs()
|
||||
}}
|
||||
>
|
||||
Go to Logs
|
||||
</Button>
|
||||
)}
|
||||
{row.issueType === 'index' && (
|
||||
<div className="flex items-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="tiny"
|
||||
className="rounded-r-none hover:z-10 focus-visible:z-10 focus-visible:rounded-r-sm"
|
||||
onClick={() => {
|
||||
setSelectedTriageRow(props.rowIdx)
|
||||
setSheetView('indexes')
|
||||
}}
|
||||
>
|
||||
Create Index
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="tiny"
|
||||
aria-label="More index actions"
|
||||
className="shrink-0 rounded-l-none px-[4px] py-[5px] -ml-px focus-visible:z-10 focus-visible:rounded-l-sm"
|
||||
icon={<ChevronDownIcon size={12} />}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40">
|
||||
<DropdownMenuItem onClick={() => handleGoToLogs()} className="gap-2">
|
||||
<ExternalLinkIcon size={14} />
|
||||
Go to Logs
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setSelectedTriageRow(props.rowIdx)
|
||||
setSheetView('explain')
|
||||
}}
|
||||
className="gap-2"
|
||||
>
|
||||
<ScanSearchIcon size={14} />
|
||||
Explain
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
{(row.issueType === 'error' || row.issueType === 'slow') && (
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<AiAssistantDropdown
|
||||
label="Fix with AI"
|
||||
buildPrompt={() => buildQueryInsightFixPrompt(row).prompt}
|
||||
onOpenAssistant={() => handleAiSuggestedFix(row)}
|
||||
copyLabel="Copy Markdown"
|
||||
additionalDropdownItems={[
|
||||
{
|
||||
label: 'Go to Logs',
|
||||
icon: <ExternalLinkIcon size={14} />,
|
||||
onClick: () => handleGoToLogs(),
|
||||
},
|
||||
...(row.issueType === 'slow'
|
||||
? [
|
||||
{
|
||||
label: 'Explain',
|
||||
icon: <ScanSearchIcon size={14} />,
|
||||
onClick: () => {
|
||||
setSelectedTriageRow(props.rowIdx)
|
||||
setSheetView('explain')
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
triageQueryColWidth,
|
||||
timeConsumedWidth,
|
||||
handleGoToLogs,
|
||||
handleAiSuggestedFix,
|
||||
setSelectedTriageRow,
|
||||
setSheetView,
|
||||
]
|
||||
)
|
||||
|
||||
return { columns, triageColumns }
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useQueries } from '@tanstack/react-query'
|
||||
|
||||
import { useIndexAdvisorStatus } from '../../QueryPerformance/hooks/useIsIndexAdvisorStatus'
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import { databaseKeys } from '@/data/database/keys'
|
||||
import { getIndexAdvisorResult } from '@/data/database/retrieve-index-advisor-result-query'
|
||||
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
||||
|
||||
function isEligibleQuery(query: string): boolean {
|
||||
const lower = query.trim().toLowerCase()
|
||||
if (!lower.startsWith('select') && !lower.startsWith('with')) return false
|
||||
// Dollar-quoted string literals (e.g. $$...$$ or $tag$...$tag$) break the single-quoted
|
||||
// SQL embedding in getIndexAdvisorResult. Plain parameter markers ($1, $2, …) are fine.
|
||||
if (/\$([A-Za-z_][A-Za-z0-9_]*)?\$/.test(query)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export function useSupamonitorIndexAdvisor(rows: QueryPerformanceRow[]): QueryPerformanceRow[] {
|
||||
const { data: project } = useSelectedProjectQuery()
|
||||
const { isIndexAdvisorEnabled } = useIndexAdvisorStatus()
|
||||
|
||||
const eligibleQueries = rows.map((r) => r.query).filter(isEligibleQuery)
|
||||
|
||||
const results = useQueries({
|
||||
queries: eligibleQueries.map((query) => ({
|
||||
queryKey: databaseKeys.indexAdvisorFromQuery(
|
||||
project?.ref,
|
||||
query,
|
||||
project?.connectionString ?? undefined
|
||||
),
|
||||
queryFn: () =>
|
||||
getIndexAdvisorResult({
|
||||
projectRef: project?.ref,
|
||||
connectionString: project?.connectionString,
|
||||
query,
|
||||
}),
|
||||
enabled: isIndexAdvisorEnabled && !!project?.ref,
|
||||
retry: false,
|
||||
staleTime: Infinity,
|
||||
})),
|
||||
})
|
||||
|
||||
if (!isIndexAdvisorEnabled) return rows
|
||||
|
||||
const resultByQuery = new Map(
|
||||
eligibleQueries.map((query, i) => {
|
||||
const result = results[i]
|
||||
// Only treat as ready when status is definitively success or error.
|
||||
// undefined/pending means data hasn't arrived yet — store undefined so
|
||||
// classifyQuery can defer slow classification and avoid flicker.
|
||||
const isReady = result?.status === 'success' || result?.status === 'error'
|
||||
return [query, isReady ? (result.data ?? null) : undefined]
|
||||
})
|
||||
)
|
||||
|
||||
return rows.map((row) => ({
|
||||
...row,
|
||||
index_advisor_result: resultByQuery.has(row.query)
|
||||
? resultByQuery.get(row.query)
|
||||
: (row.index_advisor_result ?? null),
|
||||
}))
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
import { safeSql } from '@supabase/pg-meta'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { ParsedLogEntry } from '../QueryInsights.types'
|
||||
import {
|
||||
aggregateLogsByQuery,
|
||||
parseSupamonitorLogs,
|
||||
transformLogsToChartData,
|
||||
} from './supamonitor.utils'
|
||||
|
||||
const makeSampleLog = (overrides: Partial<ParsedLogEntry> = {}): any => ({
|
||||
timestamp: '2025-01-01T00:00:00Z',
|
||||
application_name: 'test_app',
|
||||
calls: 10,
|
||||
database_name: 'test_db',
|
||||
query: 'SELECT 1',
|
||||
query_id: 1,
|
||||
total_exec_time: 100,
|
||||
total_plan_time: 20,
|
||||
user_name: 'postgres',
|
||||
mean_exec_time: 10,
|
||||
mean_plan_time: 2,
|
||||
min_exec_time: 1,
|
||||
max_exec_time: 50,
|
||||
min_plan_time: 0.5,
|
||||
max_plan_time: 5,
|
||||
p50_exec_time: 8,
|
||||
p95_exec_time: 40,
|
||||
p50_plan_time: 1.5,
|
||||
p95_plan_time: 4,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('parseSupamonitorLogs', () => {
|
||||
it('returns empty array for null or empty input', () => {
|
||||
expect(parseSupamonitorLogs(null as any)).toEqual([])
|
||||
expect(parseSupamonitorLogs([])).toEqual([])
|
||||
})
|
||||
|
||||
it('parses log entries preserving all fields', () => {
|
||||
const raw = [makeSampleLog()]
|
||||
const result = parseSupamonitorLogs(raw)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({
|
||||
timestamp: '2025-01-01T00:00:00Z',
|
||||
application_name: 'test_app',
|
||||
calls: 10,
|
||||
database_name: 'test_db',
|
||||
query: 'SELECT 1',
|
||||
query_id: 1,
|
||||
total_exec_time: 100,
|
||||
total_plan_time: 20,
|
||||
user_name: 'postgres',
|
||||
mean_exec_time: 10,
|
||||
mean_plan_time: 2,
|
||||
min_exec_time: 1,
|
||||
max_exec_time: 50,
|
||||
min_plan_time: 0.5,
|
||||
max_plan_time: 5,
|
||||
p50_exec_time: 8,
|
||||
p95_exec_time: 40,
|
||||
p50_plan_time: 1.5,
|
||||
p95_plan_time: 4,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('transformLogsToChartData', () => {
|
||||
it('returns empty array for null or empty input', () => {
|
||||
expect(transformLogsToChartData(null as any)).toEqual([])
|
||||
expect(transformLogsToChartData([])).toEqual([])
|
||||
})
|
||||
|
||||
it.each<[string, ParsedLogEntry]>([
|
||||
['no', { query: safeSql`SELECT 1`, calls: 5 }],
|
||||
['an invalid', { timestamp: 'not-a-date', calls: 5 }],
|
||||
])('filters out entries with %s timestamp', (_, log) => {
|
||||
expect(transformLogsToChartData([log])).toEqual([])
|
||||
})
|
||||
|
||||
it('transforms a valid log entry into a chart data point', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{
|
||||
timestamp: '2025-01-01T00:00:00Z',
|
||||
mean_exec_time: 10,
|
||||
mean_plan_time: 2,
|
||||
min_exec_time: 1,
|
||||
max_exec_time: 50,
|
||||
min_plan_time: 0.5,
|
||||
max_plan_time: 5,
|
||||
p50_exec_time: 8,
|
||||
p95_exec_time: 40,
|
||||
p50_plan_time: 1.5,
|
||||
p95_plan_time: 4,
|
||||
calls: 10,
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformLogsToChartData(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({
|
||||
period_start: new Date('2025-01-01T00:00:00Z').getTime(),
|
||||
timestamp: '2025-01-01T00:00:00Z',
|
||||
query_latency: 12, // 10 + 2
|
||||
mean_time: 10,
|
||||
min_time: 1.5, // 1 + 0.5
|
||||
max_time: 55, // 50 + 5
|
||||
stddev_time: 0,
|
||||
p50_time: 9.5, // 8 + 1.5
|
||||
p95_time: 44, // 40 + 4
|
||||
rows_read: 0,
|
||||
calls: 10,
|
||||
cache_hits: 0,
|
||||
cache_misses: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('defaults missing numeric fields to 0', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{
|
||||
timestamp: '2025-06-01T12:00:00Z',
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformLogsToChartData(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].query_latency).toBe(0)
|
||||
expect(result[0].calls).toBe(0)
|
||||
expect(result[0].min_time).toBe(0)
|
||||
expect(result[0].max_time).toBe(0)
|
||||
})
|
||||
|
||||
it('sorts results by period_start ascending', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ timestamp: '2025-01-03T00:00:00Z', mean_exec_time: 1 },
|
||||
{ timestamp: '2025-01-01T00:00:00Z', mean_exec_time: 2 },
|
||||
{ timestamp: '2025-01-02T00:00:00Z', mean_exec_time: 3 },
|
||||
]
|
||||
|
||||
const result = transformLogsToChartData(logs)
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
expect(result[0].timestamp).toBe('2025-01-01T00:00:00Z')
|
||||
expect(result[1].timestamp).toBe('2025-01-02T00:00:00Z')
|
||||
expect(result[2].timestamp).toBe('2025-01-03T00:00:00Z')
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateLogsByQuery', () => {
|
||||
it('returns empty array for null or empty input', () => {
|
||||
expect(aggregateLogsByQuery(null as any)).toEqual([])
|
||||
expect(aggregateLogsByQuery([])).toEqual([])
|
||||
})
|
||||
|
||||
it('skips entries with empty or whitespace-only queries', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ query: safeSql``, calls: 5 },
|
||||
{ query: safeSql` `, calls: 3 },
|
||||
]
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('aggregates a single log entry correctly', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{
|
||||
query: safeSql`SELECT 1`,
|
||||
user_name: 'postgres',
|
||||
application_name: 'app',
|
||||
calls: 10,
|
||||
total_exec_time: 100,
|
||||
total_plan_time: 20,
|
||||
min_exec_time: 1,
|
||||
max_exec_time: 50,
|
||||
min_plan_time: 0.5,
|
||||
max_plan_time: 5,
|
||||
},
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].query).toBe('SELECT 1')
|
||||
expect(result[0].rolname).toBe('postgres')
|
||||
expect(result[0].application_name).toBe('app')
|
||||
expect(result[0].calls).toBe(10)
|
||||
expect(result[0].total_time).toBe(120)
|
||||
expect(result[0].mean_time).toBe(12)
|
||||
expect(result[0].min_time).toBe(1.5)
|
||||
expect(result[0].max_time).toBe(55)
|
||||
expect(result[0].prop_total_time).toBe(100)
|
||||
})
|
||||
|
||||
it('aggregates multiple entries for the same query', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{
|
||||
query: safeSql`SELECT 1`,
|
||||
user_name: 'postgres',
|
||||
calls: 5,
|
||||
total_exec_time: 50,
|
||||
total_plan_time: 10,
|
||||
min_exec_time: 2,
|
||||
max_exec_time: 20,
|
||||
min_plan_time: 1,
|
||||
max_plan_time: 3,
|
||||
},
|
||||
{
|
||||
query: safeSql`SELECT 1`,
|
||||
user_name: 'postgres',
|
||||
calls: 10,
|
||||
total_exec_time: 100,
|
||||
total_plan_time: 20,
|
||||
min_exec_time: 1,
|
||||
max_exec_time: 50,
|
||||
min_plan_time: 0.5,
|
||||
max_plan_time: 5,
|
||||
},
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].calls).toBe(15) // 5 + 10
|
||||
expect(result[0].total_time).toBe(180) // (50+10) + (100+20)
|
||||
expect(result[0].mean_time).toBe(12) // 180 / 15
|
||||
expect(result[0].min_time).toBe(1.5) // min(2+1, 1+0.5) = 1.5
|
||||
expect(result[0].max_time).toBe(55) // max(20+3, 50+5) = 55
|
||||
expect(result[0]._count).toBe(2) // 2 log entries
|
||||
})
|
||||
|
||||
it('normalizes whitespace differences in queries', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ query: safeSql`SELECT 1`, calls: 5, total_exec_time: 50, total_plan_time: 0 },
|
||||
{ query: safeSql`SELECT 1`, calls: 3, total_exec_time: 30, total_plan_time: 0 },
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].calls).toBe(8)
|
||||
})
|
||||
|
||||
it('sorts results by total_time descending', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ query: safeSql`SELECT 1`, calls: 1, total_exec_time: 10, total_plan_time: 0 },
|
||||
{ query: safeSql`SELECT 2`, calls: 1, total_exec_time: 100, total_plan_time: 0 },
|
||||
{ query: safeSql`SELECT 3`, calls: 1, total_exec_time: 50, total_plan_time: 0 },
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
expect(result[0].query).toBe('SELECT 2')
|
||||
expect(result[1].query).toBe('SELECT 3')
|
||||
expect(result[2].query).toBe('SELECT 1')
|
||||
})
|
||||
|
||||
it('calculates prop_total_time as percentage of total execution', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ query: safeSql`SELECT 1`, calls: 1, total_exec_time: 75, total_plan_time: 0 },
|
||||
{ query: safeSql`SELECT 2`, calls: 1, total_exec_time: 25, total_plan_time: 0 },
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result[0].prop_total_time).toBe(75)
|
||||
expect(result[1].prop_total_time).toBe(25)
|
||||
})
|
||||
|
||||
it('handles zero calls gracefully (mean_time defaults to 0)', () => {
|
||||
const logs: ParsedLogEntry[] = [
|
||||
{ query: safeSql`SELECT 1`, calls: 0, total_exec_time: 100, total_plan_time: 0 },
|
||||
]
|
||||
|
||||
const result = aggregateLogsByQuery(logs)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].mean_time).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,210 +0,0 @@
|
||||
import { type SafeSqlFragment } from '@supabase/pg-meta'
|
||||
|
||||
import type { QueryPerformanceRow } from '../../QueryPerformance/QueryPerformance.types'
|
||||
import type { Logs } from '../../Settings/Logs/Logs.types'
|
||||
import {
|
||||
SCHEMA_INTROSPECTION_REGEX,
|
||||
SUPAMONITOR_EXCLUDED_APP_NAMES,
|
||||
SUPAMONITOR_EXCLUDED_ROLES,
|
||||
TRANSACTION_CONTROL_REGEX,
|
||||
} from '../QueryInsights.constants'
|
||||
import type { ChartDataPoint, ParsedLogEntry } from '../QueryInsights.types'
|
||||
|
||||
export function filterSystemLogs(
|
||||
logs: ParsedLogEntry[],
|
||||
{ includeIntrospection = false }: { includeIntrospection?: boolean } = {}
|
||||
): ParsedLogEntry[] {
|
||||
return logs.filter((log) => {
|
||||
if (log.user_name && (SUPAMONITOR_EXCLUDED_ROLES as readonly string[]).includes(log.user_name))
|
||||
return false
|
||||
if (
|
||||
log.application_name &&
|
||||
(SUPAMONITOR_EXCLUDED_APP_NAMES as readonly string[]).includes(log.application_name)
|
||||
)
|
||||
return false
|
||||
if (log.query && TRANSACTION_CONTROL_REGEX.test(log.query)) return false
|
||||
if (!includeIntrospection && log.query && SCHEMA_INTROSPECTION_REGEX.test(log.query))
|
||||
return false
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function asString(unknown: unknown): string | undefined {
|
||||
if (typeof unknown === 'string') return unknown
|
||||
if (unknown === null || unknown === undefined) return undefined
|
||||
return String(unknown)
|
||||
}
|
||||
|
||||
function asNumber(unknown: unknown): number | undefined {
|
||||
if (typeof unknown === 'number') return unknown
|
||||
if (unknown === null || unknown === undefined) return undefined
|
||||
const parsed = Number(unknown)
|
||||
return Number.isNaN(parsed) ? undefined : parsed
|
||||
}
|
||||
|
||||
export function parseSupamonitorLogs(logData: Logs['result']): ParsedLogEntry[] {
|
||||
if (!logData || logData.length === 0) return []
|
||||
|
||||
return logData.map((log) => ({
|
||||
timestamp: asString(log.timestamp),
|
||||
application_name: asString(log.application_name),
|
||||
calls: asNumber(log.calls),
|
||||
database_name: asString(log.database_name),
|
||||
query: log.query,
|
||||
query_id: asNumber(log.query_id),
|
||||
total_exec_time: asNumber(log.total_exec_time),
|
||||
total_plan_time: asNumber(log.total_plan_time),
|
||||
user_name: asString(log.user_name),
|
||||
mean_exec_time: asNumber(log.mean_exec_time),
|
||||
mean_plan_time: asNumber(log.mean_plan_time),
|
||||
min_exec_time: asNumber(log.min_exec_time),
|
||||
max_exec_time: asNumber(log.max_exec_time),
|
||||
min_plan_time: asNumber(log.min_plan_time),
|
||||
max_plan_time: asNumber(log.max_plan_time),
|
||||
p50_exec_time: asNumber(log.p50_exec_time),
|
||||
p95_exec_time: asNumber(log.p95_exec_time),
|
||||
p50_plan_time: asNumber(log.p50_plan_time),
|
||||
p95_plan_time: asNumber(log.p95_plan_time),
|
||||
}))
|
||||
}
|
||||
|
||||
export function transformLogsToChartData(parsedLogs: ParsedLogEntry[]): ChartDataPoint[] {
|
||||
if (!parsedLogs || parsedLogs.length === 0) return []
|
||||
|
||||
return parsedLogs
|
||||
.map((log: ParsedLogEntry) => {
|
||||
if (!log.timestamp) return null
|
||||
|
||||
const periodStart = new Date(log.timestamp).getTime()
|
||||
if (isNaN(periodStart)) return null
|
||||
|
||||
const meanExecTime = parseFloat(String(log.mean_exec_time ?? 0))
|
||||
const meanPlanTime = parseFloat(String(log.mean_plan_time ?? 0))
|
||||
const calls = parseInt(String(log.calls ?? 0), 10)
|
||||
|
||||
return {
|
||||
period_start: periodStart,
|
||||
timestamp: log.timestamp,
|
||||
query_latency: meanExecTime + meanPlanTime,
|
||||
mean_time: meanExecTime,
|
||||
min_time: (log.min_exec_time ?? 0) + (log.min_plan_time ?? 0),
|
||||
max_time: (log.max_exec_time ?? 0) + (log.max_plan_time ?? 0),
|
||||
stddev_time: 0,
|
||||
p50_time: (log.p50_exec_time ?? 0) + (log.p50_plan_time ?? 0),
|
||||
p95_time: (log.p95_exec_time ?? 0) + (log.p95_plan_time ?? 0),
|
||||
rows_read: 0,
|
||||
calls,
|
||||
cache_hits: 0,
|
||||
cache_misses: 0,
|
||||
}
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => item !== null)
|
||||
.sort((a, b) => a.period_start - b.period_start)
|
||||
}
|
||||
|
||||
function normalizeQuery(query: string): string {
|
||||
return query.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
export function aggregateLogsByQuery(parsedLogs: ParsedLogEntry[]): QueryPerformanceRow[] {
|
||||
if (!parsedLogs || parsedLogs.length === 0) return []
|
||||
|
||||
const queryGroups = new Map<string, ParsedLogEntry[]>()
|
||||
|
||||
parsedLogs.forEach((log) => {
|
||||
const query = normalizeQuery(log.query || '')
|
||||
if (!query) return
|
||||
|
||||
if (!queryGroups.has(query)) {
|
||||
queryGroups.set(query, [])
|
||||
}
|
||||
queryGroups.get(query)!.push(log)
|
||||
})
|
||||
|
||||
const aggregatedData: QueryPerformanceRow[] = []
|
||||
let totalExecutionTime = 0
|
||||
|
||||
const queryStats = Array.from(queryGroups.entries()).map(([query, logs]) => {
|
||||
const count = logs.length
|
||||
let totalCalls = 0
|
||||
let totalExecTime = 0
|
||||
let totalPlanTime = 0
|
||||
let p95Sum = 0
|
||||
let p95Count = 0
|
||||
let minTime = Infinity
|
||||
let maxTime = -Infinity
|
||||
const rolname = logs[0]?.user_name || ''
|
||||
const applicationName = logs[0]?.application_name || ''
|
||||
let firstSeen = logs[0]?.timestamp ?? ''
|
||||
|
||||
logs.forEach((log) => {
|
||||
if (log.timestamp && (!firstSeen || log.timestamp < firstSeen)) firstSeen = log.timestamp
|
||||
const logCalls = parseInt(String(log.calls ?? 0), 10)
|
||||
totalCalls += logCalls
|
||||
totalExecTime += parseFloat(String(log.total_exec_time ?? 0))
|
||||
totalPlanTime += parseFloat(String(log.total_plan_time ?? 0))
|
||||
const logP95 =
|
||||
parseFloat(String(log.p95_exec_time ?? 0)) + parseFloat(String(log.p95_plan_time ?? 0))
|
||||
if (logP95 > 0) {
|
||||
p95Sum += logP95
|
||||
p95Count++
|
||||
}
|
||||
minTime = Math.min(
|
||||
minTime,
|
||||
parseFloat(String(log.min_exec_time ?? 0)) + parseFloat(String(log.min_plan_time ?? 0))
|
||||
)
|
||||
maxTime = Math.max(
|
||||
maxTime,
|
||||
parseFloat(String(log.max_exec_time ?? 0)) + parseFloat(String(log.max_plan_time ?? 0))
|
||||
)
|
||||
})
|
||||
|
||||
const totalTime = totalExecTime + totalPlanTime
|
||||
const avgMeanTime = totalCalls > 0 ? totalTime / totalCalls : 0
|
||||
const avgP95Time = p95Count > 0 ? p95Sum / p95Count : 0
|
||||
const finalMinTime = minTime === Infinity ? 0 : minTime
|
||||
const finalMaxTime = maxTime === -Infinity ? 0 : maxTime
|
||||
|
||||
totalExecutionTime += totalTime
|
||||
|
||||
return {
|
||||
query,
|
||||
rolname,
|
||||
applicationName,
|
||||
firstSeen,
|
||||
count,
|
||||
avgMeanTime,
|
||||
avgP95Time,
|
||||
minTime: finalMinTime,
|
||||
maxTime: finalMaxTime,
|
||||
totalCalls,
|
||||
totalTime,
|
||||
}
|
||||
})
|
||||
|
||||
queryStats.forEach((stats) => {
|
||||
const propTotalTime = totalExecutionTime > 0 ? (stats.totalTime / totalExecutionTime) * 100 : 0
|
||||
|
||||
aggregatedData.push({
|
||||
query: stats.query as SafeSqlFragment,
|
||||
rolname: stats.rolname,
|
||||
application_name: stats.applicationName,
|
||||
calls: stats.totalCalls,
|
||||
mean_time: stats.avgMeanTime,
|
||||
p95_time: stats.avgP95Time,
|
||||
min_time: stats.minTime,
|
||||
max_time: stats.maxTime,
|
||||
total_time: stats.totalTime,
|
||||
rows_read: 0,
|
||||
cache_hit_rate: 0,
|
||||
prop_total_time: propTotalTime,
|
||||
index_advisor_result: null,
|
||||
_total_cache_hits: 0,
|
||||
_total_cache_misses: 0,
|
||||
_count: stats.count,
|
||||
first_seen: stats.firstSeen,
|
||||
})
|
||||
})
|
||||
|
||||
return aggregatedData.sort((a, b) => b.total_time - a.total_time)
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import { QueryPerformanceRow } from './QueryPerformance.types'
|
||||
import { ClassifiedQuery, QueryPerformanceRow } from './QueryPerformance.types'
|
||||
import { getColumnName, getTableName } from './QueryPerformance.utils'
|
||||
import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
|
||||
import type { ClassifiedQuery } from '@/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.types'
|
||||
import {
|
||||
getColumnName,
|
||||
getTableName,
|
||||
} from '@/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils'
|
||||
|
||||
export interface QueryExplanationPrompt {
|
||||
query: string
|
||||
|
||||
@@ -48,6 +48,12 @@ export type QueryPerformanceSort = {
|
||||
|
||||
export type QuerySource = 'dashboard' | 'non-dashboard'
|
||||
|
||||
export interface ClassifiedQuery extends QueryPerformanceRow {
|
||||
issueType: 'error' | 'index' | 'slow' | null
|
||||
hint: string
|
||||
queryType: string | null
|
||||
}
|
||||
|
||||
export type QueryPerformanceSQLParams = {
|
||||
preset: QueryPerformancePreset
|
||||
orderBy?: QueryPerformanceSort
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { formatDuration } from './QueryPerformance.utils'
|
||||
import { formatDuration, getColumnName, getTableName } from './QueryPerformance.utils'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it('should format seconds', () => {
|
||||
@@ -23,3 +23,78 @@ describe('formatDuration', () => {
|
||||
expect(formatDuration(90061000)).toBe('1d 1h 1m 1s')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTableName', () => {
|
||||
it('returns null for empty/null/undefined input', () => {
|
||||
expect(getTableName(null)).toBeNull()
|
||||
expect(getTableName(undefined)).toBeNull()
|
||||
expect(getTableName('')).toBeNull()
|
||||
})
|
||||
|
||||
it('extracts table from SELECT FROM', () => {
|
||||
expect(getTableName('SELECT * FROM users')).toBe('users')
|
||||
expect(getTableName('SELECT id FROM public.orders WHERE id = 1')).toBe('orders')
|
||||
})
|
||||
|
||||
it('extracts table from INSERT INTO', () => {
|
||||
expect(getTableName('INSERT INTO orders (id) VALUES (1)')).toBe('orders')
|
||||
})
|
||||
|
||||
it('extracts table from UPDATE', () => {
|
||||
expect(getTableName('UPDATE users SET name = $1 WHERE id = 1')).toBe('users')
|
||||
})
|
||||
|
||||
it('extracts table from DELETE FROM', () => {
|
||||
expect(getTableName('DELETE FROM logs WHERE id = 1')).toBe('logs')
|
||||
})
|
||||
|
||||
it('extracts table from CREATE TABLE', () => {
|
||||
expect(getTableName('CREATE TABLE foo (id int)')).toBe('foo')
|
||||
expect(getTableName('CREATE TABLE IF NOT EXISTS bar (id int)')).toBe('bar')
|
||||
})
|
||||
|
||||
it('extracts table from ALTER TABLE', () => {
|
||||
expect(getTableName('ALTER TABLE users ADD COLUMN email text')).toBe('users')
|
||||
})
|
||||
|
||||
it('extracts table from DROP TABLE', () => {
|
||||
expect(getTableName('DROP TABLE IF EXISTS old_table')).toBe('old_table')
|
||||
})
|
||||
|
||||
it('extracts table from TRUNCATE', () => {
|
||||
expect(getTableName('TRUNCATE TABLE logs')).toBe('logs')
|
||||
expect(getTableName('TRUNCATE logs')).toBe('logs')
|
||||
})
|
||||
|
||||
it('strips quotes', () => {
|
||||
expect(getTableName('SELECT * FROM "my_table"')).toBe('my_table')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getColumnName', () => {
|
||||
it('returns null for empty/null/undefined input', () => {
|
||||
expect(getColumnName(null)).toBeNull()
|
||||
expect(getColumnName(undefined)).toBeNull()
|
||||
expect(getColumnName('')).toBeNull()
|
||||
})
|
||||
|
||||
it('extracts column from WHERE clause', () => {
|
||||
expect(getColumnName('SELECT * FROM users WHERE id = 1')).toBe('id')
|
||||
})
|
||||
|
||||
it('extracts column from ORDER BY when no WHERE clause', () => {
|
||||
expect(getColumnName('SELECT * FROM users ORDER BY created_at')).toBe('created_at')
|
||||
})
|
||||
|
||||
it('extracts column from GROUP BY', () => {
|
||||
expect(getColumnName('SELECT status, count(*) FROM orders GROUP BY status')).toBe('status')
|
||||
})
|
||||
|
||||
it('extracts column from UPDATE SET when no WHERE clause', () => {
|
||||
expect(getColumnName('UPDATE users SET email = $1')).toBe('email')
|
||||
})
|
||||
|
||||
it('extracts first column from INSERT INTO', () => {
|
||||
expect(getColumnName('INSERT INTO users (id, name) VALUES ($1, $2)')).toBe('id')
|
||||
})
|
||||
})
|
||||
@@ -32,7 +32,7 @@ export type QueryPerformanceErrorContext = {
|
||||
projectRef?: string
|
||||
databaseIdentifier?: string
|
||||
queryPreset?: string
|
||||
queryType?: 'hitRate' | 'metrics' | 'mainQuery' | 'slowQueriesCount' | 'supamonitor'
|
||||
queryType?: 'hitRate' | 'metrics' | 'mainQuery' | 'slowQueriesCount'
|
||||
sql?: string
|
||||
postgresVersion?: string
|
||||
databaseType?: 'primary' | 'read-replica'
|
||||
@@ -69,3 +69,130 @@ export function captureQueryPerformanceError(
|
||||
Sentry.captureException(errorToCapture)
|
||||
})
|
||||
}
|
||||
|
||||
const cleanIdentifier = (identifier?: string): string | null => {
|
||||
if (!identifier) return null
|
||||
return (
|
||||
identifier
|
||||
.replace(/["`']/g, '')
|
||||
.replace(/^[\w]+\./, '')
|
||||
.trim() || null
|
||||
)
|
||||
}
|
||||
|
||||
export const getTableName = (query: string | undefined | null): string | null => {
|
||||
if (!query) return null
|
||||
const trimmed = query.trim()
|
||||
|
||||
let match = trimmed.match(
|
||||
/FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/INSERT\s+INTO\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(/UPDATE\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/DELETE\s+FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/CREATE\s+(?:TEMPORARY\s+|TEMP\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/ALTER\s+TABLE\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/TRUNCATE\s+(?:TABLE\s+)?(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
|
||||
if (trimmed.toUpperCase().startsWith('WITH')) {
|
||||
match = trimmed.match(
|
||||
/WITH\s+[\s\S]*?\s+FROM\s+(?:(?<schema>(?:"[^"]+"|[\w]+)\.)?(?<table>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.table) {
|
||||
return cleanIdentifier(match.groups.table)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export const getColumnName = (query: string | undefined | null): string | null => {
|
||||
if (!query) return null
|
||||
const trimmed = query.trim()
|
||||
|
||||
let match = trimmed.match(
|
||||
/WHERE\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match?.groups?.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/SELECT\s+(?:\*\s+FROM|(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+))(?:\s*,\s*[\w.]+)*)\s+FROM)/i
|
||||
)
|
||||
if (match?.groups?.column && match.groups.column.toUpperCase() !== '*') {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/ORDER\s+BY\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/GROUP\s+BY\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(
|
||||
/UPDATE\s+[\w.]+\s+SET\s+(?:(?<table>(?:"[^"]+"|[\w]+)\.)?(?<column>(?:"[^"]+"|[\w]+)))/i
|
||||
)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
match = trimmed.match(/INSERT\s+INTO\s+[\w.]+\s*\((?<column>(?:"[^"]+"|[\w]+))/i)
|
||||
if (match?.groups?.column) {
|
||||
return cleanIdentifier(match.groups.column)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { useSupamonitorEnabledQuery } from '@/data/database/supamonitor-enabled-query'
|
||||
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
||||
|
||||
export function useSupamonitorStatus() {
|
||||
const { data: project } = useSelectedProjectQuery()
|
||||
const { data: isSupamonitorEnabled, isLoading } = useSupamonitorEnabledQuery({
|
||||
projectRef: project?.ref,
|
||||
connectionString: project?.connectionString,
|
||||
})
|
||||
|
||||
return {
|
||||
isSupamonitorEnabled: isSupamonitorEnabled ?? false,
|
||||
isLoading,
|
||||
}
|
||||
}
|
||||
+1
-22
@@ -5,7 +5,6 @@ import {
|
||||
useGenerateCustomReportsMenu,
|
||||
useGenerateObservabilityMenu,
|
||||
} from './ObservabilityMenu.utils'
|
||||
import { useSupamonitorStatus } from '@/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus'
|
||||
import { useContentQuery } from '@/data/content/content-query'
|
||||
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
|
||||
import { useIsWarehouseEnabled } from '@/hooks/misc/useIsWarehouseEnabled'
|
||||
@@ -35,10 +34,6 @@ vi.mock('common', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus', () => ({
|
||||
useSupamonitorStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/misc/useIsFeatureEnabled', () => ({
|
||||
useIsFeatureEnabled: vi.fn(),
|
||||
}))
|
||||
@@ -65,10 +60,6 @@ describe('useGenerateObservabilityMenu', () => {
|
||||
mockIsPlatform.value = true
|
||||
vi.mocked(useFlag).mockReturnValue(false)
|
||||
vi.mocked(useParams).mockReturnValue({ ref: REF })
|
||||
vi.mocked(useSupamonitorStatus).mockReturnValue({
|
||||
isSupamonitorEnabled: false,
|
||||
isLoading: false,
|
||||
})
|
||||
vi.mocked(useIsFeatureEnabled).mockReturnValue(true)
|
||||
})
|
||||
|
||||
@@ -87,20 +78,8 @@ describe('useGenerateObservabilityMenu', () => {
|
||||
expect(getGeneralKeys()).toContain('observability')
|
||||
})
|
||||
|
||||
it('shows Query Performance or Query Insights depending on supamonitor', () => {
|
||||
vi.mocked(useSupamonitorStatus).mockReturnValue({
|
||||
isSupamonitorEnabled: false,
|
||||
isLoading: false,
|
||||
})
|
||||
it('shows Query Performance', () => {
|
||||
expect(getGeneralKeys()).toContain('query-performance')
|
||||
expect(getGeneralKeys()).not.toContain('query-insights')
|
||||
|
||||
vi.mocked(useSupamonitorStatus).mockReturnValue({
|
||||
isSupamonitorEnabled: true,
|
||||
isLoading: false,
|
||||
})
|
||||
expect(getGeneralKeys()).toContain('query-insights')
|
||||
expect(getGeneralKeys()).not.toContain('query-performance')
|
||||
})
|
||||
|
||||
it('includes API Gateway and the PRODUCT section on platform', () => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useLocation } from '@tanstack/react-router'
|
||||
import { useFlag, useParams } from 'common'
|
||||
|
||||
import { useSupamonitorStatus } from '@/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus'
|
||||
import { useContentQuery, type Content, type ContentBase } from '@/data/content/content-query'
|
||||
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
|
||||
import { useIsWarehouseEnabled } from '@/hooks/misc/useIsWarehouseEnabled'
|
||||
@@ -44,7 +43,6 @@ const usePreservedQueryParams = () => {
|
||||
export const useGenerateObservabilityMenu = () => {
|
||||
const { ref } = useParams()
|
||||
const preservedQueryParams = usePreservedQueryParams()
|
||||
const { isSupamonitorEnabled } = useSupamonitorStatus()
|
||||
|
||||
const showOverview = useFlag('observabilityOverview')
|
||||
const isWarehouseEnabled = useIsWarehouseEnabled()
|
||||
@@ -63,23 +61,12 @@ export const useGenerateObservabilityMenu = () => {
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(isSupamonitorEnabled
|
||||
? [
|
||||
{
|
||||
name: 'Query Insights',
|
||||
key: 'query-insights',
|
||||
url: `${baseUrl}/query-insights${preservedQueryParams}`,
|
||||
shortcutId: SHORTCUT_IDS.NAV_OBSERVABILITY_QUERY_PERFORMANCE,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
name: 'Query Performance',
|
||||
key: 'query-performance',
|
||||
url: `${baseUrl}/query-performance${preservedQueryParams}`,
|
||||
shortcutId: SHORTCUT_IDS.NAV_OBSERVABILITY_QUERY_PERFORMANCE,
|
||||
},
|
||||
]),
|
||||
{
|
||||
name: 'Query Performance',
|
||||
key: 'query-performance',
|
||||
url: `${baseUrl}/query-performance${preservedQueryParams}`,
|
||||
shortcutId: SHORTCUT_IDS.NAV_OBSERVABILITY_QUERY_PERFORMANCE,
|
||||
},
|
||||
...(IS_PLATFORM
|
||||
? [
|
||||
{
|
||||
|
||||
@@ -80,8 +80,6 @@ export const databaseKeys = {
|
||||
schema: string | undefined,
|
||||
table: string | undefined
|
||||
) => ['projects', projectRef, 'table-index-advisor', schema, table] as const,
|
||||
supamonitorEnabled: (projectRef: string | undefined) =>
|
||||
['projects', projectRef, 'supamonitor-enabled'] as const,
|
||||
databaseActivity: (projectRef: string | undefined) =>
|
||||
['projects', projectRef, 'database-activity'] as const,
|
||||
authenticatorRoleConfig: (projectRef: string | undefined) =>
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { safeSql } from '@supabase/pg-meta/src/pg-format'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import { databaseKeys } from './keys'
|
||||
import { unguarded } from '@/data/fetchers'
|
||||
import { executeSql } from '@/data/sql/execute-sql-mutation'
|
||||
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
||||
import { PROJECT_STATUS } from '@/lib/constants'
|
||||
import type { StudioError } from '@/lib/errors/studio-errors'
|
||||
import type { UseCustomQueryOptions } from '@/types'
|
||||
|
||||
export type SupamonitorEnabledVariables = {
|
||||
projectRef?: string
|
||||
connectionString?: string | null
|
||||
}
|
||||
|
||||
export async function getSupamonitorEnabled({
|
||||
projectRef,
|
||||
connectionString,
|
||||
}: SupamonitorEnabledVariables) {
|
||||
const { result } = await executeSql<{ libraries: string }[]>({
|
||||
projectRef,
|
||||
connectionString,
|
||||
sqlOrigin: 'studio',
|
||||
queryName: 'supamonitor-enabled',
|
||||
sql: safeSql`SELECT current_setting('shared_preload_libraries', true) AS libraries`,
|
||||
grant: unguarded.migrating,
|
||||
})
|
||||
|
||||
const libraries = result[0]?.libraries ?? ''
|
||||
return libraries.split(',').some((lib) => lib.trim() === 'supamonitor')
|
||||
}
|
||||
|
||||
export type SupamonitorEnabledData = Awaited<ReturnType<typeof getSupamonitorEnabled>>
|
||||
export type SupamonitorEnabledError = StudioError
|
||||
|
||||
export const useSupamonitorEnabledQuery = <TData = SupamonitorEnabledData>(
|
||||
{ projectRef, connectionString }: SupamonitorEnabledVariables,
|
||||
{
|
||||
enabled = true,
|
||||
...options
|
||||
}: UseCustomQueryOptions<SupamonitorEnabledData, SupamonitorEnabledError, TData> = {}
|
||||
) => {
|
||||
const { data: project } = useSelectedProjectQuery()
|
||||
const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY
|
||||
|
||||
return useQuery<SupamonitorEnabledData, SupamonitorEnabledError, TData>({
|
||||
queryKey: databaseKeys.supamonitorEnabled(projectRef),
|
||||
queryFn: () => getSupamonitorEnabled({ projectRef, connectionString }),
|
||||
enabled: enabled && typeof projectRef !== 'undefined' && isActive,
|
||||
...options,
|
||||
})
|
||||
}
|
||||
@@ -306,6 +306,11 @@ export const SHARED_REDIRECTS: StudioRedirect[] = [
|
||||
destination: '/project/:ref/observability/query-performance',
|
||||
permanent: true,
|
||||
},
|
||||
{
|
||||
source: '/project/:ref/observability/query-insights',
|
||||
destination: '/project/:ref/observability/query-performance',
|
||||
permanent: true,
|
||||
},
|
||||
{
|
||||
source: '/project/:ref/auth/column-privileges',
|
||||
destination: '/project/:ref/database/column-privileges',
|
||||
|
||||
@@ -189,7 +189,6 @@ import { Route as ProjectRefObservabilityConnectionsRouteImport } from './routes
|
||||
import { Route as ProjectRefObservabilityDatabaseRouteImport } from './routes/project/$ref/observability/database'
|
||||
import { Route as ProjectRefObservabilityEdgeFunctionsRouteImport } from './routes/project/$ref/observability/edge-functions'
|
||||
import { Route as ProjectRefObservabilityPostgrestRouteImport } from './routes/project/$ref/observability/postgrest'
|
||||
import { Route as ProjectRefObservabilityQueryInsightsRouteImport } from './routes/project/$ref/observability/query-insights'
|
||||
import { Route as ProjectRefObservabilityQueryPerformanceRouteImport } from './routes/project/$ref/observability/query-performance'
|
||||
import { Route as ProjectRefObservabilityRealtimeRouteImport } from './routes/project/$ref/observability/realtime'
|
||||
import { Route as ProjectRefObservabilityStorageRouteImport } from './routes/project/$ref/observability/storage'
|
||||
@@ -1275,12 +1274,6 @@ const ProjectRefObservabilityPostgrestRoute =
|
||||
path: '/postgrest',
|
||||
getParentRoute: () => ProjectRefObservabilityRoute,
|
||||
} as any)
|
||||
const ProjectRefObservabilityQueryInsightsRoute =
|
||||
ProjectRefObservabilityQueryInsightsRouteImport.update({
|
||||
id: '/query-insights',
|
||||
path: '/query-insights',
|
||||
getParentRoute: () => ProjectRefObservabilityRoute,
|
||||
} as any)
|
||||
const ProjectRefObservabilityQueryPerformanceRoute =
|
||||
ProjectRefObservabilityQueryPerformanceRouteImport.update({
|
||||
id: '/query-performance',
|
||||
@@ -2199,7 +2192,6 @@ export interface FileRoutesByFullPath {
|
||||
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
|
||||
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
|
||||
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
|
||||
'/project/$ref/observability/query-insights': typeof ProjectRefObservabilityQueryInsightsRoute
|
||||
'/project/$ref/observability/query-performance': typeof ProjectRefObservabilityQueryPerformanceRoute
|
||||
'/project/$ref/observability/realtime': typeof ProjectRefObservabilityRealtimeRoute
|
||||
'/project/$ref/observability/storage': typeof ProjectRefObservabilityStorageRoute
|
||||
@@ -2492,7 +2484,6 @@ export interface FileRoutesByTo {
|
||||
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
|
||||
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
|
||||
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
|
||||
'/project/$ref/observability/query-insights': typeof ProjectRefObservabilityQueryInsightsRoute
|
||||
'/project/$ref/observability/query-performance': typeof ProjectRefObservabilityQueryPerformanceRoute
|
||||
'/project/$ref/observability/realtime': typeof ProjectRefObservabilityRealtimeRoute
|
||||
'/project/$ref/observability/storage': typeof ProjectRefObservabilityStorageRoute
|
||||
@@ -2802,7 +2793,6 @@ export interface FileRoutesById {
|
||||
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
|
||||
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
|
||||
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
|
||||
'/project/$ref/observability/query-insights': typeof ProjectRefObservabilityQueryInsightsRoute
|
||||
'/project/$ref/observability/query-performance': typeof ProjectRefObservabilityQueryPerformanceRoute
|
||||
'/project/$ref/observability/realtime': typeof ProjectRefObservabilityRealtimeRoute
|
||||
'/project/$ref/observability/storage': typeof ProjectRefObservabilityStorageRoute
|
||||
@@ -3112,7 +3102,6 @@ export interface FileRouteTypes {
|
||||
| '/project/$ref/observability/database'
|
||||
| '/project/$ref/observability/edge-functions'
|
||||
| '/project/$ref/observability/postgrest'
|
||||
| '/project/$ref/observability/query-insights'
|
||||
| '/project/$ref/observability/query-performance'
|
||||
| '/project/$ref/observability/realtime'
|
||||
| '/project/$ref/observability/storage'
|
||||
@@ -3405,7 +3394,6 @@ export interface FileRouteTypes {
|
||||
| '/project/$ref/observability/database'
|
||||
| '/project/$ref/observability/edge-functions'
|
||||
| '/project/$ref/observability/postgrest'
|
||||
| '/project/$ref/observability/query-insights'
|
||||
| '/project/$ref/observability/query-performance'
|
||||
| '/project/$ref/observability/realtime'
|
||||
| '/project/$ref/observability/storage'
|
||||
@@ -3714,7 +3702,6 @@ export interface FileRouteTypes {
|
||||
| '/project/$ref/observability/database'
|
||||
| '/project/$ref/observability/edge-functions'
|
||||
| '/project/$ref/observability/postgrest'
|
||||
| '/project/$ref/observability/query-insights'
|
||||
| '/project/$ref/observability/query-performance'
|
||||
| '/project/$ref/observability/realtime'
|
||||
| '/project/$ref/observability/storage'
|
||||
@@ -5226,13 +5213,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ProjectRefObservabilityPostgrestRouteImport
|
||||
parentRoute: typeof ProjectRefObservabilityRoute
|
||||
}
|
||||
'/project/$ref/observability/query-insights': {
|
||||
id: '/project/$ref/observability/query-insights'
|
||||
path: '/query-insights'
|
||||
fullPath: '/project/$ref/observability/query-insights'
|
||||
preLoaderRoute: typeof ProjectRefObservabilityQueryInsightsRouteImport
|
||||
parentRoute: typeof ProjectRefObservabilityRoute
|
||||
}
|
||||
'/project/$ref/observability/query-performance': {
|
||||
id: '/project/$ref/observability/query-performance'
|
||||
path: '/query-performance'
|
||||
@@ -6632,7 +6612,6 @@ interface ProjectRefObservabilityRouteChildren {
|
||||
ProjectRefObservabilityDatabaseRoute: typeof ProjectRefObservabilityDatabaseRoute
|
||||
ProjectRefObservabilityEdgeFunctionsRoute: typeof ProjectRefObservabilityEdgeFunctionsRoute
|
||||
ProjectRefObservabilityPostgrestRoute: typeof ProjectRefObservabilityPostgrestRoute
|
||||
ProjectRefObservabilityQueryInsightsRoute: typeof ProjectRefObservabilityQueryInsightsRoute
|
||||
ProjectRefObservabilityQueryPerformanceRoute: typeof ProjectRefObservabilityQueryPerformanceRoute
|
||||
ProjectRefObservabilityRealtimeRoute: typeof ProjectRefObservabilityRealtimeRoute
|
||||
ProjectRefObservabilityStorageRoute: typeof ProjectRefObservabilityStorageRoute
|
||||
@@ -6653,8 +6632,6 @@ const ProjectRefObservabilityRouteChildren: ProjectRefObservabilityRouteChildren
|
||||
ProjectRefObservabilityEdgeFunctionsRoute,
|
||||
ProjectRefObservabilityPostgrestRoute:
|
||||
ProjectRefObservabilityPostgrestRoute,
|
||||
ProjectRefObservabilityQueryInsightsRoute:
|
||||
ProjectRefObservabilityQueryInsightsRoute,
|
||||
ProjectRefObservabilityQueryPerformanceRoute:
|
||||
ProjectRefObservabilityQueryPerformanceRoute,
|
||||
ProjectRefObservabilityRealtimeRoute: ProjectRefObservabilityRealtimeRoute,
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from 'ui'
|
||||
|
||||
import { OBSERVABILITY_DOCS_HREFS } from '@/components/interfaces/Observability/Observability.constants'
|
||||
import { QueryInsights } from '@/components/interfaces/QueryInsights/QueryInsights'
|
||||
import { REPORT_DATERANGE_HELPER_LABELS } from '@/components/interfaces/Reports/Reports.constants'
|
||||
import { DatabaseSelector } from '@/components/ui/DatabaseSelector'
|
||||
import { DocsButton } from '@/components/ui/DocsButton'
|
||||
import { useReportDateRange } from '@/hooks/misc/useReportDateRange'
|
||||
|
||||
export const Route = createFileRoute('/project/$ref/observability/query-insights')({
|
||||
component: QueryInsightsReport,
|
||||
staticData: {
|
||||
observabilityLayoutTitle: 'Query insights',
|
||||
},
|
||||
})
|
||||
|
||||
const PRESETS = [
|
||||
REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES,
|
||||
REPORT_DATERANGE_HELPER_LABELS.LAST_3_HOURS,
|
||||
REPORT_DATERANGE_HELPER_LABELS.LAST_24_HOURS,
|
||||
]
|
||||
|
||||
const REPORT_TITLE = 'Query Insights'
|
||||
|
||||
function QueryInsightsReport() {
|
||||
const { selectedDateRange, datePickerValue, datePickerHelpers, handleDatePickerChange } =
|
||||
useReportDateRange(REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES)
|
||||
|
||||
const handleSelect = (text: string) => {
|
||||
const helper = datePickerHelpers.find((h) => h.text === text)
|
||||
if (helper) {
|
||||
handleDatePickerChange({ from: helper.calcFrom(), to: helper.calcTo(), isHelper: true, text })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="w-full mb-0 flex lg:items-center justify-between gap-4 py-2 px-6 lg:flex-row flex-col border-b lg:h-[48px]">
|
||||
<h3 className="text-foreground text-xl prose">{REPORT_TITLE}</h3>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<DocsButton href={OBSERVABILITY_DOCS_HREFS.queryInsights} topic={REPORT_TITLE} />
|
||||
<DatabaseSelector />
|
||||
<Select
|
||||
value={datePickerValue.isHelper ? datePickerValue.text : undefined}
|
||||
onValueChange={handleSelect}
|
||||
>
|
||||
<SelectTrigger size="tiny" className="w-[150px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent align="end">
|
||||
{PRESETS.map((label) => (
|
||||
<SelectItem key={label} value={label}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<QueryInsights dateRange={selectedDateRange} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user