Files
supabase/apps/studio/data/database/entity-search-query.ts
Joshen Lim 53ffdf75c9 Joshenlim/fe 4945 cmd k support searching for all table (#53262)
## Context

Probably the final piece for this series of changes towards resource
aware Cmd K. We currently only present results for tables when searching
in Cmd K, this PR adds in other entity types like views, materialized
views, foreign tables, and partitioned tables (only the parent)

Note that the results excludes entities created from database extensions
to reduce the chance of noise

<img width="500" alt="image"
src="https://github.com/user-attachments/assets/27bf5026-937a-4883-b365-75694d551a39"
/>

## Related changes
- Tweaked the entity icon for partitioned tables a little to be blue
(previously gray) and
- Added an entity icon for child partition tables in the table editor
that's slightly lighter than the partition table icon, currently child
partition tables just render with the same icon as tables which can be
confusing
<img width="286" height="128" alt="image"
src="https://github.com/user-attachments/assets/638af7c3-512d-4264-bfae-0a8827b3ef94"
/>
- Note that i'm planning to look into this separately RE how to better
render child partition tables so this might go away subsequently

## Performance

As always, ran a claude benchmarking session - this runs on debounced
keystrokes against a live catalog, so it's benchmarked at scale:
**45,653 `pg_class` rows**
- 12k tables
- 3,143 views
- 3,002 matviews
- 3,001 foreign tables)
Taking a median of 15 runs, all variants measured against the same
catalog in one process.

| scenario | query | master | this PR | worst |
|---|---|---|---|---|
| exact table name | `t_500` | 19.5ms | 24.3ms | 29.1ms |
| view name | `v_10` | 19.3ms | 23.7ms | 25.8ms |
| foreign table name | `ft_10` | 18.9ms | 24.1ms | 26.9ms |
| no match | `zzz_nothing` | 19.4ms | 24.0ms | 27.5ms |
| broad prefix (~3k matches) | `t_1` | 30.8ms | 38.7ms | 45.1ms |
| broad matview prefix | `mv_1` | 26.6ms | 37.5ms | 41.7ms |
2026-11-12 11:37:45 +08:00

116 lines
3.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 relationFields = {
id: z.number(),
schema: z.string(),
name: z.string(),
}
const entitySearchResultSchema = z.object({
tables: z.array(
z.discriminatedUnion('type', [
z.object({
...relationFields,
type: z.enum(['r', 'p']),
rls_enabled: z.boolean(),
policy_count: z.number(),
}),
z.object({ ...relationFields, type: z.literal('v'), security_invoker: z.boolean() }),
z.object({ ...relationFields, type: z.enum(['m', 'f']) }),
])
),
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(),
})
),
triggers: z.array(
z.object({
id: z.number(),
name: z.string(),
activation: z.enum(['BEFORE', 'AFTER', 'INSTEAD OF']),
events: z.array(z.enum(['INSERT', 'UPDATE', 'DELETE', 'TRUNCATE'])),
schema: z.string(),
table: z.string(),
table_id: z.number(),
matched_function: z.string().nullable(),
})
),
functions: z.array(
z.object({
id: z.number(),
schema: z.string(),
name: z.string(),
type: z.enum(['function', 'procedure']),
args: z.string(),
})
),
})
async function getEntitySearch(
{ projectRef, connectionString, query }: EntitySearchVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
const { result } = await executeSql(
{
projectRef,
connectionString,
sqlOrigin: 'studio',
queryName: 'entity-search',
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 EntitySearchTrigger = EntitySearchData['triggers'][number]
export type EntitySearchFunction = EntitySearchData['functions'][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,
})