mirror of
https://github.com/supabase/supabase.git
synced 2026-12-05 07:59:03 +00:00
## Problem The schema visualizer (`/project/[ref]/database/schemas`) sends no telemetry. We can't tell whether people use it to explore a schema or to export it, which export format they pick, or whether they edit tables from the graph. ## Solution Adds PostHog events for the visualizer's main actions: changing the schema, selecting a Find table result, copying (schema or table as SQL/Markdown, table or column name), downloading the graph as PNG or SVG, applying Auto layout, and choosing Edit table or Edit column from a node menu. Each event fires from the action's handler, so actions started from a keyboard shortcut count too. Properties are only fixed enums (`schemaType`, `content`, `format`, `action`); no schema, table, or column names are sent. Each tracked element also gets a `data-attr` for autocapture. View in Table Editor and the empty state's New table link get a `data-attr` only, because the pageview already records them. It also fixes an empty canvas after switching back to a schema that was already loaded. The graph stays mounted in that case and fitted the view only on first load, so the new schema's tables could sit off-screen until a reload. The view now fits whenever the schema on the canvas changes. Edits within the same schema still keep the current view. Studio's database pages keep the selected schema name in the `schema` URL param, and that name is chosen by the customer. Telemetry now redacts its value to `redacted` wherever it already redacts `keywords`: the event and pageview `page_url`, the query string, the referrer, first-touch data, and the URL properties posthog-js adds. This applies to every Studio event and pageview, not just this page. Params that only contain the word, such as `schemas` or `myschema`, are left alone. ## How to verify On the PR preview, open a project's Database > Schema Visualizer with PostHog debugging on (or watch the network requests to the telemetry endpoint), then: 1. Change the schema in the selector: one `database_schema_selector_updated` event with `schemaType` of `public`, `protected` (for example `auth`), or `custom`. 2. Open Find table and select a table: one `database_schema_visualizer_find_table_clicked` event. 3. Click Copy as SQL: one `database_schema_visualizer_copied` with `content: 'schema_sql'`. Copy as Markdown from the export menu sends `content: 'schema_markdown'`. 4. Download as PNG and as SVG: one `database_schema_visualizer_image_download_clicked` each, with `format` of `png` or `svg`. 5. Open Auto layout and click Apply: one `database_schema_visualizer_auto_layout_applied`. Cancel sends nothing. 6. From a table node menu, choose Copy name, Copy as SQL, and Copy as Markdown: `database_schema_visualizer_copied` with `content` of `table_name`, `table_sql`, and `table_markdown`. Column menu Copy name sends `column_name`. 7. From a table node menu choose Edit table, and from a column menu choose Edit column: `database_schema_visualizer_node_menu_clicked` with `action` of `edit_table` and `edit_column`. 8. No event carries a schema, table, or column name. 9. Switch the schema from public to auth, then back to public, with no reload: the public tables are shown and fitted on the canvas each time. Repeat auth → public → auth. 10. Edit a column from the graph and save: the view does not jump. 11. In the telemetry requests from steps 1 to 7 and in the pageview, `page_url` and `ph.search` show `schema=redacted`, never the schema name. The page itself still shows and switches the real schema. ## Checks Ran `pnpm turbo run typecheck --filter='...[origin/master]'`. Every package passed except studio, which ran out of memory beside a parallel lint run. `pnpm --filter studio run typecheck` alone then passed, and passed again after the view fix. `pnpm turbo run lint --filter='[origin/master]'` ran out of memory twice on studio's `lint:type-checks` (2 GB default heap). So I ran `eslint` and `eslint --config eslint.type-checks.config.cjs` on the changed Studio files with a larger heap: no errors, only pre-existing warnings. `vitest run components/interfaces/Database/Schemas/Schemas.utils.test.ts` passed. For the redaction, `vitest run` in `packages/common` (all 310 tests, including the new `schema` cases) and its `typecheck` passed; `common` has no lint script. `oxfmt --check` passes on all changed files. Event names and properties follow the repo's `telemetry-standards` skill. ## Checklist - [x] I have read the [contributing guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] The change is scoped to one feature - [x] Events are defined in `packages/common/telemetry-constants.ts` and added to the `TelemetryEvent` union ## Feedback for Tedd To ask Tedd for a change to this PR, reply in Tedd's session on [FE-5031](https://linear.app/supabase/issue/FE-5031/track-usage-on-the-schema-visualizer). Tedd doesn't read comments on this PR. --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
393 lines
16 KiB
TypeScript
393 lines
16 KiB
TypeScript
import { Handle, Node, NodeProps } from '@xyflow/react'
|
|
import { TableEditor } from 'icons'
|
|
import {
|
|
CopyIcon,
|
|
DiamondIcon,
|
|
EditIcon,
|
|
FingerprintIcon,
|
|
HashIcon,
|
|
InfoIcon,
|
|
KeyIcon,
|
|
MoreVerticalIcon,
|
|
Table2Icon,
|
|
} from 'lucide-react'
|
|
import { useRouter } from 'next/router'
|
|
import { memo } from 'react'
|
|
import { toast } from 'sonner'
|
|
import {
|
|
Button,
|
|
cn,
|
|
copyToClipboard,
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuTrigger,
|
|
Tooltip,
|
|
TooltipContent,
|
|
TooltipTrigger,
|
|
} from 'ui'
|
|
|
|
import { useSchemaGraphContext } from './SchemaGraphContext'
|
|
import { TableNodeData } from './Schemas.constants'
|
|
import { getTableDefinitionAsMarkdown } from './Schemas.utils'
|
|
import { buildTableEditorUrl } from '@/components/grid/SupabaseGrid.utils'
|
|
import { getTableDefinition } from '@/data/database/table-definition-query'
|
|
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
|
|
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
|
import { formatSql } from '@/lib/formatSql'
|
|
import { useTrack } from '@/lib/telemetry/track'
|
|
|
|
// ReactFlow is scaling everything by the factor of 2
|
|
export const TABLE_NODE_WIDTH = 320
|
|
export const TABLE_NODE_ROW_HEIGHT = 40
|
|
|
|
type TableNodeOwnProps = NodeProps<Node<TableNodeData>> & { placeholder?: boolean }
|
|
|
|
const TableNodeComponent = ({
|
|
id,
|
|
data,
|
|
targetPosition,
|
|
sourcePosition,
|
|
placeholder,
|
|
}: TableNodeOwnProps) => {
|
|
// Important styles is a nasty hack to use Handles (required for edges calculations), but do not show them in the UI.
|
|
// ref: https://github.com/wbkd/react-flow/discussions/2698
|
|
const hiddenNodeConnector = 'h-px! w-px! min-w-0! min-h-0! cursor-grab! border-0! opacity-0!'
|
|
const schemaGraphContext = useSchemaGraphContext()
|
|
const { data: project } = useSelectedProjectQuery()
|
|
const { can: canUpdateColumns } = useAsyncCheckPermissionsV2(
|
|
FGA_PERMISSIONS.PROJECT.DATABASE_WRITE
|
|
)
|
|
const router = useRouter()
|
|
const track = useTrack()
|
|
const itemHeight = 'h-[22px]'
|
|
|
|
const hasEdgesSelected =
|
|
schemaGraphContext.selectedEdge?.source === id || schemaGraphContext.selectedEdge?.target === id
|
|
|
|
return (
|
|
<article>
|
|
{data.isForeign ? (
|
|
<header
|
|
className={cn(
|
|
'text-[0.55rem] px-2 py-1 border-[0.5px] rounded-[4px] bg-alternative flex gap-1 items-center',
|
|
hasEdgesSelected ? 'outline outline-1 outline-primary-bright' : undefined
|
|
)}
|
|
>
|
|
{data.name}
|
|
{targetPosition && (
|
|
<Handle
|
|
type="target"
|
|
id={data.name}
|
|
position={targetPosition}
|
|
className={cn(hiddenNodeConnector)}
|
|
/>
|
|
)}
|
|
</header>
|
|
) : (
|
|
<div
|
|
className={cn(
|
|
'border-[0.5px] overflow-hidden rounded-[4px] shadow-xs',
|
|
hasEdgesSelected ? 'outline outline-1 outline-primary-bright' : undefined
|
|
)}
|
|
style={{ width: TABLE_NODE_WIDTH / 2 }}
|
|
>
|
|
<header
|
|
className={cn(
|
|
'text-[0.55rem] pl-2 pr-1 bg-alternative flex gap-2 items-center justify-between',
|
|
itemHeight
|
|
)}
|
|
>
|
|
<div className="min-w-0 flex shrink gap-x-1 items-center">
|
|
<Table2Icon strokeWidth={1} size={12} className="text-light" />
|
|
<span className="whitespace-nowrap overflow-hidden text-ellipsis" title={data.name}>
|
|
{data.name}
|
|
</span>
|
|
</div>
|
|
{
|
|
// Hide the actions while downloading the schema as png/svg
|
|
!schemaGraphContext.isDownloading ? (
|
|
<div className="flex shrink-0 items-center gap-2">
|
|
{data.description && (
|
|
<Tooltip>
|
|
<TooltipTrigger asChild className="cursor-default ">
|
|
<InfoIcon size={10} className="text-light" />
|
|
</TooltipTrigger>
|
|
<TooltipContent side="top">{data.description}</TooltipContent>
|
|
</Tooltip>
|
|
)}
|
|
|
|
{!placeholder && (
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button
|
|
variant="text"
|
|
className="px-0 w-[16px] h-[16px] rounded-sm nodrag nopan"
|
|
>
|
|
<MoreVerticalIcon size={10} />
|
|
<span className="sr-only">{data.name} actions</span>
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent side="bottom" align="end" className="w-40">
|
|
<DropdownMenuItem
|
|
data-attr="schema-visualizer-node-edit"
|
|
className="flex items-center space-x-2 whitespace-nowrap"
|
|
onClick={() => {
|
|
track('database_schema_visualizer_node_menu_clicked', {
|
|
action: 'edit_table',
|
|
})
|
|
schemaGraphContext.onEditTable(data.id)
|
|
}}
|
|
>
|
|
<EditIcon size={12} />
|
|
<p>Edit table</p>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
data-attr="schema-visualizer-node-open-editor"
|
|
className="flex items-center space-x-2 whitespace-nowrap"
|
|
onClick={() =>
|
|
router.push(
|
|
buildTableEditorUrl({
|
|
projectRef: project?.ref,
|
|
tableId: data.id,
|
|
schema: data.schema,
|
|
})
|
|
)
|
|
}
|
|
>
|
|
<TableEditor size={12} />
|
|
<p>View in Table Editor</p>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem
|
|
data-attr="schema-visualizer-node-copy"
|
|
className="flex items-center space-x-2 whitespace-nowrap"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
copyToClipboard(data.name)
|
|
track('database_schema_visualizer_copied', { content: 'table_name' })
|
|
}}
|
|
>
|
|
<CopyIcon size={12} />
|
|
<span>Copy name</span>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
key="copy-schema-sql"
|
|
data-attr="schema-visualizer-node-copy"
|
|
className="space-x-2"
|
|
onClick={async (e) => {
|
|
e.stopPropagation()
|
|
track('database_schema_visualizer_copied', { content: 'table_sql' })
|
|
const toastId = toast.loading('Getting table schema...')
|
|
|
|
const formattedSchema = getTableDefinition({
|
|
id: data.id,
|
|
projectRef: project?.ref,
|
|
connectionString: project?.connectionString,
|
|
}).then((tableDefinition) => {
|
|
if (!tableDefinition) {
|
|
throw new Error('Failed to get table schema')
|
|
}
|
|
return formatSql(tableDefinition)
|
|
})
|
|
|
|
try {
|
|
await copyToClipboard(formattedSchema, () => {
|
|
toast.success('Table schema copied to clipboard', { id: toastId })
|
|
})
|
|
} catch (err) {
|
|
toast.error(
|
|
'Failed to copy schema: ' + ((err as Error).message || err),
|
|
{
|
|
id: toastId,
|
|
}
|
|
)
|
|
}
|
|
}}
|
|
>
|
|
<CopyIcon size={12} />
|
|
<span>Copy as SQL</span>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
key="copy-schema-markdown"
|
|
data-attr="schema-visualizer-node-copy"
|
|
className="space-x-2"
|
|
onClick={async (e) => {
|
|
e.stopPropagation()
|
|
track('database_schema_visualizer_copied', {
|
|
content: 'table_markdown',
|
|
})
|
|
const markdown = getTableDefinitionAsMarkdown(data)
|
|
|
|
try {
|
|
await copyToClipboard(markdown, () => {
|
|
toast.success('Table schema copied to clipboard')
|
|
})
|
|
} catch (err) {
|
|
toast.error(
|
|
'Failed to copy schema: ' + ((err as Error).message || err)
|
|
)
|
|
}
|
|
}}
|
|
>
|
|
<CopyIcon size={12} />
|
|
<span>Copy as Markdown</span>
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
)}
|
|
</div>
|
|
) : null
|
|
}
|
|
</header>
|
|
|
|
{data.columns.map((column) => (
|
|
<div
|
|
className={cn(
|
|
'text-[8px] leading-5 relative flex flex-row justify-items-start',
|
|
'bg-surface-100',
|
|
'border-t',
|
|
'border-t-[0.5px]',
|
|
'hover:bg-scale-500 transition cursor-default',
|
|
'group',
|
|
'pr-1',
|
|
itemHeight
|
|
)}
|
|
data-testid={`${data.name}/${column.name}`}
|
|
key={column.id}
|
|
>
|
|
<div
|
|
className={cn(
|
|
'gap-[0.24rem] flex mx-2 align-middle items-center justify-start',
|
|
column.isPrimary && 'basis-1/5'
|
|
)}
|
|
>
|
|
{column.isPrimary && (
|
|
<KeyIcon size={8} strokeWidth={1} className={cn('shrink-0', 'text-light')} />
|
|
)}
|
|
{column.isNullable && (
|
|
<DiamondIcon size={8} strokeWidth={1} className="shrink-0 text-light" />
|
|
)}
|
|
{!column.isNullable && (
|
|
<DiamondIcon
|
|
size={8}
|
|
strokeWidth={1}
|
|
fill="currentColor"
|
|
className="shrink-0 text-light"
|
|
/>
|
|
)}
|
|
{column.isUnique && (
|
|
<FingerprintIcon size={8} strokeWidth={1} className="shrink-0 text-light" />
|
|
)}
|
|
{column.isIdentity && (
|
|
<HashIcon size={8} strokeWidth={1} className="shrink-0 text-light" />
|
|
)}
|
|
</div>
|
|
<div className="flex w-full justify-between min-w-0">
|
|
<span
|
|
className={cn(
|
|
'text-ellipsis overflow-hidden whitespace-nowrap min-w-0 max-w-[80%]',
|
|
schemaGraphContext.selectedEdge?.sourceHandle === column.id ||
|
|
schemaGraphContext.selectedEdge?.targetHandle === column.id
|
|
? 'text-primary'
|
|
: undefined
|
|
)}
|
|
title={column.name}
|
|
>
|
|
{column.name}
|
|
</span>
|
|
<span className="shrink-0 pl-2 pr-1 inline-flex justify-end font-mono text-lighter text-[0.4rem] group-hover:hidden">
|
|
{column.format}
|
|
</span>
|
|
</div>
|
|
{targetPosition && (
|
|
<Handle
|
|
type="target"
|
|
id={column.id}
|
|
position={targetPosition}
|
|
className={cn(hiddenNodeConnector)}
|
|
/>
|
|
)}
|
|
{sourcePosition && (
|
|
<Handle
|
|
type="source"
|
|
id={column.id}
|
|
position={sourcePosition}
|
|
className={cn(hiddenNodeConnector)}
|
|
/>
|
|
)}
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button
|
|
variant="text"
|
|
// Use opacity to hide the button so that it remains accessible (users can tab to it)
|
|
className="opacity-0 focus:opacity-100 group-hover:opacity-100 data-open:opacity-100 absolute right-0 top-1/2 -translate-y-1/2 px-0 mr-1 w-[16px] h-[16px] rounded-sm"
|
|
>
|
|
<MoreVerticalIcon size={10} />
|
|
<span className="sr-only">
|
|
{data.name} {column.name} actions
|
|
</span>
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent side="bottom" align="end" className="w-32">
|
|
<Tooltip>
|
|
<TooltipTrigger asChild>
|
|
<DropdownMenuItem
|
|
data-attr="schema-visualizer-node-edit"
|
|
disabled={!canUpdateColumns}
|
|
onClick={() => {
|
|
track('database_schema_visualizer_node_menu_clicked', {
|
|
action: 'edit_column',
|
|
})
|
|
schemaGraphContext.onEditColumn(data.id, column.id)
|
|
}}
|
|
className="space-x-2"
|
|
>
|
|
<EditIcon size={12} />
|
|
<p>Edit column</p>
|
|
</DropdownMenuItem>
|
|
</TooltipTrigger>
|
|
{!canUpdateColumns && (
|
|
<TooltipContent side="bottom">
|
|
Additional permissions required to edit column
|
|
</TooltipContent>
|
|
)}
|
|
</Tooltip>
|
|
|
|
<DropdownMenuItem
|
|
data-attr="schema-visualizer-node-copy"
|
|
className="space-x-2"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
copyToClipboard(column.name)
|
|
track('database_schema_visualizer_copied', { content: 'column_name' })
|
|
}}
|
|
>
|
|
<CopyIcon size={12} />
|
|
<span>Copy name</span>
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</article>
|
|
)
|
|
}
|
|
|
|
// Custom comparator: xyflow re-renders nodes on selection/drag with new prop
|
|
// objects; only the listed props affect rendered output. Selection-driven styling
|
|
// (highlighted edges) is read from context inside the component, so we can safely
|
|
// ignore xyflow's `selected`/`dragging`/etc. here.
|
|
export const TableNode = memo(
|
|
TableNodeComponent,
|
|
(prev, next) =>
|
|
prev.id === next.id &&
|
|
prev.data === next.data &&
|
|
prev.targetPosition === next.targetPosition &&
|
|
prev.sourcePosition === next.sourcePosition &&
|
|
prev.placeholder === next.placeholder
|
|
)
|