Skip to content

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

feat(studio): include enums and RLS policies in Schema Visualizer Cop… (#46189)

seungjae77953e7a1fe1
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
index 1c6ac29bba8..2dcbf39311b 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
@@ -47,8 +47,10 @@ import { SchemaGraphContextProvider, SchemaGraphContextType } from './SchemaGrap
import { SchemaGraphLegend } from './SchemaGraphLegend'
import { EdgeData, TableNodeData } from './Schemas.constants'
import {
+ getEnumsAsMarkdown,
getGraphDataFromTables,
getLayoutedElementsViaDagre,
+ getPoliciesAsMarkdown,
getSchemaAsMarkdown,
} from './Schemas.utils'
import { TableNode } from './SchemaTableNode'
@@ -57,7 +59,9 @@ import { AlertError } from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { SchemaSelector } from '@/components/ui/SchemaSelector'
import { Shortcut } from '@/components/ui/Shortcut'
+import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
import { useSchemasQuery } from '@/data/database/schemas-query'
+import { useEnumeratedTypesQuery } from '@/data/enumerated-types/enumerated-types-query'
import { useInfiniteTablesQuery } from '@/data/tables/tables-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useLocalStorage } from '@/hooks/misc/useLocalStorage'
@@ -137,6 +141,20 @@ export const SchemaGraph = () => {
const tables = useMemo(() => tablesData?.pages.flat() ?? [], [tablesData])
const hasNoTables = isSuccessTables && isSuccessSchemas && tables.length === 0 && !hasNextPage
+ const { data: enumeratedTypes = [], isPending: isLoadingEnumeratedTypes } =
+ useEnumeratedTypesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { data: policies = [], isPending: isLoadingPolicies } = useDatabasePoliciesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schemas: [selectedSchema],
+ })
+
+ const isMarkdownDataLoading = isLoadingEnumeratedTypes || isLoadingPolicies
+
const schema = (schemas ?? []).find((s) => s.name === selectedSchema)
const [, setStoredPositions] = useLocalStorage(
LOCAL_STORAGE_KEYS.SCHEMA_VISUALIZER_POSITIONS(ref as string, schema?.id ?? 0),
@@ -224,11 +242,37 @@ export const SchemaGraph = () => {
}
const copyAsMarkdown = () => {
+ if (isMarkdownDataLoading) return
+
const tableNodes = reactFlowInstance
.getNodes()
.filter((node) => node.type === 'table')
.map((node) => node.data as TableNodeData)
- copyToClipboard(getSchemaAsMarkdown(selectedSchema, tableNodes))
+
+ let markdown = getSchemaAsMarkdown(selectedSchema, tableNodes)
+
+ const enumsMarkdown = getEnumsAsMarkdown(
+ selectedSchema,
+ enumeratedTypes.map((e) => ({ name: e.name, schema: e.schema, enums: e.enums }))
+ )
+ if (enumsMarkdown) markdown += enumsMarkdown
+
+ const policiesMarkdown = getPoliciesAsMarkdown(
+ selectedSchema,
+ policies.map((p) => ({
+ name: p.name,
+ schema: p.schema,
+ table: p.table,
+ command: p.command,
+ roles: p.roles,
+ action: p.action,
+ definition: p.definition ? String(p.definition) : null,
+ check: p.check ? String(p.check) : null,
+ }))
+ )
+ if (policiesMarkdown) markdown += policiesMarkdown
+
+ copyToClipboard(markdown)
setCopied(true)
toast.success('Successfully copied as Markdown')
}
@@ -246,7 +290,7 @@ export const SchemaGraph = () => {
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_COPY_SQL, copyAsSQL, { enabled: shortcutsEnabled })
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_COPY_MARKDOWN, copyAsMarkdown, {
- enabled: shortcutsEnabled,
+ enabled: shortcutsEnabled && !isMarkdownDataLoading,
})
useShortcut(SHORTCUT_IDS.SCHEMA_VISUALIZER_DOWNLOAD_PNG, () => downloadImage('png'), {
enabled: shortcutsEnabled,
@@ -423,12 +467,17 @@ export const SchemaGraph = () => {
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem
className="flex items-center space-x-2 whitespace-nowrap"
+ disabled={isMarkdownDataLoading}
onClick={(e) => {
e.stopPropagation()
copyAsMarkdown()
}}
>
- <Copy size={12} />
+ {isMarkdownDataLoading ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ <Copy size={12} />
+ )}
<span>Copy as Markdown</span>
</DropdownMenuItem>
<DropdownMenuItem
diff --git a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts
index 1a6146fdeb9..e09c66342fc 100644
--- a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts
+++ b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, test } from 'vitest'
-import { getSchemaAsMarkdown, getTableDefinitionAsMarkdown } from './Schemas.utils'
+import {
+ getEnumsAsMarkdown,
+ getPoliciesAsMarkdown,
+ getSchemaAsMarkdown,
+ getTableDefinitionAsMarkdown,
+} from './Schemas.utils'
describe('Schemas.utils', () => {
test('getSchemaAsMarkdown returns properly formatted markdown', () => {
@@ -173,4 +178,79 @@ An excellent description
| \`user_id\` | \`uuid\` | Nullable |
`)
})
+
+ test('getEnumsAsMarkdown returns formatted enum section', () => {
+ const enums = [
+ { name: 'order_status', schema: 'public', enums: ['pending', 'processing', 'shipped'] },
+ { name: 'role_type', schema: 'public', enums: ['admin', 'user'] },
+ { name: 'other_enum', schema: 'auth', enums: ['a', 'b'] },
+ ]
+ const result = getEnumsAsMarkdown('public', enums)
+ expect(result).toBe(`## Custom Types / Enums
+
+### \`order_status\`
+
+\`pending\` | \`processing\` | \`shipped\`
+
+### \`role_type\`
+
+\`admin\` | \`user\`
+
+`)
+ })
+
+ test('getEnumsAsMarkdown returns empty string when no enums match schema', () => {
+ const enums = [{ name: 'other_enum', schema: 'auth', enums: ['a', 'b'] }]
+ const result = getEnumsAsMarkdown('public', enums)
+ expect(result).toBe('')
+ })
+
+ test('getPoliciesAsMarkdown returns formatted policy table grouped by table', () => {
+ const policies = [
+ {
+ name: 'users_select',
+ schema: 'public',
+ table: 'users',
+ command: 'SELECT',
+ roles: ['authenticated'],
+ action: 'PERMISSIVE',
+ definition: 'auth.uid() = id',
+ check: null,
+ },
+ {
+ name: 'users_insert',
+ schema: 'public',
+ table: 'users',
+ command: 'INSERT',
+ roles: ['authenticated'],
+ action: 'PERMISSIVE',
+ definition: null,
+ check: 'auth.uid() = id',
+ },
+ ]
+ const result = getPoliciesAsMarkdown('public', policies)
+ expect(result).toContain('## RLS Policies')
+ expect(result).toContain('### `users`')
+ expect(result).toContain('`users_select`')
+ expect(result).toContain('`users_insert`')
+ expect(result).toContain('`auth.uid() = id`')
+ expect(result).toContain('—')
+ })
+
+ test('getPoliciesAsMarkdown returns empty string when no policies match schema', () => {
+ const policies = [
+ {
+ name: 'test',
+ schema: 'auth',
+ table: 'users',
+ command: 'SELECT',
+ roles: ['anon'],
+ action: 'PERMISSIVE',
+ definition: 'true',
+ check: null,
+ },
+ ]
+ const result = getPoliciesAsMarkdown('public', policies)
+ expect(result).toBe('')
+ })
})
diff --git a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
index 9b2d24d73a6..c328f6c91fb 100644
--- a/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
+++ b/apps/studio/components/interfaces/Database/Schemas/Schemas.utils.ts
@@ -281,3 +281,64 @@ const escapeForMarkdown = (str: string) => {
.replace(/\n/g, ' ')
)
}
+
+// ── Enum / Custom Type markdown ────────────────────────────
+
+export type EnumForMarkdown = {
+ name: string
+ schema: string
+ enums: string[]
+}
+
+export const getEnumsAsMarkdown = (schema: string, enums: EnumForMarkdown[]): string => {
+ const filtered = enums.filter((e) => e.schema === schema && e.enums.length > 0)
+ if (filtered.length === 0) return ''
+
+ let md = `## Custom Types / Enums\n\n`
+ for (const enumType of filtered) {
+ const values = enumType.enums.map((v) => `\`${escapeForMarkdown(v)}\``).join(' | ')
+ md += `### \`${escapeForMarkdown(enumType.name)}\`\n\n${values}\n\n`
+ }
+ return md
+}
+
+// ── RLS Policy markdown ────────────────────────────────────
+
+export type PolicyForMarkdown = {
+ name: string
+ schema: string
+ table: string
+ command: string
+ roles: string[]
+ action: string
+ definition: string | null
+ check: string | null
+}
+
+export const getPoliciesAsMarkdown = (schema: string, policies: PolicyForMarkdown[]): string => {
+ const filtered = policies.filter((p) => p.schema === schema)
+ if (filtered.length === 0) return ''
+
+ // Group by table
+ const byTable = new Map<string, PolicyForMarkdown[]>()
+ for (const policy of filtered) {
+ const existing = byTable.get(policy.table) ?? []
+ existing.push(policy)
+ byTable.set(policy.table, existing)
+ }
+
+ let md = `## RLS Policies\n\n`
+ for (const [table, tablePolicies] of byTable) {
+ md += `### \`${escapeForMarkdown(table)}\`\n\n`
+ md += `| Policy | Command | Roles | Action | USING | WITH CHECK |\n`
+ md += `|--------|---------|-------|--------|-------|------------|\n`
+ for (const p of tablePolicies) {
+ const roles = p.roles.map((r) => escapeForMarkdown(r)).join(', ')
+ const using = p.definition ? `\`${escapeForMarkdown(p.definition)}\`` : '—'
+ const check = p.check ? `\`${escapeForMarkdown(p.check)}\`` : '—'
+ md += `| \`${escapeForMarkdown(p.name)}\` | ${p.command} | ${roles} | ${p.action} | ${using} | ${check} |\n`
+ }
+ md += `\n`
+ }
+ return md
+}