Files
supabase/apps/studio/data/database/entity-search-query.ts
T
Joshen Lim 2b55f7db9a Joshenlim/fe 4719 cmd k support searching for policies (#52678)
## Context

Continue to build off from
[here](https://github.com/supabase/supabase/pull/52205) 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 RLS
policies.

<img width="609" height="525" alt="image"
src="https://github.com/user-attachments/assets/212a430a-314d-48c4-a27c-2f9bb06e8457"
/>

Policies are matched on, in priority, its name and the target table.

## Performance checking

Just ran a check with Claude just to make sure that the added SQL
doesn't cause any performance degradation on the database. Plan guard
passes at 12,000 tables, under its 500ms budget. Also benchmarked
locally with a 3-character query matching every policy, results look
good so should be alright:

| Catalog | Worst-case search | No-match baseline |
|---|---|---|
| 36k policies | ~52–64ms | ~16ms |
| 120k policies | ~118–134ms | ~63ms |

## To test

- [x] Search a table name: Tables first, then its policies, under
Policies
- [x] Search a policy name: it appears under Policies and opens the
editor panel in database/policies
- [x] Policy outside `public`: schema filter switches and the policy
opens
2026-11-04 14:26:37 +08:00

82 lines
2.6 KiB
TypeScript

import { getSearchEntitiesSql } from '@supabase/pg-meta'
import { queryOptions } from '@tanstack/react-query'
import { z } from 'zod'
import { databaseKeys } from './keys'
import { unguarded } from '@/data/fetchers'
import { executeSql } from '@/data/sql/execute-sql-mutation'
import type { StudioError } from '@/lib/errors/studio-errors'
export type EntitySearchVariables = {
projectRef?: string
connectionString?: string | null
query: string
}
const entitySearchResultSchema = z.object({
tables: z.array(
z.object({
id: z.number(),
schema: z.string(),
name: z.string(),
rls_enabled: z.boolean(),
policy_count: z.number(),
})
),
policies: z.array(
z.object({
id: z.number(),
name: z.string(),
command: z.enum(['ALL', 'SELECT', 'INSERT', 'UPDATE', 'DELETE']),
schema: z.string(),
table: z.string(),
table_id: z.number(),
})
),
})
async function getEntitySearch(
{ projectRef, connectionString, query }: EntitySearchVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
const { result } = await executeSql(
{
projectRef,
connectionString,
sql: getSearchEntitiesSql({ query }),
queryKey: ['entity-search'],
grant: unguarded.migrating,
},
signal
)
return entitySearchResultSchema.parse(result[0])
}
export type EntitySearchData = Awaited<ReturnType<typeof getEntitySearch>>
export type EntitySearchTable = EntitySearchData['tables'][number]
export type EntitySearchPolicy = EntitySearchData['policies'][number]
export type EntitySearchError = StudioError
export const entitySearchQueryOptions = (
{ projectRef, connectionString, query }: EntitySearchVariables,
{ enabled = true }: { enabled?: boolean } = {}
) =>
queryOptions({
queryKey: databaseKeys.entitySearch(projectRef, query),
queryFn: ({ signal }) => getEntitySearch({ projectRef, connectionString, query }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && query.length > 0,
// Results are keyed per search string; reuse them briefly so backspacing or
// retyping a query doesn't hit the database again.
staleTime: 30 * 1000,
// Keep showing the previous results while the next search is in flight,
// but never carry them over from another project.
placeholderData: (previousData, previousQuery) =>
previousQuery?.queryKey[1] === projectRef ? previousData : undefined,
// A failed search isn't worth retrying against the user's database; the
// next keystroke issues a fresh one anyway.
retry: false,
})