Files
supabase/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
T
Charis d79a276824 studio: ColumnTypeRef cascade + FK type comparison fixes (2/7) (#45903)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Refactor + bug fixes (part of the SafeSql migration stack — PR 2 of 7,
stacks on top of #45897).

## What is the current behavior?

- `pgMeta.columns.create` and the table-editor SQL builder take column
type as a string with array suffix and schema baked in (e.g.
`'private.test_enum'`, `'int4[]'`).
- The studio table-editor SQL emits the legacy schema-embedded `format`
string for enums in non-public schemas, while the pg-meta columns SQL
already returns the new shape (bare `format` + separate
`format_schema`). The two queries disagree on how to represent the same
column, surfacing as a false-positive type mismatch in the FK selector
when both ends are an enum from a non-public schema.
- The FK selector compares column types by `format` alone — same-named
enums in different schemas appear equal, and arrays vs. scalars of the
same base type pass the family check.
- `displayColumnType` renders arrays as the raw `_typname` pg-meta emits
(e.g. `_int4` instead of `int4[]`).

## What is the new behavior?

**pg-meta**

- Introduce `ColumnTypeRef` (`{ schema?, name, isArray? }`) for column
type input, replacing the legacy string-with-array-suffix format.
`pgMeta.columns.create` and the table-editor SQL builder consume the new
shape.
- Add `format_schema` to the column zod schema; pg-meta SQL emits the
type's schema for the table editor's ColumnType dropdown.
- `pgMeta.columns.create` returns a `SafeSqlFragment`.
- Studio table-editor SQL now emits bare `format` + `format_schema`,
matching pg-meta's columns SQL.

**Studio**

- `SafePostgresColumn`/`SafePostgresTable` extend the new `PG*` types
(master dropped postgres-meta).
- Pipe `ColumnTypeRef` through `SidePanelEditor` → `ColumnEditor` →
`TableEditor`, along with the column-create mutation, table
retrieve/list queries, and the `TableList`/`ColumnList` surfaces.
- `displayColumnType` helper renders arrays as `type[]` (or
`schema.type[]`) and handles non-implicit schemas.
- FK selector now carries `sourceIsArray`/`targetIsArray` and compares
the full `(format, format_schema, isArray)` triple. Family checks for
numeric/text/uuid skip when either side is an array (FKs across array
boundaries are never compatible).
- Type-mismatch and type-notice alerts pass `isArray` to the display
helper.
- Bundle `Policies.utils` + `Policies.types` + `sql-policy-mutation`,
`PolicyEditorModal`, and `SchemaGraph` here because `SidePanelEditor`
consumes `acceptGeneratedPolicy`/`AcceptedGeneratedPolicy` — splitting
requires temporary overloads with no architectural payoff.

## Additional context

Part of the SafeSql migration stack. Stacks on top of #45897.

### Manual test checklist

Surfaces touched by this PR — please exercise each:

**Table editor**
- [x] Create a new table with a mix of column types (scalar, array,
enum, foreign key)
- [x] Add a column to an existing table; verify the type dropdown lists
scalars + arrays separately and shows schema-qualified names for
non-public enums
- [x] Edit an existing column's type (scalar ↔ array, switch between
enums in different schemas) and save
- [x] Verify enum types from a non-public schema (e.g.
`private.my_enum`) display as `private.my_enum` in the column list

**Foreign key selector**
- [x] Open the FK selector for a column and pick a target column with a
matching type — no mismatch warning
- [x] Pick a target column whose type differs only by schema (two
same-named enums in different schemas) — should show a type-mismatch
alert
- [x] Pick a target column where one side is an array and the other is a
scalar of the same base type — should show a type-mismatch alert (no
auto-cast across array boundary)
- [x] When FK target sets the column type, verify `format_schema` and
`isArray` are preserved on the source column
- [x] Type-mismatch and type-notice alert messages render array types as
`type[]` (not `_type`)

**Column list / table list**
- [x] Schema-qualified type names display correctly for columns whose
type lives in a non-public schema
- [x] Array columns display as `type[]` (or `schema.type[]`)

**Policies (bundled due to import dependency)**
- [x] Open the Policies page; create/edit/delete a row-level policy via
the modal
- [x] Generate a policy via the AI assistant and accept it through
`SidePanelEditor` — verify the accepted policy lands in the editor
correctly

**Schema visualizer**
- [x] Open the Schemas → Schema Visualizer page; verify it renders
without type errors and shows tables/relationships

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Improvements**
* Support for column types in non-public schemas and richer column type
presentation (includes schema and array info).
* Stronger SQL safety around policies and constraints; draft policy SQL
is now promoted explicitly on save.
* Improved foreign-key type validation and compatibility checks using
enhanced type metadata.

* **Tests**
* Updated snapshots and tests to reflect new column metadata and SQL
fragment handling.

<!-- review_stack_entry_start -->

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/45903)

