The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(observability): guard pg_stat_statements queries against missing extension FE-2843 (#44357)
Jordi Enricc689e91160b5
diff --git a/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.ts b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.tsnew file mode 100644index 00000000000..42b27b654f8--- /dev/null+++ b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest'++import { buildSlowQueriesCountSql } from './useSlowQueriesCount'++describe('buildSlowQueriesCountSql', () => {+ it('checks pg_extension before querying pg_stat_statements', () => {+ const sql = buildSlowQueriesCountSql()+ expect(sql).toContain('pg_extension')+ expect(sql).toContain("extname = 'pg_stat_statements'")+ })++ it('returns 0 when extension is not installed', () => {+ expect(buildSlowQueriesCountSql()).toContain('ELSE 0')+ })++ it('still queries pg_stat_statements when extension exists', () => {+ const sql = buildSlowQueriesCountSql()+ expect(sql).toContain('pg_stat_statements')+ expect(sql).toContain('total_exec_time + total_plan_time > 1000')+ })+})diff --git a/apps/studio/components/interfaces/Observability/useSlowQueriesCount.ts b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.tsindex 9789a61b190..5e6f872ace6 100644--- a/apps/studio/components/interfaces/Observability/useSlowQueriesCount.ts+++ b/apps/studio/components/interfaces/Observability/useSlowQueriesCount.ts@@ -1,19 +1,31 @@import useDbQuery from 'hooks/analytics/useDbQuery'import { useMemo } from 'react'-export const useSlowQueriesCount = (projectRef?: string, refreshKey: number = 0) => {- // SQL to count queries with total execution time > 1000ms (1 second)- // refreshKey is used in useMemo to force recomputation when refresh is triggered- const sql = useMemo(- () => `+export function buildSlowQueriesCountSql(): string {+ return `-- observability-slow-queries-countset search_path to public, extensions;SELECT- count(*)::int as slow_queries_count- FROM pg_stat_statements- WHERE total_exec_time + total_plan_time > 1000;- `,+ CASE+ WHEN EXISTS (+ SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements'+ )+ THEN (+ SELECT count(*)::int+ FROM pg_stat_statements+ WHERE total_exec_time + total_plan_time > 1000+ )+ ELSE 0+ END AS slow_queries_count;+ `+}++export const useSlowQueriesCount = (projectRef?: string, refreshKey: number = 0) => {+ // refreshKey is used in useMemo to force recomputation when refresh is triggered+ const sql = useMemo(+ () => buildSlowQueriesCountSql(),+ // eslint-disable-next-line react-hooks/exhaustive-deps[refreshKey])diff --git a/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsxindex 560aac63aad..256f9add6f2 100644--- a/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx+++ b/apps/studio/components/interfaces/QueryPerformance/WithStatements/WithStatements.tsx@@ -96,16 +96,22 @@ export const WithStatements = ({useEffect(() => {if (mainQueryError) {const errorMessage = getErrorMessage(mainQueryError)- captureQueryPerformanceError(mainQueryError, {- projectRef: ref,- databaseIdentifier: state.selectedDatabaseId,- queryPreset: 'unified',- queryType: 'mainQuery',- postgresVersion: project?.dbVersion,- databaseType: isPrimaryDatabase ? 'primary' : 'read-replica',- sql: queryPerformanceQuery.resolvedSql,- errorMessage: errorMessage || undefined,- })+ const isNotInstalled =+ typeof errorMessage === 'string' &&+ errorMessage.includes('pg_stat_statements') &&+ errorMessage.includes('does not exist')+ if (!isNotInstalled) {+ captureQueryPerformanceError(mainQueryError, {+ projectRef: ref,+ databaseIdentifier: state.selectedDatabaseId,+ queryPreset: 'unified',+ queryType: 'mainQuery',+ postgresVersion: project?.dbVersion,+ databaseType: isPrimaryDatabase ? 'primary' : 'read-replica',+ sql: queryPerformanceQuery.resolvedSql,+ errorMessage: errorMessage || undefined,+ })+ }}}, [mainQueryError,@@ -155,18 +161,31 @@ export const WithStatements = ({? getErrorMessage(metricsError) || 'Failed to load query metrics': null+ const isPgStatStatementsNotInstalled =+ typeof errorMessage === 'string' &&+ errorMessage.includes('pg_stat_statements') &&+ errorMessage.includes('does not exist')+return (<>{hasError && (<div className="px-6 pt-4">- <Admonition- type="destructive"- title="Error loading query performance data"- description={- errorMessage ||- 'An error occurred while loading query performance data. Please try refreshing the page.'- }- />+ {isPgStatStatementsNotInstalled ? (+ <Admonition+ type="warning"+ title="pg_stat_statements extension is not enabled"+ description="Query Performance requires the pg_stat_statements extension. Enable it in Database → Extensions."+ />+ ) : (+ <Admonition+ type="destructive"+ title="Error loading query performance data"+ description={+ errorMessage ||+ 'An error occurred while loading query performance data. Please try refreshing the page.'+ }+ />+ )}</div>)}<QueryPerformanceMetrics />diff --git a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.tsindex 08079445784..3ab057de8f7 100644--- a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts+++ b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'+import { QueryPerformanceSort } from './QueryPerformance.types'import { generateQueryPerformanceSql } from './useQueryPerformanceQuery'describe('generateQueryPerformanceSql', () => {@@ -170,3 +171,51 @@ describe('generateQueryPerformanceSql', () => {expect(result.sql).toContain('limit 20')})})++describe('generateQueryPerformanceSql - ORDER BY column validation', () => {+ it('rejects invalid orderBy column containing colon (old URL format)', () => {+ const result = generateQueryPerformanceSql({+ preset: 'mostFrequentlyInvoked',+ orderBy: { column: 'created_at:asc' as any, order: 'desc' },+ })+ expect(result.orderBySql).toBeUndefined()+ })++ it('rejects SQL injection in orderBy column', () => {+ const result = generateQueryPerformanceSql({+ preset: 'mostFrequentlyInvoked',+ orderBy: { column: 'calls; DROP TABLE users--' as any, order: 'asc' },+ })+ expect(result.orderBySql).toBeUndefined()+ expect(result.sql).not.toContain('DROP TABLE')+ })++ it('falls back to default ORDER BY when column is invalid', () => {+ const result = generateQueryPerformanceSql({+ preset: 'mostFrequentlyInvoked',+ orderBy: { column: 'created_at:asc' as any, order: 'asc' },+ })+ expect(result.sql).toContain('order by statements.calls desc')+ })++ it('accepts all valid sort columns', () => {+ const columns: QueryPerformanceSort['column'][] = [+ 'query',+ 'rolname',+ 'total_time',+ 'prop_total_time',+ 'calls',+ 'avg_rows',+ 'max_time',+ 'mean_time',+ 'min_time',+ ]+ for (const column of columns) {+ const result = generateQueryPerformanceSql({+ preset: 'mostFrequentlyInvoked',+ orderBy: { column, order: 'asc' },+ })+ expect(result.orderBySql).toBe(`ORDER BY ${column} asc`)+ }+ })+})diff --git a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.ts b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.tsindex 023f17eacb0..1b8f593a319 100644--- a/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.ts+++ b/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.ts@@ -3,11 +3,28 @@ import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'import { executeSql } from 'data/sql/execute-sql-query'import useDbQuery from 'hooks/analytics/useDbQuery'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'+import { IS_PLATFORM } from 'lib/constants'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { PRESET_CONFIG } from '../Reports/Reports.constants'import { Presets } from '../Reports/Reports.types'-import { QueryPerformanceRow, QueryPerformanceSQLParams } from './QueryPerformance.types'+import {+ QueryPerformanceRow,+ QueryPerformanceSort,+ QueryPerformanceSQLParams,+} from './QueryPerformance.types'++const VALID_SORT_COLUMNS: ReadonlySet<string> = new Set<QueryPerformanceSort['column']>([+ 'query',+ 'rolname',+ 'total_time',+ 'prop_total_time',+ 'calls',+ 'avg_rows',+ 'max_time',+ 'mean_time',+ 'min_time',+])export function generateQueryPerformanceSql({preset,@@ -30,7 +47,12 @@ export function generateQueryPerformanceSql({const queryPerfQueries = PRESET_CONFIG[Presets.QUERY_PERFORMANCE]const baseSQL = queryPerfQueries.queries[preset]- const orderBySql = orderBy && `ORDER BY ${orderBy.column} ${orderBy.order}`+ const isValidOrderBy =+ orderBy != null &&+ VALID_SORT_COLUMNS.has(orderBy.column) &&+ (orderBy.order === 'asc' || orderBy.order === 'desc')++ const orderBySql = isValidOrderBy ? `ORDER BY ${orderBy!.column} ${orderBy!.order}` : undefinedconst whereConditions = []if (roles.length > 0) {@@ -150,7 +172,9 @@ export const useQueryPerformanceInfiniteQuery = (},// Don't run until we have a connection string for the selected database.// For replicas this prevents a silent fallback to the primary before replicas load.- enabled: Boolean(project?.ref) && Boolean(effectiveConnectionString),+ // In self-hosted mode (IS_PLATFORM=false) there is no real connection string, so we+ // skip the check — executeSql works fine without one on self-hosted deployments.+ enabled: Boolean(project?.ref) && (!IS_PLATFORM || Boolean(effectiveConnectionString)),refetchOnWindowFocus: false,refetchOnReconnect: false,})