From 6de989cc78cc51df53eb799c8fb2690ef3bb77ef Mon Sep 17 00:00:00 2001 From: Joshen Lim Date: Fri, 4 Dec 2026 14:48:19 +0700 Subject: [PATCH] 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 --- .../studio/.github/eslint-rule-baselines.json | 7 - .../ExplainVisualizer.Header.tsx | 146 ----- .../ExplainVisualizer.NodeRow.tsx | 148 ----- .../ExplainVisualizer.RowCountIndicator.tsx | 95 --- .../ExplainVisualizer/ExplainVisualizer.ai.ts | 45 -- .../ExplainVisualizer/ExplainVisualizer.tsx | 51 -- .../Observability/Observability.constants.ts | 1 - .../QueryInsights/QueryInsights.constants.ts | 66 -- .../QueryInsights/QueryInsights.tsx | 98 --- .../QueryInsights/QueryInsights.types.ts | 40 -- .../QueryInsightsChart.constants.ts | 22 - .../QueryInsightsChart/QueryInsightsChart.tsx | 262 -------- .../QueryInsightsChart.utils.test.ts | 26 - .../QueryInsightsChart.utils.ts | 12 - .../QueryInsightsChartTooltip.tsx | 37 -- .../QueryInsightsHealth.constants.ts | 24 - .../QueryInsightsHealth.tsx | 61 -- .../QueryInsightsHealth.types.ts | 11 - .../QueryInsightsHealth.utils.test.ts | 20 - .../QueryInsightsHealth.utils.ts | 8 - .../QueryInsightsHealthMetric.tsx | 31 - .../QueryInsightsHealthScore.tsx | 33 - .../QueryInsightsHealthScoreSkeleton.tsx | 9 - .../QueryInsightsDetailSheet.tsx | 158 ----- .../QueryInsightsTable.constants.ts | 44 -- .../QueryInsightsTable.test.tsx | 130 ---- .../QueryInsightsTable/QueryInsightsTable.tsx | 577 ----------------- .../QueryInsightsTable.types.ts | 2 - .../QueryInsightsTable.utils.test.ts | 136 ---- .../QueryInsightsTable.utils.ts | 170 ----- .../hooks/useQueryInsightsIssues.ts | 21 - .../useQueryInsightsIssues.utils.test.ts | 101 --- .../hooks/useQueryInsightsIssues.utils.ts | 37 -- .../hooks/useQueryInsightsMetrics.ts | 24 - .../hooks/useQueryInsightsScore.ts | 49 -- .../hooks/useQueryInsightsTableColumns.tsx | 600 ------------------ .../hooks/useSupamonitorIndexAdvisor.ts | 62 -- .../utils/supamonitor.utils.test.ts | 283 --------- .../QueryInsights/utils/supamonitor.utils.ts | 210 ------ .../QueryPerformance/QueryPerformance.ai.ts | 8 +- .../QueryPerformance.types.ts | 6 + .../QueryPerformance.utils.test.ts | 77 ++- .../QueryPerformance.utils.ts | 129 +++- .../hooks/useSupamonitorStatus.ts | 15 - .../ObservabilityMenu.utils.test.tsx | 23 +- .../ObservabilityMenu.utils.tsx | 25 +- apps/studio/data/database/keys.ts | 2 - .../database/supamonitor-enabled-query.ts | 53 -- apps/studio/redirects.shared.ts | 5 + apps/studio/routeTree.gen.ts | 23 - .../$ref/observability/query-insights.tsx | 64 -- 51 files changed, 224 insertions(+), 4063 deletions(-) delete mode 100644 apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx delete mode 100644 apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx delete mode 100644 apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx delete mode 100644 apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.ai.ts delete mode 100644 apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsights.constants.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsights.types.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.constants.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChartTooltip.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.constants.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.types.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.test.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthMetric.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScore.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScoreSkeleton.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsDetailSheet.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.constants.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.types.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.test.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsMetrics.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsScore.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx delete mode 100644 apps/studio/components/interfaces/QueryInsights/hooks/useSupamonitorIndexAdvisor.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts delete mode 100644 apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.ts delete mode 100644 apps/studio/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus.ts delete mode 100644 apps/studio/data/database/supamonitor-enabled-query.ts delete mode 100644 apps/studio/routes/project/$ref/observability/query-insights.tsx diff --git a/apps/studio/.github/eslint-rule-baselines.json b/apps/studio/.github/eslint-rule-baselines.json index 3dbcdc4c086..21df4739e0e 100644 --- a/apps/studio/.github/eslint-rule-baselines.json +++ b/apps/studio/.github/eslint-rule-baselines.json @@ -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, diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx deleted file mode 100644 index 5d50ab3ae90..00000000000 --- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.Header.tsx +++ /dev/null @@ -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 ( -
- {/* Title row */} -
-
-

Query Execution Plan

- - - - - -

How to read

-

- Start at the bottom where data is read from tables, then follow upward as each step - processes the results. -

- - {isVisual && ( - <> -

Key

-
-
- - Seq Scan (slow) -
-
- - Index Scan (fast) -
-
- - )} -
-
- {/* Summary stats - only show in visual mode when we have the data */} - {hasSummaryStats && ( -
- {summary.totalTime > 0 && ( -
- / - Total time - - {summary.totalTime.toFixed(2)}ms - -
- )} -
- )} -
-
- {id && rows && ( - - )} - -
-
-
- ) -} diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx deleted file mode 100644 index eaff13989c8..00000000000 --- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.NodeRow.tsx +++ /dev/null @@ -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 */} -
- {/* Main row */} -
- {/* Left section: expand button + operation info */} -
- {/* Expand/collapse button */} - - - {/* Operation name and cost info */} -
- - {node.operation} - - - (cost {node.cost?.end?.toFixed(1) ?? -} - , estimated {node.rows?.toLocaleString() ?? ?}{' '} - {node.rows === 1 ? row : rows} - ) - -
-
- - {/* Right section: duration bar visualization */} -
- {hasTimingData && ( - <> - {/* Duration bar - width represents % of slowest operation */} -
- {/* Duration and row count info */} -
- - - - {formatNodeDuration(duration)} - - - -

Execution time: {formatNodeDuration(duration)}

-

- 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. -

-
-
- / - -
- - )} -
-
- - {/* Expanded details section */} - {isExpanded && detailLines.length > 0 && ( -
-
- {detailLines.map((line, idx) => ( -
- {line.label && {line.label}} - {line.value} -
- ))} -
-
- )} -
- - {/* Render children recursively */} - {hasChildren && - node.children.map((child, idx) => ( - - ))} - - ) -} diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx deleted file mode 100644 index 00222f80fd5..00000000000 --- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.RowCountIndicator.tsx +++ /dev/null @@ -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 ( - - -
- {formatRowCount(totalRowsScanned)} - - - -{formatRowCount(rowsRemovedByFilter)} - - - - {formatRowCount(actualRows)} {actualRows === 1 ? row : rows} - -
-
- -

Filter applied

-

- {formatRowCount(totalRowsScanned)} rows were scanned,{' '} - {formatRowCount(rowsRemovedByFilter)} were filtered out, leaving{' '} - {formatRowCount(actualRows)} rows. Consider adding an index to reduce rows scanned. -

-
-
- ) - } - - // Simple row count with actual rows - if (hasActualRows) { - return ( - - - - {formatRowCount(actualRows)} {actualRows === 1 ? row : rows} - - - -