<!-- review_stack_entry_end -->
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-14 15:12:08 -04:00

423 lines
15 KiB
TypeScript

import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { noop } from 'lodash'
import {
Braces,
Calendar,
DiamondIcon,
Fingerprint,
Hash,
Key,
Link as LinkIcon,
ListPlus,
MoreVertical,
Plus,
Search,
ToggleRight,
Trash,
Type,
} from 'lucide-react'
import { useState } from 'react'
import {
Button,
Card,
cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { ProtectedSchemaWarning } from '../ProtectedSchemaWarning'
import {
getColumnTypeAffordance,
getForeignKeyColumnNames,
getPrimaryKeyColumnNames,
getUniqueIndexColumnNames,
} from './ColumnList.utils'
import { ConstraintToken } from './ConstraintToken'
import { displayColumnType } from '@/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'
import AlertError from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'
import { NoSearchResults } from '@/components/ui/NoSearchResults'
import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'
import { isTableLike } from '@/data/table-editor/table-editor-types'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'
import type { SafePostgresColumn } from '@/lib/postgres-types'
const getColumnTypeAffordancePresentation = (column: SafePostgresColumn) => {
const { kind, label } = getColumnTypeAffordance(column.format)
const iconClassName = 'text-foreground-muted'
switch (kind) {
case 'number':
return {
icon: <Hash size={14} className={iconClassName} strokeWidth={1.5} />,
label,
}
case 'time':
return {
icon: <Calendar size={14} className={iconClassName} strokeWidth={1.5} />,
label,
}
case 'text':
return {
icon: <Type size={14} className={iconClassName} strokeWidth={1.5} />,
label,
}
case 'json':
return {
icon: <Braces size={14} className={iconClassName} strokeWidth={1.5} />,
label,
}
case 'bool':
return {
icon: <ToggleRight size={14} className={iconClassName} strokeWidth={1.5} />,
label,
}
default:
return {
icon: <ListPlus size={16} className={iconClassName} strokeWidth={1.5} />,
label,
}
}
}
interface ColumnListProps {
onAddColumn: () => void
onEditColumn: (column: SafePostgresColumn) => void
onDeleteColumn: (column: SafePostgresColumn) => void
}
export const ColumnList = ({
onAddColumn = noop,
onEditColumn = noop,
onDeleteColumn = noop,
}: ColumnListProps) => {
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
const { data: project } = useSelectedProjectQuery()
const {
data: selectedTable,
error,
isError,
isPending: isLoading,
isSuccess,
} = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
const [filterString, setFilterString] = useState<string>('')
const isTableEntity = isTableLike(selectedTable)
const tableConstraintSource = isTableEntity ? selectedTable : undefined
const primaryKeyColumns = getPrimaryKeyColumnNames(tableConstraintSource)
const foreignKeyColumns = getForeignKeyColumnNames(tableConstraintSource)
const uniqueIndexColumns = getUniqueIndexColumnNames(tableConstraintSource)
const columns =
(filterString.length === 0
? (selectedTable?.columns ?? [])
: selectedTable?.columns?.filter((column) =>
column.name.toLowerCase().includes(filterString.toLowerCase())
)) ?? []
const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedTable?.schema ?? '' })
const { can: canUpdateColumns } = useAsyncCheckPermissions(
PermissionAction.TENANT_SQL_ADMIN_WRITE,
'columns'
)
const deleteColumnTooltipText = !canUpdateColumns
? 'Additional permissions required to delete column'
: undefined
return (
<div className="space-y-4">
<div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
<div className="w-full lg:w-52">
<Input
size="tiny"
placeholder="Filter columns"
value={filterString}
onChange={(e) => setFilterString(e.target.value)}
icon={<Search />}
/>
</div>
{!isSchemaLocked && isTableEntity && (
<ButtonTooltip
icon={<Plus />}
disabled={!canUpdateColumns}
onClick={() => onAddColumn()}
tooltip={{
content: {
side: 'bottom',
text: !canUpdateColumns
? 'You need additional permissions to create columns'
: undefined,
},
}}
>
New column
</ButtonTooltip>
)}
</div>
{isSchemaLocked && (
<ProtectedSchemaWarning schema={selectedTable?.schema ?? ''} entity="columns" />
)}
<Card>
{isLoading ? (
<div className="p-4">
<GenericSkeletonLoader />
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-0 px-0!" />
<TableHead
className={cn(columns.length === 0 ? 'text-foreground-muted' : undefined)}
>
Name
</TableHead>
<TableHead className={columns.length === 0 ? 'text-foreground-muted' : undefined}>
Type
</TableHead>
<TableHead className={columns.length === 0 ? 'text-foreground-muted' : undefined}>
Constraints
</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{isError && (
<TableRow className="[&>td]:hover:bg-inherit">
<TableCell colSpan={5}>
<AlertError
error={error}
subject={`Failed to retrieve columns for table "${selectedTable?.schema}.${selectedTable?.name}"`}
/>
</TableCell>
</TableRow>
)}
{isSuccess && columns.length === 0 && filterString.length > 0 && (
<TableRow className="[&>td]:hover:bg-inherit">
<TableCell colSpan={5}>
<NoSearchResults
withinTableCell
searchString={filterString}
onResetFilter={() => setFilterString('')}
/>
</TableCell>
</TableRow>
)}
{isSuccess && columns.length === 0 && filterString.length === 0 && (
<TableRow className="[&>td]:hover:bg-inherit">
<TableCell colSpan={5}>
<p className="text-sm text-foreground">No columns created yet</p>
<p className="text-sm text-foreground-light">
There are no columns in "{selectedTable?.schema}.{selectedTable?.name}"
</p>
</TableCell>
</TableRow>
)}
{isSuccess &&
columns.map((column) => {
const { icon: TypeIcon, label: typeLabel } =
getColumnTypeAffordancePresentation(column)
const constraintTokens = [
primaryKeyColumns.has(column.name) ? (
<ConstraintToken
key="primary"
icon={<Key size={12} strokeWidth={1.7} className="shrink-0" />}
label="Primary"
variant="primary"
/>
) : null,
foreignKeyColumns.has(column.name) ? (
<ConstraintToken
key="foreign-key"
icon={
<LinkIcon
size={12}
strokeWidth={1.7}
className="shrink-0 text-foreground-muted"
/>
}
label="Foreign key"
/>
) : null,
column.is_unique || uniqueIndexColumns.has(column.name) ? (
<ConstraintToken
key="unique"
icon={
<Fingerprint
size={12}
strokeWidth={1.7}
className="shrink-0 text-foreground-light"
/>
}
label="Unique"
/>
) : null,
column.is_identity ? (
<ConstraintToken
key="identity"
icon={
<Hash
size={12}
strokeWidth={1.7}
className="shrink-0 text-foreground-lighter"
/>
}
label="Identity"
/>
) : null,
<ConstraintToken
key="nullability"
icon={
<DiamondIcon
size={12}
strokeWidth={1.7}
className="shrink-0"
fill={column.is_nullable ? 'none' : 'currentColor'}
/>
}
label={column.is_nullable ? 'Nullable' : 'Non-nullable'}
variant="secondary"
/>,
].filter(Boolean)
return (
<TableRow key={column.name}>
<TableCell className="w-0 pl-5! pr-1!">
<Tooltip>
<TooltipTrigger asChild className="cursor-default" aria-label={typeLabel}>
<div className="flex w-4 justify-center">{TypeIcon}</div>
</TooltipTrigger>
<TooltipContent side="bottom">
<div className="flex flex-col">
<span>{column.data_type}</span>
{column.format !== column.data_type && (
<span className="text-xs text-foreground-light">
{displayColumnType(
column.format,
column.format_schema,
column.data_type === 'ARRAY'
)}
</span>
)}
</div>
</TooltipContent>
</Tooltip>
</TableCell>
<TableCell className="max-w-[160px] sm:max-w-[280px]">
<div className="flex min-w-0 flex-col">
<p>{column.name}</p>
{column.comment !== null ? (
<span
className="max-w-md truncate text-foreground-lighter"
title={column.comment}
>
{column.comment}
</span>
) : null}
</div>
</TableCell>
<TableCell>
<p className="text-foreground-lighter">
{displayColumnType(
column.format,
column.format_schema,
column.data_type === 'ARRAY'
)}
</p>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1.5">{constraintTokens}</div>
</TableCell>
<TableCell className="text-right">
{!isSchemaLocked && isTableEntity && (
<div className="flex justify-end gap-2">
<ButtonTooltip
type="default"
disabled={!canUpdateColumns}
onClick={() => onEditColumn(column)}
tooltip={{
content: {
side: 'bottom',
text: !canUpdateColumns
? 'Additional permissions required to edit column'
: undefined,
},
}}
>
Edit
</ButtonTooltip>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="default" className="px-1" icon={<MoreVertical />} />
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end" className="w-32">
<DropdownMenuItemTooltip
disabled={!canUpdateColumns}
onClick={() => onDeleteColumn(column)}
className="gap-x-2"
tooltip={{
content: {
side: 'left',
text: deleteColumnTooltipText,
},
}}
>
<Trash size={12} />
<p>Delete column</p>
</DropdownMenuItemTooltip>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
{isSuccess && (
<TableFooter className="font-normal">
<TableRow className="border-b-0 [&>td]:hover:bg-inherit">
<TableCell colSpan={5} className="text-foreground-muted">
{columns.length} {columns.length === 1 ? 'column' : 'columns'}
</TableCell>
</TableRow>
</TableFooter>
)}
</Table>
)}
</Card>
</div>
)
}