The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): query performance metric cards (#38634)
kemal.earth604be766a82e
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.tsindex 05758348293..3fd1dbfbbea 100644--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.constants.ts@@ -14,9 +14,9 @@ export const QUERY_PERFORMANCE_PRESET_MAP = {export const QUERY_PERFORMANCE_COLUMNS = [{ id: 'query', name: 'Query', description: undefined, minWidth: 500 },- { id: 'calls', name: 'Calls', description: undefined, minWidth: 100 },+ { id: 'prop_total_time', name: 'Time consumed', description: undefined, minWidth: 130 },{ id: 'total_time', name: 'Total time', description: 'latency', minWidth: 150 },- { 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 },diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsxindex 9df7a22eda7..c65e22d85a9 100644--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.tsx@@ -1,5 +1,4 @@import { X } from 'lucide-react'-import { parseAsArrayOf, parseAsString, useQueryStates } from 'nuqs'import { useEffect, useState } from 'react'import { toast } from 'sonner'@@ -16,29 +15,25 @@ import { Button, LoadingLine, cn } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { Markdown } from '../Markdown'import { PresetHookResult } from '../Reports/Reports.utils'+import { QueryPerformanceMetrics } from './QueryPerformanceMetrics'import { QueryPerformanceFilterBar } from './QueryPerformanceFilterBar'import { QueryPerformanceGrid } from './QueryPerformanceGrid'interface QueryPerformanceProps {queryHitRate: PresetHookResultqueryPerformanceQuery: DbQueryHook<any>+ queryMetrics: PresetHookResult}export const QueryPerformance = ({queryHitRate,queryPerformanceQuery,+ queryMetrics,}: QueryPerformanceProps) => {const { ref } = useParams()const { data: project } = useSelectedProjectQuery()const state = useDatabaseSelectorStateSnapshot()- const [{ search: searchQuery, roles }] = useQueryStates({- sort: parseAsString,- search: parseAsString,- order: parseAsString,- roles: parseAsArrayOf(parseAsString).withDefault([]),- })-const { isLoading, isRefetching } = queryPerformanceQueryconst isPrimaryDatabase = state.selectedDatabaseId === refconst formattedDatabaseId = formatDatabaseID(state.selectedDatabaseId ?? '')@@ -53,6 +48,7 @@ export const QueryPerformance = ({const handleRefresh = () => {queryPerformanceQuery.runQuery()queryHitRate.runQuery()+ queryMetrics.runQuery()}const { data: databases } = useReadReplicasQuery({ projectRef: ref })@@ -64,6 +60,7 @@ export const QueryPerformance = ({return (<>+ <QueryPerformanceMetrics /><QueryPerformanceFilterBarqueryPerformanceQuery={queryPerformanceQuery}onResetReportClick={() => setShowResetgPgStatStatements(true)}diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsxindex 0775f723264..a2d91081a21 100644--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceFilterBar.tsx@@ -65,7 +65,7 @@ export const QueryPerformanceFilterBar = ({}, [searchValue])return (- <div className="px-6 py-2 bg-surface-200 border-t -mt-px flex justify-between items-center overflow-x-auto w-full">+ <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="flex items-center gap-x-4"><div className="flex items-center gap-x-2"><Inputdiff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsxindex afbe23df0d1..acf01e6b997 100644--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx@@ -51,6 +51,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceconst result: Column<any> = {key: col.id,name: col.name,+ cellClass: `column-${col.id}`,resizable: true,minWidth: col.minWidth ?? 120,sortable: !nonSortableColumns.includes(col.id),@@ -113,7 +114,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformanceconst value = props.row?.[col.id]if (col.id === 'query') {return (- <div className="w-full flex items-center gap-x-3">+ <div className="w-full flex items-center gap-x-3 ml-4">{hasIndexRecommendations(props.row.index_advisor_result, true) && (<IndexSuggestionIconindexAdvisorResult={props.row.index_advisor_result}@@ -146,8 +147,18 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance}if (col.id === 'prop_total_time') {+ const percentage = props.row.prop_total_time || 0+ const fillWidth = Math.min(percentage, 100)+return (<div className="w-full flex flex-col justify-center text-xs">+ <div+ className={`absolute inset-0 bg-foreground transition-all duration-200 z-0`}+ style={{+ width: `${fillWidth}%`,+ opacity: 0.04,+ }}+ /><p>{value ? `${value.toFixed(1)}%` : 'n/a'}</p></div>)@@ -274,7 +285,7 @@ export const QueryPerformanceGrid = ({ queryPerformanceQuery }: QueryPerformance`${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' : ''}`,'[&>.rdg-cell]:box-border [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',- '[&>.rdg-cell:first-child>div]:ml-4',+ '[&>.rdg-cell.column-prop_total_time]:relative',].join(' ')}}renderers={{diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceMetrics.tsx b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceMetrics.tsxnew file mode 100644index 00000000000..e8e3b908578--- /dev/null+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformanceMetrics.tsx@@ -0,0 +1,50 @@+import { useMemo } from 'react'++import { Skeleton } from 'ui'+import { useQueryPerformanceQuery } from '../Reports/Reports.queries'++export const QueryPerformanceMetrics = () => {+ const { data: queryMetrics, isLoading } = useQueryPerformanceQuery({+ preset: 'queryMetrics',+ })++ const stats = useMemo(() => {+ return [+ {+ title: queryMetrics?.[0]?.slow_queries === '1' ? 'Slow Query' : 'Slow Queries',+ value: queryMetrics?.[0]?.slow_queries || '0',+ },+ {+ title: 'Cache Hit Rate',+ value: queryMetrics?.[0]?.cache_hit_rate || '0%',+ },+ {+ title: 'Avg. Rows Per Call',+ value: queryMetrics?.[0]?.avg_rows_per_call || '0',+ },+ ]+ }, [queryMetrics])++ return (+ <section className="px-6 pt-2 pb-4 flex flex-wrap gap-x-6 gap-y-2 w-full">+ {stats.map((card, i) => (+ <>+ <div+ key={i}+ className="flex items-baseline gap-2 heading-subSection text-foreground-light"+ >+ {isLoading ? (+ <Skeleton className="h-5 w-24" />+ ) : (+ <>+ <span className="text-foreground">{card.value}</span>+ <span>{card.title}</span>+ </>+ )}+ </div>+ {i < stats.length - 1 && <span className="text-foreground-muted">/</span>}+ </>+ ))}+ </section>+ )+}diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.tsindex 28e90679530..aea68a98aea 100644--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts@@ -539,6 +539,38 @@ select${orderBy || 'order by statements.total_exec_time + statements.total_plan_time desc'}limit 20`,},+ slowQueriesCount: {+ queryType: 'db',+ sql: () => `+ -- reports-query-performance-slow-queries-count+ set search_path to public, extensions;++ -- Count of slow queries (> 1 second average)+ SELECT count(*) as slow_queries_count+ FROM pg_stat_statements+ WHERE statements.mean_exec_time > 1000;`,+ },+ queryMetrics: {+ queryType: 'db',+ sql: (_params, where, orderBy, runIndexAdvisor = false) => `+ -- reports-query-performance-metrics+ set search_path to public, extensions;++ SELECT+ COALESCE(ROUND(AVG(statements.rows::numeric / NULLIF(statements.calls, 0)), 1), 0) as avg_rows_per_call,+ COUNT(*) FILTER (WHERE statements.total_exec_time + statements.total_plan_time > 1000) as slow_queries,+ COALESCE(+ ROUND(+ SUM(statements.shared_blks_hit) * 100.0 /+ NULLIF(SUM(statements.shared_blks_hit + statements.shared_blks_read), 0),+ 2+ ), 0+ ) || '%' as cache_hit_rate+ FROM pg_stat_statements as statements+ WHERE statements.calls > 0+ ${where || ''}+ ${orderBy || ''}`,+ },},},[Presets.DATABASE]: {diff --git a/apps/studio/components/interfaces/Reports/Reports.queries.ts b/apps/studio/components/interfaces/Reports/Reports.queries.tsindex 1ceae347892..25151abfaf3 100644--- a/apps/studio/components/interfaces/Reports/Reports.queries.ts+++ b/apps/studio/components/interfaces/Reports/Reports.queries.ts@@ -23,6 +23,8 @@ export type QueryPerformanceQueryOpts = {| 'slowestExecutionTime'| 'queryHitRate'| 'unified'+ | 'slowQueriesCount'+ | 'queryMetrics'searchQuery?: stringorderBy?: QueryPerformanceSortroles?: string[]diff --git a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx b/apps/studio/pages/project/[ref]/advisors/query-performance.tsxindex fccb44e2069..b94a267b3c1 100644--- a/apps/studio/pages/project/[ref]/advisors/query-performance.tsx+++ b/apps/studio/pages/project/[ref]/advisors/query-performance.tsx@@ -5,10 +5,6 @@ import { EnableIndexAdvisorButton } from 'components/interfaces/QueryPerformanceimport { useIndexAdvisorStatus } from 'components/interfaces/QueryPerformance/hooks/useIsIndexAdvisorStatus'import { useQueryPerformanceSort } from 'components/interfaces/QueryPerformance/hooks/useQueryPerformanceSort'import { QueryPerformance } from 'components/interfaces/QueryPerformance/QueryPerformance'-import {- QUERY_PERFORMANCE_PRESET_MAP,- QUERY_PERFORMANCE_REPORT_TYPES,-} from 'components/interfaces/QueryPerformance/QueryPerformance.constants'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'@@ -35,6 +31,7 @@ const QueryPerformanceReport: NextPageWithLayout = () => {const config = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]const hooks = queriesFactory(config.queries, ref ?? 'default')const queryHitRate = hooks.queryHitRate()+ const queryMetrics = hooks.queryMetrics()const queryPerformanceQuery = useQueryPerformanceQuery({searchQuery,@@ -57,7 +54,11 @@ const QueryPerformanceReport: NextPageWithLayout = () => {</div>}/>- <QueryPerformance queryHitRate={queryHitRate} queryPerformanceQuery={queryPerformanceQuery} />+ <QueryPerformance+ queryHitRate={queryHitRate}+ queryPerformanceQuery={queryPerformanceQuery}+ queryMetrics={queryMetrics}+ /></div>)}