Files
supabase/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearch.utils.ts
T
Joshen Lim 06d43f6881 Joshenlim/fe 4721 cmd k support searching for triggers (#52755)
## Context

Building off from
[here](https://github.com/supabase/supabase/pull/52751) to make Cmd+K
resource-aware so finding and inspecting anything in a project doesn't
depend on knowing where it lives in the dashboard.

Specifically looking into database entities for now - end state would be
that you could search for a table name for example, and Cmd K will pull
up everything related to that table for you to skim (e.g Policies,
Functions, Triggers, etc). Changes in this PR sets up searching for
**database triggers**, and will probably be the last database entity
that we'll add into context aware cmd K for now given that we'll have
tables, policies, functions and triggers which are the primary building
blocks for a project.

<img width="500" alt="image"
src="https://github.com/user-attachments/assets/242ec517-88cd-4f3d-96ce-741edaa8560d"
/>

Triggers will also match if it's function matches the search input, and
its description will tweak slightly as well
<img width="500" alt="image"
src="https://github.com/user-attachments/assets/65f515df-b875-4b92-95b7-00389d8a070b"
/>

## Performance

Had Claude do some benchmarking against `getSearchEntitiesSql` (`EXPLAIN
ANALYZE`, median of 5 runs, local Postgres, warm cache) on one synthetic
catalog:
- 12,000 tables (36,651 `pg_class`), 6,001 policies, 27,261 `pg_proc`
(12,000 user + 12,000 extension-owned functions), 56,304 `pg_trigger`
- 3,500 user triggers, 500 of which run one shared function; the rest
are internal FK triggers
  - 297,921 `pg_depend`.

Compared against master (tables + policies) and the functions PR (before
triggers).

| Search | What it exercises | master | functions PR | this PR | Δ this
PR |
|---|---|---|---|---|---|
| `t_1` | broad table match | 12ms | 26ms | 30ms | +4ms |
| `p_1` | broad policy-name match | 15ms | 27ms | 35ms | +8ms |
| `fn_1` | broad function match | 10ms | 26ms | 33ms | +7ms |
| `trg_1` | broad trigger-name match | 9ms | 23ms | 32ms | +9ms |
| `trg_` | every user trigger matches by name | 10ms | 25ms | 40ms |
+15ms |
| `audit_row_fn` | function match; its 500 triggers match only through
the function | 9ms | 24ms | 31ms | +7ms |
| `ri_constraint` | only internal FK triggers match | 9ms | 24ms | 30ms
| +6ms |
| `stress.fn_1` | schema-qualified | 12ms | 33ms | 40ms | +7ms |
| `zzz` | no match | 9ms | 22ms | 27ms | +5ms |

- Triggers add +4 to +15ms over the functions PR. The worst case is a
search matching every user trigger, at 40ms in total.
- Matching triggers through their function shares the single
`pg_trigger` pass the name search already does, with no extra scan. A
separate pass measured about 30ms more on every search.

## To test
- [ ] Search a table name: Tables first, then policies, and functions,
and triggers
- [ ] Search a trigger name: it appears under triggers and opens the
editor panel in database/triggers
- [ ] Search a function name: trigger results should appear if the
trigger uses that function
- [ ] Trigger outside public: schema filter switches and the trigger
opens
2026-11-06 17:04:39 +08:00

136 lines
5.0 KiB
TypeScript

import { SEARCH_ENTITIES_MAX_QUERY_LENGTH } from '@supabase/pg-meta'
import type {
EntitySearchFunction,
EntitySearchPolicy,
EntitySearchTable,
EntitySearchTrigger,
} from '@/data/database/entity-search-query'
// Each search runs SQL against the user's database, so keep it to queries that
// are specific enough to be useful: short queries match too broadly to be worth
// the round-trip.
export const ENTITY_SEARCH_MIN_QUERY_LENGTH = 3
export const ENTITY_SEARCH_DEBOUNCE_MS = 300
export function getEntitySearchQuery(query: string) {
const trimmed = query.trim()
const isSearchable =
trimmed.length >= ENTITY_SEARCH_MIN_QUERY_LENGTH &&
trimmed.length <= SEARCH_ENTITIES_MAX_QUERY_LENGTH
return { query: trimmed, isSearchable }
}
/**
* Client-side mirror of the matching in getSearchEntitiesSql: the name contains
* the query, or for `schema.name` queries, the schema starts with the part
* before the first dot and the name contains the part after it. Used to narrow
* results from a previous search while the current one is still in flight.
*/
export function matchesEntitySearch(
{ schema, name }: Pick<EntitySearchTable, 'schema' | 'name'>,
query: string
) {
const lowerQuery = query.toLowerCase()
const lowerName = name.toLowerCase()
if (lowerName.includes(lowerQuery)) return true
const dotIndex = lowerQuery.indexOf('.')
if (dotIndex === -1) return false
const schemaPart = lowerQuery.slice(0, dotIndex)
const namePart = lowerQuery.slice(dotIndex + 1)
return schema.toLowerCase().startsWith(schemaPart) && lowerName.includes(namePart)
}
/**
* Client-side mirror of how policies and triggers are matched in
* getSearchEntitiesSql: the entity's own name contains the query, or its table
* matches it. Used to narrow results from a previous search while the current
* one is still in flight.
*/
export function matchesTableRelatedSearch(
{ name, schema, table }: Pick<EntitySearchPolicy, 'name' | 'schema' | 'table'>,
query: string
) {
if (name.toLowerCase().includes(query.toLowerCase())) return true
return matchesEntitySearch({ schema, name: table }, query)
}
export function formatTableSearchDetails({
policy_count,
rls_enabled,
}: Pick<EntitySearchTable, 'policy_count' | 'rls_enabled'>) {
const policies = `${policy_count} ${policy_count === 1 ? 'policy' : 'policies'}`
return `${policies} • RLS ${rls_enabled ? 'enabled' : 'disabled'}`
}
export function getTableEditorRoute(
projectRef: string,
table: Pick<EntitySearchTable, 'id' | 'schema'>
): `/${string}` {
return `/project/${projectRef}/editor/${table.id}?schema=${encodeURIComponent(table.schema)}`
}
// The policies page lists policies per schema, so the schema must be set for
// the policy to be found and opened for editing.
export function getPolicyEditorRoute(
projectRef: string,
policy: Pick<EntitySearchPolicy, 'id' | 'schema'>
): `/${string}` {
return `/project/${projectRef}/database/policies?schema=${encodeURIComponent(policy.schema)}&edit=${policy.id}`
}
// Triggers found through their function don't match by name or table, so say which
// function they run instead of their timing
export function formatTriggerSearchDetails({
activation,
events,
schema,
table,
matched_function,
}: Pick<EntitySearchTrigger, 'activation' | 'events' | 'schema' | 'table' | 'matched_function'>) {
if (matched_function) return `Runs ${matched_function}`
return `${activation} ${events.join(' OR ')} on ${schema}.${table}`
}
/**
* Client-side mirror of how triggers are matched in getSearchEntitiesSql: like
* policies, by name or table, plus triggers found through the function they run.
*/
export function matchesTriggerSearch(
trigger: Pick<EntitySearchTrigger, 'name' | 'schema' | 'table' | 'matched_function'>,
query: string
) {
if (matchesTableRelatedSearch(trigger, query)) return true
return trigger.matched_function?.toLowerCase().includes(query.toLowerCase()) ?? false
}
// The triggers page lists triggers per schema (of their table), so the schema
// must be set for the trigger to be found and opened for editing. The index
// route only redirects, and drops the query string, so link to the list directly.
export function getTriggerEditorRoute(
projectRef: string,
trigger: Pick<EntitySearchTrigger, 'id' | 'schema'>
): `/${string}` {
return `/project/${projectRef}/database/triggers/data?schema=${encodeURIComponent(trigger.schema)}&edit=${trigger.id}`
}
export function formatFunctionSearchDetails({
type,
args,
}: Pick<EntitySearchFunction, 'type' | 'args'>) {
const procedure = type === 'procedure' ? 'procedure' : ''
if (args.length === 0) return procedure
return `${procedure} (${args})`.trim()
}
// The functions page lists functions per schema, so the schema must be set for
// the function to be found and opened for editing.
export function getFunctionEditorRoute(
projectRef: string,
fn: Pick<EntitySearchFunction, 'id' | 'schema'>
): `/${string}` {
return `/project/${projectRef}/database/functions?schema=${encodeURIComponent(fn.schema)}&edit=${fn.id}`
}