Skip to content

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

feat(studio): query performance metrics chart (#39431)

kemal.earth70a64f8c00b4
diff --git a/apps/studio/components/interfaces/QueryPerformance/EnableIndexAdvisorButton.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx
similarity index 100%
rename from apps/studio/components/interfaces/QueryPerformance/EnableIndexAdvisorButton.tsx
rename to apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton.tsx
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexAdvisorDisabledState.tsx
similarity index 98%
rename from apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx
rename to apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexAdvisorDisabledState.tsx
index 18e8be8ae94..be9fdbe3a5a 100644
--- a/apps/studio/components/interfaces/QueryPerformance/IndexAdvisorDisabledState.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexAdvisorDisabledState.tsx
@@ -8,7 +8,7 @@ import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-ex
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { DOCS_URL } from 'lib/constants'
import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'
-import { Markdown } from '../Markdown'
+import { Markdown } from '../../Markdown'
import { getIndexAdvisorExtensions } from './index-advisor.utils'
export const IndexAdvisorDisabledState = () => {
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexImprovementText.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexImprovementText.tsx
similarity index 100%
rename from apps/studio/components/interfaces/QueryPerformance/IndexImprovementText.tsx
rename to apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexImprovementText.tsx
diff --git a/apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexSuggestionIcon.tsx
similarity index 97%
rename from apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx
rename to apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexSuggestionIcon.tsx
index 7ecc5975359..5aed88b1479 100644
--- a/apps/studio/components/interfaces/QueryPerformance/IndexSuggestionIcon.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/IndexSuggestionIcon.tsx
@@ -14,8 +14,8 @@ import {
WarningIcon,
} from 'ui'
import { IndexImprovementText } from './IndexImprovementText'
-import { QueryPanelScoreSection } from './QueryPanel'
-import { useIndexInvalidation } from './hooks/useIndexInvalidation'
+import { QueryPanelScoreSection } from '../QueryPanel'
+import { useIndexInvalidation } from '../hooks/useIndexInvalidation'
import { createIndexes } from './index-advisor.utils'
interface IndexSuggestionIconProps {
diff --git a/apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils.ts
similarity index 97%
rename from apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts
rename to apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils.ts
index b6275421cbd..134aea1c322 100644
--- a/apps/studio/components/interfaces/QueryPerformance/index-advisor.utils.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils.ts
@@ -96,7 +96,7 @@ export async function createIndexes({
* @returns Whether there are index recommendations available
*/
export function hasIndexRecommendations(
- result: GetIndexAdvisorResultResponse | undefined,
+ result: GetIndexAdvisorResultResponse | undefined | null,
isSuccess: boolean
): boolean {
return Boolean(isSuccess && result?.index_statements && result.index_statements.length > 0)
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
index f35e1e9e30f..6234374fc98 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
@@ -1,11 +1,9 @@
-import { Lightbulb, ChevronsUpDown, Expand } from 'lucide-react'
+import { Lightbulb, ChevronsUpDown } from 'lucide-react'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
-import dayjs from 'dayjs'
import { formatSql } from 'lib/formatSql'
import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, cn } from 'ui'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { QueryPanelContainer, QueryPanelSection } from './QueryPanel'
import {
QUERY_PERFORMANCE_COLUMNS,
@@ -170,7 +168,7 @@ export const QueryDetail = ({ selectedRow, onClickViewSuggestion }: QueryDetailP
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 === 'string' || typeof rawValue === 'number' ? (
<p
className={cn(
cacheHitRateToNumber(rawValue).toFixed(2) === '0.00' &&
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
index 3ad1f99c133..3c68de3b599 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryIndexes.tsx
@@ -23,11 +23,15 @@ import {
cn,
} from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import { IndexAdvisorDisabledState } from './IndexAdvisorDisabledState'
-import { IndexImprovementText } from './IndexImprovementText'
+import { IndexAdvisorDisabledState } from './IndexAdvisor/IndexAdvisorDisabledState'
+import { IndexImprovementText } from './IndexAdvisor/IndexImprovementText'
import { QueryPanelContainer, QueryPanelScoreSection, QueryPanelSection } from './QueryPanel'
import { useIndexInvalidation } from './hooks/useIndexInvalidation'
-import { calculateImprovement, createIndexes, hasIndexRecommendations } from './index-advisor.utils'
+import {
+ calculateImprovement,
+ createIndexes,
+ hasIndexRecommendations,
+} from './IndexAdvisor/index-advisor.utils'
interface QueryIndexesProps {
selectedRow: any
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
index 97de6b437b1..130dd700a15 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts
@@ -68,3 +68,66 @@ export const QUERY_PERFORMANCE_ROLE_DESCRIPTION = [
'PgBouncer is a lightweight connection pooler for PostgreSQL. Available on paid plans only.',
},
] as const
+
+export const QUERY_PERFORMANCE_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 QUERY_PERFORMANCE_TIME_RANGES = [
+ {
+ id: 'last_60_minutes',
+ label: 'Last 60 minutes',
+ },
+ {
+ id: 'last_3_hours',
+ label: 'Last 3 hours',
+ },
+ {
+ id: 'last_24_hours',
+ label: 'Last 24 hours',
+ },
+]
+
+export const getPgStatMonitorLogsQuery = (startTime: string, endTime: string) =>
+ `
+select
+ id,
+ pgl.timestamp as timestamp,
+ 'postgres' as log_type,
+ CAST(pgl_parsed.sql_state_code AS STRING) as status,
+ CASE
+ WHEN pgl_parsed.error_severity = 'LOG' THEN 'success'
+ WHEN pgl_parsed.error_severity = 'WARNING' THEN 'warning'
+ WHEN pgl_parsed.error_severity = 'FATAL' THEN 'error'
+ WHEN pgl_parsed.error_severity = 'ERROR' THEN 'error'
+ ELSE null
+ END as level,
+ event_message as event_message
+from postgres_logs as pgl
+cross join unnest(pgl.metadata) as pgl_metadata
+cross join unnest(pgl_metadata.parsed) as pgl_parsed
+WHERE pgl.event_message LIKE '%[pg_stat_monitor]%'
+ AND pgl.timestamp >= CAST('${startTime}' AS TIMESTAMP)
+ AND pgl.timestamp <= CAST('${endTime}' AS TIMESTAMP)
+ORDER BY timestamp DESC
+`.trim()
+
+export const PG_STAT_MONITOR_LOGS_QUERY = getPgStatMonitorLogsQuery(
+ new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
+ new Date().toISOString()
+)
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
index d57961890d5..82844f1ca19 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx
@@ -1,158 +1,50 @@
-import { X } from 'lucide-react'
-import { useEffect, useState } from 'react'
-import { toast } from 'sonner'
+import { useEffect } from 'react'
-import { LOCAL_STORAGE_KEYS, useParams } from 'common'
-import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
-import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
-import { executeSql } from 'data/sql/execute-sql-query'
+import { WithMonitor } from './WithMonitor/WithMonitor'
+import { WithStatements } from './WithStatements/WithStatements'
+import { useParams } from 'common'
import { DbQueryHook } from 'hooks/analytics/useDbQuery'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { DOCS_URL, IS_PLATFORM } from 'lib/constants'
import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
-import { Button, LoadingLine, cn } from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { Markdown } from '../Markdown'
import { PresetHookResult } from '../Reports/Reports.utils'
-import { QueryPerformanceFilterBar } from './QueryPerformanceFilterBar'
-import { QueryPerformanceGrid } from './QueryPerformanceGrid'
-import { QueryPerformanceMetrics } from './QueryPerformanceMetrics'
interface QueryPerformanceProps {
queryHitRate: PresetHookResult
queryPerformanceQuery: DbQueryHook<any>
queryMetrics: PresetHookResult
+ isPgStatMonitorEnabled: boolean
+ dateRange?: {
+ period_start: { date: string; time_period: string }
+ period_end: { date: string; time_period: string }
+ interval: string
+ }
+ onDateRangeChange?: (from: string, to: string) => void
}
export const QueryPerformance = ({
queryHitRate,
queryPerformanceQuery,
queryMetrics,
+ isPgStatMonitorEnabled,
+ dateRange,
+ onDateRangeChange,
}: QueryPerformanceProps) => {
const { ref } = useParams()
- const { data: project } = useSelectedProjectQuery()
const state = useDatabaseSelectorStateSnapshot()
- const { isLoading, isRefetching } = queryPerformanceQuery
- const isPrimaryDatabase = state.selectedDatabaseId === ref
- const formattedDatabaseId = formatDatabaseID(state.selectedDatabaseId ?? '')
-
- const [showResetgPgStatStatements, setShowResetgPgStatStatements] = useState(false)
-
- const [showBottomSection, setShowBottomSection] = useLocalStorageQuery(
- LOCAL_STORAGE_KEYS.QUERY_PERF_SHOW_BOTTOM_SECTION,
- true
- )
-
- const handleRefresh = () => {
- queryPerformanceQuery.runQuery()
- queryHitRate.runQuery()
- queryMetrics.runQuery()
- }
-
- const { data: databases } = useReadReplicasQuery({ projectRef: ref })
-
useEffect(() => {
state.setSelectedDatabaseId(ref)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref])
- return (
- <>
- <QueryPerformanceMetrics />
- <QueryPerformanceFilterBar
- queryPerformanceQuery={queryPerformanceQuery}
- onResetReportClick={() => setShowResetgPgStatStatements(true)}
- />
- <LoadingLine loading={isLoading || isRefetching} />
-
- <QueryPerformanceGrid queryPerformanceQuery={queryPerformanceQuery} />
-
- <div
- className={cn('px-6 py-6 flex gap-x-4 border-t relative', {
- hidden: showBottomSection === false,
- })}
- >
- <Button
- className="absolute top-1.5 right-3 px-1.5"
- type="text"
- size="tiny"
- onClick={() => setShowBottomSection(false)}
- >
- <X size="14" />
- </Button>
- <div className="w-[33%] flex flex-col gap-y-1 text-sm">
- <p>Reset report</p>
- <p className="text-xs text-foreground-light">
- Consider resetting the analysis after optimizing any queries
- </p>
- <Button
- type="default"
- className="!mt-3 w-min"
- onClick={() => setShowResetgPgStatStatements(true)}
- >
- Reset report
- </Button>
- </div>
-
- <div className="w-[33%] flex flex-col gap-y-1 text-sm">
- <p>How is this report generated?</p>
- <Markdown
- className="text-xs"
- content={`This report uses the pg_stat_statements table, and pg_stat_statements extension. [Learn more here](${DOCS_URL}/guides/platform/performance#examining-query-performance).`}
- />
- </div>
-
- <div className="w-[33%] flex flex-col gap-y-1 text-sm">
- <p>Inspect your database for potential issues</p>
- <Markdown
- className="text-xs"
- content={`The Supabase CLI comes with a range of tools to help inspect your Postgres instances for
- potential issues. [Learn more here](${DOCS_URL}/guides/database/inspect).`}
- />
- </div>
- </div>
-
- <ConfirmationModal
- visible={showResetgPgStatStatements}
- size="medium"
- variant="destructive"
- title="Reset query performance analysis"
- confirmLabel="Reset report"
- confirmLabelLoading="Resetting report"
- onCancel={() => setShowResetgPgStatStatements(false)}
- onConfirm={async () => {
- const connectionString = databases?.find(
- (db) => db.identifier === state.selectedDatabaseId
- )?.connectionString
-
- if (IS_PLATFORM && !connectionString) {
- return toast.error('Unable to run query: Connection string is missing')
- }
+ if (isPgStatMonitorEnabled) {
+ return <WithMonitor dateRange={dateRange} onDateRangeChange={onDateRangeChange} />
+ }
- try {
- await executeSql({
- projectRef: project?.ref,
- connectionString,
- sql: `SELECT pg_stat_statements_reset();`,
- })
- handleRefresh()
- setShowResetgPgStatStatements(false)
- } catch (error: any) {
- toast.error(`Failed to reset analysis: ${error.message}`)
- }
- }}
- >
- <p className="text-foreground-light text-sm">
- This will reset the pg_stat_statements table in the extensions schema on your{' '}
- <span className="text-foreground">
- {isPrimaryDatabase ? 'primary database' : `read replica (ID: ${formattedDatabaseId})`}
- </span>
- , which is used to calculate query performance. This data will repopulate immediately
- after.
- </p>
- </ConfirmationModal>
- </>
+ return (
+ <WithStatements
+ queryHitRate={queryHitRate}
+ queryPerformanceQuery={queryPerformanceQuery}
+ queryMetrics={queryMetrics}
+ />
)
}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts
new file mode 100644
index 00000000000..e7499b46d9a
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts
@@ -0,0 +1,18 @@
+import { GetIndexAdvisorResultResponse } from 'data/database/retrieve-index-advisor-result-query'
+
+export interface QueryPerformanceRow {
+ query: string
+ prop_total_time: number
+ total_time: number
+ calls: number
+ max_time: number
+ mean_time: number
+ min_time: number
+ rows_read: number
+ cache_hit_rate: number
+ rolname: string
+ index_advisor_result?: GetIndexAdvisorResultResponse | null
+ _total_cache_hits?: number
+ _total_cache_misses?: number
+ _count?: number
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
index ce7d211123e..fb13634e4b2 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
@@ -24,3 +24,14 @@ export const formatDuration = (milliseconds: number) => {
return parts.length > 0 ? parts.join(' ') : '0s'
}
+
+export const transformLogsToJSON = (log: string) => {
+ try {
+ let jsonString = log.replace('[pg_stat_monitor] ', '')
+ jsonString = jsonString.replace(/""/g, '","')
+ const jsonObject = JSON.parse(jsonString)
+ return jsonObject
+ } catch (error) {
+ return null
+ }
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceChart.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceChart.tsx
new file mode 100644
index 00000000000..30fa2578e1f
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceChart.tsx
@@ -0,0 +1,360 @@
+import { useState, useMemo } from 'react'
+import { Tabs_Shadcn_, TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_ } from 'ui'
+import { QUERY_PERFORMANCE_CHART_TABS } from './QueryPerformance.constants'
+import { Loader2 } from 'lucide-react'
+import { ComposedChart } from 'components/ui/Charts/ComposedChart'
+import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
+import type { ChartDataPoint } from './WithMonitor/WithMonitor.utils'
+
+interface QueryPerformanceChartProps {
+ dateRange?: {
+ period_start: { date: string; time_period: string }
+ period_end: { date: string; time_period: string }
+ interval: string
+ }
+ onDateRangeChange?: (from: string, to: string) => void
+ chartData: ChartDataPoint[]
+ isLoading: boolean
+ error: any
+ currentSelectedQuery: string | null
+ parsedLogs: any[]
+}
+
+const QueryMetricBlock = ({
+ label,
+ value,
+}: {
+ label: string
+ value: string | number | undefined
+}) => {
+ return (
+ <div className="flex flex-col gap-0.5 text-xs">
+ <span className="font-mono text-xs text-foreground-lighter uppercase">{label}</span>
+ <span className="text-lg tabular-nums">{value}</span>
+ </div>
+ )
+}
+
+const formatTimeValue = (value: number): string => {
+ if (value >= 1000) {
+ return `${(value / 1000).toFixed(1)}s`
+ }
+ return `${value.toFixed(1)}ms`
+}
+
+const formatNumberValue = (value: number): string => {
+ return value.toLocaleString()
+}
+
+export const QueryPerformanceChart = ({
+ onDateRangeChange,
+ chartData,
+ isLoading,
+ error,
+ currentSelectedQuery,
+ parsedLogs,
+}: QueryPerformanceChartProps) => {
+ const [selectedMetric, setSelectedMetric] = useState('query_latency')
+
+ const currentMetrics = useMemo(() => {
+ if (!chartData || chartData.length === 0) return []
+
+ switch (selectedMetric) {
+ case 'query_latency': {
+ const avgP95 = chartData.reduce((sum, d) => sum + d.p95_time, 0) / chartData.length
+
+ return [
+ {
+ label: 'Average p95',
+ value: avgP95 >= 100 ? `${(avgP95 / 1000).toFixed(2)}s` : `${Math.round(avgP95)}ms`,
+ },
+ ]
+ }
+ case 'rows_read': {
+ const totalRowsRead = chartData.reduce((sum, d) => sum + d.rows_read, 0)
+
+ return [
+ {
+ label: 'Total Rows Read',
+ value: totalRowsRead.toLocaleString(),
+ },
+ ]
+ }
+ case 'calls': {
+ const totalCalls = chartData.reduce((sum, d) => sum + d.calls, 0)
+
+ return [
+ {
+ label: 'Total Calls',
+ value: totalCalls.toLocaleString(),
+ },
+ ]
+ }
+ case 'cache_hits': {
+ const totalHits = chartData.reduce((sum, d) => sum + d.cache_hits, 0)
+ const totalMisses = chartData.reduce((sum, d) => sum + d.cache_misses, 0)
+ const total = totalHits + totalMisses
+ const hitRate = total > 0 ? (totalHits / total) * 100 : 0
+
+ return [
+ {
+ label: 'Cache Hit Rate',
+ value: `${hitRate.toFixed(2)}%`,
+ },
+ ]
+ }
+ default:
+ return []
+ }
+ }, [chartData, selectedMetric])
+
+ const transformedChartData = useMemo(() => {
+ if (selectedMetric !== 'query_latency') return chartData
+
+ const transformed = chartData.map((dataPoint) => ({
+ ...dataPoint,
+ p50_time: parseFloat((dataPoint.p50_time / 1000).toFixed(3)),
+ p95_time: parseFloat((dataPoint.p95_time / 1000).toFixed(3)),
+ }))
+
+ return transformed
+ }, [chartData, selectedMetric])
+
+ const querySpecificData = useMemo(() => {
+ if (!currentSelectedQuery || !parsedLogs.length) return null
+
+ const normalizedSelected = currentSelectedQuery.replace(/\s+/g, ' ').trim()
+ const queryLogs = parsedLogs.filter((log) => {
+ const normalized = (log.query || '').replace(/\s+/g, ' ').trim()
+ return normalized === normalizedSelected
+ })
+
+ const queryDataMap = new Map<
+ number,
+ {
+ time: number
+ rows_read: number
+ calls: number
+ cache_hits: number
+ }
+ >()
+
+ queryLogs.forEach((log) => {
+ const timestamps = [log.bucket_start_time, log.bucket, log.timestamp, log.ts]
+ const validTimestamp = timestamps.find((t) => t && !isNaN(new Date(t).getTime()))
+
+ if (!validTimestamp) return
+
+ const time = new Date(validTimestamp).getTime()
+ const meanTime = log.mean_time ?? log.mean_exec_time ?? log.mean_query_time ?? 0
+ const rowsRead = log.rows_read ?? log.rows ?? 0
+ const calls = log.calls ?? 0
+ const cacheHits = log.shared_blks_hit ?? log.cache_hits ?? 0
+
+ queryDataMap.set(time, {
+ time: parseFloat(String(meanTime)),
+ rows_read: parseFloat(String(rowsRead)),
+ calls: parseFloat(String(calls)),
+ cache_hits: parseFloat(String(cacheHits)),
+ })
+ })
+
+ return queryDataMap
+ }, [currentSelectedQuery, parsedLogs])
+
+ const mergedChartData = useMemo(() => {
+ if (!querySpecificData || !currentSelectedQuery) {
+ return transformedChartData
+ }
+
+ return transformedChartData.map((dataPoint) => {
+ const queryData = querySpecificData.get(dataPoint.period_start)
+
+ return {
+ ...dataPoint,
+ selected_query_time:
+ queryData?.time !== undefined
+ ? selectedMetric === 'query_latency'
+ ? queryData.time / 1000
+ : queryData.time
+ : null,
+ selected_query_rows_read: queryData?.rows_read !== undefined ? queryData.rows_read : null,
+ selected_query_calls: queryData?.calls !== undefined ? queryData.calls : null,
+ selected_query_cache_hits:
+ queryData?.cache_hits !== undefined ? queryData.cache_hits : null,
+ }
+ })
+ }, [transformedChartData, querySpecificData, currentSelectedQuery, selectedMetric])
+
+ const getChartAttributes = useMemo((): MultiAttribute[] => {
+ const attributeMap: Record<string, MultiAttribute[]> = {
+ query_latency: [
+ {
+ attribute: 'p50_time',
+ label: 'p50',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#8B5CF6', dark: '#8B5CF6' },
+ },
+ {
+ attribute: 'p95_time',
+ label: 'p95',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#65BCD9', dark: '#65BCD9' },
+ },
+ ],
+ rows_read: [
+ {
+ attribute: 'rows_read',
+ label: 'Rows Read',
+ provider: 'logs',
+ },
+ ],
+ calls: [
+ {
+ attribute: 'calls',
+ label: 'Calls',
+ provider: 'logs',
+ },
+ ],
+ cache_hits: [
+ {
+ attribute: 'cache_hits',
+ label: 'Cache Hits',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#10B981', dark: '#10B981' },
+ },
+ ],
+ }
+
+ const baseAttributes = attributeMap[selectedMetric] || []
+
+ // Add selected query line based on current metric
+ if (currentSelectedQuery && querySpecificData) {
+ const selectedQueryAttributes: Record<string, MultiAttribute> = {
+ query_latency: {
+ attribute: 'selected_query_time',
+ label: 'Selected Query',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#10B981', dark: '#10B981' },
+ strokeWidth: 3,
+ },
+ rows_read: {
+ attribute: 'selected_query_rows_read',
+ label: 'Selected Query',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#F59E0B', dark: '#F59E0B' },
+ strokeWidth: 3,
+ },
+ calls: {
+ attribute: 'selected_query_calls',
+ label: 'Selected Query',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#EC4899', dark: '#EC4899' },
+ strokeWidth: 3,
+ },
+ cache_hits: {
+ attribute: 'selected_query_cache_hits',
+ label: 'Selected Query',
+ provider: 'logs',
+ type: 'line',
+ color: { light: '#8B5CF6', dark: '#8B5CF6' },
+ strokeWidth: 3,
+ },
+ }
+
+ const selectedQueryAttr = selectedQueryAttributes[selectedMetric]
+ if (selectedQueryAttr) {
+ return [...baseAttributes, selectedQueryAttr]
+ }
+ }
+
+ return baseAttributes
+ }, [selectedMetric, currentSelectedQuery, querySpecificData])
+
+ const updateDateRange = (from: string, to: string) => {
+ onDateRangeChange?.(from, to)
+ }
+
+ const getYAxisFormatter = useMemo(() => {
+ if (selectedMetric === 'query_latency') {
+ return formatTimeValue
+ }
+ return formatNumberValue
+ }, [selectedMetric])
+
+ return (
+ <div className="bg-surface-200 border-t">
+ <Tabs_Shadcn_
+ value={selectedMetric}
+ onValueChange={(value) => setSelectedMetric(value as string)}
+ className="w-full"
+ >
+ <TabsList_Shadcn_ className="flex justify-start rounded-none gap-x-4 border-b !mt-0 pt-0 px-6">
+ {QUERY_PERFORMANCE_CHART_TABS.map((tab) => (
+ <TabsTrigger_Shadcn_
+ key={tab.id}
+ value={tab.id}
+ className="flex items-center gap-2 text-xs py-3 border-b-[1px] font-mono uppercase"
+ >
+ {tab.label}
+ </TabsTrigger_Shadcn_>
+ ))}
+ </TabsList_Shadcn_>
+
+ <TabsContent_Shadcn_ value={selectedMetric} className="bg-surface-200 mt-0 h-inherit">
+ <div className="w-full flex items-center justify-center min-h-[320px]">
+ {isLoading ? (
+ <Loader2 size={20} className="animate-spin text-foreground-lighter" />
+ ) : error ? (
+ <p className="text-sm text-foreground-light text-center h-full flex items-center justify-center">
+ Error loading chart data
+ </p>
+ ) : (
+ <div className="w-full flex flex-col h-full px-6 py-4">
+ <div className="flex gap-6 mb-4">
+ {currentMetrics.map((metric, index) => (
+ <QueryMetricBlock key={index} label={metric.label} value={metric.value} />
+ ))}
+ </div>
+ <ComposedChart
+ data={mergedChartData as any}
+ attributes={getChartAttributes}
+ yAxisKey={getChartAttributes[0]?.attribute || ''}
+ xAxisKey="period_start"
+ title=""
+ customDateFormat="MMM D, YYYY hh:mm A"
+ hideChartType={true}
+ hideHighlightArea={true}
+ showTooltip={true}
+ showGrid={true}
+ showLegend={
+ selectedMetric === 'query_latency' ||
+ selectedMetric === 'cache_hits' ||
+ selectedMetric === 'rows_read' ||
+ selectedMetric === 'calls'
+ }
+ showTotal={false}
+ showMaxValue={false}
+ updateDateRange={updateDateRange}
+ YAxisProps={{
+ tick: true,
+ width: 60,
+ tickFormatter: getYAxisFormatter,
+ }}
+ xAxisIsDate={true}
+ className="mt-6"
+ />
+ </div>
+ )}
+ </div>
+ </TabsContent_Shadcn_>
+ </Tabs_Shadcn_>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
index a2d91081a21..9c115b62f84 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx
@@ -1,60 +1,23 @@
import { useDebounce } from '@uidotdev/usehooks'
-import { RefreshCw, Search, X } from 'lucide-react'
-import { parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'
-import { ChangeEvent, useEffect, useState } from 'react'
+import { Search, X } from 'lucide-react'
+import { parseAsString, useQueryStates } from 'nuqs'
+import { ChangeEvent, ReactNode, useEffect, useState } from 'react'
-import { LOCAL_STORAGE_KEYS, useParams } from 'common'
-import { DownloadResultsButton } from 'components/ui/DownloadResultsButton'
-import { FilterPopover } from 'components/ui/FilterPopover'
-import { useDatabaseRolesQuery } from 'data/database-roles/database-roles-query'
-import { DbQueryHook } from 'hooks/analytics/useDbQuery'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { useQueryPerformanceSort } from './hooks/useQueryPerformanceSort'
-export const QueryPerformanceFilterBar = ({
- queryPerformanceQuery,
- onResetReportClick,
-}: {
- queryPerformanceQuery: DbQueryHook<any>
- onResetReportClick?: () => void
-}) => {
- const { ref } = useParams()
- const { data: project } = useSelectedProjectQuery()
+export const QueryPerformanceFilterBar = ({ actions }: { actions?: ReactNode }) => {
const { sort, clearSort } = useQueryPerformanceSort()
- const [showBottomSection] = useLocalStorageQuery(
- LOCAL_STORAGE_KEYS.QUERY_PERF_SHOW_BOTTOM_SECTION,
- true
- )
- const [{ search: searchQuery, roles: defaultFilterRoles }, setSearchParams] = useQueryStates({
+ const [{ search: searchQuery }, setSearchParams] = useQueryStates({
search: parseAsString.withDefault(''),
- roles: parseAsArrayOf(parseAsString).withDefault([]),
})
const [inputValue, setInputValue] = useState(searchQuery)
const debouncedInputValue = useDebounce(inputValue, 500)
const searchValue = inputValue.length === 0 ? inputValue : debouncedInputValue
- const [filters, setFilters] = useState<{ roles: string[]; query: string }>({
- roles: defaultFilterRoles,
- query: '',
- })
-
- const { isLoading, isRefetching } = queryPerformanceQuery
- const { data, isLoading: isLoadingRoles } = useDatabaseRolesQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- })
- const roles = (data ?? []).sort((a, b) => a.name.localeCompare(b.name))
-
- const onFilterRolesChange = (roles: string[]) => {
- setFilters({ ...filters, roles })
- setSearchParams({ roles })
- }
-
const onSearchQueryChange = (value: string) => {
setSearchParams({ search: value || '' })
}
@@ -65,7 +28,7 @@ export const QueryPerformanceFilterBar = ({
}, [searchValue])
return (
- <div className="px-4 py-2 bg-surface-200 border-t -mt-px flex justify-between items-center overflow-x-auto overflow-y-hidden w-full">
+ <div className="px-4 py-1.5 bg-surface-200 border-t -mt-px flex justify-between items-center overflow-x-auto overflow-y-hidden w-full flex-shrink-0">
<div className="flex items-center gap-x-4">
<div className="flex items-center gap-x-2">
<Input
@@ -91,16 +54,6 @@ export const QueryPerformanceFilterBar = ({
]}
/>
- <FilterPopover
- name="Roles"
- options={roles}
- labelKey="name"
- valueKey="name"
- activeOptions={isLoadingRoles ? [] : filters.roles}
- onSaveFilters={onFilterRolesChange}
- className="w-56"
- />
-
{sort && (
<div className="text-xs border rounded-md px-1.5 md:px-2.5 py-1 h-[26px] flex items-center gap-x-2">
<p className="md:inline-flex gap-x-1 hidden truncate">
@@ -116,32 +69,7 @@ export const QueryPerformanceFilterBar = ({
)}
</div>
</div>
-
- <div className="flex gap-2 items-center pl-2">
- {!showBottomSection && onResetReportClick && (
- <Button type="default" onClick={() => onResetReportClick()}>
- Reset report
- </Button>
- )}
- <Button
- size="tiny"
- type="default"
- onClick={() => queryPerformanceQuery.runQuery()}
- disabled={isLoading || isRefetching}
- icon={
- <RefreshCw
- className={`text-foreground-light ${isLoading || isRefetching ? 'animate-spin' : ''}`}
- />
- }
- >
- Refresh
- </Button>
- <DownloadResultsButton
- results={queryPerformanceQuery.data ?? []}
- fileName={`Supabase Query Performance (${ref})`}
- align="end"
- />
- </div>
+ <div className="flex gap-2 items-center pl-2">{actions}</div>
</div>
)
}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
index e8e3c87ee0b..e680c93d09d 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
@@ -1,9 +1,8 @@
-import { ArrowDown, ArrowUp, ChevronDown, TextSearch } from 'lucide-react'
+import { ArrowDown, ArrowUp, ChevronDown, ArrowRight, TextSearch } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'
import { useParams } from 'common'
-import { DbQueryHook } from 'hooks/analytics/useDbQuery'
import {
Button,
DropdownMenu,
@@ -22,8 +21,8 @@ import {
} from 'ui'
import { InfoTooltip } from 'ui-patterns/info-tooltip'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import { hasIndexRecommendations } from './index-advisor.utils'
-import { IndexSuggestionIcon } from './IndexSuggestionIcon'
+import { hasIndexRecommendations } from './IndexAdvisor/index-advisor.utils'
+import { IndexSuggestionIcon } from './IndexAdvisor/IndexSuggestionIcon'
import { QueryDetail } from './QueryDetail'
import { QueryIndexes } from './QueryIndexes'
import {
@@ -33,24 +32,14 @@ import {
} from './QueryPerformance.constants'
import { useQueryPerformanceSort } from './hooks/useQueryPerformanceSort'
import { formatDuration } from './QueryPerformance.utils'
-import { GetIndexAdvisorResultResponse } from 'data/database/retrieve-index-advisor-result-query'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { QueryPerformanceRow } from './QueryPerformance.types'
interface QueryPerformanceGridProps {
- queryPerformanceQuery: DbQueryHook<any>
-}
-
-interface QueryPerformanceRow {
- query: string
- prop_total_time: number
- total_time: number
- calls: number
- max_time: number
- mean_time: number
- min_time: number
- rows_read: number
- cache_hit_rate: string
- rolname: string
- index_advisor_result: GetIndexAdvisorResultResponse | null
+ aggregatedData: QueryPerformanceRow[]
+ isLoading: boolean
+ currentSelectedQuery?: string | null // Make optional
+ onCurrentSelectQuery?: (query: string) => void // Make optional
}
const calculateTimeConsumedWidth = (data: QueryPerformanceRow[]) => {
@@ -75,11 +64,15 @@ const calculateTimeConsumedWidth = (data: QueryPerformanceRow[]) => {
return Math.min(maxWidth, 300)
}
-export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceGridProps) => {
+export const QueryPerformanceGrid = ({
+ aggregatedData,
+ isLoading,
+ currentSelectedQuery,
+ onCurrentSelectQuery,
+}: QueryPerformanceGridProps) => {
const { sort, setSortConfig } = useQueryPerformanceSort()
const gridRef = useRef<DataGridHandle>(null)
const { sort: urlSort, order, roles, search } = useParams()
- const { isLoading, data } = queryPerformanceQuery
const dataGridContainerRef = useRef<HTMLDivElement>(null)
const [view, setView] = useState<'details' | 'suggestion'>('details')
@@ -95,7 +88,9 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
cellClass: `column-${col.id}`,
resizable: true,
minWidth:
- col.id === 'prop_total_time' ? calculateTimeConsumedWidth(data ?? []) : col.minWidth ?? 120,
+ col.id === 'prop_total_time'
+ ? calculateTimeConsumedWidth((aggregatedData as any) ?? [])
+ : col.minWidth ?? 120,
sortable: !nonSortableColumns.includes(col.id),
headerCellClass: 'first:pl-6 cursor-pointer',
renderHeaderCell: () => {
@@ -156,26 +151,43 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
const value = props.row?.[col.id]
if (col.id === 'query') {
return (
- <div className="w-full flex items-center gap-x-3 ml-4">
- {hasIndexRecommendations(props.row.index_advisor_result, true) && (
- <IndexSuggestionIcon
- indexAdvisorResult={props.row.index_advisor_result}
- onClickIcon={() => {
- setSelectedRow(props.rowIdx)
- setView('suggestion')
- gridRef.current?.scrollToCell({ idx: 0, rowIdx: props.rowIdx })
- }}
- />
- )}
+ <div className="w-full flex items-center gap-x-3 group">
+ <div className="flex-shrink-0 w-4">
+ {hasIndexRecommendations(props.row.index_advisor_result, true) && (
+ <IndexSuggestionIcon
+ indexAdvisorResult={props.row.index_advisor_result}
+ onClickIcon={() => {
+ setSelectedRow(props.rowIdx)
+ setView('suggestion')
+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: props.rowIdx })
+ }}
+ />
+ )}
+ </div>
<CodeBlock
language="pgsql"
- className="!bg-transparent !p-0 !m-0 !border-none !whitespace-nowrap [&>code]:!whitespace-nowrap [&>code]:break-words !overflow-visible !truncate !w-full !pr-8 flex-grow pointer-events-none"
- wrapperClassName="!max-w-full"
+ className="!bg-transparent !p-0 !m-0 !border-none !whitespace-nowrap [&>code]:!whitespace-nowrap [&>code]:break-words !overflow-visible !truncate !w-full !pr-20 pointer-events-none"
+ wrapperClassName="!max-w-full flex-1"
hideLineNumbers
hideCopy
value={value.replace(/\s+/g, ' ').trim() as string}
wrapLines={false}
/>
+ {onCurrentSelectQuery && (
+ <ButtonTooltip
+ tooltip={{ content: { text: 'Query details' } }}
+ icon={<ArrowRight size={14} />}
+ size="tiny"
+ type="default"
+ onClick={(e) => {
+ e.stopPropagation()
+ setSelectedRow(props.rowIdx)
+ setView('details')
+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: props.rowIdx })
+ }}
+ className="p-1 flex-shrink-0 -translate-x-2 group-hover:flex hidden"
+ />
+ )}
</div>
)
}
@@ -267,21 +279,12 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
)
}
- const cacheHitRateToNumber = (value: number | string) => {
- if (typeof value === 'number') return value
- return parseFloat(value.toString().replace('%', '')) || 0
- }
-
if (col.id === 'cache_hit_rate') {
return (
<div className="w-full flex flex-col justify-center text-xs text-right tabular-nums font-mono">
- {typeof value === 'string' ? (
- <p
- className={cn(
- cacheHitRateToNumber(value).toFixed(2) === '0.00' && 'text-foreground-lighter'
- )}
- >
- {cacheHitRateToNumber(value).toLocaleString(undefined, {
+ {typeof value === 'number' && !isNaN(value) && isFinite(value) ? (
+ <p className={cn(value.toFixed(2) === '0.00' && 'text-foreground-lighter')}>
+ {value.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
@@ -325,27 +328,36 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
})
const reportData = useMemo(() => {
- const rawData = data ?? []
+ let data = [...aggregatedData]
- if (sort?.column === 'prop_total_time') {
- const sortedData = [...rawData].sort((a, b) => {
- const getNumericValue = (value: number | string) => {
- if (!value || value === 'n/a') return 0
- if (typeof value === 'number') return value
- return parseFloat(value.toString().replace('%', '')) || 0
- }
+ if (search && typeof search === 'string' && search.length > 0) {
+ data = data.filter((row) => row.query.toLowerCase().includes(search.toLowerCase()))
+ }
- const aValue = getNumericValue(a.prop_total_time)
- const bValue = getNumericValue(b.prop_total_time)
+ if (roles && Array.isArray(roles) && roles.length > 0) {
+ data = data.filter((row) => row.rolname && roles.includes(row.rolname))
+ }
+ if (sort?.column === 'prop_total_time') {
+ data.sort((a, b) => {
+ const aValue = a.prop_total_time || 0
+ const bValue = b.prop_total_time || 0
return sort.order === 'asc' ? aValue - bValue : bValue - aValue
})
+ } else if (sort?.column && sort.column !== 'query') {
+ data.sort((a, b) => {
+ const aValue = a[sort.column as keyof QueryPerformanceRow] || 0
+ const bValue = b[sort.column as keyof QueryPerformanceRow] || 0
- return sortedData
+ if (typeof aValue === 'number' && typeof bValue === 'number') {
+ return sort.order === 'asc' ? aValue - bValue : bValue - aValue
+ }
+ return 0
+ })
}
- return rawData
- }, [data, sort])
+ return data
+ }, [aggregatedData, sort, search, roles])
const selectedQuery = selectedRow !== undefined ? reportData[selectedRow]?.query : undefined
const query = (selectedQuery ?? '').trim().toLowerCase()
@@ -366,7 +378,6 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return
- // stop default RDG behavior (which moves focus to header when selectedRow is 0)
event.stopPropagation()
let nextIndex = selectedRow
@@ -410,9 +421,14 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
rows={reportData}
rowClass={(_, idx) => {
const isSelected = idx === selectedRow
+ const query = reportData[idx]?.query
+ const isCharted = currentSelectedQuery ? currentSelectedQuery === query : false
+
return [
`${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,
- `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-foreground' : ''}`,
+ `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:!border-l-foreground' : ''}`,
+ `${isCharted ? 'bg-surface-200 dark:bg-surface-200' : ''}`,
+ `${isCharted ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-brand' : ''}`,
'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',
'[&>.rdg-cell.column-prop_total_time]:relative',
].join(' ')
@@ -427,12 +443,17 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance
event.stopPropagation()
if (typeof idx === 'number' && idx >= 0) {
- setSelectedRow(idx)
- gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })
-
- const rowQuery = reportData[idx]?.query ?? ''
- if (!rowQuery.trim().toLowerCase().startsWith('select')) {
+ // If onCurrentSelectQuery is provided, use the chart selection logic
+ if (onCurrentSelectQuery) {
+ const query = reportData[idx]?.query
+ if (query) {
+ onCurrentSelectQuery(query)
+ }
+ } else {
+ // Otherwise, open the detail panel
+ setSelectedRow(idx)
setView('details')
+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })
}
}
}}
diff --git a/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx b/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx
deleted file mode 100644
index 1e6be9f3c9e..00000000000
--- a/apps/studio/components/interfaces/QueryPerformance/TextSearchPopover.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { useState } from 'react'
-import {
- Button,
- PopoverContent_Shadcn_,
- PopoverTrigger_Shadcn_,
- Popover_Shadcn_,
- TextArea_Shadcn_,
-} from 'ui'
-
-interface TextSearchPopoverProps {
- name: string
- value: string
- placeholder?: string
- rows?: number
- onSaveText: (value: string) => void
-}
-
-export const TextSearchPopover = ({
- name,
- value = '',
- placeholder,
- rows = 4,
- onSaveText,
-}: TextSearchPopoverProps) => {
- const [open, setOpen] = useState(false)
- const [search, setSearch] = useState<string>(value)
-
- const applySearch = () => {
- onSaveText(search)
- setOpen(false)
- }
-
- return (
- <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
- <PopoverTrigger_Shadcn_ asChild>
- <Button
- asChild
- type={value.length > 0 ? 'default' : 'dashed'}
- onClick={() => setOpen(false)}
- >
- <div className="max-w-[170px]">
- <span>{name}</span>
- {value.length > 0 && <span className="mr-1">:</span>}
- <span className="truncate">{value}</span>
- </div>
- </Button>
- </PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ portal className="p-0" side="bottom" align="start">
- <div className="space-y-4 p-3 min-w-[170px]">
- <TextArea_Shadcn_
- value={search}
- onChange={(event) => setSearch(event.target.value)}
- rows={rows}
- className="text-xs font-mono tracking-tight"
- placeholder={placeholder ?? 'Search for a query'}
- onKeyDown={(event) => {
- if (event.metaKey && (event.code === 'Enter' || event.code === 'NumpadEnter'))
- applySearch()
- }}
- />
- </div>
- <div className="flex items-center justify-end gap-2 border-t border-overlay bg-surface-200 py-2 px-3">
- <Button
- size="tiny"
- type="default"
- onClick={() => {
- onSaveText('')
- setSearch('')
- setOpen(false)
- }}
- >
- Clear
- </Button>
- <Button type="primary" onClick={() => applySearch()}>
- Apply search
- </Button>
- </div>
- </PopoverContent_Shadcn_>
- </Popover_Shadcn_>
- )
-}
diff --git a/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx b/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx
new file mode 100644
index 00000000000..db34a8def4c
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.tsx
@@ -0,0 +1,111 @@
+import { QueryPerformanceGrid } from '../QueryPerformanceGrid'
+import { LoadingLine } from 'ui'
+import { QueryPerformanceChart } from '../QueryPerformanceChart'
+import { QueryPerformanceFilterBar } from '../QueryPerformanceFilterBar'
+import { useMemo, useState } from 'react'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+import useLogsQuery from 'hooks/analytics/useLogsQuery'
+import { getPgStatMonitorLogsQuery } from '../QueryPerformance.constants'
+import {
+ parsePgStatMonitorLogs,
+ transformLogsToChartData,
+ aggregateLogsByQuery,
+} from './WithMonitor.utils'
+import { useParams } from 'common'
+import { DownloadResultsButton } from 'components/ui/DownloadResultsButton'
+
+dayjs.extend(utc)
+
+interface WithMonitorProps {
+ dateRange?: {
+ period_start: { date: string; time_period: string }
+ period_end: { date: string; time_period: string }
+ interval: string
+ }
+ onDateRangeChange?: (from: string, to: string) => void
+}
+
+export const WithMonitor = ({ dateRange, onDateRangeChange }: WithMonitorProps) => {
+ const { ref } = useParams()
+ const [selectedQuery, setSelectedQuery] = useState<string | null>(null)
+
+ // [kemal]: Fetch pg_stat_monitor logs. This will need to change when we move to the actual extension.
+ const effectiveDateRange = useMemo(() => {
+ if (dateRange) {
+ return {
+ iso_timestamp_start: dateRange.period_start.date,
+ iso_timestamp_end: dateRange.period_end.date,
+ }
+ }
+
+ // [kemal]: Fallback to default 24 hours
+ const end = dayjs.utc()
+ const start = end.subtract(24, 'hours')
+ return {
+ iso_timestamp_start: start.toISOString(),
+ iso_timestamp_end: end.toISOString(),
+ }
+ }, [dateRange])
+
+ const queryWithTimeRange = useMemo(() => {
+ return getPgStatMonitorLogsQuery(
+ effectiveDateRange.iso_timestamp_start,
+ effectiveDateRange.iso_timestamp_end
+ )
+ }, [effectiveDateRange])
+
+ const pgStatMonitorLogs = useLogsQuery(ref as string, {
+ sql: queryWithTimeRange,
+ iso_timestamp_start: effectiveDateRange.iso_timestamp_start,
+ iso_timestamp_end: effectiveDateRange.iso_timestamp_end,
+ })
+
+ const { logData, isLoading: isLogsLoading, error: logsError } = pgStatMonitorLogs
+
+ const parsedLogs = useMemo(() => {
+ return parsePgStatMonitorLogs(logData || [])
+ }, [logData])
+
+ const chartData = useMemo(() => {
+ return transformLogsToChartData(parsedLogs)
+ }, [parsedLogs])
+
+ const aggregatedGridData = useMemo(() => {
+ return aggregateLogsByQuery(parsedLogs)
+ }, [parsedLogs])
+
+ const handleSelectQuery = (query: string) => {
+ setSelectedQuery((prev) => (prev === query ? null : query))
+ }
+
+ return (
+ <>
+ <QueryPerformanceChart
+ dateRange={dateRange}
+ onDateRangeChange={onDateRangeChange}
+ chartData={chartData}
+ isLoading={isLogsLoading}
+ error={logsError}
+ currentSelectedQuery={selectedQuery}
+ parsedLogs={parsedLogs}
+ />
+ <QueryPerformanceFilterBar
+ actions={
+ <DownloadResultsButton
+ results={aggregatedGridData}
+ fileName={`Supabase Query Performance Monitor (${ref})`}
+ align="end"
+ />
+ }
+ />
+ <LoadingLine loading={isLogsLoading} />
+ <QueryPerformanceGrid
+ aggregatedData={aggregatedGridData}
+ isLoading={isLogsLoading}
+ currentSelectedQuery={selectedQuery}
+ onCurrentSelectQuery={handleSelectQuery}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.utils.ts b/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.utils.ts
new file mode 100644
index 00000000000..f65cfb30930
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/WithMonitor/WithMonitor.utils.ts
@@ -0,0 +1,301 @@
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+import { transformLogsToJSON } from '../QueryPerformance.utils'
+import { QueryPerformanceRow } from '../QueryPerformance.types'
+
+dayjs.extend(utc)
+
+export interface ParsedLogEntry {
+ bucket_start_time?: string
+ bucket?: string
+ timestamp?: string
+ ts?: string
+ mean_time?: number
+ mean_exec_time?: number
+ mean_query_time?: number
+ min_time?: number
+ min_exec_time?: number
+ min_query_time?: number
+ max_time?: number
+ max_exec_time?: number
+ max_query_time?: number
+ stddev_time?: number
+ stddev_exec_time?: number
+ stddev_query_time?: number
+ rows?: number
+ calls?: number
+ shared_blks_hit?: number
+ shared_blks_read?: number
+ query?: string
+ userid?: string
+ rolname?: string
+ resp_calls?: number[]
+ [key: string]: any
+}
+
+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 const parsePgStatMonitorLogs = (logData: any[]): ParsedLogEntry[] => {
+ if (!logData || logData.length === 0) return []
+
+ const validParsedLogs = logData
+ .map((log) => ({
+ ...log,
+ parsedEventMessage: transformLogsToJSON(log.event_message),
+ }))
+ .filter((log) => log.parsedEventMessage !== null)
+ .filter((log) => log.parsedEventMessage?.event === 'bucket_query')
+
+ return validParsedLogs.map((log) => log.parsedEventMessage)
+}
+
+export const transformLogsToChartData = (parsedLogs: ParsedLogEntry[]): ChartDataPoint[] => {
+ if (!parsedLogs || parsedLogs.length === 0) return []
+
+ // [kemal]: here for debugging
+ // if (parsedLogs.length > 0) {
+ // console.log('🟡 Parsed logs:', parsedLogs)
+ // }
+
+ return parsedLogs
+ .map((log: ParsedLogEntry) => {
+ const possibleTimestamps = [log.bucket_start_time, log.bucket, log.timestamp, log.ts]
+
+ let periodStart: number | null = null
+
+ for (const ts of possibleTimestamps) {
+ if (ts) {
+ const date = new Date(ts)
+ const time = date.getTime()
+ if (!isNaN(time) && time > 0 && time > 946684800000) {
+ periodStart = time
+ break
+ }
+ }
+ }
+
+ if (!periodStart) {
+ return null
+ }
+
+ const percentiles =
+ log.resp_calls && Array.isArray(log.resp_calls)
+ ? calculatePercentilesFromHistogram(log.resp_calls)
+ : { p50: 0, p95: 0 }
+
+ return {
+ period_start: periodStart,
+ timestamp: possibleTimestamps.find((t) => t) || '',
+ query_latency: parseFloat(
+ String(log.mean_time ?? log.mean_exec_time ?? log.mean_query_time ?? 0)
+ ),
+ mean_time: parseFloat(
+ String(log.mean_time ?? log.mean_exec_time ?? log.mean_query_time ?? 0)
+ ),
+ min_time: parseFloat(String(log.min_time ?? log.min_exec_time ?? log.min_query_time ?? 0)),
+ max_time: parseFloat(String(log.max_time ?? log.max_exec_time ?? log.max_query_time ?? 0)),
+ stddev_time: parseFloat(
+ String(log.stddev_time ?? log.stddev_exec_time ?? log.stddev_query_time ?? 0)
+ ),
+ p50_time: percentiles.p50,
+ p95_time: percentiles.p95,
+ rows_read: parseInt(String(log.rows ?? 0), 10),
+ calls: parseInt(String(log.calls ?? 0), 10),
+ cache_hits: parseFloat(String(log.shared_blks_hit ?? 0)),
+ cache_misses: parseFloat(String(log.shared_blks_read ?? 0)),
+ }
+ })
+ .filter((item): item is NonNullable<typeof item> => item !== null)
+ .sort((a, b) => a.period_start - b.period_start)
+}
+
+const normalizeQuery = (query: string): string => {
+ return query.replace(/\s+/g, ' ').trim()
+}
+
+export const aggregateLogsByQuery = (parsedLogs: ParsedLogEntry[]): QueryPerformanceRow[] => {
+ if (!parsedLogs || parsedLogs.length === 0) return []
+
+ const queryGroups = new Map<string, ParsedLogEntry[]>()
+
+ parsedLogs.forEach((log) => {
+ const query = normalizeQuery(log.query || '')
+ if (!query) return
+
+ if (!queryGroups.has(query)) {
+ queryGroups.set(query, [])
+ }
+ queryGroups.get(query)!.push(log)
+ })
+
+ const aggregatedData: QueryPerformanceRow[] = []
+ let totalExecutionTime = 0
+
+ const queryStats = Array.from(queryGroups.entries()).map(([query, logs]) => {
+ const count = logs.length
+ let totalCalls = 0
+ let totalRowsRead = 0
+ let totalCacheHits = 0
+ let totalCacheMisses = 0
+ let rolname = logs[0].username
+ let minTime = Infinity
+ let maxTime = -Infinity
+ let totalExecutionTimeForQuery = 0
+
+ logs.forEach((log) => {
+ const logMeanTime = parseFloat(
+ String(log.mean_time ?? log.mean_exec_time ?? log.mean_query_time ?? 0)
+ )
+ const logMinTime = parseFloat(
+ String(log.min_time ?? log.min_exec_time ?? log.min_query_time ?? 0)
+ )
+ const logMaxTime = parseFloat(
+ String(log.max_time ?? log.max_exec_time ?? log.max_query_time ?? 0)
+ )
+ const logCalls = parseInt(String(log.calls ?? 0), 10)
+ const logRows = parseInt(String(log.rows ?? 0), 10)
+ const logCacheHits = parseFloat(String(log.shared_blks_hit ?? 0))
+ const logCacheMisses = parseFloat(String(log.shared_blks_read ?? 0))
+
+ minTime = Math.min(minTime, logMinTime)
+ maxTime = Math.max(maxTime, logMaxTime)
+ totalCalls += logCalls
+ totalRowsRead += logRows
+ totalCacheHits += logCacheHits
+ totalCacheMisses += logCacheMisses
+ totalExecutionTimeForQuery += logMeanTime * logCalls
+ })
+
+ // Overall mean time is the weighted average
+ const avgMeanTime = totalCalls > 0 ? totalExecutionTimeForQuery / totalCalls : 0
+ const finalMinTime = minTime === Infinity ? 0 : minTime
+ const finalMaxTime = maxTime === -Infinity ? 0 : maxTime
+
+ totalExecutionTime += totalExecutionTimeForQuery
+
+ return {
+ query,
+ rolname,
+ count,
+ avgMeanTime,
+ minTime: finalMinTime,
+ maxTime: finalMaxTime,
+ totalCalls,
+ totalRowsRead,
+ totalTime: totalExecutionTimeForQuery,
+ totalCacheHits,
+ totalCacheMisses,
+ }
+ })
+
+ queryStats.forEach((stats) => {
+ const totalCacheAccess = stats.totalCacheHits + stats.totalCacheMisses
+ const cacheHitRate = totalCacheAccess > 0 ? (stats.totalCacheHits / totalCacheAccess) * 100 : 0
+
+ const propTotalTime = totalExecutionTime > 0 ? (stats.totalTime / totalExecutionTime) * 100 : 0
+
+ aggregatedData.push({
+ query: stats.query,
+ rolname: stats.rolname,
+ calls: stats.totalCalls,
+ mean_time: stats.avgMeanTime,
+ min_time: stats.minTime,
+ max_time: stats.maxTime,
+ total_time: stats.totalTime,
+ rows_read: stats.totalRowsRead,
+ cache_hit_rate: cacheHitRate,
+ prop_total_time: propTotalTime,
+ index_advisor_result: null,
+ _total_cache_hits: stats.totalCacheHits,
+ _total_cache_misses: stats.totalCacheMisses,
+ _count: stats.count,
+ })
+ })
+
+ return aggregatedData.sort((a, b) => b.total_time - a.total_time)
+}
+
+export const calculatePercentilesFromHistogram = (
+ respCalls: number[]
+): {
+ p50: number
+ p95: number
+} => {
+ const bucketBoundaries = [
+ { min: 0, max: 1 },
+ { min: 1, max: 10 },
+ { min: 10, max: 100 },
+ { min: 100, max: 1000 },
+ { min: 1000, max: 10000 },
+ { min: 10000, max: 100000 },
+ ]
+
+ const totalCalls = respCalls.reduce((sum, count) => sum + count, 0)
+
+ if (totalCalls === 0) {
+ return { p50: 0, p95: 0 }
+ }
+
+ const distribution: {
+ minValue: number
+ maxValue: number
+ cumulativeCount: number
+ count: number
+ }[] = []
+ let cumulativeCount = 0
+
+ respCalls.forEach((count, index) => {
+ if (count > 0 && index < bucketBoundaries.length) {
+ const bucket = bucketBoundaries[index]
+ cumulativeCount += count
+ distribution.push({
+ minValue: bucket.min,
+ maxValue: bucket.max,
+ cumulativeCount,
+ count,
+ })
+ }
+ })
+
+ const getPercentile = (percentile: number): number => {
+ const targetCount = totalCalls * percentile
+
+ for (let i = 0; i < distribution.length; i++) {
+ const prevCumulativeCount = i > 0 ? distribution[i - 1].cumulativeCount : 0
+
+ if (distribution[i].cumulativeCount >= targetCount) {
+ const positionInBucket = (targetCount - prevCumulativeCount) / distribution[i].count
+ const bucketMin = distribution[i].minValue
+ const bucketMax = distribution[i].maxValue
+ const logMin = Math.log10(Math.max(bucketMin, 0.1))
+ const logMax = Math.log10(bucketMax)
+ const logValue = logMin + positionInBucket * (logMax - logMin)
+
+ return Math.pow(10, logValue)
+ }
+ }
+
+ return distribution[distribution.length - 1]?.maxValue || 0
+ }
+
+ const result = {
+ p50: getPercentile(0.5),
+ p95: getPercentile(0.95),
+ }
+
+ return result
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
new file mode 100644
index 00000000000..b35864d3a46
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx
@@ -0,0 +1,186 @@
+import { LoadingLine, cn } from 'ui'
+import { useState, useEffect, useMemo } from 'react'
+
+import { Button } from 'ui'
+import { X, RefreshCw, RotateCcw } from 'lucide-react'
+import { Markdown } from '../../Markdown'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { LOCAL_STORAGE_KEYS, useParams } from 'common'
+import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { DOCS_URL, IS_PLATFORM } from 'lib/constants'
+import { executeSql } from 'data/sql/execute-sql-query'
+import { toast } from 'sonner'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
+import { PresetHookResult } from 'components/interfaces/Reports/Reports.utils'
+import { DbQueryHook } from 'hooks/analytics/useDbQuery'
+import { QueryPerformanceMetrics } from '../QueryPerformanceMetrics'
+import { QueryPerformanceFilterBar } from '../QueryPerformanceFilterBar'
+import { QueryPerformanceGrid } from '../QueryPerformanceGrid'
+import { transformStatementDataToRows } from './WithStatements.utils'
+import { DownloadResultsButton } from 'components/ui/DownloadResultsButton'
+
+interface WithStatementsProps {
+ queryHitRate: PresetHookResult
+ queryPerformanceQuery: DbQueryHook<any>
+ queryMetrics: PresetHookResult
+}
+
+export const WithStatements = ({
+ queryHitRate,
+ queryPerformanceQuery,
+ queryMetrics,
+}: WithStatementsProps) => {
+ const { ref } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+ const state = useDatabaseSelectorStateSnapshot()
+ const { data, isLoading, isRefetching } = queryPerformanceQuery
+ const isPrimaryDatabase = state.selectedDatabaseId === ref
+ const formattedDatabaseId = formatDatabaseID(state.selectedDatabaseId ?? '')
+
+ const [showResetgPgStatStatements, setShowResetgPgStatStatements] = useState(false)
+
+ const [showBottomSection, setShowBottomSection] = useLocalStorageQuery(
+ LOCAL_STORAGE_KEYS.QUERY_PERF_SHOW_BOTTOM_SECTION,
+ true
+ )
+
+ const handleRefresh = () => {
+ queryPerformanceQuery.runQuery()
+ queryHitRate.runQuery()
+ queryMetrics.runQuery()
+ }
+
+ const processedData = useMemo(() => {
+ return transformStatementDataToRows(data || [])
+ }, [data])
+
+ const { data: databases } = useReadReplicasQuery({ projectRef: ref })
+
+ useEffect(() => {
+ state.setSelectedDatabaseId(ref)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ref])
+
+ return (
+ <>
+ <QueryPerformanceMetrics />
+ <QueryPerformanceFilterBar
+ actions={
+ <>
+ <Button
+ type="default"
+ size="tiny"
+ icon={<RefreshCw />}
+ onClick={handleRefresh}
+ loading={isRefetching}
+ >
+ Refresh
+ </Button>
+ <Button
+ type="default"
+ size="tiny"
+ icon={<RotateCcw />}
+ onClick={() => setShowResetgPgStatStatements(true)}
+ >
+ Reset report
+ </Button>
+ <DownloadResultsButton
+ results={processedData}
+ fileName={`Supabase Query Performance Statements (${ref})`}
+ align="end"
+ />
+ </>
+ }
+ />
+ <LoadingLine loading={isLoading || isRefetching} />
+ <QueryPerformanceGrid aggregatedData={processedData} isLoading={isLoading} />
+ <div
+ className={cn('px-6 py-6 flex gap-x-4 border-t relative', {
+ hidden: showBottomSection === false,
+ })}
+ >
+ <Button
+ className="absolute top-1.5 right-3 px-1.5"
+ type="text"
+ size="tiny"
+ onClick={() => setShowBottomSection(false)}
+ >
+ <X size="14" />
+ </Button>
+ <div className="w-[33%] flex flex-col gap-y-1 text-sm">
+ <p>Reset report</p>
+ <p className="text-xs text-foreground-light">
+ Consider resetting the analysis after optimizing any queries
+ </p>
+ <Button
+ type="default"
+ className="!mt-3 w-min"
+ onClick={() => setShowResetgPgStatStatements(true)}
+ >
+ Reset report
+ </Button>
+ </div>
+
+ <div className="w-[33%] flex flex-col gap-y-1 text-sm">
+ <p>How is this report generated?</p>
+ <Markdown
+ className="text-xs"
+ content={`This report uses the pg_stat_statements table, and pg_stat_statements extension. [Learn more here](${DOCS_URL}/guides/platform/performance#examining-query-performance).`}
+ />
+ </div>
+
+ <div className="w-[33%] flex flex-col gap-y-1 text-sm">
+ <p>Inspect your database for potential issues</p>
+ <Markdown
+ className="text-xs"
+ content={`The Supabase CLI comes with a range of tools to help inspect your Postgres instances for
+ potential issues. [Learn more here](${DOCS_URL}/guides/database/inspect).`}
+ />
+ </div>
+ </div>
+
+ <ConfirmationModal
+ visible={showResetgPgStatStatements}
+ size="medium"
+ variant="destructive"
+ title="Reset query performance analysis"
+ confirmLabel="Reset report"
+ confirmLabelLoading="Resetting report"
+ onCancel={() => setShowResetgPgStatStatements(false)}
+ onConfirm={async () => {
+ const connectionString = databases?.find(
+ (db) => db.identifier === state.selectedDatabaseId
+ )?.connectionString
+
+ if (IS_PLATFORM && !connectionString) {
+ return toast.error('Unable to run query: Connection string is missing')
+ }
+
+ try {
+ await executeSql({
+ projectRef: project?.ref,
+ connectionString,
+ sql: `SELECT pg_stat_statements_reset();`,
+ })
+ handleRefresh()
+ setShowResetgPgStatStatements(false)
+ } catch (error: any) {
+ toast.error(`Failed to reset analysis: ${error.message}`)
+ }
+ }}
+ >
+ <p className="text-foreground-light text-sm">
+ This will reset the pg_stat_statements table in the extensions schema on your{' '}
+ <span className="text-foreground">
+ {isPrimaryDatabase ? 'primary database' : `read replica (ID: ${formattedDatabaseId})`}
+ </span>
+ , which is used to calculate query performance. This data will repopulate immediately
+ after.
+ </p>
+ </ConfirmationModal>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.utils.ts b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.utils.ts
new file mode 100644
index 00000000000..8e5ba0b86f3
--- /dev/null
+++ b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.utils.ts
@@ -0,0 +1,22 @@
+import { QueryPerformanceRow } from '../QueryPerformance.types'
+
+export const transformStatementDataToRows = (data: any[]): QueryPerformanceRow[] => {
+ if (!data || data.length === 0) return []
+
+ const totalTimeAcrossAllQueries = data.reduce((sum, row) => sum + (row.total_time || 0), 0)
+
+ return data.map((row) => ({
+ query: row.query,
+ rolname: row.rolname || undefined,
+ calls: row.calls || 0,
+ mean_time: row.mean_time || 0,
+ min_time: row.min_time || 0,
+ max_time: row.max_time || 0,
+ total_time: row.total_time || 0,
+ rows_read: row.rows_read || 0,
+ cache_hit_rate: row.cache_hit_rate || 0,
+ prop_total_time:
+ totalTimeAcrossAllQueries > 0 ? (row.total_time / totalTimeAcrossAllQueries) * 100 : 0,
+ index_advisor_result: row.index_advisor_result || null,
+ }))
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus.ts b/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus.ts
index 5775541954b..7001611ce78 100644
--- a/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus.ts
@@ -1,4 +1,4 @@
-import { getIndexAdvisorExtensions } from 'components/interfaces/QueryPerformance/index-advisor.utils'
+import { getIndexAdvisorExtensions } from 'components/interfaces/QueryPerformance/IndexAdvisor/index-advisor.utils'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
diff --git a/apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.ts b/apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.tsx
similarity index 86%
rename from apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.ts
rename to apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.tsx
index ee22c2d7ba5..5566c59aff1 100644
--- a/apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.ts
+++ b/apps/studio/components/layouts/AdvisorsLayout/AdvisorsMenu.utils.tsx
@@ -1,6 +1,7 @@
import type { ProductMenuGroup } from 'components/ui/ProductMenu/ProductMenu.types'
import type { Project } from 'data/projects/project-detail-query'
import { IS_PLATFORM } from 'lib/constants'
+import { ArrowUpRight } from 'lucide-react'
export const generateAdvisorsMenu = (
project?: Project,
@@ -27,8 +28,9 @@ export const generateAdvisorsMenu = (
{
name: 'Query Performance',
key: 'query-performance',
- url: `/project/${ref}/advisors/query-performance`,
+ url: `/project/${ref}/reports/query-performance`,
items: [],
+ rightIcon: <ArrowUpRight size={14} strokeWidth={1.5} className="h-4 w-4" />,
},
],
},
diff --git a/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx b/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx
index 1895819ffac..20d2216ec6e 100644
--- a/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx
+++ b/apps/studio/components/layouts/ReportsLayout/Reports.Commands.tsx
@@ -77,7 +77,7 @@ export function useReportsGotoCommands(options?: CommandOptions) {
{
id: QUERY_PERFORMANCE_COMMAND_ID,
name: 'Query Performance Reports',
- route: `/project/${ref}/advisors/query-performance`,
+ route: `/project/${ref}/reports/query-performance`,
defaultHidden: true,
},
]
diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
index a770362494a..f0644ef7740 100644
--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
@@ -1,5 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { Plus, ArrowUpRight } from 'lucide-react'
+import { Plus } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useMemo, useState } from 'react'
@@ -149,8 +149,7 @@ const ReportsMenu = () => {
{
name: 'Query Performance',
key: 'query-performance',
- url: `/project/${ref}/advisors/query-performance`,
- rightIcon: <ArrowUpRight strokeWidth={1} className="h-4 w-4" />,
+ url: `/project/${ref}/reports/query-performance${preservedQueryParams}`,
},
...(postgrestReportEnabled
? [
@@ -261,9 +260,6 @@ const ReportsMenu = () => {
className="flex-grow h-7 flex justify-between items-center pl-3"
>
<span>{subItem.name}</span>
- {subItem.rightIcon && (
- <span className="shrink-0">{subItem.rightIcon}</span>
- )}
</Link>
</li>
))}
diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsx
index 86a83834146..94df3ecdab9 100644
--- a/apps/studio/components/ui/Charts/ChartHeader.tsx
+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx
@@ -9,6 +9,7 @@ import {
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
+import { cn } from 'ui'
import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
@@ -26,6 +27,8 @@ export interface ChartHeaderProps {
highlightedLabel?: number | string | any | null
highlightedValue?: number | string | any | null
hideHighlightedValue?: boolean
+ hideHighlightedLabel?: boolean
+ hideHighlightArea?: boolean
hideChartType?: boolean
chartStyle?: string
onChartStyleChange?: (style: string) => void
@@ -50,6 +53,8 @@ export const ChartHeader = ({
highlightedValue,
highlightedLabel,
hideHighlightedValue = false,
+ hideHighlightedLabel = false,
+ hideHighlightArea = false,
title,
minimalHeader = false,
hideChartType = false,
@@ -202,11 +207,14 @@ export const ChartHeader = ({
if (minimalHeader) {
return (
- <div className="flex flex-row items-center gap-x-4" style={{ minHeight: '1.8rem' }}>
+ <div
+ className={cn('flex flex-row items-center gap-x-4', hideHighlightArea && 'hidden')}
+ style={{ minHeight: '1.8rem' }}
+ >
{title && chartTitle}
<div className="flex flex-row items-baseline gap-x-2">
{highlightedValue !== undefined && !hideHighlightedValue && highlighted}
- {label}
+ {!hideHighlightedLabel && label}
</div>
</div>
)
@@ -215,12 +223,17 @@ export const ChartHeader = ({
const hasHighlightedValue = highlightedValue !== undefined && !hideHighlightedValue
return (
- <div className="flex-grow flex justify-between items-start min-h-16">
+ <div
+ className={cn(
+ 'flex-grow flex justify-between items-start min-h-16',
+ hideHighlightArea && 'hidden'
+ )}
+ >
<div className="flex flex-col">
{title && chartTitle}
<div className="h-4">
{hasHighlightedValue && highlighted}
- {label}
+ {!hideHighlightedLabel && label}
</div>
</div>
<div className="flex items-center gap-2">
diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsx
index 94ef08ac6f9..acbcfc62db5 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx
@@ -62,6 +62,8 @@ export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
titleTooltip?: string
hideYAxis?: boolean
hideHighlightedValue?: boolean
+ hideHighlightedLabel?: boolean
+ hideHighlightArea?: boolean
syncId?: string
docsUrl?: string
sql?: string
@@ -101,6 +103,8 @@ export function ComposedChart({
updateDateRange,
hideYAxis,
hideHighlightedValue,
+ hideHighlightedLabel = false,
+ hideHighlightArea = false,
syncId,
docsUrl,
sql,
@@ -316,6 +320,8 @@ export function ComposedChart({
hideHighlightedValue={hideHighlightedValue}
title={title}
format={format}
+ hideHighlightedLabel={hideHighlightedLabel}
+ hideHighlightArea={hideHighlightArea}
titleTooltip={titleTooltip}
customDateFormat={customDateFormat}
highlightedValue={formatHighlightedValue(resolvedHighlightedValue)}
diff --git a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx b/apps/studio/pages/project/[ref]/reports/query-performance.tsx
similarity index 61%
rename from apps/studio/pages/project/[ref]/advisors/query-performance.tsx
rename to apps/studio/pages/project/[ref]/reports/query-performance.tsx
index 4db0331e911..f0a78fb3f4d 100644
--- a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx
+++ b/apps/studio/pages/project/[ref]/reports/query-performance.tsx
@@ -1,7 +1,7 @@
import { parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'
import { useParams } from 'common'
-import { EnableIndexAdvisorButton } from 'components/interfaces/QueryPerformance/EnableIndexAdvisorButton'
+import { EnableIndexAdvisorButton } from 'components/interfaces/QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton'
import { useIndexAdvisorStatus } from 'components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus'
import { useQueryPerformanceSort } from 'components/interfaces/QueryPerformance/hooks/useQueryPerformanceSort'
import { QueryPerformance } from 'components/interfaces/QueryPerformance/QueryPerformance'
@@ -9,19 +9,32 @@ import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'
import { useQueryPerformanceQuery } from 'components/interfaces/Reports/Reports.queries'
import { Presets } from 'components/interfaces/Reports/Reports.types'
import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'
-import AdvisorsLayout from 'components/layouts/AdvisorsLayout/AdvisorsLayout'
+import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import DatabaseSelector from 'components/ui/DatabaseSelector'
import { DocsButton } from 'components/ui/DocsButton'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import { DOCS_URL } from 'lib/constants'
import type { NextPageWithLayout } from 'types'
+import { LogsDatePicker } from 'components/interfaces/Settings/Logs/Logs.DatePickers'
+import { useReportDateRange } from 'hooks/misc/useReportDateRange'
+import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
const QueryPerformanceReport: NextPageWithLayout = () => {
const { ref } = useParams()
+ const { data: project } = useSelectedProjectQuery()
const { isIndexAdvisorEnabled } = useIndexAdvisorStatus()
const { sort: sortConfig } = useQueryPerformanceSort()
+ const {
+ selectedDateRange,
+ datePickerValue,
+ datePickerHelpers,
+ updateDateRange,
+ handleDatePickerChange,
+ } = useReportDateRange(REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES)
+
const [{ search: searchQuery, roles }] = useQueryStates({
sort: parseAsString,
order: parseAsString,
@@ -42,18 +55,32 @@ const QueryPerformanceReport: NextPageWithLayout = () => {
runIndexAdvisor: isIndexAdvisorEnabled,
})
+ const isPgStatMonitorEnabled = project?.dbVersion === '17.4.1.076-psml-1'
+
return (
<div className="h-full flex flex-col">
<FormHeader
- className="py-4 px-6 !mb-0"
+ className="py-4 px-6 !mb-0 md:flex-row flex-col"
title="Query Performance"
actions={
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<EnableIndexAdvisorButton />
<DocsButton
href={`${DOCS_URL}/guides/platform/performance#examining-query-performance`}
/>
<DatabaseSelector />
+ {isPgStatMonitorEnabled && (
+ <LogsDatePicker
+ value={datePickerValue}
+ helpers={datePickerHelpers.filter(
+ (h) =>
+ h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES ||
+ h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_3_HOURS ||
+ h.text === REPORT_DATERANGE_HELPER_LABELS.LAST_24_HOURS
+ )}
+ onSubmit={handleDatePickerChange}
+ />
+ )}
</div>
}
/>
@@ -61,6 +88,9 @@ const QueryPerformanceReport: NextPageWithLayout = () => {
queryHitRate={queryHitRate}
queryPerformanceQuery={queryPerformanceQuery}
queryMetrics={queryMetrics}
+ isPgStatMonitorEnabled={isPgStatMonitorEnabled}
+ dateRange={selectedDateRange}
+ onDateRangeChange={updateDateRange}
/>
</div>
)
@@ -68,7 +98,7 @@ const QueryPerformanceReport: NextPageWithLayout = () => {
QueryPerformanceReport.getLayout = (page) => (
<DefaultLayout>
- <AdvisorsLayout title="Query performance">{page}</AdvisorsLayout>
+ <ReportsLayout title="Query performance">{page}</ReportsLayout>
</DefaultLayout>
)