Files
supabase/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
kemal.earth 70a64f8c00 feat(studio): query performance metrics chart (#39431)
* feat: setup chart area and tabs

This sets up the area where we can expect the insights chart as well as the tabs mechanism.

* feat: parse pg_stat_monitor logs as json

* feat: create query perf chart utils and move transfrom function

Created a utils file for our QueryPerformanceChart component. This moves the logs to JSON transform function there.

* feat: add timerange to chart

* feat: add date selector to query perf overview

This adds the selector to the top right of the page allowing the user to switch between last hour, 3 hours and 24 hours

* feat: modify chart component to accomodate hiding bits

* feat: add metrics to each tab

* chore: update to 60 min by default and some css

* feat: centralise data parsing for logs

* feat: clean up filters bar

This rewires the export to give you the aggregate pg_stat_monitor data. Also removes unused buttons and filters.

* feat: percentiles for query latency chart

* feat: filter out non evenets from pg_stat_monitor logs

* feat: utils for cache misses and hits

* feat: add selected query to chart on click

* feat: add click through to query panel

* chore: tidy up files

* chore: distinction between selected and open panel

* feat: move query performance fully into reports area

* fix: preserve query params on reports link

* fix: remove right icon syntax in report menu

* chore: remove cache misses from cache chart

* refactor: backwards compatibility for statements if right db version isnt available

* chore: delete randomly generated empty file

* chore: tidy up unused imports and vars

* chore: remove console logs

* chore: remove isMounted from query perf

* fix: cmd k query perf path

* feat: simplify query latency only p50 and p95

This seems to give us a more accurate reading as we can calculate these two

* fix: cache hit rate not showing inside query details

* chore: chart bg colour adjust

So it contrasts a little better on light mode.

* feat: show selected query on other verticals

* feat: bring back symlink in advisors
2025-10-15 13:39:29 +01:00

205 lines
7.7 KiB
TypeScript

import { Lightbulb, ChevronsUpDown } from 'lucide-react'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
import { formatSql } from 'lib/formatSql'
import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, cn } from 'ui'
import { QueryPanelContainer, QueryPanelSection } from './QueryPanel'
import {
QUERY_PERFORMANCE_COLUMNS,
QUERY_PERFORMANCE_REPORT_TYPES,
} from './QueryPerformance.constants'
import { formatDuration } from './QueryPerformance.utils'
interface QueryDetailProps {
reportType: QUERY_PERFORMANCE_REPORT_TYPES
selectedRow: any
onClickViewSuggestion: () => void
}
// Load SqlMonacoBlock (monaco editor) client-side only (does not behave well server-side)
const SqlMonacoBlock = dynamic(
() => import('./SqlMonacoBlock').then(({ SqlMonacoBlock }) => SqlMonacoBlock),
{
ssr: false,
}
)
export const QueryDetail = ({ selectedRow, onClickViewSuggestion }: QueryDetailProps) => {
// [Joshen] TODO implement this logic once the linter rules are in
const isLinterWarning = false
const report = QUERY_PERFORMANCE_COLUMNS
const [query, setQuery] = useState(selectedRow?.['query'])
useEffect(() => {
if (selectedRow !== undefined) {
const formattedQuery = formatSql(selectedRow['query'])
setQuery(formattedQuery)
}
}, [selectedRow])
const [isExpanded, setIsExpanded] = useState(false)
return (
<QueryPanelContainer>
<QueryPanelSection className="pt-2 border-b relative">
<h4 className="mb-4">Query pattern</h4>
<div
className={cn(
'overflow-hidden pb-0 z-0 relative transition-all duration-300',
isExpanded ? 'h-[348px]' : 'h-[120px]'
)}
>
<SqlMonacoBlock
value={query}
height={322}
lineNumbers="off"
wrapperClassName={cn('pl-3 bg-surface-100', !isExpanded && 'pointer-events-none')}
/>
{isLinterWarning && (
<Alert_Shadcn_
variant="default"
className="mt-2 border-brand-400 bg-alternative [&>svg]:p-0.5 [&>svg]:bg-transparent [&>svg]:text-brand"
>
<Lightbulb />
<AlertTitle_Shadcn_>Suggested optimization: Add an index</AlertTitle_Shadcn_>
<AlertDescription_Shadcn_>
Adding an index will help this query execute faster
</AlertDescription_Shadcn_>
<AlertDescription_Shadcn_>
<Button className="mt-3" onClick={() => onClickViewSuggestion()}>
View suggestion
</Button>
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
)}
</div>
<div
className={cn(
'absolute left-0 bottom-0 w-full bg-gradient-to-t from-black/30 to-transparent h-24 transition-opacity duration-300',
isExpanded && 'opacity-0 pointer-events-none'
)}
/>
<div className="absolute -bottom-[13px] left-0 right-0 w-full flex items-center justify-center z-10">
<Button
type="default"
className="rounded-full"
icon={<ChevronsUpDown />}
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? 'Collapse' : 'Expand'}
</Button>
</div>
</QueryPanelSection>
<QueryPanelSection className="pb-3 pt-6">
<h4 className="mb-2">Metadata</h4>
<ul className="flex flex-col gap-y-3 divide-y divide-dashed">
{report
.filter((x) => x.id !== 'query')
.map((x) => {
const rawValue = selectedRow?.[x.id]
const isTime = x.name.includes('time')
const formattedValue = isTime
? typeof rawValue === 'number' && !isNaN(rawValue) && isFinite(rawValue)
? `${Math.round(rawValue).toLocaleString()}ms`
: 'n/a'
: rawValue != null
? String(rawValue)
: 'n/a'
if (x.id === 'prop_total_time') {
const percentage = selectedRow?.prop_total_time || 0
const totalTime = selectedRow?.total_time || 0
return (
<li key={x.id} className="flex justify-between pt-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{percentage && totalTime ? (
<p className="flex items-center gap-x-1.5">
<span
className={cn(
'tabular-nums',
percentage.toFixed(1) === '0.0' && 'text-foreground-lighter'
)}
>
{percentage.toFixed(1)}%
</span>{' '}
<span className="text-muted">/</span>{' '}
<span
className={cn(
'tabular-nums',
formatDuration(totalTime) === '0.00s' && 'text-foreground-lighter'
)}
>
{formatDuration(totalTime)}
</span>
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
if (x.id == 'rows_read') {
return (
<li key={x.id} className="flex justify-between pt-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{typeof rawValue === 'number' && !isNaN(rawValue) && isFinite(rawValue) ? (
<p
className={cn('tabular-nums', rawValue === 0 && 'text-foreground-lighter')}
>
{rawValue.toLocaleString()}
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
const cacheHitRateToNumber = (value: number | string) => {
if (typeof value === 'number') return value
return parseFloat(value.toString().replace('%', '')) || 0
}
if (x.id === 'cache_hit_rate') {
return (
<li key={x.id} className="flex justify-between pt-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
{typeof rawValue === 'string' || typeof rawValue === 'number' ? (
<p
className={cn(
cacheHitRateToNumber(rawValue).toFixed(2) === '0.00' &&
'text-foreground-lighter'
)}
>
{cacheHitRateToNumber(rawValue).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
%
</p>
) : (
<p className="text-muted">&ndash;</p>
)}
</li>
)
}
return (
<li key={x.id} className="flex justify-between pt-3 text-sm">
<p className="text-foreground-light">{x.name}</p>
<p className={cn('tabular-nums', x.id === 'rolname' && 'font-mono')}>
{formattedValue}
</p>
</li>
)
})}
</ul>
</QueryPanelSection>
</QueryPanelContainer>
)
}