Skip to content

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

Support for composite foreign keys in table editor (#21078)

Joshen Lim0ee75935f767
diff --git a/apps/studio/components/interfaces/Database/Tables/TableList.tsx b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
index efdb55ad083..b21f5122ef3 100644
--- a/apps/studio/components/interfaces/Database/Tables/TableList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
@@ -243,7 +243,7 @@ const TableList = ({
{(x.live_rows_estimate ?? x.live_row_count).toLocaleString()}
</Table.td>
<Table.td className="hidden text-right xl:table-cell">
- <code className="text-sm">{x.size}</code>
+ <code className="text-xs">{x.size}</code>
</Table.td>
<Table.td className="hidden xl:table-cell text-center">
{(realtimePublication?.tables ?? []).find(
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index 363acefc6c4..a5b13a8aa1f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -24,22 +24,17 @@ import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constra
import { usePostgresTypesQuery } from 'data/database/types-query'
import { EXCLUDED_SCHEMAS_WITHOUT_EXTENSIONS } from 'lib/constants/schemas'
import { Dictionary } from 'types'
-import { ForeignKeySelector } from '..'
import ActionBar from '../ActionBar'
+import { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
+import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
import { TEXT_TYPES } from '../SidePanelEditor.constants'
-import {
- ColumnField,
- CreateColumnPayload,
- ExtendedPostgresRelationship,
- UpdateColumnPayload,
-} from '../SidePanelEditor.types'
+import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from '../SidePanelEditor.types'
import ColumnDefaultValue from './ColumnDefaultValue'
import {
generateColumnField,
generateColumnFieldFromPostgresColumn,
generateCreateColumnPayload,
generateUpdateColumnPayload,
- getColumnForeignKey,
validateFields,
} from './ColumnEditor.utils'
import ColumnForeignKey from './ColumnForeignKey'
@@ -53,7 +48,6 @@ export interface ColumnEditorProps {
closePanel: () => void
saveChanges: (
payload: CreateColumnPayload | UpdateColumnPayload,
- foreignKey: ExtendedPostgresRelationship | undefined,
isNewRecord: boolean,
configuration: {
columnId: string | undefined
@@ -76,7 +70,7 @@ const ColumnEditor = ({
const [errors, setErrors] = useState<Dictionary<any>>({})
const [columnFields, setColumnFields] = useState<ColumnField>()
- const [isEditingRelation, setIsEditingRelation] = useState<boolean>(false)
+ const [fkRelations, setFkRelations] = useState<ForeignKey[]>([])
const { data: types } = usePostgresTypesQuery({
projectRef: project?.ref,
@@ -91,20 +85,21 @@ const ColumnEditor = ({
connectionString: project?.connectionString,
schema: selectedTable?.schema,
})
- const foreignKeyMeta = data || []
const isNewRecord = column === undefined
- const originalForeignKey = column
- ? getColumnForeignKey(column, selectedTable, foreignKeyMeta)
- : undefined
+ const foreignKeyMeta = data || []
+ const foreignKeys = foreignKeyMeta.filter((relation) => {
+ return relation.source_id === column?.table_id && relation.source_columns.includes(column.name)
+ })
useEffect(() => {
if (visible) {
setErrors({})
const columnFields = isNewRecord
- ? generateColumnField()
+ ? generateColumnField({ schema: selectedTable.schema, table: selectedTable.name })
: generateColumnFieldFromPostgresColumn(column!, selectedTable, foreignKeyMeta)
setColumnFields(columnFields)
+ setFkRelations(formatForeignKeys(foreignKeys))
}
}, [visible])
@@ -127,36 +122,6 @@ const ColumnEditor = ({
setErrors(updatedErrors)
}
- const saveColumnForeignKey = (foreignKeyConfiguration?: {
- table: PostgresTable
- column: PostgresColumn
- deletionAction: string
- updateAction: string
- }) => {
- onUpdateField({
- foreignKey:
- foreignKeyConfiguration !== undefined
- ? {
- id: 0,
- constraint_name: '',
- source_schema: selectedTable.schema,
- source_table_name: selectedTable.name,
- source_column_name: columnFields?.name || column?.name || '',
- target_table_schema: foreignKeyConfiguration.table.schema,
- target_table_name: foreignKeyConfiguration.table.name,
- target_column_name: foreignKeyConfiguration.column.name,
- deletion_action: foreignKeyConfiguration.deletionAction,
- update_action: foreignKeyConfiguration.updateAction,
- }
- : undefined,
- ...(foreignKeyConfiguration !== undefined && {
- format: foreignKeyConfiguration.column.format,
- defaultValue: null,
- }),
- })
- setIsEditingRelation(false)
- }
-
const onSaveChanges = (resolve: () => void) => {
if (columnFields) {
const errors = validateFields(columnFields)
@@ -166,11 +131,8 @@ const ColumnEditor = ({
const payload = isNewRecord
? generateCreateColumnPayload(selectedTable.id, columnFields)
: generateUpdateColumnPayload(column!, selectedTable, columnFields)
- const foreignKey = columnFields.foreignKey
- ? { ...columnFields.foreignKey, source_column_name: columnFields.name }
- : undefined
const configuration = { columnId: column?.id }
- saveChanges(payload, foreignKey, isNewRecord, configuration, resolve)
+ saveChanges(payload, isNewRecord, configuration, resolve)
} else {
resolve()
}
@@ -217,24 +179,6 @@ const ColumnEditor = ({
</FormSectionContent>
</FormSection>
<SidePanel.Separator />
- <FormSection
- header={
- <FormSectionLabel className="lg:!col-span-4">Foreign Key Relation</FormSectionLabel>
- }
- >
- <FormSectionContent loading={false} className="lg:!col-span-8">
- <div>
- <ColumnForeignKey
- column={columnFields}
- originalForeignKey={originalForeignKey}
- onSelectEditRelation={() => setIsEditingRelation(true)}
- onSelectRemoveRelation={() => onUpdateField({ foreignKey: undefined })}
- onSelectCancelRemoveRelation={() => onUpdateField({ foreignKey: originalForeignKey })}
- />
- </div>
- </FormSectionContent>
- </FormSection>
- <SidePanel.Separator />
<FormSection
header={
<FormSectionLabel
@@ -279,7 +223,12 @@ const ColumnEditor = ({
layout="vertical"
enumTypes={enumTypes}
error={errors.format}
- disabled={columnFields?.foreignKey !== undefined}
+ description={
+ columnFields.foreignKey !== undefined
+ ? 'Column type cannot be changed as it has a foreign key relation'
+ : ''
+ }
+ disabled={columnFields.foreignKey !== undefined}
onOptionSelect={(format: string) => onUpdateField({ format, defaultValue: null })}
/>
{columnFields.foreignKey === undefined && (
@@ -322,6 +271,20 @@ const ColumnEditor = ({
</FormSectionContent>
</FormSection>
<SidePanel.Separator />
+ <FormSection
+ header={<FormSectionLabel className="lg:!col-span-4">Foreign Keys</FormSectionLabel>}
+ >
+ <FormSectionContent loading={false} className="lg:!col-span-8">
+ <div>
+ <ColumnForeignKey
+ column={columnFields}
+ relations={fkRelations}
+ closePanel={closePanel}
+ />
+ </div>
+ </FormSectionContent>
+ </FormSection>
+ <SidePanel.Separator />
<FormSection
header={<FormSectionLabel className="lg:!col-span-4">Constraints</FormSectionLabel>}
>
@@ -423,13 +386,6 @@ const ColumnEditor = ({
</FormSection>
</>
)}
-
- <ForeignKeySelector
- column={columnFields}
- visible={isEditingRelation}
- closePanel={() => setIsEditingRelation(false)}
- saveChanges={saveColumnForeignKey}
- />
</SidePanel>
)
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index f2330bf9edc..d5afd301545 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -31,10 +31,12 @@ const isSQLExpression = (input: string) => {
}
export const generateColumnField = (field: any = {}): ColumnField => {
- const { name, format } = field
+ const { name, table, schema, format } = field
return {
id: uuidv4(),
name: name || '',
+ table: table || '',
+ schema: schema || '',
comment: '',
format: format || '',
defaultValue: null,
@@ -63,6 +65,8 @@ export const generateColumnFieldFromPostgresColumn = (
return {
foreignKey,
id: column?.id ?? uuidv4(),
+ table: column.table,
+ schema: column.schema,
name: column.name,
comment: column?.comment ?? '',
format: isArray ? column.format.slice(1) : column.format,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
index 9f77fe7dc1e..67e6cd8fcd1 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
@@ -1,320 +1,91 @@
-import { isUndefined } from 'lodash'
-import { Badge, Button, IconArrowRight } from 'ui'
+import { noop } from 'lodash'
+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'
-import InformationBox from 'components/ui/InformationBox'
-import type { ExtendedPostgresRelationship } from '../SidePanelEditor.types'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
+import { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import { ColumnField } from '../SidePanelEditor.types'
-import { getForeignKeyCascadeAction, getForeignKeyUIState } from './ColumnEditor.utils'
+import { ForeignKeyRow } from '../TableEditor/ForeignKeysManagement/ForeignKeyRow'
+import { checkIfRelationChanged } from '../TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
interface ColumnForeignKeyProps {
column: ColumnField
- originalForeignKey: ExtendedPostgresRelationship | undefined
- onSelectEditRelation: () => void
- onSelectRemoveRelation: () => void
- onSelectCancelRemoveRelation: () => void
+ relations: ForeignKey[]
+ closePanel: () => void
}
-const ColumnForeignKey = ({
- column,
- originalForeignKey,
- onSelectEditRelation,
- onSelectRemoveRelation,
- onSelectCancelRemoveRelation,
-}: ColumnForeignKeyProps) => {
- const hasNoForeignKey = isUndefined(originalForeignKey) && isUndefined(column?.foreignKey)
- if (hasNoForeignKey) {
- return (
- <Button type="default" onClick={onSelectEditRelation}>
- Add foreign key relation
- </Button>
- )
+const ColumnForeignKey = ({ column, relations, closePanel }: ColumnForeignKeyProps) => {
+ const { project } = useProjectContext()
+ const snap = useTableEditorStateSnapshot()
+ const { data } = useForeignKeyConstraintsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: column.schema,
+ })
+
+ const getRelationStatus = (fk: ForeignKey) => {
+ const existingRelation = (data ?? []).find((x) => x.id === fk.id)
+ const stateRelation = relations.find((x) => x.id === fk.id)
+
+ if (stateRelation?.toRemove) return 'REMOVE'
+ if (existingRelation === undefined && stateRelation !== undefined) return 'ADD'
+ if (existingRelation !== undefined && stateRelation !== undefined) {
+ const hasUpdated = checkIfRelationChanged(existingRelation, stateRelation)
+ if (hasUpdated) return 'UPDATE'
+ else return undefined
+ }
}
- const foreignKeyUIState = getForeignKeyUIState(originalForeignKey, column?.foreignKey)
-
- switch (foreignKeyUIState) {
- case 'Add':
- return (
- <ColumnForeignKeyAdded
- columnName={column.name}
- foreignKey={column.foreignKey}
- onSelectEditRelation={onSelectEditRelation}
- onSelectRemoveRelation={onSelectRemoveRelation}
- />
- )
- case 'Remove':
- return (
- <ColumnForeignKeyRemoved
- columnName={column.name}
- originalForeignKey={originalForeignKey}
- onSelectEditRelation={onSelectEditRelation}
- onSelectCancelRemoveRelation={onSelectCancelRemoveRelation}
- />
- )
- case 'Update':
- return (
- <ColumnForeignKeyUpdated
- columnName={column.name}
- originalForeignKey={originalForeignKey}
- updatedForeignKey={column.foreignKey}
- onSelectEditRelation={onSelectEditRelation}
- onSelectRemoveRelation={onSelectRemoveRelation}
- />
- )
- case 'Info':
- return (
- <ColumnForeignKeyInformation
- columnName={column.name}
- foreignKey={column.foreignKey}
- onSelectEditRelation={onSelectEditRelation}
- onSelectRemoveRelation={onSelectRemoveRelation}
- />
- )
- default:
- return <div />
- }
-}
-
-export default ColumnForeignKey
-
-// Just to break the components into smaller ones, we can create separate files for these
-
-interface ColumnForeignKeyInformationProps {
- columnName: string
- foreignKey?: ExtendedPostgresRelationship
- onSelectEditRelation: () => void
- onSelectRemoveRelation: () => void
-}
-
-const ColumnForeignKeyInformation = ({
- columnName,
- foreignKey,
- onSelectEditRelation,
- onSelectRemoveRelation,
-}: ColumnForeignKeyInformationProps) => {
- const updateAction = getForeignKeyCascadeAction(foreignKey?.update_action)
- const deletionAction = getForeignKeyCascadeAction(foreignKey?.deletion_action)
-
- return (
- <InformationBox
- block
- title={
- <div className="flex flex-col space-y-4">
- <div className="space-y-2">
- <p className="text-foreground-light">
- This column has the following foreign key relation:
- </p>
- <div className="flex items-center space-x-2 text-foreground">
- <p className="text-xs text-code font-mono">{columnName}</p>
- <IconArrowRight size={14} strokeWidth={2} />
- <p className="text-xs text-code font-mono">
- {foreignKey?.target_table_schema}.{foreignKey?.target_table_name}.
- {foreignKey?.target_column_name}
- </p>
- </div>
- <div className="flex items-center space-x-2">
- {updateAction !== undefined && <Badge color="gray">On update: {updateAction}</Badge>}
- {deletionAction !== undefined && (
- <Badge color="gray">On delete: {deletionAction}</Badge>
- )}
- </div>
- </div>
- <div className="flex items-center space-x-2">
- <Button type="outline" onClick={onSelectEditRelation}>
- Edit relation
- </Button>
- <Button type="outline" onClick={onSelectRemoveRelation}>
- Remove
- </Button>
- </div>
- </div>
- }
- />
- )
-}
-
-interface ColumnForeignKeyAddedProps {
- columnName: string
- foreignKey?: ExtendedPostgresRelationship
- onSelectEditRelation: () => void
- onSelectRemoveRelation: () => void
-}
-
-const ColumnForeignKeyAdded = ({
- columnName,
- foreignKey,
- onSelectEditRelation,
- onSelectRemoveRelation,
-}: ColumnForeignKeyAddedProps) => {
- const updateAction = getForeignKeyCascadeAction(foreignKey?.update_action)
- const deletionAction = getForeignKeyCascadeAction(foreignKey?.deletion_action)
-
- return (
- <InformationBox
- block
- title={
- <div className="flex flex-col space-y-4 text-foreground-light">
- <div className="space-y-2">
- <span>
- The following foreign key relation will be <span className="text-brand">added</span>:
- </span>
- <div className="flex items-center space-x-2 text-foreground">
- <p
- className={`${
- columnName.length > 0 ? 'text-code font-mono text-xs' : ''
- } max-w-xs truncate`}
- >
- {columnName || 'This column'}
- </p>
- <IconArrowRight size={14} strokeWidth={2} />
- <p className="max-w-xs text-xs truncate text-code font-mono">
- {foreignKey?.target_table_schema}.{foreignKey?.target_table_name}.
- {foreignKey?.target_column_name}
- </p>
- </div>
- <div className="flex items-center space-x-2">
- {updateAction !== undefined && <Badge color="gray">On update: {updateAction}</Badge>}
- {deletionAction !== undefined && (
- <Badge color="gray">On delete: {deletionAction}</Badge>
- )}
- </div>
- </div>
- <div className="flex items-center space-x-2">
- <Button type="outline" onClick={onSelectEditRelation}>
- Edit relation
- </Button>
- <Button type="outline" onClick={onSelectRemoveRelation}>
- Remove
- </Button>
- </div>
- </div>
- }
- />
- )
-}
-
-interface ColumnForeignKeyRemovedProps {
- columnName: string
- originalForeignKey?: ExtendedPostgresRelationship
- onSelectEditRelation: () => void
- onSelectCancelRemoveRelation: () => void
-}
-
-const ColumnForeignKeyRemoved = ({
- columnName,
- originalForeignKey,
- onSelectEditRelation,
- onSelectCancelRemoveRelation,
-}: ColumnForeignKeyRemovedProps) => {
return (
- <InformationBox
- block
- title={
- <div className="flex flex-col space-y-4">
- <div className="space-y-2">
- <p className="text-foreground-light">
- The following foreign key relation will be{' '}
- <span className="text-amber-900">removed</span>:
- </p>
- <div className="flex items-center space-x-2">
- <code className="text-xs font-mono">{columnName}</code>
- <IconArrowRight size={14} strokeWidth={2} />
- <code className="text-xs font-mono">
- {originalForeignKey?.target_table_schema}.{originalForeignKey?.target_table_name}.
- {originalForeignKey?.target_column_name}
- </code>
- </div>
- </div>
- <div className="flex items-center space-x-2">
- <Button type="outline" onClick={onSelectEditRelation}>
- Edit relation
- </Button>
- <Button type="outline" onClick={onSelectCancelRemoveRelation}>
- Cancel remove
- </Button>
- </div>
- </div>
- }
- />
+ <div className="flex flex-col gap-y-2">
+ <div>
+ {relations.map((relation) => {
+ const status = getRelationStatus(relation)
+ return (
+ <ForeignKeyRow
+ disabled
+ key={relation.id}
+ layout="vertical"
+ status={status}
+ foreignKey={relation}
+ closePanel={closePanel}
+ onSelectEdit={noop}
+ onSelectRemove={noop}
+ onSelectUndoRemove={noop}
+ />
+ )
+ })}
+ </div>
+ <Alert_Shadcn_>
+ <AlertTitle_Shadcn_>
+ {relations.length > 0 ? (
+ <>
+ These are the foreign keys which the column{' '}
+ <code className="text-xs">{column.name}</code> is included
+ </>
+ ) : column.isNewColumn ? (
+ <>Foreign keys can be added after creating the column</>
+ ) : (
+ <>
+ Foreign keys which include the column <code className="text-xs">{column.name}</code>{' '}
+ will be shown here
+ </>
+ )}
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ All foreign keys on the table can be managed by editing the{' '}
+ <code className="text-xs">
+ {column.schema}.{column.table}
+ </code>{' '}
+ table.
+ </AlertDescription_Shadcn_>
+ <Button type="default" className="mt-3" onClick={() => snap.onEditTable()}>
+ Edit table
+ </Button>
+ </Alert_Shadcn_>
+ </div>
)
}
-interface ColumnForeignKeyUpdatedProps {
- columnName: string
- originalForeignKey?: ExtendedPostgresRelationship
- updatedForeignKey?: ExtendedPostgresRelationship
- onSelectEditRelation: () => void
- onSelectRemoveRelation: () => void
-}
-
-const ColumnForeignKeyUpdated = ({
- columnName,
- originalForeignKey,
- updatedForeignKey,
- onSelectEditRelation,
- onSelectRemoveRelation,
-}: ColumnForeignKeyUpdatedProps) => {
- const originalKey = `${originalForeignKey?.target_table_schema}.${originalForeignKey?.target_table_name}.${originalForeignKey?.target_column_name}`
- const updatedKey = `${updatedForeignKey?.target_table_schema}.${updatedForeignKey?.target_table_name}.${updatedForeignKey?.target_column_name}`
-
- const originalUpdateAction = getForeignKeyCascadeAction(originalForeignKey?.update_action)
- const updatedUpdateAction = getForeignKeyCascadeAction(updatedForeignKey?.update_action)
-
- const originalDeletionAction = getForeignKeyCascadeAction(originalForeignKey?.deletion_action)
- const updatedDeletionAction = getForeignKeyCascadeAction(updatedForeignKey?.deletion_action)
-
- return (
- <InformationBox
- block
- title={
- <div className="flex flex-col space-y-4">
- <div className="space-y-2">
- <p>
- The foreign key relation will be <span className="text-brand">updated</span> as such:
- </p>
- <div className="flex items-start space-x-2">
- <code className="text-xs font-mono">{columnName}</code>
- <IconArrowRight className="mt-1" size={14} strokeWidth={2} />
- <div className="flex flex-col space-y-2">
- {originalKey !== updatedKey && (
- <p className="line-through">
- <code className="text-xs font-mono">{originalKey}</code>
- </p>
- )}
- <code className="text-xs font-mono">{updatedKey}</code>
- </div>
- </div>
- <div className="flex items-center space-x-2">
- {originalDeletionAction !== updatedDeletionAction && (
- <>
- <Badge color="gray" className="line-through">
- On delete: {originalDeletionAction ?? 'No action'}
- </Badge>
- <Badge color="green">On delete: {updatedDeletionAction ?? 'No action'}</Badge>
- </>
- )}
- </div>
- <div className="flex items-center space-x-2">
- {originalUpdateAction !== updatedUpdateAction && (
- <>
- <Badge color="gray" className="line-through">
- On update: {originalUpdateAction ?? 'No action'}
- </Badge>
- <Badge color="green">On update: {updatedUpdateAction ?? 'No action'}</Badge>
- </>
- )}
- </div>
- </div>
- <div className="flex items-center space-x-2">
- <Button type="outline" onClick={onSelectEditRelation}>
- Edit relation
- </Button>
- <Button type="outline" onClick={onSelectRemoveRelation}>
- Remove
- </Button>
- </div>
- </div>
- }
- />
- )
-}
+export default ColumnForeignKey
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx
index ada75e45011..c3e4607a0bc 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnType.tsx
@@ -1,3 +1,4 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
import type { PostgresType } from '@supabase/postgres-meta'
import { noop } from 'lodash'
import Link from 'next/link'
@@ -6,6 +7,7 @@ import {
Alert,
Button,
IconCalendar,
+ IconCircle,
IconExternalLink,
IconHash,
IconToggleRight,
@@ -54,25 +56,6 @@ const ColumnType = ({
const isAvailableType = value ? availableTypes.includes(value) : true
const recommendation = RECOMMENDED_ALTERNATIVE_DATA_TYPE[value]
- if (!isAvailableType) {
- return (
- <Input
- readOnly
- disabled
- label={showLabel ? 'Type' : ''}
- layout={showLabel ? 'horizontal' : undefined}
- className="md:gap-x-0"
- size="small"
- value={value}
- descriptionText={
- showLabel
- ? 'Custom non-native psql data types cannot currently be changed to a different data type via Supabase Studio'
- : ''
- }
- />
- )
- }
-
const inferIcon = (type: string) => {
switch (type) {
case 'number':
@@ -90,10 +73,86 @@ const ColumnType = ({
case 'bool':
return <IconToggleRight size={16} className="text-foreground" strokeWidth={1.5} />
default:
- return <div />
+ return <IconCircle size={16} className="text-foreground p-0.5" strokeWidth={1.5} />
}
}
+ if (!isAvailableType) {
+ return (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <Input
+ readOnly
+ disabled
+ label={showLabel ? 'Type' : ''}
+ layout={showLabel ? 'horizontal' : undefined}
+ className="md:gap-x-0"
+ size="small"
+ icon={inferIcon(POSTGRES_DATA_TYPE_OPTIONS.find((x) => x.name === value)?.type ?? '')}
+ value={value}
+ descriptionText={
+ showLabel
+ ? 'Custom non-native psql data types currently cannot be changed to a different data type via Supabase Studio'
+ : ''
+ }
+ />
+ </Tooltip.Trigger>
+ {!showLabel && (
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background w-[240px]',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Custom non-native psql data types currently cannot be changed to a different data
+ type via Supabase Studio
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ )}
+ </Tooltip.Root>
+ )
+ }
+
+ if (disabled && !showLabel) {
+ return (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <Input
+ readOnly
+ disabled
+ label={showLabel ? 'Type' : ''}
+ layout={showLabel ? 'horizontal' : undefined}
+ className="md:gap-x-0"
+ size="small"
+ icon={inferIcon(POSTGRES_DATA_TYPE_OPTIONS.find((x) => x.name === value)?.type ?? '')}
+ value={value}
+ />
+ </Tooltip.Trigger>
+ {!showLabel && description && (
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background w-[240px]',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">{description}</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ )}
+ </Tooltip.Root>
+ )
+ }
+
return (
<div className="space-y-2">
<Listbox
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/InputWithSuggestions.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/InputWithSuggestions.tsx
index c4bfbb3770c..5a63560fa75 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/InputWithSuggestions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/InputWithSuggestions.tsx
@@ -98,8 +98,8 @@ const InputWithSuggestions = ({
<Tooltip.Root delayDuration={0}>
<DropdownMenuTrigger asChild>
<Tooltip.Trigger asChild>
- <Button type="default" className="!px-1 mr-1">
- <IconList strokeWidth={1.5} />
+ <Button type="default" className="!px-1 mr-0.5">
+ <IconList strokeWidth={1.5} size={14} />
</Button>
</Tooltip.Trigger>
</DropdownMenuTrigger>
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
index ea075246638..4b56050abd6 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
@@ -1,212 +1,216 @@
-import type { PostgresColumn, PostgresSchema, PostgresTable } from '@supabase/postgres-meta'
-import { find, get, isEmpty, sortBy } from 'lodash'
-import { useEffect, useState } from 'react'
-
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import InformationBox from 'components/ui/InformationBox'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
-import { useSchemasQuery } from 'data/database/schemas-query'
-import { useTablesQuery } from 'data/tables/tables-query'
-import { Dictionary } from 'types'
+import { PostgresTable } from '@supabase/postgres-meta'
+import { sortBy } from 'lodash'
+import { Table } from 'lucide-react'
+import { Fragment, useEffect, useState } from 'react'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
Alert_Shadcn_,
- IconAlertCircle,
- IconAlertTriangle,
+ Button,
+ IconArrowRight,
IconDatabase,
+ IconExternalLink,
IconHelpCircle,
- Input,
+ IconX,
Listbox,
SidePanel,
} from 'ui'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import InformationBox from 'components/ui/InformationBox'
+import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { useSchemasQuery } from 'data/database/schemas-query'
+import { useTablesQuery } from 'data/tables/tables-query'
+import { uuidv4 } from 'lib/helpers'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
import ActionBar from '../ActionBar'
-import { ColumnField } from '../SidePanelEditor.types'
+import { NUMERICAL_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'
import { FOREIGN_KEY_CASCADE_OPTIONS } from './ForeignKeySelector.constants'
import { ForeignKey } from './ForeignKeySelector.types'
import { generateCascadeActionDescription } from './ForeignKeySelector.utils'
+const EMPTY_STATE: ForeignKey = {
+ id: undefined,
+ schema: 'public',
+ table: '',
+ columns: [] as { source: string; target: string }[],
+ deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
+ updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
+}
+
interface ForeignKeySelectorProps {
- column: ColumnField
- metadata?: any
visible: boolean
- closePanel: () => void
- saveChanges: (
- value:
- | {
- table: PostgresTable
- column: PostgresColumn
- deletionAction: string
- updateAction: string
- }
- | undefined
- ) => void
+ table: { id: number; name: string; columns: any[] }
+ foreignKey?: ForeignKey
+ onClose: () => void
+ onSaveRelation: (fk: ForeignKey) => void
}
-const ForeignKeySelector = ({
- column,
- visible = false,
- closePanel,
- saveChanges,
+export const ForeignKeySelector = ({
+ visible,
+ table,
+ foreignKey,
+ onClose,
+ onSaveRelation,
}: ForeignKeySelectorProps) => {
const { project } = useProjectContext()
- const [errors, setErrors] = useState<any>({})
- const [selectedForeignKey, setSelectedForeignKey] = useState<ForeignKey>({
- schema: 'public',
- table: '',
- column: '',
- deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- })
+ const snap = useTableEditorStateSnapshot()
+
+ const [fk, setFk] = useState(EMPTY_STATE)
+ const [errors, setErrors] = useState<{ columns?: string; types?: any[]; typeNotice?: any[] }>({})
+ const hasTypeErrors = (errors?.types ?? []).filter((x: any) => x !== undefined).length > 0
+ const hasTypeNotices = (errors?.typeNotice ?? []).filter((x: any) => x !== undefined).length > 0
const { data: schemas } = useSchemasQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
- // change the return type because of the includeColumns param
const { data: tables } = useTablesQuery<PostgresTable[] | undefined>({
projectRef: project?.ref,
connectionString: project?.connectionString,
- schema: selectedForeignKey.schema,
+ schema: fk.schema,
includeColumns: true,
})
- const foreignKey = column?.foreignKey
- const selectedTable: PostgresTable | undefined = find(tables, {
- name: selectedForeignKey?.table,
- schema: selectedForeignKey?.schema,
- })
- const selectedColumn: PostgresColumn | undefined = find(selectedTable?.columns ?? [], {
- name: selectedForeignKey?.column,
- })
+ const selectedTable = (tables ?? []).find((x) => x.name === fk.table && x.schema === fk.schema)
- useEffect(() => {
- // Reset the state of the side panel
- if (visible) {
- setErrors({})
-
- if (foreignKey) {
- setSelectedForeignKey({
- schema: foreignKey.target_table_schema,
- table: foreignKey.target_table_name,
- column: foreignKey.target_column_name,
- deletionAction: foreignKey.deletion_action,
- updateAction: foreignKey.update_action,
- })
- } else {
- setSelectedForeignKey({
- schema: 'public',
- table: '',
- column: '',
- deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- })
- }
- }
- }, [visible])
+ const disableApply = selectedTable === undefined || hasTypeErrors
const updateSelectedSchema = (schema: string) => {
- const updatedForeignKey = {
- schema,
- table: '',
- column: '',
- deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- }
- setSelectedForeignKey(updatedForeignKey)
+ const updatedFk = { ...EMPTY_STATE, schema }
+ setFk(updatedFk)
}
const updateSelectedTable = (tableId: number) => {
setErrors({})
if (!tableId) {
- return setSelectedForeignKey({
- schema: '',
- table: '',
- column: '',
- deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- })
+ return setFk({ ...EMPTY_STATE, schema: fk.schema, columns: [{ source: '', target: '' }] })
}
-
- const table = find(tables, { id: tableId })
- if (table) {
- const primaryColumn = table.primary_keys[0]?.name
- const firstColumn = table.columns?.length ? table.columns[0].name : undefined
-
- setSelectedForeignKey({
+ const table = (tables ?? []).find((x) => x.id === tableId)
+ if (table)
+ setFk({
+ ...EMPTY_STATE,
+ tableId: table.id,
schema: table.schema,
table: table.name,
- column: primaryColumn ?? firstColumn,
- deletionAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
+ columns: [{ source: '', target: '' }],
})
- }
}
- const updateSelectedColumn = (columnId: string) => {
- setErrors({})
- const column = find(selectedTable?.columns, { id: columnId })
- if (column) {
- const updatedForeignKey = { ...selectedForeignKey, column: column.name } as ForeignKey
- setSelectedForeignKey(updatedForeignKey)
- }
+ const addColumn = () => {
+ setFk({ ...fk, columns: fk.columns.concat([{ source: '', target: '' }]) })
+ }
+
+ const onRemoveColumn = (idx: number) => {
+ setFk({ ...fk, columns: fk.columns.filter((_, i) => i !== idx) })
+ }
+
+ const updateSelectedColumn = (idx: number, key: 'target' | 'source', value: string) => {
+ const updatedRelations = fk.columns.map((x, i) => {
+ if (i === idx) {
+ if (key === 'target') {
+ const targetType = selectedTable?.columns?.find((col) => col.name === value)?.format
+ return { ...x, [key]: value, targetType }
+ } else {
+ const sourceType = table.columns.find((col) => col.name === value)?.format as string
+ return { ...x, [key]: value, sourceType }
+ }
+ } else {
+ return x
+ }
+ })
+ setFk({ ...fk, columns: updatedRelations })
}
const updateCascadeAction = (action: 'updateAction' | 'deletionAction', value: string) => {
setErrors({})
- setSelectedForeignKey({ ...selectedForeignKey, [action]: value })
+ setFk({ ...fk, [action]: value })
}
- const onSaveChanges = (resolve: () => void) => {
- const errors = {} as Dictionary<any>
- if (!selectedForeignKey?.table) {
- errors['table'] = 'Please select a table'
- }
- if (selectedForeignKey?.table && !selectedForeignKey.column) {
- errors['column'] = `The table ${selectedForeignKey.table} has no columns`
+ const validateSelection = (resolve: any) => {
+ const errors: any = {}
+ const incompleteColumns = fk.columns.filter(
+ (column) => column.source === '' || column.target === ''
+ )
+ if (incompleteColumns.length > 0) errors['columns'] = 'Please ensure that columns are selected'
+
+ if (Object.keys(errors).length > 0) {
+ setErrors(errors)
+ resolve()
+ return
+ } else {
+ if (fk.table !== '') onSaveRelation(fk)
+ onClose()
+ resolve()
}
- setErrors(errors)
- if (isEmpty(errors)) {
- if (!selectedTable || !selectedColumn) {
- // Remove foreign key since no table selected
- saveChanges(undefined)
- } else {
- saveChanges({
- table: selectedTable,
- column: selectedColumn,
- deletionAction: selectedForeignKey.deletionAction,
- updateAction: selectedForeignKey.updateAction,
- })
+ }
+
+ const validateType = () => {
+ const typeNotice: any = []
+ const typeErrors: any = []
+
+ fk.columns.forEach((column) => {
+ const { source, target, sourceType: sType, targetType: tType } = column
+ const sourceColumn = table.columns.find((col) => col.name === source)
+ const sourceType = sType ?? sourceColumn?.format
+ const targetType =
+ tType ?? selectedTable?.columns?.find((col) => col.name === target)?.format ?? ''
+
+ // [Joshen] Doing this way so that its more readable
+ // If either source or target not selected yet, thats okay
+ if (source === '' || target === '') {
+ return typeErrors.push(undefined)
}
- }
- resolve()
+
+ if (sourceColumn?.isNewColumn && targetType !== '') {
+ return typeNotice.push({ sourceType, targetType })
+ }
+
+ // If source and target are in the same type of data types, thats okay
+ if (
+ (NUMERICAL_TYPES.includes(sourceType) && NUMERICAL_TYPES.includes(targetType)) ||
+ (TEXT_TYPES.includes(sourceType) && TEXT_TYPES.includes(targetType)) ||
+ (TEXT_TYPES.includes(sourceType) && TEXT_TYPES.includes(targetType)) ||
+ (sourceType === 'uuid' && targetType === 'uuid')
+ ) {
+ return typeErrors.push(undefined)
+ }
+
+ // Otherwise just check if the format is equal to each other
+ if (sourceType === targetType) {
+ return typeErrors.push(undefined)
+ }
+
+ typeErrors.push({ sourceType, targetType })
+ })
+
+ setErrors({ types: typeErrors, typeNotice })
}
- const matchingColumnTypes = selectedColumn?.format === column?.format
+ useEffect(() => {
+ if (visible) {
+ if (foreignKey !== undefined) setFk(foreignKey)
+ else setFk({ ...EMPTY_STATE, id: uuidv4() })
+ }
+ }, [visible])
+
+ useEffect(() => {
+ if (visible) validateType()
+ }, [fk])
return (
<SidePanel
- key="ForeignKeySelector"
- size="medium"
visible={visible}
- onCancel={closePanel}
- header={
- <span>
- Edit foreign key relation{' '}
- {column?.name && (
- <>
- for <span className="text-code">{get(column, ['name'], '')}</span>
- </>
- )}
- </span>
- }
+ onCancel={onClose}
+ className="max-w-[480px]"
+ header={`${foreignKey === undefined ? 'Add' : 'Manage'} foreign key relationship${foreignKey === undefined ? ' to' : 's for'} ${table.name.length > 0 ? table.name : 'new table'}`}
customFooter={
<ActionBar
backButtonLabel="Cancel"
- disableApply={!!column?.format && !matchingColumnTypes}
+ disableApply={disableApply}
applyButtonLabel="Save"
- closePanel={closePanel}
- applyFunction={onSaveChanges}
+ closePanel={onClose}
+ applyFunction={(resolve: any) => validateSelection(resolve)}
/>
}
>
@@ -225,11 +229,10 @@ const ForeignKeySelector = ({
<Listbox
id="schema"
label="Select a schema"
- value={selectedForeignKey.schema}
- error={errors.schema}
+ value={fk.schema}
onChange={(value: string) => updateSelectedSchema(value)}
>
- {schemas?.map((schema: PostgresSchema) => {
+ {schemas?.map((schema) => {
return (
<Listbox.Option
key={schema.id}
@@ -251,7 +254,6 @@ const ForeignKeySelector = ({
id="table"
label="Select a table to reference to"
value={selectedTable?.id ?? 1}
- error={errors.table}
onChange={(value: string) => updateSelectedTable(Number(value))}
>
<Listbox.Option key="empty" value={1} label="---">
@@ -259,7 +261,12 @@ const ForeignKeySelector = ({
</Listbox.Option>
{sortBy(tables, ['schema']).map((table) => {
return (
- <Listbox.Option key={table.id} value={table.id} label={table.name}>
+ <Listbox.Option
+ key={table.id}
+ value={table.id}
+ label={table.name}
+ addOnBefore={() => <Table size={16} strokeWidth={1.5} />}
+ >
<div className="flex items-center gap-2">
{/* For aria searching to target the table name instead of schema */}
<span className="hidden">{table.name}</span>
@@ -271,86 +278,150 @@ const ForeignKeySelector = ({
})}
</Listbox>
- {selectedForeignKey?.table && (
+ {fk.schema && fk.table && (
<>
- {(selectedTable?.columns ?? []).length === 0 ? (
- <Input
- disabled
- label={
- <div>
- Select a column from{' '}
- <code className="text-xs">
- {selectedForeignKey?.schema}.{selectedForeignKey?.table}
- </code>{' '}
- to reference to
- </div>
- }
- error={errors.column}
- placeholder="This table has no columns available"
- />
- ) : (
- <Listbox
- id="column"
- value={selectedColumn?.id}
- // @ts-ignore
- label={
- <div>
- Select a column from{' '}
- <code className="text-xs">
- {selectedForeignKey?.schema}.{selectedForeignKey?.table}
- </code>{' '}
- to reference to
- </div>
- }
- error={errors.column}
- onChange={(value: string) => updateSelectedColumn(value)}
- >
- {(selectedTable?.columns ?? []).map((column: PostgresColumn) => (
- <Listbox.Option key={column.id} value={column.id} label={column.name}>
- <div className="flex items-center gap-2">
- <span className="text-foreground">{column.name}</span>
- <span className="text-foreground-lighter">{column.format}</span>
+ <div className="flex flex-col gap-y-3">
+ <label className="text-foreground-light text-sm">
+ Select columns from{' '}
+ <code className="text-xs">
+ {fk.schema}.{fk.table}
+ </code>
+ to reference to
+ </label>
+ <div className="grid grid-cols-10 gap-y-2">
+ <div className="col-span-5 text-xs text-foreground-lighter">
+ {snap.selectedSchemaName}.
+ {table.name.length > 0 ? table.name : '[unnamed table]'}
+ </div>
+ <div className="col-span-4 text-xs text-foreground-lighter text-right">
+ {fk.schema}.{fk.table}
+ </div>
+ {fk.columns.length === 0 && (
+ <Alert_Shadcn_ className="col-span-10 py-2 px-3">
+ <AlertDescription_Shadcn_>
+ There are no foreign key relations between the tables
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )}
+ {fk.columns.map((_, idx) => (
+ <Fragment key={`${uuidv4}`}>
+ <div className="col-span-4">
+ <Listbox
+ id="column"
+ value={fk.columns[idx].source}
+ onChange={(value: string) => updateSelectedColumn(idx, 'source', value)}
+ >
+ <Listbox.Option key="empty" value={''} label="---" className="!w-[170px]">
+ ---
+ </Listbox.Option>
+ {(table?.columns ?? [])
+ .filter((x) => x.name.length !== 0)
+ .map((column) => (
+ <Listbox.Option
+ key={column.id}
+ value={column.name}
+ label={column.name}
+ className="!w-[170px]"
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-foreground">{column.name}</span>
+ <span className="text-foreground-lighter">
+ {column.format === '' ? '-' : column.format}
+ </span>
+ </div>
+ </Listbox.Option>
+ ))}
+ </Listbox>
+ </div>
+ <div className="col-span-1 flex justify-center items-center">
+ <IconArrowRight />
+ </div>
+ <div className="col-span-4">
+ <Listbox
+ id="column"
+ value={fk.columns[idx].target}
+ onChange={(value: string) => updateSelectedColumn(idx, 'target', value)}
+ >
+ <Listbox.Option key="empty" value={''} label="---" className="!w-[170px]">
+ ---
+ </Listbox.Option>
+ {(selectedTable?.columns ?? []).map((column) => (
+ <Listbox.Option
+ key={column.id}
+ value={column.name}
+ label={column.name}
+ className="!w-[170px]"
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-foreground">{column.name}</span>
+ <span className="text-foreground-lighter">{column.format}</span>
+ </div>
+ </Listbox.Option>
+ ))}
+ </Listbox>
+ </div>
+ <div className="col-span-1 flex justify-end items-center">
+ <Button
+ type="default"
+ className="px-1"
+ icon={<IconX />}
+ disabled={fk.columns.length === 1}
+ onClick={() => onRemoveColumn(idx)}
+ />
</div>
- </Listbox.Option>
+ </Fragment>
))}
- </Listbox>
- )}
- {!matchingColumnTypes && !column?.format && (
- <Alert_Shadcn_ variant="default">
- <IconAlertCircle className="h-4 w-4" />
- <AlertTitle_Shadcn_>
- The referenced column's type will be updated to {selectedColumn?.data_type}
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_ className="leading-6">
- <span>The referenced column</span>
- {column?.name && <span className="text-code">{column.name}</span>}
- <span>
- {' '}
- must match the type of the selected foreign column when creating a foreign key
- relationship.
- </span>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
- {!matchingColumnTypes && column?.format && (
- <Alert_Shadcn_ variant="warning">
- <IconAlertTriangle strokeWidth={2} />
- <AlertTitle_Shadcn_>Column types do not match</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_ className="leading-6">
- <span>The referenced column</span>
- {column?.name && <span className="text-code">{column.name}</span>}
- <span> is of type </span>
- <span className="text-code">{column.format}</span>
- <span> while the selected foreign column </span>
- <span className="text-code">
- {selectedTable?.name}.{selectedColumn?.name}
- </span>
- <span> has </span>
- <span className="text-code">{selectedColumn?.data_type}</span>type. These two
- columns can't be referenced until they are of the same type.
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )}
+ </div>
+ <div className="space-y-2">
+ <Button type="default" onClick={addColumn}>
+ Add another column
+ </Button>
+ {errors.columns && <p className="text-red-900 text-sm">{errors.columns}</p>}
+ {hasTypeErrors && (
+ <Alert_Shadcn_ variant="warning">
+ <AlertTitle_Shadcn_>Column types do not match</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ The following columns cannot be referenced as they are not of the same type:
+ </AlertDescription_Shadcn_>
+ <ul className="list-disc pl-5 mt-2 text-foreground-light">
+ {(errors?.types ?? []).map((x, idx: number) => {
+ if (x === undefined) return null
+ return (
+ <li key={`type-error-${idx}`}>
+ <code className="text-xs">{fk.columns[idx]?.source}</code> (
+ {x.sourceType}) and{' '}
+ <code className="text-xs">{fk.columns[idx]?.target}</code>(
+ {x.targetType})
+ </li>
+ )
+ })}
+ </ul>
+ </Alert_Shadcn_>
+ )}
+ {hasTypeNotices && (
+ <Alert_Shadcn_>
+ <AlertTitle_Shadcn_>Column types will be updated</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ The following columns will have their types updated to match their
+ referenced column
+ </AlertDescription_Shadcn_>
+ <ul className="list-disc pl-5 mt-2 text-foreground-light">
+ {(errors?.typeNotice ?? []).map((x, idx: number) => {
+ if (x === undefined) return null
+ return (
+ <li key={`type-error-${idx}`}>
+ <div className="flex items-center gap-x-1">
+ <code className="text-xs">{fk.columns[idx]?.source}</code>{' '}
+ <IconArrowRight /> {x.targetType}
+ </div>
+ </li>
+ )
+ })}
+ </ul>
+ </Alert_Shadcn_>
+ )}
+ </div>
+ </div>
<SidePanel.Separator />
@@ -392,18 +463,17 @@ const ForeignKeySelector = ({
<Listbox
id="updateAction"
- value={selectedForeignKey.updateAction}
+ value={fk.updateAction}
label="Action if referenced row is updated"
descriptionText={
<p>
{generateCascadeActionDescription(
'update',
- selectedForeignKey.updateAction,
- `${selectedForeignKey.schema}.${selectedForeignKey.table}`
+ fk.updateAction,
+ `${fk.schema}.${fk.table}`
)}
</p>
}
- error={errors.column}
onChange={(value: string) => updateCascadeAction('updateAction', value)}
>
{FOREIGN_KEY_CASCADE_OPTIONS.filter((option) =>
@@ -417,30 +487,32 @@ const ForeignKeySelector = ({
<Listbox
id="deletionAction"
- value={selectedForeignKey.deletionAction}
+ value={fk.deletionAction}
+ className="[&>div>label]:flex [&>div>label]:items-center"
label="Action if referenced row is removed"
+ // @ts-ignore
+ labelOptional={
+ <Button asChild type="default" icon={<IconExternalLink />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://supabase.com/docs/guides/database/postgres/cascade-deletes"
+ >
+ Documentation
+ </a>
+ </Button>
+ }
descriptionText={
<>
<p>
{generateCascadeActionDescription(
'delete',
- selectedForeignKey.deletionAction,
- `${selectedForeignKey.schema}.${selectedForeignKey.table}`
+ fk.deletionAction,
+ `${fk.schema}.${fk.table}`
)}
</p>
- <p className="mt-2">
- <a
- href="https://supabase.com/docs/guides/database/postgres/cascade-deletes"
- target="_blank"
- rel="noreferrer"
- className="text-brand opacity-75"
- >
- Learn more about cascade deletes
- </a>
- </p>
</>
}
- error={errors.column}
onChange={(value: string) => updateCascadeAction('deletionAction', value)}
>
{FOREIGN_KEY_CASCADE_OPTIONS.map((option) => (
@@ -456,5 +528,3 @@ const ForeignKeySelector = ({
</SidePanel>
)
}
-
-export default ForeignKeySelector
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
index 7dcc9d8d1fe..ac3705a3784 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
@@ -1,7 +1,12 @@
export interface ForeignKey {
+ id?: number | string
+ name?: string
+ tableId?: number
+
schema: string
table: string
- column?: string
+ columns: { source: string; sourceType?: string; target: string; targetType?: string }[]
deletionAction: string
updateAction: string
+ toRemove?: boolean
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
index 16226850d80..5b5352ac721 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils.tsx
@@ -1,7 +1,25 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { IconHelpCircle } from 'ui'
+
+import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { getForeignKeyCascadeAction } from '../ColumnEditor/ColumnEditor.utils'
+import { ForeignKey } from './ForeignKeySelector.types'
+
+export const formatForeignKeys = (fks: ForeignKeyConstraint[]): ForeignKey[] => {
+ return fks.map((x) => {
+ return {
+ id: x.id,
+ name: x.constraint_name,
+ tableId: x.target_id,
+ schema: x.target_schema,
+ table: x.target_table,
+ columns: x.source_columns.map((y, i) => ({ source: y, target: x.target_columns[i] })),
+ deletionAction: x.deletion_action,
+ updateAction: x.update_action,
+ }
+ })
+}
export const generateCascadeActionDescription = (
action: 'update' | 'delete',
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
index 1def91748b0..7e925616466 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
@@ -164,7 +164,7 @@ const ForeignRowSelector = ({
<SelectorGrid
table={supaTable}
rows={data.rows}
- onRowSelect={(row) => onSelect(row[columnName ?? ''])}
+ onRowSelect={(row) => onSelect(row[columnName?.[0] ?? ''])}
/>
) : (
<div className="flex h-full items-center justify-center border-b border-t border-default">
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants.ts
index e9d7dd63492..47140892b7f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants.ts
@@ -1,7 +1,15 @@
import { sortBy, concat } from 'lodash'
import { PostgresDataTypeOption } from './SidePanelEditor.types'
-const NUMERICAL_TYPES = ['int2', 'int4', 'int8', 'float4', 'float8', 'numeric', 'double precision']
+export const NUMERICAL_TYPES = [
+ 'int2',
+ 'int4',
+ 'int8',
+ 'float4',
+ 'float8',
+ 'numeric',
+ 'double precision',
+]
export const JSON_TYPES = ['json', 'jsonb']
export const TEXT_TYPES = ['text', 'varchar']
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index afde0a63ce3..89e11737435 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -10,6 +10,7 @@ import ConfirmationModal from 'components/ui/ConfirmationModal'
import { useDatabasePublicationCreateMutation } from 'data/database-publications/database-publications-create-mutation'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
import { useDatabasePublicationUpdateMutation } from 'data/database-publications/database-publications-update-mutation'
+import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { entityTypeKeys } from 'data/entity-types/keys'
import { sqlKeys } from 'data/sql/keys'
import { useTableRowCreateMutation } from 'data/table-rows/table-row-create-mutation'
@@ -21,15 +22,12 @@ import { useGetImpersonatedRole } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { Dictionary } from 'types'
import { ColumnEditor, RowEditor, SpreadsheetImport, TableEditor } from '.'
+import { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
import ForeignRowSelector from './RowEditor/ForeignRowSelector/ForeignRowSelector'
import JsonEdit from './RowEditor/JsonEditor/JsonEditor'
+import { TextEditor } from './RowEditor/TextEditor'
import SchemaEditor from './SchemaEditor'
-import {
- ColumnField,
- CreateColumnPayload,
- ExtendedPostgresRelationship,
- UpdateColumnPayload,
-} from './SidePanelEditor.types'
+import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
import {
createColumn,
createTable,
@@ -40,7 +38,6 @@ import {
updateTable,
} from './SidePanelEditor.utils'
import { ImportContent } from './TableEditor/TableEditor.types'
-import { TextEditor } from './RowEditor/TextEditor'
export interface SidePanelEditorProps {
editable?: boolean
@@ -211,7 +208,6 @@ const SidePanelEditor = ({
const saveColumn = async (
payload: CreateColumnPayload | UpdateColumnPayload,
- foreignKey: ExtendedPostgresRelationship | undefined,
isNewRecord: boolean,
configuration: { columnId?: string },
resolve: any
@@ -225,7 +221,6 @@ const SidePanelEditor = ({
connectionString: project?.connectionString,
payload: payload as CreateColumnPayload,
selectedTable: selectedTable as PostgresTable,
- foreignKey,
})
: await updateColumn({
projectRef: project?.ref!,
@@ -233,7 +228,6 @@ const SidePanelEditor = ({
id: columnId as string,
payload: payload as UpdateColumnPayload,
selectedTable: selectedTable as PostgresTable,
- foreignKey,
})
if (response?.error) {
@@ -366,6 +360,7 @@ const SidePanelEditor = ({
comment?: string | undefined
},
columns: ColumnField[],
+ foreignKeyRelations: ForeignKey[],
isNewRecord: boolean,
configuration: {
tableId?: number
@@ -373,12 +368,19 @@ const SidePanelEditor = ({
isRLSEnabled: boolean
isRealtimeEnabled: boolean
isDuplicateRows: boolean
+ existingForeignKeyRelations: ForeignKeyConstraint[]
},
resolve: any
) => {
let toastId
let saveTableError = false
- const { importContent, isRLSEnabled, isRealtimeEnabled, isDuplicateRows } = configuration
+ const {
+ importContent,
+ isRLSEnabled,
+ isRealtimeEnabled,
+ isDuplicateRows,
+ existingForeignKeyRelations,
+ } = configuration
try {
if (
@@ -388,15 +390,13 @@ const SidePanelEditor = ({
) {
const tableToDuplicate = selectedTable
- toastId = ui.setNotification({
- category: 'loading',
- message: `Duplicating table: ${tableToDuplicate.name}...`,
- })
+ toastId = toast.loading(`Duplicating table: ${tableToDuplicate.name}...`)
const table = await duplicateTable(project?.ref!, project?.connectionString, payload, {
isRLSEnabled,
isDuplicateRows,
duplicateTable: tableToDuplicate,
+ foreignKeyRelations,
})
if (isRealtimeEnabled) await updateTableRealtime(table, isRealtimeEnabled)
@@ -405,28 +405,24 @@ const SidePanelEditor = ({
queryClient.invalidateQueries(entityTypeKeys.list(project?.ref)),
])
- ui.setNotification({
- id: toastId,
- category: 'success',
- message: `Table ${tableToDuplicate.name} has been successfully duplicated into ${table.name}!`,
- })
-
+ toast.success(
+ `Table ${tableToDuplicate.name} has been successfully duplicated into ${table.name}!`,
+ { id: toastId }
+ )
onTableCreated(table)
} else if (isNewRecord) {
- toastId = ui.setNotification({
- category: 'loading',
- message: `Creating new table: ${payload.name}...`,
- })
+ toastId = toast.loading(`Creating new table: ${payload.name}...`)
- const table = await createTable(
- project?.ref!,
- project?.connectionString,
+ const table = await createTable({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
toastId,
payload,
columns,
+ foreignKeyRelations,
isRLSEnabled,
- importContent
- )
+ importContent,
+ })
if (isRealtimeEnabled) await updateTableRealtime(table as PostgresTable, true)
await Promise.all([
@@ -434,36 +430,26 @@ const SidePanelEditor = ({
queryClient.invalidateQueries(entityTypeKeys.list(project?.ref)),
])
- ui.setNotification({
- id: toastId,
- category: 'success',
- message: `Table ${table.name} is good to go!`,
- })
-
+ toast.success(`Table ${table.name} is good to go!`, { id: toastId })
onTableCreated(table as PostgresTable)
} else if (selectedTable) {
- toastId = ui.setNotification({
- category: 'loading',
- message: `Updating table: ${selectedTable?.name}...`,
- })
+ toastId = toast.loading(`Updating table: ${selectedTable?.name}...`)
- const { table, hasError } = await updateTable(
- project?.ref!,
- project?.connectionString,
+ const { table, hasError } = await updateTable({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
toastId,
- selectedTable,
+ table: selectedTable,
payload,
- columns
- )
+ columns,
+ foreignKeyRelations,
+ existingForeignKeyRelations,
+ })
await updateTableRealtime(table, isRealtimeEnabled)
if (hasError) {
- ui.setNotification({
- id: toastId,
- category: 'info',
- message: `Table ${table.name} has been updated, but there were some errors`,
- })
+ toast(`Table ${table.name} has been updated, but there were some errors`, { id: toastId })
} else {
queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints']))
await Promise.all([
@@ -481,16 +467,12 @@ const SidePanelEditor = ({
queryClient.invalidateQueries(tableKeys.table(project?.ref, table.id)),
])
- ui.setNotification({
- id: toastId,
- category: 'success',
- message: `Successfully updated ${table.name}!`,
- })
+ toast.success(`Successfully updated ${table.name}!`, { id: toastId })
}
}
} catch (error: any) {
saveTableError = true
- ui.setNotification({ error, id: toastId, category: 'error', message: error.message })
+ toast.error(error.message, { id: toastId })
}
if (!saveTableError) {
@@ -637,6 +619,7 @@ const SidePanelEditor = ({
/>
<ForeignRowSelector
visible={snap.sidePanel?.type === 'foreign-row-selector'}
+ // @ts-ignore
foreignKey={
snap.sidePanel?.type === 'foreign-row-selector'
? snap.sidePanel.foreignKey.foreignKey
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
index d877d66223c..508e0be22f1 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
@@ -43,11 +43,13 @@ export interface ExtendedPostgresRelationship extends PostgresRelationship {
export interface ColumnField {
id: string
name: string
+ table: string
+ schema: string
check: string | null
comment?: string
format: string
defaultValue: string | null
- foreignKey: ExtendedPostgresRelationship | undefined
+ foreignKey?: ExtendedPostgresRelationship
isNullable: boolean
isUnique: boolean
isArray: boolean
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index cc69c0880ad..a240a4718aa 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -1,16 +1,20 @@
-import { PostgresPrimaryKey, PostgresRelationship, PostgresTable } from '@supabase/postgres-meta'
+import { PostgresPrimaryKey, PostgresTable } from '@supabase/postgres-meta'
import { chunk, find, isEmpty, isEqual } from 'lodash'
import Papa from 'papaparse'
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Query } from 'components/grid/query/Query'
+import SparkBar from 'components/ui/SparkBar'
import { createDatabaseColumn } from 'data/database-columns/database-column-create-mutation'
import { deleteDatabaseColumn } from 'data/database-columns/database-column-delete-mutation'
import { updateDatabaseColumn } from 'data/database-columns/database-column-update-mutation'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
+import { entityTypeKeys } from 'data/entity-types/keys'
import { getQueryClient } from 'data/query-client'
import { executeSql } from 'data/sql/execute-sql-query'
+import { sqlKeys } from 'data/sql/keys'
import { tableKeys } from 'data/tables/keys'
import { createTable as createTableMutation } from 'data/tables/table-create-mutation'
import { deleteTable as deleteTableMutation } from 'data/tables/table-delete-mutation'
@@ -25,16 +29,10 @@ import {
generateCreateColumnPayload,
generateUpdateColumnPayload,
} from './ColumnEditor/ColumnEditor.utils'
-import {
- ColumnField,
- CreateColumnPayload,
- ExtendedPostgresRelationship,
- UpdateColumnPayload,
-} from './SidePanelEditor.types'
+import { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
+import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
+import { checkIfRelationChanged } from './TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'
import { ImportContent } from './TableEditor/TableEditor.types'
-import { sqlKeys } from 'data/sql/keys'
-import { entityTypeKeys } from 'data/entity-types/keys'
-import SparkBar from 'components/ui/SparkBar'
const BATCH_SIZE = 1000
const CHUNK_SIZE = 1024 * 1024 * 0.1 // 0.1MB
@@ -129,40 +127,62 @@ export const removePrimaryKey = async (
})
}
-// [Joshen TODO] Eventually need to extend this to composite foreign keys
-export const addForeignKey = async (
- projectRef: string,
- connectionString: string | undefined,
- relationship: ExtendedPostgresRelationship
-) => {
- const { deletion_action, update_action } = relationship
- const deletionAction =
- deletion_action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
+export const getAddForeignKeySQL = ({
+ table,
+ foreignKeys,
+}: {
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ const getOnDeleteSql = (action: string) =>
+ action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
? 'ON DELETE CASCADE'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
? 'ON DELETE RESTRICT'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
+ : action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
? 'ON DELETE SET DEFAULT'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
+ : action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
? 'ON DELETE SET NULL'
: ''
- const updateAction =
- update_action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
+ const getOnUpdateSql = (action: string) =>
+ action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
? 'ON UPDATE CASCADE'
- : update_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ : action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
? 'ON UPDATE RESTRICT'
: ''
+ return (
+ foreignKeys
+ .map((relation) => {
+ const { deletionAction, updateAction } = relation
+ const onDeleteSql = getOnDeleteSql(deletionAction)
+ const onUpdateSql = getOnUpdateSql(updateAction)
+ return `
+ ALTER TABLE "${table.schema}"."${table.name}"
+ ADD CONSTRAINT "${table.schema}_${table.name}_${relation.columns.map((x) => x.source).join('_')}_fkey"
+ FOREIGN KEY (${relation.columns.map((column) => `"${column.source}"`).join(',')})
+ REFERENCES "${relation.schema}"."${relation.table}" (${relation.columns.map((column) => `"${column.target}"`).join(',')})
+ ${onUpdateSql}
+ ${onDeleteSql}
+ `
+ .replace(/\s+/g, ' ')
+ .trim()
+ })
+ .join(';') + ';'
+ )
+}
- const query = `
- ALTER TABLE "${relationship.source_schema}"."${relationship.source_table_name}"
- ADD CONSTRAINT "${relationship.source_table_name}_${relationship.source_column_name}_fkey"
- FOREIGN KEY ("${relationship.source_column_name}")
- REFERENCES "${relationship.target_table_schema}"."${relationship.target_table_name}" ("${relationship.target_column_name}")
- ${updateAction}
- ${deletionAction};
- `
- .replace(/\s+/g, ' ')
- .trim()
+export const addForeignKey = async ({
+ projectRef,
+ connectionString,
+ table,
+ foreignKeys,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ const query = getAddForeignKeySQL({ table, foreignKeys })
return await executeSql({
projectRef: projectRef,
connectionString: connectionString,
@@ -171,17 +191,61 @@ export const addForeignKey = async (
})
}
-export const removeForeignKey = async (
- projectRef: string,
- connectionString: string | undefined,
- relationship: Partial<PostgresRelationship>
-) => {
- const constraintName =
- relationship.constraint_name ||
- `${relationship.source_table_name}_${relationship.source_column_name}_fkey`
+export const getRemoveForeignKeySQL = ({
+ table,
+ foreignKeys,
+}: {
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ return (
+ foreignKeys
+ .map((relation) =>
+ `
+ALTER TABLE IF EXISTS "${table.schema}"."${table.name}"
+DROP CONSTRAINT IF EXISTS "${relation.name}"
+`
+ .replace(/\s+/g, ' ')
+ .trim()
+ )
+ .join(';') + ';'
+ )
+}
+
+export const removeForeignKey = async ({
+ projectRef,
+ connectionString,
+ table,
+ foreignKeys,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
+ const query = getRemoveForeignKeySQL({ table, foreignKeys })
+ return await executeSql({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ sql: query,
+ queryKey: ['foreign-keys'],
+ })
+}
+
+export const updateForeignKey = async ({
+ projectRef,
+ connectionString,
+ table,
+ foreignKeys,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ table: { schema: string; name: string }
+ foreignKeys: ForeignKey[]
+}) => {
const query = `
- ALTER TABLE "${relationship.source_schema}"."${relationship.source_table_name}"
- DROP CONSTRAINT IF EXISTS "${constraintName}"
+ ${getRemoveForeignKeySQL({ table, foreignKeys })}
+ ${getAddForeignKeySQL({ table, foreignKeys })}
`
.replace(/\s+/g, ' ')
.trim()
@@ -202,13 +266,11 @@ export const createColumn = async ({
connectionString,
payload,
selectedTable,
- foreignKey,
}: {
projectRef: string
connectionString: string | undefined
payload: CreateColumnPayload
selectedTable: PostgresTable
- foreignKey?: ExtendedPostgresRelationship
}) => {
const toastId = toast.loading(`Creating column "${payload.name}"...`)
try {
@@ -239,12 +301,6 @@ export const createColumn = async ({
primaryKeyColumns
)
}
-
- if (foreignKey !== undefined) {
- toast.loading('Adding foreign key to column...', { id: toastId })
- await addForeignKey(projectRef, connectionString, foreignKey)
- }
-
toast.success(`Successfully created column "${column.name}"`, { id: toastId })
} catch (error: any) {
toast.error(`An error occurred while creating the column "${payload.name}"`, { id: toastId })
@@ -258,7 +314,6 @@ export const updateColumn = async ({
id,
payload,
selectedTable,
- foreignKey,
skipPKCreation,
skipSuccessMessage = false,
}: {
@@ -267,7 +322,6 @@ export const updateColumn = async ({
id: string
payload: UpdateColumnPayload
selectedTable: PostgresTable
- foreignKey?: ExtendedPostgresRelationship
skipPKCreation?: boolean
skipSuccessMessage?: boolean
}) => {
@@ -280,11 +334,6 @@ export const updateColumn = async ({
payload: formattedPayload,
})
- const originalColumn = selectedTable.columns?.find((c) => c.id === id)
- const existingForeignKey = selectedTable.relationships.find(
- (r) => r.source_column_name === originalColumn!.name
- )
-
if (!skipPKCreation && isPrimaryKey !== undefined) {
const existingPrimaryKeys = selectedTable.primary_keys.map((x) => x.name)
@@ -307,20 +356,7 @@ export const updateColumn = async ({
)
}
}
-
- // For updating of foreign key relationship, we remove the original one by default
- // Then just add whatever was in foreignKey - simplicity over trying to derive whether to update or not
- if (existingForeignKey !== undefined) {
- await removeForeignKey(projectRef, connectionString, existingForeignKey)
- }
-
- if (foreignKey !== undefined) {
- await addForeignKey(projectRef, connectionString, foreignKey)
- }
-
- if (!skipSuccessMessage) {
- toast.success(`Successfully updated column "${column.name}"`)
- }
+ if (!skipSuccessMessage) toast.success(`Successfully updated column "${column.name}"`)
} catch (error: any) {
return { error }
}
@@ -334,9 +370,11 @@ export const duplicateTable = async (
duplicateTable: PostgresTable
isRLSEnabled: boolean
isDuplicateRows: boolean
+ foreignKeyRelations: ForeignKey[]
}
) => {
- const { duplicateTable, isRLSEnabled, isDuplicateRows } = metadata
+ const queryClient = getQueryClient()
+ const { duplicateTable, isRLSEnabled, isDuplicateRows, foreignKeyRelations } = metadata
const { name: sourceTableName, schema: sourceTableSchema } = duplicateTable
const duplicatedTableName = payload.name
@@ -347,23 +385,21 @@ export const duplicateTable = async (
connectionString,
sql: `CREATE TABLE "${sourceTableSchema}"."${duplicatedTableName}" (LIKE "${sourceTableSchema}"."${sourceTableName}" INCLUDING ALL);`,
})
+ await queryClient.invalidateQueries(tableKeys.list(projectRef, sourceTableSchema))
// Duplicate foreign key constraints over
- const relationships = duplicateTable.relationships
- if (relationships.length > 0) {
- relationships.map(async (relationship: PostgresRelationship) => {
- await addForeignKey(projectRef, connectionString, {
- ...relationship,
- source_table_name: duplicatedTableName,
- deletion_action: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- update_action: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- })
+ if (foreignKeyRelations.length > 0) {
+ await addForeignKey({
+ projectRef,
+ connectionString,
+ table: { ...duplicateTable, name: payload.name },
+ foreignKeys: foreignKeyRelations,
})
}
// Duplicate rows if needed
if (isDuplicateRows) {
- const rows = await executeSql({
+ await executeSql({
projectRef,
connectionString,
sql: `INSERT INTO "${sourceTableSchema}"."${duplicatedTableName}" SELECT * FROM "${sourceTableSchema}"."${sourceTableName}";`,
@@ -373,7 +409,7 @@ export const duplicateTable = async (
const columns = duplicateTable.columns ?? []
const identityColumns = columns.filter((column) => column.identity_generation !== null)
identityColumns.map(async (column) => {
- const identity = await executeSql({
+ await executeSql({
projectRef,
connectionString,
sql: `SELECT setval('"${sourceTableSchema}"."${duplicatedTableName}_${column.name}_seq"', (SELECT MAX("${column.name}") FROM "${sourceTableSchema}"."${sourceTableName}"));`,
@@ -381,7 +417,6 @@ export const duplicateTable = async (
})
}
- const queryClient = getQueryClient()
const tables = await queryClient.fetchQuery({
queryKey: tableKeys.list(projectRef, sourceTableSchema),
queryFn: ({ signal }) =>
@@ -403,19 +438,29 @@ export const duplicateTable = async (
return duplicatedTable
}
-export const createTable = async (
- projectRef: string,
- connectionString: string | undefined,
- toastId: string,
+export const createTable = async ({
+ projectRef,
+ connectionString,
+ toastId,
+ payload,
+ columns = [],
+ foreignKeyRelations,
+ isRLSEnabled,
+ importContent,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ toastId: string
payload: {
name: string
schema: string
comment?: string | undefined
- },
- columns: ColumnField[] = [],
- isRLSEnabled: boolean,
+ }
+ columns: ColumnField[]
+ foreignKeyRelations: ForeignKey[]
+ isRLSEnabled: boolean
importContent?: ImportContent
-) => {
+}) => {
// Create the table first. Error may be thrown.
const table = await createTableMutation({
projectRef: projectRef,
@@ -466,10 +511,13 @@ export const createTable = async (
}
// Then add the foreign key constraints here
- for (const column of columns) {
- if (column.foreignKey !== undefined) {
- await addForeignKey(projectRef, connectionString, column.foreignKey)
- }
+ if (foreignKeyRelations.length > 0) {
+ await addForeignKey({
+ projectRef,
+ connectionString,
+ table: { schema: table.schema, name: table.name },
+ foreignKeys: foreignKeyRelations,
+ })
}
// If the user is importing data via a spreadsheet
@@ -570,14 +618,25 @@ export const createTable = async (
}
}
-export const updateTable = async (
- projectRef: string,
- connectionString: string | undefined,
- toastId: string,
- table: PostgresTable,
- payload: any,
+export const updateTable = async ({
+ projectRef,
+ connectionString,
+ toastId,
+ table,
+ payload,
+ columns,
+ foreignKeyRelations,
+ existingForeignKeyRelations,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ toastId: string
+ table: PostgresTable
+ payload: any
columns: ColumnField[]
-) => {
+ foreignKeyRelations: ForeignKey[]
+ existingForeignKeyRelations: ForeignKeyConstraint[]
+}) => {
// Prepare a check to see if primary keys to the tables were updated or not
const primaryKeyColumns = columns
.filter((column) => column.isPrimaryKey)
@@ -635,7 +694,6 @@ export const updateTable = async (
connectionString: connectionString,
payload: columnPayload,
selectedTable: updatedTable as PostgresTable,
- foreignKey: column.foreignKey,
})
} else {
const originalColumn = find(originalColumns, { id: column.id })
@@ -645,14 +703,7 @@ export const updateTable = async (
updatedTable as PostgresTable,
column
)
- const originalForeignKey = find(table.relationships, {
- source_schema: originalColumn.schema,
- source_table_name: originalColumn.table,
- source_column_name: originalColumn.name,
- })
-
- const hasForeignKeyUpdated = !isEqual(originalForeignKey, column.foreignKey)
- if (!isEmpty(columnPayload) || hasForeignKeyUpdated) {
+ if (!isEmpty(columnPayload)) {
toast.loading(`Updating column ${column.name} from ${updatedTable.name}`, { id: toastId })
const skipPKCreation = true
const skipSuccessMessage = true
@@ -662,7 +713,6 @@ export const updateTable = async (
id: column.id,
payload: columnPayload,
selectedTable: updatedTable as PostgresTable,
- foreignKey: column.foreignKey,
skipPKCreation,
skipSuccessMessage,
})
@@ -686,6 +736,43 @@ export const updateTable = async (
)
}
+ // Foreign keys will get updated here accordingly
+ const relationsToAdd = foreignKeyRelations.filter((x) => x.id === undefined)
+ if (relationsToAdd.length > 0) {
+ await addForeignKey({
+ projectRef,
+ connectionString,
+ table: updatedTable,
+ foreignKeys: relationsToAdd,
+ })
+ }
+
+ const relationsToRemove = foreignKeyRelations.filter((x) => x.toRemove)
+ if (relationsToRemove.length > 0) {
+ await removeForeignKey({
+ projectRef,
+ connectionString,
+ table: updatedTable,
+ foreignKeys: relationsToRemove,
+ })
+ }
+
+ const remainingRelations = foreignKeyRelations.filter((x) => x.id !== undefined && !x.toRemove)
+ const relationsToUpdate = remainingRelations.filter((x) => {
+ const existingRelation = existingForeignKeyRelations.find((y) => x.id === y.id)
+ if (existingRelation !== undefined) {
+ return checkIfRelationChanged(existingRelation as unknown as ForeignKeyConstraint, x)
+ } else return false
+ })
+ if (relationsToUpdate.length > 0) {
+ await updateForeignKey({
+ projectRef,
+ connectionString,
+ table: updatedTable,
+ foreignKeys: relationsToUpdate,
+ })
+ }
+
const queryClient = getQueryClient()
await Promise.all([
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx
index 97700a9c2e3..ccac707e934 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/Column.tsx
@@ -1,26 +1,13 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
import type { PostgresType } from '@supabase/postgres-meta'
-
-import {
- Button,
- Checkbox,
- IconArrowRight,
- IconLink,
- IconMenu,
- IconSettings,
- IconX,
- Input,
- Popover,
-} from 'ui'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { noop } from 'lodash'
+import { Checkbox, IconMenu, IconSettings, IconX, Input, Popover } from 'ui'
+
+import { EMPTY_ARR, EMPTY_OBJ } from 'lib/void'
import { typeExpressionSuggestions } from '../ColumnEditor/ColumnEditor.constants'
import { Suggestion } from '../ColumnEditor/ColumnEditor.types'
-import { getForeignKeyCascadeAction } from '../ColumnEditor/ColumnEditor.utils'
import ColumnType from '../ColumnEditor/ColumnType'
import InputWithSuggestions from '../ColumnEditor/InputWithSuggestions'
import { ColumnField } from '../SidePanelEditor.types'
-import { EMPTY_ARR, EMPTY_OBJ } from 'lib/void'
/**
* [Joshen] For context:
@@ -44,9 +31,9 @@ interface ColumnProps {
column: ColumnField
enumTypes: PostgresType[]
isNewRecord: boolean
+ hasForeignKeys: boolean
hasImportContent: boolean
dragHandleProps?: any
- onEditRelation: (column: any) => void
onUpdateColumn: (changes: Partial<ColumnField>) => void
onRemoveColumn: () => void
}
@@ -55,9 +42,9 @@ const Column = ({
column = EMPTY_OBJ as ColumnField,
enumTypes = EMPTY_ARR as PostgresType[],
isNewRecord = false,
+ hasForeignKeys = false,
hasImportContent = false,
dragHandleProps = EMPTY_OBJ,
- onEditRelation = noop,
onUpdateColumn = noop,
onRemoveColumn = noop,
}: ColumnProps) => {
@@ -77,7 +64,7 @@ const Column = ({
<IconMenu strokeWidth={1} size={15} />
</div>
</div>
- <div className="w-[20%]">
+ <div className="w-[25%]">
<div className="flex w-[95%] items-center justify-between">
<Input
value={column.name}
@@ -92,54 +79,6 @@ const Column = ({
/>
</div>
</div>
- <div className="w-[5%] mr-2.5">
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type={column.foreignKey !== undefined ? 'secondary' : 'default'}
- onClick={() => onEditRelation(column)}
- className="px-1 py-2"
- >
- <IconLink size={14} strokeWidth={column.foreignKey !== undefined ? 2 : 1} />
- </Button>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background
- 'border border-background', //border
- ].join(' ')}
- >
- {column.foreignKey === undefined ? (
- <span className="text-xs text-foreground">Edit foreign key relation</span>
- ) : (
- <div>
- <p className="text-xs text-foreground-light">Foreign key relation:</p>
- <div className="flex items-center space-x-1">
- <p className="text-xs text-foreground">
- {column.foreignKey.source_schema}.{column.foreignKey.source_table_name}.
- {column.foreignKey.source_column_name}
- </p>
- <IconArrowRight size="tiny" strokeWidth={1.5} />
- <p className="text-xs text-foreground">
- {column.foreignKey.target_table_schema}.
- {column.foreignKey.target_table_name}.{column.foreignKey.target_column_name}
- </p>
- </div>
- {column.foreignKey.deletion_action !== FOREIGN_KEY_CASCADE_ACTION.NO_ACTION && (
- <p className="text-xs text-foreground mt-1">
- On delete: {getForeignKeyCascadeAction(column.foreignKey.deletion_action)}
- </p>
- )}
- </div>
- )}
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- </div>
<div className="w-[25%]">
<div className="w-[95%]">
<ColumnType
@@ -148,7 +87,10 @@ const Column = ({
size="small"
showLabel={false}
className="table-editor-column-type lg:gap-0 "
- disabled={column.foreignKey !== undefined}
+ disabled={hasForeignKeys}
+ description={
+ hasForeignKeys ? 'Column type cannot be changed as it has a foreign key relation' : ''
+ }
onOptionSelect={(format: string) => {
const defaultValue = format === 'uuid' ? 'gen_random_uuid()' : null
onUpdateColumn({ format, defaultValue })
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ColumnManagement.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ColumnManagement.tsx
index ddf764cd3e4..aa3b0193ce6 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ColumnManagement.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ColumnManagement.tsx
@@ -1,8 +1,6 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import type { PostgresColumn, PostgresTable, PostgresType } from '@supabase/postgres-meta'
+import type { PostgresType } from '@supabase/postgres-meta'
import { isEmpty, noop, partition } from 'lodash'
-import Link from 'next/link'
-import { useState } from 'react'
import {
DragDropContext,
Draggable,
@@ -14,15 +12,15 @@ import { Alert, Button, IconEdit, IconExternalLink, IconHelpCircle, IconKey, Ico
import InformationBox from 'components/ui/InformationBox'
import { generateColumnField } from '../ColumnEditor/ColumnEditor.utils'
-import ForeignKeySelector from '../ForeignKeySelector/ForeignKeySelector'
+import { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import { TEXT_TYPES } from '../SidePanelEditor.constants'
import { ColumnField, ExtendedPostgresRelationship } from '../SidePanelEditor.types'
import Column from './Column'
import { ImportContent } from './TableEditor.types'
interface ColumnManagementProps {
- table?: Partial<PostgresTable>
columns?: ColumnField[]
+ relations: ForeignKey[]
enumTypes: PostgresType[]
importContent?: ImportContent
isNewRecord: boolean
@@ -32,8 +30,8 @@ interface ColumnManagementProps {
}
const ColumnManagement = ({
- table,
columns = [],
+ relations,
enumTypes = [],
importContent,
isNewRecord,
@@ -41,44 +39,17 @@ const ColumnManagement = ({
onSelectImportData = noop,
onClearImportContent = noop,
}: ColumnManagementProps) => {
- const [selectedColumnToEditRelation, setSelectedColumnToEditRelation] = useState<ColumnField>()
-
const hasImportContent = !isEmpty(importContent)
const [primaryKeyColumns, otherColumns] = partition(
columns,
(column: ColumnField) => column.isPrimaryKey
)
- const saveColumnForeignKey = (foreignKeyConfiguration?: {
- table: PostgresTable
- column: PostgresColumn
- deletionAction: string
- updateAction: string
- }) => {
- if (selectedColumnToEditRelation !== undefined) {
- onUpdateColumn(selectedColumnToEditRelation, {
- foreignKey:
- foreignKeyConfiguration !== undefined
- ? {
- id: 0,
- constraint_name: '',
- source_schema: table?.schema ?? '',
- source_table_name: table?.name ?? '',
- source_column_name: selectedColumnToEditRelation?.name,
- target_table_schema: foreignKeyConfiguration.table.schema,
- target_table_name: foreignKeyConfiguration.table.name,
- target_column_name: foreignKeyConfiguration.column.name,
- deletion_action: foreignKeyConfiguration.deletionAction,
- update_action: foreignKeyConfiguration.updateAction,
- }
- : undefined,
- ...(foreignKeyConfiguration !== undefined && {
- format: foreignKeyConfiguration.column.format,
- defaultValue: null,
- }),
- })
- }
- setSelectedColumnToEditRelation(undefined)
+ const checkIfHaveForeignKeys = (column: ColumnField) => {
+ return (
+ relations.find((relation) => relation.columns.find((x) => x.source === column.name)) !==
+ undefined
+ )
}
const onUpdateColumn = (columnToUpdate: ColumnField, changes: Partial<ColumnField>) => {
@@ -143,24 +114,36 @@ const ColumnManagement = ({
<div className="w-full space-y-4 table-editor-columns">
<div className="flex items-center justify-between w-full">
<h5>Columns</h5>
- {isNewRecord && (
- <>
- {hasImportContent ? (
- <div className="flex items-center space-x-3">
- <Button type="default" icon={<IconEdit />} onClick={onSelectImportData}>
- Edit content
- </Button>
- <Button type="danger" icon={<IconTrash />} onClick={onClearImportContent}>
- Remove content
+ <div className="flex items-center gap-x-2">
+ <Button asChild type="default" icon={<IconExternalLink size={12} strokeWidth={2} />}>
+ <a
+ href="https://supabase.com/docs/guides/database/tables#data-types"
+ target="_blank"
+ rel="noreferrer"
+ >
+ About data types
+ </a>
+ </Button>
+ {isNewRecord && (
+ <>
+ <div className="py-3 border-r" />
+ {hasImportContent ? (
+ <div className="flex items-center gap-x-2">
+ <Button type="default" icon={<IconEdit />} onClick={onSelectImportData}>
+ Edit content
+ </Button>
+ <Button type="danger" icon={<IconTrash />} onClick={onClearImportContent}>
+ Remove content
+ </Button>
+ </div>
+ ) : (
+ <Button type="default" onClick={onSelectImportData}>
+ Import data via spreadsheet
</Button>
- </div>
- ) : (
- <Button type="default" onClick={onSelectImportData}>
- Import data via spreadsheet
- </Button>
- )}
- </>
- )}
+ )}
+ </>
+ )}
+ </div>
</div>
{hasImportContent && (
@@ -207,7 +190,7 @@ const ColumnManagement = ({
<div
className={[
'rounded bg-alternative py-1 px-2 leading-none shadow', // background
- 'border border-background', //border
+ 'border border-background w-[300px]', //border
].join(' ')}
>
<span className="text-xs text-foreground">
@@ -237,7 +220,7 @@ const ColumnManagement = ({
<div
className={[
'rounded bg-alternative py-1 px-2 leading-none shadow', // background
- 'border border-background', //border
+ 'border border-background w-[300px]', //border
].join(' ')}
>
<span className="text-xs text-foreground">
@@ -280,12 +263,10 @@ const ColumnManagement = ({
<Column
column={column}
enumTypes={enumTypes}
+ hasForeignKeys={checkIfHaveForeignKeys(column)}
isNewRecord={isNewRecord}
hasImportContent={hasImportContent}
dragHandleProps={draggableProvided.dragHandleProps}
- onEditRelation={() => {
- setSelectedColumnToEditRelation(column)
- }}
onUpdateColumn={(changes) => onUpdateColumn(column, changes)}
onRemoveColumn={() => onRemoveColumn(column)}
/>
@@ -315,11 +296,9 @@ const ColumnManagement = ({
column={column}
enumTypes={enumTypes}
isNewRecord={isNewRecord}
+ hasForeignKeys={checkIfHaveForeignKeys(column)}
hasImportContent={hasImportContent}
dragHandleProps={draggableProvided.dragHandleProps}
- onEditRelation={() => {
- setSelectedColumnToEditRelation(column)
- }}
onUpdateColumn={(changes) => onUpdateColumn(column, changes)}
onRemoveColumn={() => onRemoveColumn(column)}
/>
@@ -334,34 +313,14 @@ const ColumnManagement = ({
</DragDropContext>
</div>
- <div className="flex items-center justify-between">
- {!hasImportContent && (
+ {!hasImportContent && (
+ <div className="flex items-center justify-center rounded border border-strong border-dashed py-3">
<Button type="default" onClick={() => onAddColumn()}>
Add column
</Button>
- )}
- <Button
- asChild
- type="text"
- className="text-foreground-light hover:text-foreground"
- icon={<IconExternalLink size={12} strokeWidth={2} />}
- >
- <Link
- href="https://supabase.com/docs/guides/database/tables#data-types"
- target="_blank"
- rel="noreferrer"
- >
- Learn more about data types
- </Link>
- </Button>
- </div>
+ </div>
+ )}
</div>
- <ForeignKeySelector
- column={selectedColumnToEditRelation as ColumnField}
- visible={selectedColumnToEditRelation !== undefined}
- closePanel={() => setSelectedColumnToEditRelation(undefined)}
- saveChanges={saveColumnForeignKey}
- />
</>
)
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeyRow.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeyRow.tsx
new file mode 100644
index 00000000000..3787487df2d
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeyRow.tsx
@@ -0,0 +1,115 @@
+import clsx from 'clsx'
+import { useParams } from 'common'
+import Link from 'next/link'
+import SVG from 'react-inlinesvg'
+import { Badge, Button, IconArrowRight } from 'ui'
+
+import { BASE_PATH } from 'lib/constants'
+import { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
+
+interface ForeignKeyProps {
+ foreignKey: ForeignKey
+ disabled?: boolean
+ status?: 'ADD' | 'UPDATE' | 'REMOVE'
+ layout?: 'vertical' | 'horizontal'
+ closePanel: () => void
+ onSelectEdit: () => void
+ onSelectRemove: () => void
+ onSelectUndoRemove: () => void
+}
+
+export const ForeignKeyRow = ({
+ foreignKey,
+ disabled = false,
+ status,
+ layout = 'horizontal',
+ closePanel,
+ onSelectEdit,
+ onSelectRemove,
+ onSelectUndoRemove,
+}: ForeignKeyProps) => {
+ const { ref } = useParams()
+
+ return (
+ <div
+ className={clsx(
+ layout === 'horizontal' ? 'items-center justify-between gap-x-2' : 'flex-col gap-y-3',
+ 'flex border border-strong px-4 py-4',
+ 'border-b-0 last:border-b first:rounded-t-md last:rounded-b-md'
+ )}
+ >
+ <div className="flex flex-col gap-y-2">
+ <div className="flex flex-col gap-y-1">
+ {foreignKey.name && (
+ <p title={foreignKey.name} className="text-xs text-foreground font-mono">
+ {foreignKey.name}
+ </p>
+ )}
+ <div className="flex items-center gap-x-2">
+ {status !== undefined && (
+ <Badge color={status === 'ADD' ? 'green' : status === 'UPDATE' ? 'amber' : 'red'}>
+ {status}
+ </Badge>
+ )}
+ <p className="text-sm text-foreground-light">
+ {foreignKey.columns.length > 1 ? 'Composite foreign' : 'Foreign'} key relation to:
+ </p>
+ <Button
+ asChild
+ type="default"
+ title={`${foreignKey.schema}.${foreignKey.table}`}
+ className="py-0.5 px-1.5 font-mono"
+ icon={
+ <SVG
+ className="table-icon"
+ src={`${BASE_PATH}/img/icons/table-icon.svg`}
+ style={{ width: `16px`, height: `16px`, strokeWidth: '1px' }}
+ preProcessor={(code: any) =>
+ code.replace(/svg/, 'svg class="m-auto text-color-inherit"')
+ }
+ loader={<span className="block w-4 h-4 bg-[#133929] rounded-sm" />}
+ cacheRequests={true}
+ />
+ }
+ >
+ <Link
+ href={`/project/${ref}/editor/${foreignKey.tableId}`}
+ onClick={() => closePanel()}
+ >
+ {foreignKey.schema}.{foreignKey.table}
+ </Link>
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-y-1">
+ {foreignKey.columns.map((x, idx) => (
+ <div key={`relation-${idx}}`} className="flex items-center gap-x-2">
+ <code className="text-xs">{x.source}</code>
+ <IconArrowRight />
+ <code className="text-xs">
+ {foreignKey.schema}.{foreignKey.table}.{x.target}
+ </code>
+ </div>
+ ))}
+ </div>
+ </div>
+ {!disabled && (
+ <div className="flex items-center gap-x-2">
+ <Button type="default" onClick={onSelectEdit}>
+ Edit
+ </Button>
+ {foreignKey.toRemove ? (
+ <Button type="default" onClick={onSelectUndoRemove}>
+ Cancel remove
+ </Button>
+ ) : (
+ <Button type="default" onClick={onSelectRemove}>
+ Remove
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx
new file mode 100644
index 00000000000..fc87f35a88e
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx
@@ -0,0 +1,142 @@
+import { useState } from 'react'
+import { Button } from 'ui'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import AlertError from 'components/ui/AlertError'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
+import { useTableEditorStateSnapshot } from 'state/table-editor'
+import { ResponseError } from 'types'
+import { ForeignKeySelector } from '../../ForeignKeySelector/ForeignKeySelector'
+import { TableField } from '../TableEditor.types'
+import { ForeignKeyRow } from './ForeignKeyRow'
+import { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
+import { checkIfRelationChanged } from './ForeignKeysManagement.utils'
+
+interface ForeignKeysManagementProps {
+ table: TableField
+ relations: ForeignKey[]
+ closePanel: () => void
+ setEditorDirty: () => void
+ onUpdateFkRelations: (relations: ForeignKey[]) => void
+}
+
+export const ForeignKeysManagement = ({
+ table,
+ relations,
+ closePanel,
+ setEditorDirty,
+ onUpdateFkRelations,
+}: ForeignKeysManagementProps) => {
+ const { project } = useProjectContext()
+ const snap = useTableEditorStateSnapshot()
+
+ const [open, setOpen] = useState(false)
+ const [selectedFk, setSelectedFk] = useState<ForeignKey>()
+
+ const { data, error, isLoading, isSuccess, isError } = useForeignKeyConstraintsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: snap.selectedSchemaName,
+ })
+
+ const getRelationStatus = (fk: ForeignKey) => {
+ const existingRelation = (data ?? []).find((x) => x.id === fk.id)
+ const stateRelation = relations.find((x) => x.id === fk.id)
+
+ if (stateRelation?.toRemove) return 'REMOVE'
+ if (existingRelation === undefined && stateRelation !== undefined) return 'ADD'
+ if (existingRelation !== undefined && stateRelation !== undefined) {
+ const hasUpdated = checkIfRelationChanged(existingRelation, stateRelation)
+ if (hasUpdated) return 'UPDATE'
+ else return undefined
+ }
+ }
+
+ return (
+ <>
+ <div className="w-full space-y-4 ">
+ <h5>Foreign keys</h5>
+
+ {isLoading && <GenericSkeletonLoader />}
+
+ {isError && (
+ <AlertError
+ error={error as unknown as ResponseError}
+ subject="Failed to retrieve foreign key relationships"
+ />
+ )}
+
+ {isSuccess && (
+ <div>
+ {relations.map((fk) => {
+ const status = getRelationStatus(fk)
+ return (
+ <ForeignKeyRow
+ key={fk.id}
+ status={status}
+ foreignKey={fk}
+ closePanel={closePanel}
+ onSelectEdit={() => {
+ setOpen(true)
+ setSelectedFk(fk)
+ }}
+ onSelectRemove={() => {
+ setEditorDirty()
+ if (fk.id === undefined) {
+ const updatedRelations = relations.filter((x) => x.id !== fk.id)
+ onUpdateFkRelations(updatedRelations)
+ } else {
+ const updatedRelations = relations.map((x) => {
+ if (x.id === fk.id) return { ...x, toRemove: true }
+ else return x
+ })
+ onUpdateFkRelations(updatedRelations)
+ }
+ }}
+ onSelectUndoRemove={() => {
+ setEditorDirty()
+ const updatedRelations = relations.map((x) => {
+ if (x.id === fk.id) return { ...x, toRemove: false }
+ else return x
+ })
+ onUpdateFkRelations(updatedRelations)
+ }}
+ />
+ )
+ })}
+ </div>
+ )}
+
+ <div className="flex items-center justify-center rounded border border-strong border-dashed py-3">
+ <Button type="default" onClick={() => setOpen(true)}>
+ Add foreign key relation
+ </Button>
+ </div>
+ </div>
+ <ForeignKeySelector
+ visible={open}
+ table={{ id: table.id, name: table.name, columns: table.columns }}
+ foreignKey={selectedFk}
+ onClose={() => {
+ setOpen(false)
+ setSelectedFk(undefined)
+ }}
+ onSaveRelation={(fk) => {
+ setEditorDirty()
+ const existingRelationIds = relations.map((x) => x.id)
+ if (fk.id !== undefined && existingRelationIds.includes(fk.id)) {
+ onUpdateFkRelations(
+ relations.map((x) => {
+ if (x.id === fk.id) return fk
+ return x
+ })
+ )
+ } else {
+ onUpdateFkRelations(relations.concat([fk]))
+ }
+ }}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils.ts
new file mode 100644
index 00000000000..7d8c54e726d
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils.ts
@@ -0,0 +1,16 @@
+import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
+import { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
+import { isEqual } from 'lodash'
+
+export const checkIfRelationChanged = (existing: ForeignKeyConstraint, state: ForeignKey) => {
+ const stateSourceColumns = state.columns.map((x) => x.source)
+ const stateTargetColumns = state.columns.map((x) => x.target)
+ return (
+ existing.deletion_action !== state.deletionAction ||
+ existing.update_action !== state.updateAction ||
+ existing.target_schema !== state.schema ||
+ existing.target_table !== state.table ||
+ !isEqual(existing.source_columns, stateSourceColumns) ||
+ !isEqual(existing.target_columns, stateTargetColumns)
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.constants.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.constants.ts
index 7b924cffdbe..069d613bdf0 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.constants.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.constants.ts
@@ -5,6 +5,8 @@ export const DEFAULT_COLUMNS: ColumnField[] = [
{
id: uuidv4(),
name: 'id',
+ schema: '',
+ table: '',
format: 'int8',
defaultValue: null,
check: null,
@@ -20,6 +22,8 @@ export const DEFAULT_COLUMNS: ColumnField[] = [
{
id: uuidv4(),
name: 'created_at',
+ schema: '',
+ table: '',
format: 'timestamptz',
defaultValue: 'now()',
check: null,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index a05833b938a..2433c8c413c 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -2,20 +2,26 @@ import type { PostgresTable } from '@supabase/postgres-meta'
import { isEmpty, isUndefined, noop } from 'lodash'
import Link from 'next/link'
import { useEffect, useState } from 'react'
+import { Alert, Badge, Button, Checkbox, IconBookOpen, Input, Modal, SidePanel } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
-import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
+import {
+ ForeignKeyConstraint,
+ useForeignKeyConstraintsQuery,
+} from 'data/database/foreign-key-constraints-query'
import { usePostgresTypesQuery } from 'data/database/types-query'
import { useIsFeatureEnabled, useStore } from 'hooks'
import { EXCLUDED_SCHEMAS_WITHOUT_EXTENSIONS } from 'lib/constants/schemas'
import { useTableEditorStateSnapshot } from 'state/table-editor'
-import { Alert, Badge, Button, Checkbox, IconBookOpen, Input, Modal, SidePanel } from 'ui'
import { SpreadsheetImport } from '../'
import ActionBar from '../ActionBar'
+import { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
+import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
import { ColumnField } from '../SidePanelEditor.types'
import ColumnManagement from './ColumnManagement'
+import { ForeignKeysManagement } from './ForeignKeysManagement/ForeignKeysManagement'
import HeaderTitle from './HeaderTitle'
import RLSDisableModalContent from './RLSDisableModal'
import { DEFAULT_COLUMNS } from './TableEditor.constants'
@@ -39,6 +45,7 @@ export interface TableEditorProps {
comment?: string | undefined
},
columns: ColumnField[],
+ foreignKeyRelations: ForeignKey[],
isNewRecord: boolean,
configuration: {
tableId?: number
@@ -46,6 +53,7 @@ export interface TableEditorProps {
isRLSEnabled: boolean
isRealtimeEnabled: boolean
isDuplicateRows: boolean
+ existingForeignKeyRelations: ForeignKeyConstraint[]
},
resolve: any
) => void
@@ -88,44 +96,21 @@ const TableEditor = ({
const [errors, setErrors] = useState<any>({})
const [tableFields, setTableFields] = useState<TableField>()
+ const [fkRelations, setFkRelations] = useState<ForeignKey[]>([])
+
const [isDuplicateRows, setIsDuplicateRows] = useState<boolean>(false)
const [importContent, setImportContent] = useState<ImportContent>()
const [isImportingSpreadsheet, setIsImportingSpreadsheet] = useState<boolean>(false)
const [rlsConfirmVisible, setRlsConfirmVisible] = useState<boolean>(false)
- const { data } = useForeignKeyConstraintsQuery({
+ const { data: foreignKeyMeta } = useForeignKeyConstraintsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
schema: table?.schema,
})
- const foreignKeyMeta = data || []
-
- useEffect(() => {
- if (visible) {
- setErrors({})
- setImportContent(undefined)
- setIsDuplicateRows(false)
- if (isNewRecord) {
- const tableFields = generateTableField()
- setTableFields(tableFields)
- } else {
- const tableFields = generateTableFieldFromPostgresTable(
- table!,
- foreignKeyMeta,
- isDuplicating,
- isRealtimeEnabled
- )
- setTableFields(tableFields)
- }
- }
- }, [visible])
-
- useEffect(() => {
- if (importContent && !isEmpty(importContent)) {
- const importedColumns = formatImportedContentToColumnFields(importContent)
- onUpdateField({ columns: importedColumns })
- }
- }, [importContent])
+ const foreignKeys = (foreignKeyMeta ?? []).filter(
+ (fk) => fk.source_schema === table?.schema && fk.source_table === table?.name
+ )
const onUpdateField = (changes: Partial<TableField>) => {
const updatedTableFields = { ...tableFields, ...changes } as TableField
@@ -139,6 +124,33 @@ const TableEditor = ({
setErrors(updatedErrors)
}
+ const onUpdateFkRelations = (relations: ForeignKey[]) => {
+ if (tableFields === undefined) return
+ const updatedColumns: ColumnField[] = []
+
+ relations.forEach((relation) => {
+ relation.columns.forEach((column) => {
+ const sourceColumn = tableFields.columns.find((col) => col.name === column.source)
+ if (sourceColumn?.isNewColumn && column.targetType) {
+ updatedColumns.push({ ...sourceColumn, format: column.targetType })
+ }
+ })
+ })
+
+ if (updatedColumns.length > 0) {
+ const updatedTableFields = {
+ ...tableFields,
+ columns: tableFields.columns.map((col) => {
+ const updatedColumn = updatedColumns.find((x) => x.id === col.id)
+ if (updatedColumn) return updatedColumn
+ else return col
+ }),
+ }
+ setTableFields(updatedTableFields)
+ }
+ setFkRelations(relations)
+ }
+
const onSaveChanges = (resolve: any) => {
if (tableFields) {
const errors: any = validateFields(tableFields)
@@ -154,30 +166,51 @@ const TableEditor = ({
comment: tableFields.comment,
...(!isNewRecord && { rls_enabled: tableFields.isRLSEnabled }),
}
- const columns = tableFields.columns.map((column) => {
- if (column.foreignKey) {
- return {
- ...column,
- foreignKey: { ...column.foreignKey, source_table_name: tableFields.name },
- }
- }
- return column
- })
const configuration = {
tableId: table?.id,
importContent,
isRLSEnabled: tableFields.isRLSEnabled,
isRealtimeEnabled: tableFields.isRealtimeEnabled,
isDuplicateRows: isDuplicateRows,
+ existingForeignKeyRelations: foreignKeys,
}
- saveChanges(payload, columns, isNewRecord, configuration, resolve)
+ saveChanges(payload, tableFields.columns, fkRelations, isNewRecord, configuration, resolve)
} else {
resolve()
}
}
}
+ useEffect(() => {
+ if (visible) {
+ setErrors({})
+ setImportContent(undefined)
+ setIsDuplicateRows(false)
+ if (isNewRecord) {
+ const tableFields = generateTableField()
+ setTableFields(tableFields)
+ setFkRelations([])
+ } else {
+ const tableFields = generateTableFieldFromPostgresTable(
+ table!,
+ foreignKeyMeta || [],
+ isDuplicating,
+ isRealtimeEnabled
+ )
+ setTableFields(tableFields)
+ setFkRelations(formatForeignKeys(foreignKeys))
+ }
+ }
+ }, [visible])
+
+ useEffect(() => {
+ if (importContent && !isEmpty(importContent)) {
+ const importedColumns = formatImportedContentToColumnFields(importContent)
+ onUpdateField({ columns: importedColumns })
+ }
+ }, [importContent])
+
if (!tableFields) return null
return (
@@ -200,182 +233,184 @@ const TableEditor = ({
/>
}
>
- <>
- <SidePanel.Content>
- <div className="space-y-10 py-6">
- <Input
- label="Name"
- layout="horizontal"
- type="text"
- error={errors.name}
- value={tableFields?.name}
- onChange={(event: any) => onUpdateField({ name: event.target.value })}
- />
- <Input
- label="Description"
- placeholder="Optional"
- layout="horizontal"
- type="text"
- value={tableFields?.comment ?? ''}
- onChange={(event: any) => onUpdateField({ comment: event.target.value })}
- />
- </div>
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <div className="space-y-10 py-6">
+ <SidePanel.Content className="space-y-10 py-6">
+ <Input
+ label="Name"
+ layout="horizontal"
+ type="text"
+ error={errors.name}
+ value={tableFields?.name}
+ onChange={(event: any) => onUpdateField({ name: event.target.value })}
+ />
+ <Input
+ label="Description"
+ placeholder="Optional"
+ layout="horizontal"
+ type="text"
+ value={tableFields?.comment ?? ''}
+ onChange={(event: any) => onUpdateField({ comment: event.target.value })}
+ />
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content className="space-y-10 py-6">
+ <Checkbox
+ id="enable-rls"
+ // @ts-ignore
+ label={
+ <div className="flex items-center space-x-2">
+ <span>Enable Row Level Security (RLS)</span>
+ <Badge color="gray">Recommended</Badge>
+ </div>
+ }
+ // @ts-ignore
+ description={
+ <>
+ <p>Restrict access to your table by enabling RLS and writing Postgres policies.</p>
+ </>
+ }
+ checked={tableFields.isRLSEnabled}
+ onChange={() => {
+ // if isEnabled, show confirm modal to turn off
+ // if not enabled, allow turning on without modal confirmation
+ tableFields.isRLSEnabled
+ ? setRlsConfirmVisible(true)
+ : onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
+ }}
+ size="medium"
+ />
+ {tableFields.isRLSEnabled ? (
+ <Alert
+ withIcon
+ variant="info"
+ className="!px-4 !py-3 !mt-3"
+ title="Policies are required to query data"
+ >
+ <p>
+ You need to write an access policy before you can query data from this table. Without
+ a policy, querying this table will result in an <u>empty array</u> of results.
+ </p>
+ {isNewRecord && (
+ <p className="mt-3">You can create policies after you create this table.</p>
+ )}
+ <p className="mt-4">
+ <Button asChild type="default" icon={<IconBookOpen strokeWidth={1.5} />}>
+ <Link
+ href="https://supabase.com/docs/guides/auth/row-level-security"
+ target="_blank"
+ rel="noreferrer"
+ >
+ RLS Documentation
+ </Link>
+ </Button>
+ </p>
+ </Alert>
+ ) : (
+ <Alert
+ withIcon
+ variant="warning"
+ className="!px-4 !py-3 mt-3"
+ title="You are allowing anonymous access to your table"
+ >
+ <p>
+ {tableFields.name ? `The table ${tableFields.name}` : 'Your table'} will be publicly
+ writable and readable
+ </p>
+ <p className="mt-4">
+ <Button asChild type="default" icon={<IconBookOpen strokeWidth={1.5} />}>
+ <Link
+ href="https://supabase.com/docs/guides/auth/row-level-security"
+ target="_blank"
+ rel="noreferrer"
+ >
+ RLS Documentation
+ </Link>
+ </Button>
+ </p>
+ </Alert>
+ )}
+ {realtimeEnabled && (
+ <Checkbox
+ id="enable-realtime"
+ label="Enable Realtime"
+ description="Broadcast changes on this table to authorized subscribers"
+ checked={tableFields.isRealtimeEnabled}
+ onChange={() => onUpdateField({ isRealtimeEnabled: !tableFields.isRealtimeEnabled })}
+ size="medium"
+ />
+ )}
+ </SidePanel.Content>
+ <SidePanel.Separator />
+ <SidePanel.Content className="space-y-10 py-6">
+ {!isDuplicating && (
+ <ColumnManagement
+ columns={tableFields?.columns}
+ relations={fkRelations}
+ enumTypes={enumTypes}
+ isNewRecord={isNewRecord}
+ importContent={importContent}
+ onColumnsUpdated={(columns) => onUpdateField({ columns })}
+ onSelectImportData={() => setIsImportingSpreadsheet(true)}
+ onClearImportContent={() => {
+ onUpdateField({ columns: DEFAULT_COLUMNS })
+ setImportContent(undefined)
+ }}
+ />
+ )}
+ {isDuplicating && (
+ <>
<Checkbox
- id="enable-rls"
- // @ts-ignore
- label={
- <div className="flex items-center space-x-2">
- <span>Enable Row Level Security (RLS)</span>
- <Badge color="gray">Recommended</Badge>
- </div>
- }
- // @ts-ignore
- description={
- <>
- <p>
- Restrict access to your table by enabling RLS and writing Postgres policies.
- </p>
- </>
- }
- checked={tableFields.isRLSEnabled}
- onChange={() => {
- // if isEnabled, show confirm modal to turn off
- // if not enabled, allow turning on without modal confirmation
- tableFields.isRLSEnabled
- ? setRlsConfirmVisible(true)
- : onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
- }}
+ id="duplicate-rows"
+ label="Duplicate table entries"
+ description="This will copy all the data in the table into the new table"
+ checked={isDuplicateRows}
+ onChange={() => setIsDuplicateRows(!isDuplicateRows)}
size="medium"
/>
- {tableFields.isRLSEnabled ? (
- <Alert
- withIcon
- variant="info"
- className="!px-4 !py-3 mt-3"
- title="Policies are required to query data"
- >
- <p>
- You need to write an access policy before you can query data from this table.
- Without a policy, querying this table will result in an <u>empty array</u> of
- results.
- </p>
- {isNewRecord && (
- <p className="mt-3">You can create policies after you create this table.</p>
- )}
- <p className="mt-4">
- <Button asChild type="default" icon={<IconBookOpen strokeWidth={1.5} />}>
- <Link
- href="https://supabase.com/docs/guides/auth/row-level-security"
- target="_blank"
- rel="noreferrer"
- >
- RLS Documentation
- </Link>
- </Button>
- </p>
- </Alert>
- ) : (
- <Alert
- withIcon
- variant="warning"
- className="!px-4 !py-3 mt-3"
- title="You are allowing anonymous access to your table"
- >
- <p>
- {tableFields.name ? `The table ${tableFields.name}` : 'Your table'} will be
- publicly writable and readable
- </p>
- <p className="mt-4">
- <Button asChild type="default" icon={<IconBookOpen strokeWidth={1.5} />}>
- <Link
- href="https://supabase.com/docs/guides/auth/row-level-security"
- target="_blank"
- rel="noreferrer"
- >
- RLS Documentation
- </Link>
- </Button>
- </p>
- </Alert>
- )}
- {realtimeEnabled && (
- <Checkbox
- id="enable-realtime"
- label="Enable Realtime"
- description="Broadcast changes on this table to authorized subscribers"
- checked={tableFields.isRealtimeEnabled}
- onChange={() =>
- onUpdateField({ isRealtimeEnabled: !tableFields.isRealtimeEnabled })
- }
- size="medium"
- />
- )}
- </div>
- </SidePanel.Content>
- <SidePanel.Separator />
- <SidePanel.Content>
- <div className="space-y-10 py-6">
- {!isDuplicating && (
- <ColumnManagement
- table={{ name: tableFields.name, schema: snap.selectedSchemaName }}
- columns={tableFields?.columns}
- enumTypes={enumTypes}
- isNewRecord={isNewRecord}
- importContent={importContent}
- onColumnsUpdated={(columns) => onUpdateField({ columns })}
- onSelectImportData={() => setIsImportingSpreadsheet(true)}
- onClearImportContent={() => {
- onUpdateField({ columns: DEFAULT_COLUMNS })
- setImportContent(undefined)
- }}
- />
- )}
- {isDuplicating && (
- <>
- <Checkbox
- id="duplicate-rows"
- label="Duplicate table entries"
- description="This will copy all the data in the table into the new table"
- checked={isDuplicateRows}
- onChange={() => setIsDuplicateRows(!isDuplicateRows)}
- size="medium"
- />
- </>
- )}
+ </>
+ )}
- <SpreadsheetImport
- visible={isImportingSpreadsheet}
- headers={importContent?.headers}
- rows={importContent?.rows}
- saveContent={(prefillData: ImportContent) => {
- setImportContent(prefillData)
- setIsImportingSpreadsheet(false)
- }}
- closePanel={() => setIsImportingSpreadsheet(false)}
- />
+ <SpreadsheetImport
+ visible={isImportingSpreadsheet}
+ headers={importContent?.headers}
+ rows={importContent?.rows}
+ saveContent={(prefillData: ImportContent) => {
+ setImportContent(prefillData)
+ setIsImportingSpreadsheet(false)
+ }}
+ closePanel={() => setIsImportingSpreadsheet(false)}
+ />
- <ConfirmationModal
- visible={rlsConfirmVisible}
- header="Turn off Row Level Security"
- buttonLabel="Confirm"
- size="medium"
- onSelectCancel={() => setRlsConfirmVisible(false)}
- onSelectConfirm={() => {
- onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
- setRlsConfirmVisible(false)
- }}
- >
- <Modal.Content>
- <RLSDisableModalContent />
- </Modal.Content>
- </ConfirmationModal>
- </div>
- </SidePanel.Content>
- </>
+ <ConfirmationModal
+ visible={rlsConfirmVisible}
+ header="Turn off Row Level Security"
+ buttonLabel="Confirm"
+ size="medium"
+ onSelectCancel={() => setRlsConfirmVisible(false)}
+ onSelectConfirm={() => {
+ onUpdateField({ isRLSEnabled: !tableFields.isRLSEnabled })
+ setRlsConfirmVisible(false)
+ }}
+ >
+ <Modal.Content>
+ <RLSDisableModalContent />
+ </Modal.Content>
+ </ConfirmationModal>
+ </SidePanel.Content>
+
+ {!isDuplicating && (
+ <>
+ <SidePanel.Separator />
+ <SidePanel.Content className="py-6">
+ <ForeignKeysManagement
+ table={tableFields}
+ relations={fkRelations}
+ closePanel={closePanel}
+ setEditorDirty={() => updateEditorDirty()}
+ onUpdateFkRelations={onUpdateFkRelations}
+ />
+ </SidePanel.Content>
+ </>
+ )}
</SidePanel>
)
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/index.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/index.ts
index 6b0602c7648..0ce48468acd 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/index.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/index.ts
@@ -3,7 +3,6 @@ import RowEditor from './RowEditor/RowEditor'
import ColumnEditor from './ColumnEditor/ColumnEditor'
import TableEditor from './TableEditor/TableEditor'
import SpreadsheetImport from './SpreadsheetImport/SpreadsheetImport'
-import ForeignKeySelector from './ForeignKeySelector/ForeignKeySelector'
-export { RowEditor, ColumnEditor, TableEditor, ForeignKeySelector, SpreadsheetImport }
+export { RowEditor, ColumnEditor, TableEditor, SpreadsheetImport }
export default SidePanelEditor
diff --git a/apps/studio/data/database/foreign-key-constraints-query.ts b/apps/studio/data/database/foreign-key-constraints-query.ts
index b57ac57f84a..064bf0fa07b 100644
--- a/apps/studio/data/database/foreign-key-constraints-query.ts
+++ b/apps/studio/data/database/foreign-key-constraints-query.ts
@@ -5,7 +5,7 @@ type GetForeignKeyConstraintsVariables = {
schema?: string
}
-export type ForeignKeyConstraint = {
+export type ForeignKeyConstraintRaw = {
id: number
constraint_name: string
deletion_action: string
@@ -20,6 +20,21 @@ export type ForeignKeyConstraint = {
target_columns: string
}
+export type ForeignKeyConstraint = {
+ id: number
+ constraint_name: string
+ deletion_action: string
+ update_action: string
+ source_id: number
+ source_schema: string
+ source_table: string
+ source_columns: string[]
+ target_id: number
+ target_schema: string
+ target_table: string
+ target_columns: string[]
+}
+
export const getForeignKeyConstraintsQuery = ({ schema }: GetForeignKeyConstraintsVariables) => {
const sql = /* SQL */ `
SELECT
@@ -96,7 +111,7 @@ export const useForeignKeyConstraintsQuery = <
},
{
select(data) {
- return ((data as any)?.result ?? []).map((foreignKey: ForeignKeyConstraint) => {
+ return ((data as any)?.result ?? []).map((foreignKey: ForeignKeyConstraintRaw) => {
return {
...foreignKey,
source_columns: foreignKey.source_columns.replace('{', '').replace('}', '').split(','),