Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Joshenlim/fe 4712 cmd k support searching for database tables (#52205)

Joshen Lim7d63d764fc9a
diff --git a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx
index 73865eb4e1b..5370e7579bd 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.tsx
@@ -14,6 +14,7 @@ import { useApiKeysCommands } from './ApiKeys'
import { useApiUrlCommand } from './ApiUrl'
import { useContextSearchCommands } from './ContextSearchCommands'
import { useCreateCommands } from './CreateCommands'
+import { useDatabaseEntitySearchCommands } from './DatabaseEntitySearchCommands'
import { useFeaturePreviewCommands } from './FeaturePreviews'
import { orderCommandSectionsByPriority } from './ordering'
import { useConfigureOrganizationCommand, useProjectSwitchCommand } from './OrgProjectSwitcher'
@@ -38,7 +39,7 @@ export function CommandMenuInnerContent() {
)
}
-export default function StudioCommandMenu() {
+export function StudioCommandMenu() {
useCreateCommands()
useApiKeysCommands()
useApiUrlCommand()
@@ -60,6 +61,7 @@ export default function StudioCommandMenu() {
useChangelogCommand({ enabled: IS_PLATFORM })
useThemeSwitcherCommands()
useContextSearchCommands()
+ useDatabaseEntitySearchCommands()
useFeaturePreviewCommands()
return (
diff --git a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts
index 832332f31c7..169ac5da457 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts
+++ b/apps/studio/components/interfaces/App/CommandMenu/CommandMenu.utils.ts
@@ -6,6 +6,7 @@ export const COMMAND_MENU_SECTIONS = {
TABLE: 'Table Editor',
SQL: 'SQL Editor',
DATABASE: 'Database',
+ DATABASE_TABLES: 'Tables',
INTEGRATIONS: 'Integrations',
SHORTCUTS: 'Shortcuts',
} as const
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ContextSearchResults.shared.tsx b/apps/studio/components/interfaces/App/CommandMenu/ContextSearchResults.shared.tsx
index 4177044763e..003ec376b21 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/ContextSearchResults.shared.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/ContextSearchResults.shared.tsx
@@ -98,7 +98,7 @@ export function ResultsList({
<div className="flex flex-col min-w-0 text-foreground-light">
<TextHighlighter>{command.name}</TextHighlighter>
{command.value && command.value !== command.name && (
- <p className="text-xs text-foreground-lighter/70 truncate mt-0.5">
+ <p className="text-xs text-foreground-lighter truncate">
{command.value.replace(command.name, '').trim()}
</p>
)}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearch.utils.ts b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearch.utils.ts
new file mode 100644
index 00000000000..755bffcb6aa
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearch.utils.ts
@@ -0,0 +1,54 @@
+import { SEARCH_ENTITIES_MAX_QUERY_LENGTH } from '@supabase/pg-meta'
+
+import type { EntitySearchTable } 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)
+}
+
+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)}`
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.test.tsx b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.test.tsx
new file mode 100644
index 00000000000..f8b9dc42b75
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.test.tsx
@@ -0,0 +1,194 @@
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { HttpResponse } from 'msw'
+import { useEffect, useState } from 'react'
+import {
+ CommandHeader,
+ CommandMenuInput,
+ CommandMenuList,
+ CommandWrapper,
+ useCommands,
+ useSetCommandMenuOpen,
+ useSetQuery,
+} from 'ui-patterns/CommandMenu'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { useDatabaseEntitySearchCommands } from './DatabaseEntitySearchCommands'
+import type { EntitySearchData } from '@/data/database/entity-search-query'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+const { mockUseSelectedProjectQuery } = vi.hoisted(() => ({
+ mockUseSelectedProjectQuery: vi.fn(),
+}))
+
+vi.mock('@/hooks/misc/useSelectedProject', () => ({
+ useSelectedProjectQuery: mockUseSelectedProjectQuery,
+}))
+
+const SEARCH_RESULT: EntitySearchData = {
+ tables: [
+ { id: 101, schema: 'public', name: 'blog_posts', rls_enabled: true, policy_count: 4 },
+ { id: 102, schema: 'blog', name: 'blog_posts_archive', rls_enabled: false, policy_count: 1 },
+ ],
+}
+
+/** Renders the registered command sections as a plain list, driven by a text input. */
+const CommandMenuHarness = () => {
+ useDatabaseEntitySearchCommands()
+ const setQuery = useSetQuery()
+ const setOpen = useSetCommandMenuOpen()
+ const sections = useCommands()
+ const [value, setValue] = useState('')
+
+ useEffect(() => setOpen(true), [setOpen])
+
+ return (
+ <>
+ <input
+ aria-label="Search"
+ value={value}
+ onChange={(event) => {
+ setValue(event.target.value)
+ setQuery(event.target.value)
+ }}
+ />
+ {sections.map((section) => (
+ <section key={section.id} aria-label={section.name}>
+ {section.commands.map((command) => (
+ <div key={command.id}>
+ <span>{command.name}</span>
+ {command.badge?.()}
+ {'route' in command && <span>{command.route}</span>}
+ </div>
+ ))}
+ </section>
+ ))}
+ </>
+ )
+}
+
+describe('useDatabaseEntitySearchCommands', () => {
+ let searchRequests: string[]
+
+ beforeEach(() => {
+ searchRequests = []
+ mockUseSelectedProjectQuery.mockReturnValue({
+ data: { id: 1, ref: 'default', name: 'default', connectionString: 'encrypted' },
+ })
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: async ({ request }) => {
+ const { query } = (await request.json()) as { query: string }
+ searchRequests.push(query)
+ return HttpResponse.json([SEARCH_RESULT])
+ },
+ })
+ })
+
+ it('lists matching tables with their policy count and RLS status', async () => {
+ customRender(<CommandMenuHarness />)
+
+ await userEvent.type(screen.getByRole('textbox', { name: 'Search' }), 'blog_posts')
+
+ const section = await screen.findByRole('region', { name: 'Tables' })
+ expect(section).toHaveTextContent('public.blog_posts')
+ expect(section).toHaveTextContent('4 policies • RLS enabled')
+ expect(section).toHaveTextContent('blog.blog_posts_archive')
+ expect(section).toHaveTextContent('1 policy • RLS disabled')
+ expect(section).toHaveTextContent('/project/default/editor/101?schema=public')
+ })
+
+ it('debounces typing into a single database query', async () => {
+ customRender(<CommandMenuHarness />)
+
+ await userEvent.type(screen.getByRole('textbox', { name: 'Search' }), 'blog_posts')
+
+ await screen.findByRole('region', { name: 'Tables' })
+ expect(searchRequests).toHaveLength(1)
+ })
+
+ it('does not query the database for short searches', async () => {
+ customRender(<CommandMenuHarness />)
+
+ await userEvent.type(screen.getByRole('textbox', { name: 'Search' }), 'bl')
+
+ // Wait past the debounce window before asserting nothing was sent
+ await new Promise((resolve) => setTimeout(resolve, 500))
+ expect(searchRequests).toHaveLength(0)
+ expect(screen.queryByRole('region', { name: 'Tables' })).not.toBeInTheDocument()
+ })
+
+ it('does not show results from a previous project while searching another', async () => {
+ let project = { id: 1, ref: 'default', name: 'default', connectionString: 'encrypted' }
+ mockUseSelectedProjectQuery.mockImplementation(() => ({ data: project }))
+ let resolveSecondSearch: (() => void) | undefined
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: async ({ params }) => {
+ // Hold the second project's search in flight until the test releases it
+ if (params.ref === 'other') {
+ await new Promise<void>((resolve) => (resolveSecondSearch = resolve))
+ }
+ return HttpResponse.json([SEARCH_RESULT])
+ },
+ })
+
+ const { rerender } = customRender(<CommandMenuHarness />)
+ const input = screen.getByRole('textbox', { name: 'Search' })
+ await userEvent.type(input, 'blog')
+ await screen.findByRole('region', { name: 'Tables' })
+
+ project = { id: 2, ref: 'other', name: 'other', connectionString: 'encrypted' }
+ rerender(<CommandMenuHarness />)
+ await userEvent.type(input, '_posts')
+
+ await waitFor(() => expect(resolveSecondSearch).toBeDefined())
+ expect(screen.queryByRole('region', { name: 'Tables' })).not.toBeInTheDocument()
+
+ resolveSecondSearch?.()
+ const section = await screen.findByRole('region', { name: 'Tables' })
+ expect(section).toHaveTextContent('/project/other/editor/101?schema=public')
+ })
+})
+
+/** Renders the real command menu list, to check how results interact with its empty state. */
+const CommandMenuListHarness = () => {
+ useDatabaseEntitySearchCommands()
+ const setOpen = useSetCommandMenuOpen()
+
+ useEffect(() => setOpen(true), [setOpen])
+
+ return (
+ <CommandWrapper>
+ <CommandHeader>
+ <CommandMenuInput />
+ </CommandHeader>
+ <CommandMenuList />
+ </CommandWrapper>
+ )
+}
+
+describe('useDatabaseEntitySearchCommands in the command menu list', () => {
+ beforeEach(() => {
+ mockUseSelectedProjectQuery.mockReturnValue({
+ data: { id: 1, ref: 'default', name: 'default', connectionString: 'encrypted' },
+ })
+ })
+
+ it('hides the empty state once table results arrive', async () => {
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: () => HttpResponse.json([SEARCH_RESULT]),
+ })
+ customRender(<CommandMenuListHarness />)
+
+ await userEvent.type(screen.getByRole('combobox'), 'blog_posts')
+
+ expect(await screen.findByText('4 policies • RLS enabled')).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByText('No results found.')).not.toBeInTheDocument())
+ })
+})
diff --git a/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.tsx b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.tsx
new file mode 100644
index 00000000000..a7e6d299c86
--- /dev/null
+++ b/apps/studio/components/interfaces/App/CommandMenu/DatabaseEntitySearchCommands.tsx
@@ -0,0 +1,85 @@
+import { useQuery } from '@tanstack/react-query'
+import { useDebounce } from '@uidotdev/usehooks'
+import { DatabaseIcon } from 'lucide-react'
+import type { ICommand } from 'ui-patterns/CommandMenu'
+import {
+ useCommandMenuOpen,
+ useQuery as useCommandMenuQuery,
+ useRegisterCommands,
+} from 'ui-patterns/CommandMenu'
+
+import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
+import {
+ ENTITY_SEARCH_DEBOUNCE_MS,
+ formatTableSearchDetails,
+ getEntitySearchQuery,
+ getTableEditorRoute,
+ matchesEntitySearch,
+} from './DatabaseEntitySearch.utils'
+import { orderCommandSectionsByPriority } from './ordering'
+import { entitySearchQueryOptions } from '@/data/database/entity-search-query'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+
+/**
+ * Searches the project's database entities by name as the user types in the
+ * command menu, and registers matches as their own section. Filtering happens
+ * in the database (see getSearchEntitiesSql), so results are force-mounted to
+ * stop cmdk from filtering them a second time.
+ */
+export function useDatabaseEntitySearchCommands() {
+ const { data: project } = useSelectedProjectQuery()
+ const isOpen = useCommandMenuOpen()
+ const commandMenuQuery = useCommandMenuQuery()
+ const debouncedQuery = useDebounce(commandMenuQuery, ENTITY_SEARCH_DEBOUNCE_MS)
+ const currentSearch = getEntitySearchQuery(commandMenuQuery)
+ const debouncedSearch = getEntitySearchQuery(debouncedQuery)
+
+ const { data, isPlaceholderData } = useQuery(
+ entitySearchQueryOptions(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ query: debouncedSearch.query,
+ },
+ { enabled: isOpen && debouncedSearch.isSearchable }
+ )
+ )
+
+ // Results lag behind the input (debounce, request in flight, placeholder data
+ // from the previous search). Until they catch up, only keep the ones that
+ // still match what's typed, so e.g. `blog_posts` results never show for
+ // `colors`, while refining `blog` to `blog_p` narrows smoothly.
+ const canShowResults = isOpen && currentSearch.isSearchable
+ const isStale = isPlaceholderData || debouncedSearch.query !== currentSearch.query
+ const results = data?.tables ?? []
+ const visibleResults = isStale
+ ? results.filter((table) => matchesEntitySearch(table, currentSearch.query))
+ : results
+ const tables = canShowResults ? visibleResults : []
+ const projectRef = project?.ref ?? '_'
+
+ const tableCommands: ICommand[] = tables.map((table) => {
+ const displayName = `${table.schema}.${table.name}`
+ return {
+ id: `entity-search-table-${table.id}`,
+ name: displayName,
+ value: `entity-search-table-${table.id} ${displayName}`,
+ forceMount: true,
+ icon: () => <DatabaseIcon />,
+ badge: () => (
+ <span className="text-xs text-foreground-lighter truncate pl-4 shrink-0">
+ {formatTableSearchDetails(table)}
+ </span>
+ ),
+ route: getTableEditorRoute(projectRef, table),
+ }
+ })
+
+ useRegisterCommands(COMMAND_MENU_SECTIONS.DATABASE_TABLES, tableCommands, {
+ deps: [tables, projectRef],
+ enabled: tableCommands.length > 0,
+ forceMountSection: true,
+ orderSection: orderCommandSectionsByPriority,
+ sectionMeta: { priority: 2 },
+ })
+}
diff --git a/apps/studio/components/interfaces/App/CommandMenu/TableSearchResults.tsx b/apps/studio/components/interfaces/App/CommandMenu/TableSearchResults.tsx
index 6e9ad4a358a..e8c31b62ac1 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/TableSearchResults.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/TableSearchResults.tsx
@@ -99,19 +99,20 @@ export function TableSearchResults({ debouncedFilterString }: TableSearchResults
<EmptyState icon={DatabaseIcon} label="Database Tables" query={debouncedFilterString} />
) : (
<>
- <ResultsList
- results={tableResults}
- icon={DatabaseIcon}
- getRoute={(result) => {
- const table = tables?.find((t) => String(t.id) === result.id)
- if (!table || !projectRef) return `/project/${projectRef}/editor` as `/${string}`
+ <div className="h-full pb-9">
+ <ResultsList
+ results={tableResults}
+ icon={DatabaseIcon}
+ getRoute={(result) => {
+ const table = tables?.find((t) => String(t.id) === result.id)
+ if (!table || !projectRef) return `/project/${projectRef}/editor` as `/${string}`
- const schemaParam = table.schema ? `?schema=${table.schema}` : ''
- return `/project/${projectRef}/editor/${table.id}${schemaParam}` as `/${string}`
- }}
- infiniteLoadingObserverRef={sentinelRef}
- className="pb-9"
- />
+ const schemaParam = table.schema ? `?schema=${table.schema}` : ''
+ return `/project/${projectRef}/editor/${table.id}${schemaParam}` as `/${string}`
+ }}
+ infiniteLoadingObserverRef={sentinelRef}
+ />
+ </div>
<div className="absolute bottom-0 left-0 right-0 flex items-center justify-between min-h-9 h-9 px-4 border-t bg-surface-200 text-xs text-foreground-light z-10">
<div className="flex items-center gap-x-2">
{isLoadingTables ? (
diff --git a/apps/studio/components/interfaces/App/CommandMenu/index.tsx b/apps/studio/components/interfaces/App/CommandMenu/index.tsx
index 17dccfcb7b3..b0f5f45f2d7 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/index.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/index.tsx
@@ -1,7 +1,12 @@
import dynamic from 'next/dynamic'
import { useCommandMenuInitiated } from 'ui-patterns/CommandMenu'
-const LazyCommandMenu = dynamic(() => import('./CommandMenu'), { ssr: false })
+const LazyCommandMenu = dynamic(
+ () => import('./CommandMenu').then((mod) => mod.StudioCommandMenu),
+ {
+ ssr: false,
+ }
+)
export const StudioCommandMenu = () => {
const isInitiated = useCommandMenuInitiated()
diff --git a/apps/studio/data/database/entity-search-query.ts b/apps/studio/data/database/entity-search-query.ts
new file mode 100644
index 00000000000..1515e4c71f1
--- /dev/null
+++ b/apps/studio/data/database/entity-search-query.ts
@@ -0,0 +1,69 @@
+import { getSearchEntitiesSql } from '@supabase/pg-meta'
+import { queryOptions } from '@tanstack/react-query'
+import { z } from 'zod'
+
+import { databaseKeys } from './keys'
+import { executeSql } from '@/data/sql/execute-sql-mutation'
+import type { ResponseError } from '@/types'
+
+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(),
+ })
+ ),
+})
+
+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'],
+ },
+ signal
+ )
+
+ return entitySearchResultSchema.parse(result[0])
+}
+
+export type EntitySearchData = Awaited<ReturnType<typeof getEntitySearch>>
+export type EntitySearchTable = EntitySearchData['tables'][number]
+export type EntitySearchError = ResponseError
+
+export const entitySearchQueryOptions = (
+ { projectRef, connectionString, query }: EntitySearchVariables,
+ { enabled = true }: { enabled?: boolean } = {}
+) =>
+ queryOptions({
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps -- connection string doesn't change the result of the query
+ 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,
+ })
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index 7d1e515f2f4..59296c6c16a 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -3,6 +3,8 @@ import { sqlKeys } from '@/data/sql/keys'
export const databaseKeys = {
schemas: (projectRef: string | undefined) => ['projects', projectRef, 'schemas'] as const,
keywords: (projectRef: string | undefined) => ['projects', projectRef, 'keywords'] as const,
+ entitySearch: (projectRef: string | undefined, query: string) =>
+ ['projects', projectRef, 'entity-search', query] as const,
migrations: (projectRef: string | undefined) => ['projects', projectRef, 'migrations'] as const,
tableColumns: (
projectRef: string | undefined,
diff --git a/packages/pg-meta/src/helpers.ts b/packages/pg-meta/src/helpers.ts
index 4ef7b378b40..a20c671da92 100644
--- a/packages/pg-meta/src/helpers.ts
+++ b/packages/pg-meta/src/helpers.ts
@@ -36,3 +36,8 @@ export function filterByList(include?: string[], exclude?: string[], defaultExcl
export function exceptionIdentifierNotFound(entityName: string, whereClause: string) {
return safeSql`raise exception 'Cannot find ${ident(entityName)} with: %', ${literal(whereClause)};`
}
+
+// Escape LIKE/ILIKE wildcards so user input is matched literally. ILIKE's
+// default escape character is `\`, so we escape `\`, `%`, and `_` and let the
+// pattern carry its own surrounding `%`s as wildcards.
+export const escapeIlikeLiteral = (value: string) => value.replace(/([\\%_])/g, '\\$1')
diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.ts
index f323bdcceb0..848e2950bdc 100644
--- a/packages/pg-meta/src/sql/studio/database/index.ts
+++ b/packages/pg-meta/src/sql/studio/database/index.ts
@@ -12,6 +12,7 @@ export * from './misc'
export * from './privileges'
export * from './queues'
export * from './rows'
+export * from './search-entities'
export * from './table-definition'
export * from './tables-paginated'
export * from './triggers'
diff --git a/packages/pg-meta/src/sql/studio/database/search-entities.ts b/packages/pg-meta/src/sql/studio/database/search-entities.ts
new file mode 100644
index 00000000000..7cb3fc9abd9
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/database/search-entities.ts
@@ -0,0 +1,139 @@
+import { DEFAULT_SYSTEM_SCHEMAS } from '../../../constants'
+import { escapeIlikeLiteral } from '../../../helpers'
+import { joinSqlFragments, literal, safeSql, type SafeSqlFragment } from '../../../pg-format'
+
+// Postgres identifiers are capped at 63 bytes, so a longer search string can
+// never match a name. Callers should skip the request entirely in that case.
+export const SEARCH_ENTITIES_MAX_QUERY_LENGTH = 63
+
+// How many name matches are considered before the (comparatively expensive)
+// privilege checks run. Kept well above `limit` so that the odd relation the
+// role can't access doesn't starve the result set.
+const CANDIDATE_LIMIT = 50
+
+export type SearchEntitiesTable = {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ policy_count: number
+}
+
+export type SearchEntitiesResult = {
+ tables: SearchEntitiesTable[]
+}
+
+/**
+ * Name search across database entities, for the command menu.
+ *
+ * This runs on (debounced) keystrokes against the user's live catalog, so it is
+ * built to stay cheap on very large catalogs:
+ * - The substring match is the only work done per pg_class row. A leading-
+ * wildcard ILIKE can't use pg_class_relname_nsp_index, so one filtered seq
+ * scan of pg_class is structurally unavoidable (see the plan-guard test).
+ * - Candidates are capped in a MATERIALIZED CTE so privilege checks and policy
+ * counts only ever run on a bounded set of rows, never the whole catalog.
+ * - Policy counts are index probes on pg_policy (polrelid, polname).
+ * - No size functions, column/constraint enrichment, or definition rendering.
+ *
+ * A query containing a dot is also treated as `schema.name`: the schema must
+ * start with the part before the first dot and the name must contain the part
+ * after it, so `public.colors` and `pub.colors` both find `public.colors`. The
+ * full query is still matched against names too, since names may contain dots.
+ *
+ * Returns a single row with one JSON array per entity type, so other entity
+ * types (policies, functions, triggers) can be added without changing the
+ * response shape.
+ */
+export const getSearchEntitiesSql = ({
+ query,
+ limit = 6,
+}: {
+ query: string
+ limit?: number
+}): SafeSqlFragment => {
+ const dotIndex = query.indexOf('.')
+ const schemaPart = dotIndex === -1 ? undefined : query.slice(0, dotIndex)
+ const namePart = dotIndex === -1 ? query : query.slice(dotIndex + 1)
+
+ const nameFilter = safeSql`c.relname ilike ${literal(`%${escapeIlikeLiteral(query)}%`)}`
+ const matchFilter =
+ schemaPart === undefined
+ ? nameFilter
+ : safeSql`(
+ ${nameFilter}
+ or (
+ nc.nspname ilike ${literal(`${escapeIlikeLiteral(schemaPart)}%`)}
+ and c.relname ilike ${literal(`%${escapeIlikeLiteral(namePart)}%`)}
+ )
+ )`
+
+ // Rank on the name part, so `public.colors` ranks the `colors` table first
+ const prefixPattern = literal(`${escapeIlikeLiteral(namePart)}%`)
+ const exactName = literal(namePart.toLowerCase())
+ const excludedSchemas = joinSqlFragments(
+ DEFAULT_SYSTEM_SCHEMAS.map((schema) => literal(schema)),
+ ', '
+ )
+
+ return safeSql`
+ with table_candidates as materialized (
+ select
+ c.oid,
+ c.relname,
+ c.relowner,
+ c.relrowsecurity,
+ nc.nspname,
+ case
+ when lower(c.relname) = ${exactName} then 0
+ when c.relname ilike ${prefixPattern} then 1
+ else 2
+ end as rank
+ from pg_class c
+ join pg_namespace nc on nc.oid = c.relnamespace
+ where c.relkind in ('r', 'p')
+ and not c.relispartition
+ and nc.nspname not in (${excludedSchemas})
+ and not pg_is_other_temp_schema(nc.oid)
+ and ${matchFilter}
+ order by rank, length(c.relname), c.relname
+ limit ${literal(CANDIDATE_LIMIT)}
+ ),
+ matched_tables as (
+ select
+ tc.oid::int8 as id,
+ tc.nspname as schema,
+ tc.relname as name,
+ tc.relrowsecurity as rls_enabled,
+ (select count(*) from pg_policy pol where pol.polrelid = tc.oid)::int as policy_count,
+ tc.rank
+ from table_candidates tc
+ where
+ pg_has_role(tc.relowner, 'USAGE')
+ or has_table_privilege(
+ tc.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ )
+ or has_any_column_privilege(tc.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ order by tc.rank, length(tc.relname), tc.relname
+ limit ${literal(limit)}
+ )
+ select
+ coalesce(
+ (
+ select jsonb_agg(
+ jsonb_build_object(
+ 'id', t.id,
+ 'schema', t.schema,
+ 'name', t.name,
+ 'rls_enabled', t.rls_enabled,
+ 'policy_count', t.policy_count
+ )
+ order by t.rank, length(t.name), t.name
+ )
+ from matched_tables t
+ ),
+ '[]'::jsonb
+ ) as tables
+ `
+}
diff --git a/packages/pg-meta/src/sql/studio/database/tables-paginated.ts b/packages/pg-meta/src/sql/studio/database/tables-paginated.ts
index 10e4974b167..55b0bcae9e1 100644
--- a/packages/pg-meta/src/sql/studio/database/tables-paginated.ts
+++ b/packages/pg-meta/src/sql/studio/database/tables-paginated.ts
@@ -1,5 +1,5 @@
import { DEFAULT_SYSTEM_SCHEMAS } from '../../../constants'
-import { coalesceRowsToArray, filterByList } from '../../../helpers'
+import { coalesceRowsToArray, escapeIlikeLiteral, filterByList } from '../../../helpers'
import { literal, safeSql, type SafeSqlFragment } from '../../../pg-format'
import { getColumnsSql } from '../../columns'
@@ -209,8 +209,3 @@ export const getTablesPaginatedSql = ({
order by tables.id
`
}
-
-// Escape LIKE/ILIKE wildcards so user input is matched literally. ILIKE's
-// default escape character is `\`, so we escape `\`, `%`, and `_` and let the
-// pattern carry its own surrounding `%`s as wildcards.
-const escapeIlikeLiteral = (value: string) => value.replace(/([\\%_])/g, '\\$1')
diff --git a/packages/pg-meta/test/db/stress-catalog.ts b/packages/pg-meta/test/db/stress-catalog.ts
index f3e62fe618f..0e37ce6ed88 100644
--- a/packages/pg-meta/test/db/stress-catalog.ts
+++ b/packages/pg-meta/test/db/stress-catalog.ts
@@ -32,7 +32,8 @@ export const STRESS_TABLE_COUNT = Number(
* has a composite FK to t_0, making t_0 a hub with many incoming FKs (the
* structurally unavoidable pg_constraint seq scan, since there is no index on
* pg_constraint.confrelid). Using composite FKs exercises ordinal column
- * pairing across the full stress catalog.
+ * pairing across the full stress catalog. Every other table also has RLS
+ * enabled with one policy, so pg_policy scales with the catalog.
*
* The catalog is built via a server-side procedure with batched commits every
* 100 tables -- a single transaction creating thousands of tables/indexes/
@@ -55,6 +56,13 @@ export async function buildStressCatalog(
case when i > 0 then format(', fk_id int, fk_tenant_id int, foreign key (fk_id, fk_tenant_id) references stress.t_%s(id, tenant_id)', i - 1) else '' end,
case when i > 0 and i % 10 = 0 then ', hub_id int, hub_tenant_id int, foreign key (hub_id, hub_tenant_id) references stress.t_0(id, tenant_id)' else '' end
);
+ -- Every other table gets RLS + a policy so pg_policy grows with the
+ -- catalog (as it does in real projects) and planners don't treat it
+ -- as an empty table.
+ if i % 2 = 0 then
+ execute format('alter table stress.t_%s enable row level security', i);
+ execute format('create policy p_%s on stress.t_%s for select using (true)', i, i);
+ end if;
if i % 100 = 99 then commit; end if;
end loop;
end $$;
diff --git a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts
index ddb4786bb4d..5cfc664a639 100644
--- a/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts
+++ b/packages/pg-meta/test/sql/studio/catalog-plan-guard.test.ts
@@ -6,6 +6,7 @@ import {
getEntityTypesSQL,
getForeignKeyConstraintsSql,
getIndexesSQL,
+ getSearchEntitiesSql,
getTableColumnsSql,
getTableConstraintsSql,
getTableDefinitionSql,
@@ -470,3 +471,31 @@ test('tables.retrieve: composite FKs stay ordinally paired at stress scale', asy
['fk_tenant_id', 'tenant_id'],
])
}, 60_000)
+
+// ── getSearchEntitiesSql (database/search-entities.ts) — command menu search ─
+// Runs on debounced keystrokes, so every case below must stay cheap at scale.
+// A substring (leading-wildcard) ILIKE cannot use pg_class_relname_nsp_index,
+// so one filtered seq scan of pg_class is structurally unavoidable. Everything
+// downstream (privilege checks, policy counts) is capped by the materialized
+// candidate CTE, so no other scaling catalog may be scanned.
+const SEARCH_ENTITIES_BUDGET = {
+ allowedSeqScans: {
+ pg_class: {
+ max: 1,
+ reason:
+ 'substring name search: a leading-wildcard ILIKE cannot use pg_class_relname_nsp_index, so one filtered pass of pg_class is unavoidable',
+ },
+ },
+ maxExecutionTimeMs: 500,
+}
+
+test('getSearchEntitiesSql: broad search (thousands of matches) stays within budget', async () => {
+ // `t_1` matches t_1, t_10..t_19, t_100..t_199, ... -- a large share of the catalog
+ const result = await explainAnalyze(db, getSearchEntitiesSql({ query: 't_1' }))
+ assertPlanWithinBudget(result, SEARCH_ENTITIES_BUDGET)
+}, 60_000)
+
+test('getSearchEntitiesSql: schema-qualified search stays within budget', async () => {
+ const result = await explainAnalyze(db, getSearchEntitiesSql({ query: 'stress.t_1' }))
+ assertPlanWithinBudget(result, SEARCH_ENTITIES_BUDGET)
+}, 60_000)
diff --git a/packages/pg-meta/test/sql/studio/search-entities.test.ts b/packages/pg-meta/test/sql/studio/search-entities.test.ts
new file mode 100644
index 00000000000..8fdf7d70344
--- /dev/null
+++ b/packages/pg-meta/test/sql/studio/search-entities.test.ts
@@ -0,0 +1,118 @@
+import { afterAll, expect, test } from 'vitest'
+
+import { getSearchEntitiesSql, type SearchEntitiesResult } from '../../../src'
+import { cleanupRoot, createTestDatabase } from '../../db/utils'
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+const withTestDatabase = (
+ name: string,
+ fn: (db: Awaited<ReturnType<typeof createTestDatabase>>) => Promise<void>
+) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+const search = async (db: Awaited<ReturnType<typeof createTestDatabase>>, query: string) => {
+ const [row] = await db.executeQuery<SearchEntitiesResult[]>(getSearchEntitiesSql({ query }))
+ return row.tables.map((t) => `${t.schema}.${t.name}`)
+}
+
+withTestDatabase('ranks exact, then prefix, then substring matches', async (db) => {
+ await db.executeQuery(`
+ create table public.old_blog_posts (id int);
+ create table public.blog_posts_archive (id int);
+ create table public.blog_posts (id int);
+ `)
+
+ expect(await search(db, 'blog_posts')).toEqual([
+ 'public.blog_posts',
+ 'public.blog_posts_archive',
+ 'public.old_blog_posts',
+ ])
+})
+
+withTestDatabase('treats LIKE wildcards in the query literally', async (db) => {
+ await db.executeQuery(`
+ create schema my_app;
+ create schema myxapp;
+ create table my_app.blog_posts (id int);
+ create table my_app.blogxposts (id int);
+ create table myxapp.blog_posts (id int);
+ `)
+
+ expect((await search(db, 'blog_posts')).sort()).toEqual([
+ 'my_app.blog_posts',
+ 'myxapp.blog_posts',
+ ])
+ expect(await search(db, 'my_app.blog_posts')).toEqual(['my_app.blog_posts'])
+ expect(await search(db, '%')).toEqual([])
+})
+
+withTestDatabase('matches schema-qualified searches', async (db) => {
+ await db.executeQuery(`
+ create schema blog;
+ create table blog.colors (id int);
+ create table public.colors (id int);
+ create table public.colors_archive (id int);
+ create table public."v1.palette" (id int);
+ `)
+
+ expect(await search(db, 'public.colors')).toEqual(['public.colors', 'public.colors_archive'])
+ // A partial schema name matches too
+ expect(await search(db, 'pub.colors')).toEqual(['public.colors', 'public.colors_archive'])
+ // Table names that themselves contain a dot are still found
+ expect(await search(db, 'v1.palette')).toEqual(['public.v1.palette'])
+})
+
+withTestDatabase('only returns tables, excluding partitions and system schemas', async (db) => {
+ await db.executeQuery(`
+ create table public.blog_posts (id int);
+ create view public.blog_view as select 1;
+ create materialized view public.blog_mat_view as select 1;
+ create table public.blog_events (id int, region text) partition by list (region);
+ create table public.blog_events_east partition of public.blog_events for values in ('east');
+ `)
+
+ expect((await search(db, 'blog')).sort()).toEqual(['public.blog_events', 'public.blog_posts'])
+ expect(await search(db, 'pg_class')).toEqual([])
+})
+
+withTestDatabase('returns RLS status and policy count', async (db) => {
+ await db.executeQuery(`
+ create table public.posts (id int);
+ alter table public.posts enable row level security;
+ create policy "read" on public.posts for select using (true);
+ create policy "write" on public.posts for insert with check (true);
+ create table public.posts_drafts (id int);
+ `)
+
+ const [row] = await db.executeQuery<SearchEntitiesResult[]>(
+ getSearchEntitiesSql({ query: 'posts' })
+ )
+
+ expect(row.tables).toEqual([
+ {
+ id: expect.any(Number),
+ schema: 'public',
+ name: 'posts',
+ rls_enabled: true,
+ policy_count: 2,
+ },
+ {
+ id: expect.any(Number),
+ schema: 'public',
+ name: 'posts_drafts',
+ rls_enabled: false,
+ policy_count: 0,
+ },
+ ])
+})
diff --git a/packages/ui-patterns/src/CommandMenu/internal/CommandMenuEmpty.tsx b/packages/ui-patterns/src/CommandMenu/internal/CommandMenuEmpty.tsx
index f0ce9f833e9..ab0d0bff2ac 100644
--- a/packages/ui-patterns/src/CommandMenu/internal/CommandMenuEmpty.tsx
+++ b/packages/ui-patterns/src/CommandMenu/internal/CommandMenuEmpty.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState, type PropsWithChildren, type RefObject } from 'react'
import { cn } from 'ui'
+import { useCommands } from '../api/hooks/commandsHooks'
import { useQuery } from '../api/hooks/queryHooks'
const CommandMenuEmpty = ({
@@ -21,12 +22,15 @@ const CommandMenuEmpty = ({
listRef: RefObject<HTMLDivElement | undefined>
}>) => {
const query = useQuery()
+ // Re-check when sections are registered or removed after the query changed,
+ // e.g. search results that load asynchronously
+ const commandSections = useCommands()
const [render, setRender] = useState(false)
useEffect(() => {
if (!query) return setRender(false)
setRender(!listRef?.current?.querySelector('[cmdk-item]'))
- }, [query])
+ }, [query, commandSections])
return (
render && (