Files
supabase/apps/studio/components/interfaces/QueryPerformance/useQueryPerformanceQuery.test.ts
T
Drew McLellan 8cda1fc977 fix(studio): apply query performance calls and total time filters in SQL (#53459)
## Problem

On the Query Performance page, the calls filter only applied to rows
already loaded in the grid. The page loads 20 rows at a time, so a
filter like `calls >= 200` showed "No queries detected" whenever none of
the loaded rows matched, even if matching queries existed further down.
The filter bar writes a `callsFilter` URL param, but the page only
passed a separate `minCalls` param to the SQL, which nothing set.

The total time filter had a related gap: only `>` and `>=` reached the
SQL, and the other operators were ignored.

Fixes part of FE-5092. The lazy-load fix is in #53457.

## Solution

- `generateQueryPerformanceSql` takes `callsFilter` and
`totalTimeFilter` and builds the `WHERE` clause for all six comparison
operators. The operator comes from a fixed lookup and the value goes
through `literal()`. Filters with a non-finite value or an unknown
operator are dropped.
- The page passes both filters to the query, and the unused `minCalls`
param is removed.
- The grid no longer filters search, roles or calls in memory, since the
SQL already does.

- The query search is now a literal, case-insensitive substring match.
It was a regex (`~*`), so characters like `[` or `(` produced a SQL
error while typing. This matches what the grid's old in-memory search
did.

Behavior changes to be aware of:

- Regex search no longer works. Searching for `a.*b` now looks for that
exact text.
- Old `?minCalls=` links no longer have any effect. The UI never
produced them.

## Review instructions

1. Open Observability → Query Performance on a project with more than 20
statements.
2. Add a Calls filter of `>= 200` (or a value higher than anything in
the first 20 rows). Confirm matching queries appear.
3. Try the other operators on Calls and on Total time, including `!=`.
4. Search for `[` and `pg_sleep(` and confirm the grid shows matches (or
an empty state) instead of a SQL error.
5. Clear the filters and confirm the full list returns.

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-11-17 15:09:52 +00:00

232 lines
7.7 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { QueryPerformanceSort } from './QueryPerformance.types'
import { generateQueryPerformanceSql } from './useQueryPerformanceQuery'
describe('generateQueryPerformanceSql', () => {
it('generates sql with no filters', () => {
const result = generateQueryPerformanceSql({ preset: 'mostFrequentlyInvoked' })
expect(result.sql).toBeDefined()
expect(result.whereSql).toBe('')
expect(result.orderBySql).toBeUndefined()
})
it('generates ORDER BY clause', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
orderBy: { column: 'calls', order: 'desc' },
})
expect(result.orderBySql).toBe('ORDER BY calls desc')
})
it('filters by roles', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
roles: ['postgres', 'anon'],
})
expect(result.whereSql).toContain("auth.rolname in ('postgres', 'anon')")
})
it('filters by search query', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
searchQuery: 'SELECT',
})
expect(result.whereSql).toBe("strpos(lower(statements.query), lower('SELECT')) > 0")
})
it.each(['[', 'pg_sleep(', '(unclosed', 'a\\b', "it's", '100%', 'under_score'])(
'treats %s in the search query as literal text',
(searchQuery) => {
const result = generateQueryPerformanceSql({ preset: 'mostFrequentlyInvoked', searchQuery })
expect(result.whereSql).not.toContain('~*')
expect(result.whereSql).toMatch(/^strpos\(lower\(statements\.query\), lower\(.+\)\) > 0$/)
}
)
it('filters by dashboard source only', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
sources: ['dashboard'],
})
expect(result.whereSql).toContain("statements.query ~* 'source: dashboard'")
})
it('filters by non-dashboard source only', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
sources: ['non-dashboard'],
})
expect(result.whereSql).toContain("statements.query !~* 'source: dashboard'")
})
it('does not add source filter when both sources are selected', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
sources: ['dashboard', 'non-dashboard'],
})
expect(result.whereSql).not.toContain('source: dashboard')
})
it.each([
['=', '='],
['>=', '>='],
['<=', '<='],
['>', '>'],
['<', '<'],
['!=', '<>'],
] as const)('filters calls with the %s operator', (operator, sqlOperator) => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
callsFilter: { operator, value: 200 },
})
expect(result.whereSql).toBe(`statements.calls ${sqlOperator} 200`)
})
it.each([
['=', '='],
['>=', '>='],
['<=', '<='],
['>', '>'],
['<', '<'],
['!=', '<>'],
] as const)('filters total time with the %s operator', (operator, sqlOperator) => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
totalTimeFilter: { operator, value: 500 },
})
expect(result.whereSql).toBe(
`(statements.total_exec_time + statements.total_plan_time) ${sqlOperator} 500`
)
})
it('keeps a filter value of 0', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
callsFilter: { operator: '<=', value: 0 },
})
expect(result.whereSql).toBe('statements.calls <= 0')
})
it('ignores a filter with a non-finite value', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
callsFilter: { operator: '>=', value: Number.NaN },
})
expect(result.whereSql).toBe('')
})
it.each(['>= 0 OR 1=1 --', 'constructor', '__proto__', 'toString'])(
'ignores a filter with the unknown operator %s',
(operator) => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
// URL params are not validated at runtime, so an injected operator must be dropped
callsFilter: { operator: operator as never, value: 1 },
})
expect(result.whereSql).toBe('')
}
)
it('combines multiple WHERE conditions with AND', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
roles: ['postgres'],
searchQuery: 'SELECT',
callsFilter: { operator: '>=', value: 5 },
})
expect(result.whereSql).toContain("auth.rolname in ('postgres')")
expect(result.whereSql).toContain("lower('SELECT')")
expect(result.whereSql).toContain('statements.calls >= 5')
expect(result.whereSql.split(' AND ').length).toBe(3)
})
it('passes WHERE clause to base sql function', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
roles: ['postgres'],
})
expect(result.sql).toContain('WHERE')
})
it.each([
'mostFrequentlyInvoked',
'mostTimeConsuming',
'slowestExecutionTime',
'queryHitRate',
'unified',
] as const)('generates sql for the %s preset', (preset) => {
expect(generateQueryPerformanceSql({ preset }).sql.length).toBeGreaterThan(0)
})
it.each([0, -5])('clamps page=%s to page=1 (no negative offset)', (page) => {
const result = generateQueryPerformanceSql({ preset: 'unified', page, pageSize: 20 })
expect(result.sql).toContain('offset 0')
expect(result.sql).not.toMatch(/offset -\d/)
})
it('clamps pageSize above 100 to 100', () => {
const result = generateQueryPerformanceSql({ preset: 'unified', page: 1, pageSize: 9999 })
expect(result.sql).toContain('limit 100')
expect(result.sql).not.toContain('limit 9999')
})
it('applies LIMIT and OFFSET for page 2', () => {
const result = generateQueryPerformanceSql({ preset: 'unified', page: 2, pageSize: 20 })
expect(result.sql).toContain('limit 20 offset 20')
})
it('does not produce NaN in SQL when page is NaN', () => {
const result = generateQueryPerformanceSql({ preset: 'unified', page: NaN, pageSize: 20 })
expect(result.sql).not.toContain('NaN')
expect(result.sql).toContain('offset 0')
})
it('does not produce NaN in SQL when pageSize is NaN', () => {
const result = generateQueryPerformanceSql({ preset: 'unified', page: 1, pageSize: NaN })
expect(result.sql).not.toContain('NaN')
expect(result.sql).toContain('limit 20')
})
})
describe('generateQueryPerformanceSql - ORDER BY column validation', () => {
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('rejects an orderBy column containing a colon (old URL format) and falls back to the default', () => {
const result = generateQueryPerformanceSql({
preset: 'mostFrequentlyInvoked',
orderBy: { column: 'created_at:asc' as any, order: 'asc' },
})
expect(result.orderBySql).toBeUndefined()
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`)
}
})
})