Rows returned

-

- This operation processed and returned {formatRowCount(actualRows)} rows. -

-
-
- ) - } - - // Only estimated rows available (EXPLAIN without ANALYZE) - if (hasEstimatedRows) { - return ( - - - - est. {formatRowCount(estimatedRows)}{' '} - {estimatedRows === 1 ? row : rows} - - - -

Estimated rows

-

- The planner estimates this operation will return {formatRowCount(estimatedRows)} rows. - Run with EXPLAIN ANALYZE to see actual row counts. -

-
-
- ) - } - - return - -} diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.ai.ts b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.ai.ts deleted file mode 100644 index 1258cb526b4..00000000000 --- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.ai.ts +++ /dev/null @@ -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, - } -} diff --git a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx b/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx deleted file mode 100644 index fea215fc036..00000000000 --- a/apps/studio/components/interfaces/ExplainVisualizer/ExplainVisualizer.tsx +++ /dev/null @@ -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 ( -
-

- No execution plan data available -

-
- ) - } - - return ( -
- {onShowRaw && ( - - )} - - {/* Plan nodes */} -
-
- {parsedTree.map((node, idx) => ( - - ))} -
-
-
- ) -} diff --git a/apps/studio/components/interfaces/Observability/Observability.constants.ts b/apps/studio/components/interfaces/Observability/Observability.constants.ts index 2c47e519e38..54d07245c1c 100644 --- a/apps/studio/components/interfaces/Observability/Observability.constants.ts +++ b/apps/studio/components/interfaces/Observability/Observability.constants.ts @@ -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`, diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsights.constants.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsights.constants.ts deleted file mode 100644 index 79802d63754..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsights.constants.ts +++ /dev/null @@ -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() -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx deleted file mode 100644 index 4e0802c8745..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx +++ /dev/null @@ -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(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 ( -
- - - -
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsights.types.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsights.types.ts deleted file mode 100644 index d9236b1bf41..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsights.types.ts +++ /dev/null @@ -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 -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.constants.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.constants.ts deleted file mode 100644 index ebcad57322f..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.constants.ts +++ /dev/null @@ -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 = { - 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)' diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.tsx deleted file mode 100644 index ec9b7c8dff6..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.tsx +++ /dev/null @@ -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>(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 - 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 ( -
- - - {CHART_TABS.map((tab) => ( - - {tab.label} - - ))} - - - -
- {legendItems.map((item: { dataKey: string; label: string; color: string }) => ( - - ))} - {hasSelection && ( - - )} -
-
-
- {isLoading ? ( -
- -
- ) : data.length === 0 ? ( -
-

No data available

-
- ) : ( - - - - {legendItems.map((item) => ( - - - - - ))} - {hasSelection && ( - - - - - )} - - - - selectedMetric === 'query_latency' - ? `${Math.round(v)}ms` - : `${Math.round(v)}` - } - mirror={true} - /> - } - cursor={{ - stroke: isDarkMode ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)', - strokeWidth: 1, - }} - /> - - {legendItems.map((item) => ( - - ))} - {hasSelection && ( - - )} - - - )} -
- - {data.length > 0 && ( -
- {formatTime(data[0].time)} - {formatTime(data[data.length - 1].time)} -
- )} -
-
-
-
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts deleted file mode 100644 index 3c117836ed0..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.test.ts +++ /dev/null @@ -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/) - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.ts deleted file mode 100644 index 7bb52a9eaca..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChart.utils.ts +++ /dev/null @@ -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', - }) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChartTooltip.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChartTooltip.tsx deleted file mode 100644 index d89cd783338..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsChart/QueryInsightsChartTooltip.tsx +++ /dev/null @@ -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) => { - if (!active || !payload?.length) return null - - const time = payload[0]?.payload?.time - const localTimeZone = guessLocalTimezone() - - return ( -
-

{localTimeZone}

-

{dayjs(time).format('MMM D, hh:mm:ssa')}

-
- {payload.map((entry, index) => ( -
- - - - {entry.name} - - {typeof entry.value === 'number' - ? isTimeMetric(typeof entry.dataKey === 'string' ? entry.dataKey : '') - ? formatDuration(entry.value) - : entry.value.toLocaleString() - : entry.value} - -
- ))} -
-
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.constants.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.constants.ts deleted file mode 100644 index 45ebd92413d..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.constants.ts +++ /dev/null @@ -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 = { - healthy: { label: 'Healthy', min: 70 }, - warning: { label: 'Needs attention', min: 40 }, - critical: { label: 'Critical', min: 0 }, -} - -export const HEALTH_COLORS: Record = { - healthy: 'hsl(var(--brand-default))', - warning: 'var(--warning)', - critical: 'hsl(var(--destructive-default))', -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.tsx deleted file mode 100644 index c99fc266b54..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.tsx +++ /dev/null @@ -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 ( -
-
- {isLoading ? ( - - ) : ( - - )} -
-
-
- - - - -
-
-
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.types.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.types.ts deleted file mode 100644 index 2a469533dce..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.types.ts +++ /dev/null @@ -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 -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.test.ts deleted file mode 100644 index 1aaa160d80c..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.test.ts +++ /dev/null @@ -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') - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.ts deleted file mode 100644 index ed78d729b2e..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealth.utils.ts +++ /dev/null @@ -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' -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthMetric.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthMetric.tsx deleted file mode 100644 index ab2ff3e9412..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthMetric.tsx +++ /dev/null @@ -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 ( -
- {label} - {isLoading ? ( -
- ) : ( - {value} - )} -
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScore.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScore.tsx deleted file mode 100644 index d870e60f581..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScore.tsx +++ /dev/null @@ -1,33 +0,0 @@ -export const QueryInsightsHealthScore = ({ - score, - color, - label, -}: { - score: number - color: string - label: string -}) => ( - <> -
-
- {score} -
-
-
- - Health Score - - - {label} - -
- -) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScoreSkeleton.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScoreSkeleton.tsx deleted file mode 100644 index a683b63a30a..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsHealth/QueryInsightsHealthScoreSkeleton.tsx +++ /dev/null @@ -1,9 +0,0 @@ -export const QueryInsightsHealthScoreSkeleton = () => ( - <> -
-
-
-
-
- -) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsDetailSheet.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsDetailSheet.tsx deleted file mode 100644 index cbb98c749a0..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsDetailSheet.tsx +++ /dev/null @@ -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 - triageContainerRef: React.RefObject - explainLoadingQuery: string | null - explainResults: Record -} - -export const QueryInsightsDetailSheet = ({ - open, - onOpenChange, - activeSheetRow, - sheetView, - onSheetViewChange, - onClose, - dataGridContainerRef, - triageContainerRef, - explainLoadingQuery, - explainResults, -}: QueryInsightsDetailSheetProps) => { - const { openSidebar } = useSidebarManagerSnapshot() - const aiSnap = useAiAssistantStateSnapshot() - - return ( - - Query details - Query Insights Details & Indexes - { - if ( - dataGridContainerRef.current?.contains(event.target as Node) || - triageContainerRef.current?.contains(event.target as Node) - ) { - event.preventDefault() - } - }} - > - onSheetViewChange(v as 'details' | 'indexes' | 'explain')} - > -
- - - Query details - - - Indexes - - {activeSheetRow?.issueType !== 'error' && ( - - Explain - - )} - -
- - {activeSheetRow && ( - onSheetViewChange('indexes')} - onClose={onClose} - /> - )} - - - {activeSheetRow && } - - - {explainLoadingQuery ? ( -
- Running EXPLAIN ANALYZE... -
- ) : activeSheetRow && explainResults[activeSheetRow.query]?.length > 0 ? ( - <> -
-

EXPLAIN ANALYZE output

- -
-
- -
- - ) : ( -
- No explain results available. -
- )} -
-
-
-
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.constants.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.constants.ts deleted file mode 100644 index 97becd52f15..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.constants.ts +++ /dev/null @@ -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 = { - 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 diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx deleted file mode 100644 index 75bb84a4832..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx +++ /dev/null @@ -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( - - - , - { 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' }) - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx deleted file mode 100644 index ca57af53ae6..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.tsx +++ /dev/null @@ -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('triage') - const [filter, setFilter] = useState('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() - const [selectedTriageRow, setSelectedTriageRow] = useState() - const [sheetView, setSheetView] = useState<'details' | 'indexes' | 'explain'>('details') - const gridRef = useRef(null) - const triageGridRef = useRef(null) - const dataGridContainerRef = useRef(null) - const triageContainerRef = useRef(null) - const scrollContainerRef = useRef(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>({}) - const [explainLoadingQuery, setExplainLoadingQuery] = useState(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 ( -
-
-
-
- setMode(mode as Mode)} - /> - {appNameFilter.length > 0 ? ( - setAppNameFilter([])} - /> - ) : ( - - )} -
- -
- {mode === 'triage' ? ( - setFilter(v as IssueFilter)}> - - - All{triageItems.length > 0 && {` (${triageItems.length})`}} - - - Errors{errorCount > 0 && {` (${errorCount})`}} - - - Index{indexCount > 0 && {` (${indexCount})`}} - - - Slow{slowCount > 0 && {` (${slowCount})`}} - - - - ) : ( - } - value={searchQuery} - onChange={(e) => setSearchQuery(e.target.value)} - name="search" - id="search" - placeholder="Search queries..." - className="w-64" - actions={[ - searchQuery && ( -
-
-
- -
-
- - - -
- {isLoading ? ( -
- -
- ) : mode === 'triage' ? ( -
- { - 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 ( - { - event.stopPropagation() - if (typeof idx === 'number' && idx >= 0) { - const query = filteredTriageItems[idx]?.query - if (query && onCurrentSelectQuery) { - onCurrentSelectQuery(currentSelectedQuery === query ? null : query) - } - } - }} - /> - ) - }, - noRowsFallback: ( -
- -
-

No issues found

-

- {data.length === 0 - ? 'No query data available yet' - : 'No issues detected for the selected filter'} -

-
-
- ), - }} - /> -
- ) : ( -
- { - 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 ( - { - event.stopPropagation() - if (typeof idx === 'number' && idx >= 0) { - const query = explorerItems[idx]?.query - if (query && onCurrentSelectQuery) { - onCurrentSelectQuery(currentSelectedQuery === query ? null : query) - } - } - }} - /> - ) - }, - noRowsFallback: ( -
- -
-

No queries found

-

- {searchQuery.trim() - ? 'No queries match your search criteria' - : 'No query data available yet'} -

-
-
- ), - }} - /> -
- )} -
- - { - 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} - /> -
- ) -} diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.types.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.types.ts deleted file mode 100644 index 932e77ff456..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.types.ts +++ /dev/null @@ -1,2 +0,0 @@ -export type Mode = 'triage' | 'explorer' -export type IssueFilter = 'all' | 'error' | 'index' | 'slow' diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts deleted file mode 100644 index db6150dd263..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.test.ts +++ /dev/null @@ -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 –, –') - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.ts b/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.ts deleted file mode 100644 index 51e7814d52c..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.utils.ts +++ /dev/null @@ -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+(?:(?(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match( - /INSERT\s+INTO\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match(/UPDATE\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match( - /DELETE\s+FROM\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match( - /ALTER\s+TABLE\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match( - /DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.table) { - return cleanIdentifier(match.groups.table) - } - - match = trimmed.match( - /TRUNCATE\s+(?:TABLE\s+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.column) { - return cleanIdentifier(match?.groups?.column) - } - - match = trimmed.match( - /SELECT\s+(?:\*\s+FROM|(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\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+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.column) { - return cleanIdentifier(match.groups.column) - } - - match = trimmed.match( - /GROUP\s+BY\s+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.column) { - return cleanIdentifier(match.groups.column) - } - - match = trimmed.match( - /UPDATE\s+[\w.]+\s+SET\s+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i - ) - if (match?.groups?.column) { - return cleanIdentifier(match.groups.column) - } - - match = trimmed.match(/INSERT\s+INTO\s+[\w.]+\s*\((?(?:"[^"]+"|[\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}` -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.ts deleted file mode 100644 index 6061ff6b08f..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.ts +++ /dev/null @@ -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]) -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.test.ts deleted file mode 100644 index 8b87bc260e5..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.test.ts +++ /dev/null @@ -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() - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.ts deleted file mode 100644 index 360a99e18f6..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsIssues.utils.ts +++ /dev/null @@ -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: '' } -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsMetrics.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsMetrics.ts deleted file mode 100644 index 28dd8c88ed5..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsMetrics.ts +++ /dev/null @@ -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 } -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsScore.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsScore.ts deleted file mode 100644 index 09ea9e79384..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsScore.ts +++ /dev/null @@ -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]) -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx b/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx deleted file mode 100644 index 68c30e4ec4e..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useQueryInsightsTableColumns.tsx +++ /dev/null @@ -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 - 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[] - triageColumns: Column[] -} { - const columns = useMemo(() => { - return QUERY_INSIGHTS_EXPLORER_COLUMNS.map((col) => { - const isSortable = !NON_SORTABLE_COLUMNS.includes(col.id as never) - - const result: Column = { - 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 ( -
-
-

{col.name}

- {col.description && ( -

{col.description}

- )} -
- - {isSortable && ( - - -
- ) - }, - 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 ( -
-
- {row.issueType && IssueIcon && ( - - -
- -
-
- {row.hint && ( - - {row.hint} - - )} -
- )} -
- - } - 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" - /> -
- ) - } - - 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 ( -
-
- {percentage && totalTime ? ( - - - {percentage.toFixed(1)}% - - / - - {formatDuration(totalTime)} - - - ) : ( -

–

- )} -
- ) - } - - if (col.id === 'calls') { - return ( -
- {typeof value === 'number' && !isNaN(value) && isFinite(value) ? ( -

- {value.toLocaleString()} -

- ) : ( -

–

- )} -
- ) - } - - if (col.id === 'max_time' || col.id === 'mean_time' || col.id === 'min_time') { - return ( -
- {typeof value === 'number' && !isNaN(value) && isFinite(value) ? ( -

- {Math.round(value).toLocaleString()}ms -

- ) : ( -

–

- )} -
- ) - } - - if (col.id === 'rows_read') { - return ( -
- {typeof value === 'number' && !isNaN(value) && isFinite(value) ? ( -

- {value.toLocaleString()} -

- ) : ( -

–

- )} -
- ) - } - - if (col.id === 'cache_hit_rate') { - const num = typeof value === 'number' ? value : parseFloat(value ?? '0') - return ( -
- {typeof num === 'number' && !isNaN(num) && isFinite(num) ? ( -

- {num.toLocaleString(undefined, { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - })} - % -

- ) : ( -

–

- )} -
- ) - } - - if (col.id === 'rolname') { - return ( -
- {value ? ( - -

{value}

- - { - QUERY_PERFORMANCE_ROLE_DESCRIPTION.find((r) => r.name === value) - ?.description - } - -
- ) : ( -

–

- )} -
- ) - } - - if (col.id === 'application_name') { - return ( -
- {value ? ( -

{value}

- ) : ( -

–

- )} -
- ) - } - - return null - }, - } - return result - }) - }, [sort, setSort, timeConsumedWidth, gridRef, setSelectedRow, setSheetView]) - - const triageColumns = useMemo( - (): Column[] => [ - { - key: 'query', - name: 'Query', - minWidth: triageQueryColWidth, - width: triageQueryColWidth, - resizable: true, - headerCellClass: 'first:pl-6 cursor-default', - renderHeaderCell: () => ( -
-

Query

-
- ), - renderCell: (props) => { - const row = props.row as ClassifiedQuery - const IssueIcon = row.issueType ? ISSUE_ICONS[row.issueType] : null - return ( -
-
- {row.issueType && IssueIcon && ( -
- -
- )} -
-
-

- {row.queryType ?? –} - {getTableName(row.query) && ( - <> - {' '} - in {getTableName(row.query)} - - )} - {getColumnName(row.query) && ( - <> - , {getColumnName(row.query)} - - )} -

-

- {row.hint} -

-
- } - size="tiny" - onClick={(e: React.MouseEvent) => { - e.stopPropagation() - setSelectedTriageRow(props.rowIdx) - setSheetView('details') - }} - className="p-1 shrink-0 group-hover:flex hidden" - /> -
- ) - }, - }, - { - key: 'prop_total_time', - name: 'Time consumed', - minWidth: timeConsumedWidth, - resizable: true, - cellClass: 'column-prop_total_time', - headerCellClass: 'cursor-default', - renderHeaderCell: () => ( -
-

Time consumed

-
- ), - 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 ( -
-
- {percentage && totalTime ? ( - - - {percentage.toFixed(1)}% - - / - - {formatDuration(totalTime)} - - - ) : ( -

–

- )} -
- ) - }, - }, - { - key: 'calls', - name: 'Calls', - minWidth: 90, - resizable: true, - headerCellClass: 'cursor-default', - renderHeaderCell: () => ( -
-

Calls

-
- ), - renderCell: (props) => { - const value = (props.row as ClassifiedQuery).calls - return ( -
- {typeof value === 'number' && !isNaN(value) && isFinite(value) ? ( -

- {value.toLocaleString()} -

- ) : ( -

–

- )} -
- ) - }, - }, - { - key: 'mean_time', - name: 'Mean time', - minWidth: 90, - resizable: true, - headerCellClass: 'cursor-default', - renderHeaderCell: () => ( -
-

Mean time

-
- ), - renderCell: (props) => { - const value = (props.row as ClassifiedQuery).mean_time - return ( -
- {typeof value === 'number' && !isNaN(value) && isFinite(value) ? ( -

- {formatDuration(value)} -

- ) : ( -

–

- )} -
- ) - }, - }, - { - key: 'actions', - name: 'Actions', - minWidth: 200, - resizable: false, - headerCellClass: 'cursor-default', - renderHeaderCell: () => ( -
-

Actions

-
- ), - renderCell: (props) => { - const row = props.row as ClassifiedQuery - return ( -
- {!row.issueType && ( - - )} - {row.issueType === 'index' && ( -
e.stopPropagation()}> - - - -
- )} - {(row.issueType === 'error' || row.issueType === 'slow') && ( -
e.stopPropagation()}> - buildQueryInsightFixPrompt(row).prompt} - onOpenAssistant={() => handleAiSuggestedFix(row)} - copyLabel="Copy Markdown" - additionalDropdownItems={[ - { - label: 'Go to Logs', - icon: , - onClick: () => handleGoToLogs(), - }, - ...(row.issueType === 'slow' - ? [ - { - label: 'Explain', - icon: , - onClick: () => { - setSelectedTriageRow(props.rowIdx) - setSheetView('explain') - }, - }, - ] - : []), - ]} - /> -
- )} -
- ) - }, - }, - ], - [ - triageQueryColWidth, - timeConsumedWidth, - handleGoToLogs, - handleAiSuggestedFix, - setSelectedTriageRow, - setSheetView, - ] - ) - - return { columns, triageColumns } -} diff --git a/apps/studio/components/interfaces/QueryInsights/hooks/useSupamonitorIndexAdvisor.ts b/apps/studio/components/interfaces/QueryInsights/hooks/useSupamonitorIndexAdvisor.ts deleted file mode 100644 index 3b4f5a5c4e7..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/hooks/useSupamonitorIndexAdvisor.ts +++ /dev/null @@ -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), - })) -} diff --git a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts b/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts deleted file mode 100644 index 67360628520..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.test.ts +++ /dev/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 = {}): 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) - }) -}) diff --git a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.ts b/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.ts deleted file mode 100644 index 7f326965be7..00000000000 --- a/apps/studio/components/interfaces/QueryInsights/utils/supamonitor.utils.ts +++ /dev/null @@ -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 => 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() - - 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) -} diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts index 23e681a7a35..d4ae680e6fd 100644 --- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts +++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts @@ -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 diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts index 3c438a4666e..cd8af0dccd7 100644 --- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts +++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts @@ -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 diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.test.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.test.ts index 96ce1004607..dc0b14f7cb2 100644 --- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.test.ts +++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.test.ts @@ -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') + }) +}) diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts index be187c11aae..bbf7980197f 100644 --- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts +++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts @@ -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+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match( + /INSERT\s+INTO\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match(/UPDATE\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match( + /DELETE\s+FROM\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match( + /ALTER\s+TABLE\s+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match( + /DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.table) { + return cleanIdentifier(match.groups.table) + } + + match = trimmed.match( + /TRUNCATE\s+(?:TABLE\s+)?(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+(?:(?(?:"[^"]+"|[\w]+)\.)?(?
(?:"[^"]+"|[\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+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.column) { + return cleanIdentifier(match?.groups?.column) + } + + match = trimmed.match( + /SELECT\s+(?:\*\s+FROM|(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\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+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.column) { + return cleanIdentifier(match.groups.column) + } + + match = trimmed.match( + /GROUP\s+BY\s+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.column) { + return cleanIdentifier(match.groups.column) + } + + match = trimmed.match( + /UPDATE\s+[\w.]+\s+SET\s+(?:(?
(?:"[^"]+"|[\w]+)\.)?(?(?:"[^"]+"|[\w]+)))/i + ) + if (match?.groups?.column) { + return cleanIdentifier(match.groups.column) + } + + match = trimmed.match(/INSERT\s+INTO\s+[\w.]+\s*\((?(?:"[^"]+"|[\w]+))/i) + if (match?.groups?.column) { + return cleanIdentifier(match.groups.column) + } + + return null +} diff --git a/apps/studio/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus.ts b/apps/studio/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus.ts deleted file mode 100644 index 0b70e1aba9b..00000000000 --- a/apps/studio/components/interfaces/QueryPerformance/hooks/useSupamonitorStatus.ts +++ /dev/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, - } -} diff --git a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx index c6f877962d6..bfe2c6fe022 100644 --- a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx +++ b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.test.tsx @@ -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', () => { diff --git a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx index 0b36753ae18..0d336decdb9 100644 --- a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx +++ b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx @@ -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 ? [ { diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts index 9ff1df0470e..91da6ccee89 100644 --- a/apps/studio/data/database/keys.ts +++ b/apps/studio/data/database/keys.ts @@ -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) => diff --git a/apps/studio/data/database/supamonitor-enabled-query.ts b/apps/studio/data/database/supamonitor-enabled-query.ts deleted file mode 100644 index 8cf75cbf20d..00000000000 --- a/apps/studio/data/database/supamonitor-enabled-query.ts +++ /dev/null @@ -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> -export type SupamonitorEnabledError = StudioError - -export const useSupamonitorEnabledQuery = ( - { projectRef, connectionString }: SupamonitorEnabledVariables, - { - enabled = true, - ...options - }: UseCustomQueryOptions = {} -) => { - const { data: project } = useSelectedProjectQuery() - const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY - - return useQuery({ - queryKey: databaseKeys.supamonitorEnabled(projectRef), - queryFn: () => getSupamonitorEnabled({ projectRef, connectionString }), - enabled: enabled && typeof projectRef !== 'undefined' && isActive, - ...options, - }) -} diff --git a/apps/studio/redirects.shared.ts b/apps/studio/redirects.shared.ts index f8b2088c507..a141fa81907 100644 --- a/apps/studio/redirects.shared.ts +++ b/apps/studio/redirects.shared.ts @@ -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', diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts index c9913b6f22b..8408b462311 100644 --- a/apps/studio/routeTree.gen.ts +++ b/apps/studio/routeTree.gen.ts @@ -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, diff --git a/apps/studio/routes/project/$ref/observability/query-insights.tsx b/apps/studio/routes/project/$ref/observability/query-insights.tsx deleted file mode 100644 index a9751ed56df..00000000000 --- a/apps/studio/routes/project/$ref/observability/query-insights.tsx +++ /dev/null @@ -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 ( -
-
-

{REPORT_TITLE}

-
- - - -
-
- -
- ) -}