Skip to content

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

Add query to fetch foreign key constraints meta and implement cascade deletes via column editor side panel

Joshen Lim1742c9b2aa8d
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index 251104fc29e..6ea51394495 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -1,12 +1,11 @@
import Link from 'next/link'
import { FC, useEffect, useState } from 'react'
-import { isUndefined, isEmpty } from 'lodash'
+import { isEmpty } from 'lodash'
import { Dictionary } from 'components/grid'
import { Checkbox, SidePanel, Input, Button, IconExternalLink, Toggle } from 'ui'
import type {
PostgresColumn,
PostgresExtension,
- PostgresRelationship,
PostgresTable,
PostgresType,
} from '@supabase/postgres-meta'
@@ -27,19 +26,26 @@ import {
generateUpdateColumnPayload,
} from './ColumnEditor.utils'
import { TEXT_TYPES } from '../SidePanelEditor.constants'
-import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from '../SidePanelEditor.types'
+import {
+ ColumnField,
+ CreateColumnPayload,
+ ExtendedPostgresRelationship,
+ UpdateColumnPayload,
+} from '../SidePanelEditor.types'
import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'
import { EncryptionKeySelector } from 'components/interfaces/Settings/Vault'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
+
interface Props {
column?: PostgresColumn
selectedTable: PostgresTable
- tables: PostgresTable[]
visible: boolean
closePanel: () => void
saveChanges: (
payload: CreateColumnPayload | UpdateColumnPayload,
- foreignKey: Partial<PostgresRelationship> | undefined,
+ foreignKey: ExtendedPostgresRelationship | undefined,
isNewRecord: boolean,
configuration: {
columnId: string | undefined
@@ -55,7 +61,6 @@ interface Props {
const ColumnEditor: FC<Props> = ({
column,
selectedTable,
- tables = [],
visible = false,
closePanel = () => {},
saveChanges = () => {},
@@ -63,31 +68,41 @@ const ColumnEditor: FC<Props> = ({
}) => {
const { ref } = useParams()
const { meta, vault } = useStore()
+ const { project } = useProjectContext()
const isTCEEnabled = useFlag('transparentColumnEncryption')
- const isNewRecord = isUndefined(column)
- const originalForeignKey = column ? getColumnForeignKey(column, selectedTable) : undefined
+ const [errors, setErrors] = useState<Dictionary<any>>({})
+ const [columnFields, setColumnFields] = useState<ColumnField>()
+ const [isEditingRelation, setIsEditingRelation] = useState<boolean>(false)
+
+ const { data, isLoading } = useForeignKeyConstraintsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: selectedTable?.schema,
+ })
+ const foreignKeyMeta = data?.result ?? []
const keys = vault.listKeys()
const enumTypes = meta.types.list(
(type: PostgresType) => !meta.excludedSchemas.includes(type.schema)
)
- const [errors, setErrors] = useState<Dictionary<any>>({})
- const [columnFields, setColumnFields] = useState<ColumnField>()
- const [isEditingRelation, setIsEditingRelation] = useState<boolean>(false)
-
const [pgsodiumExtension] = meta.extensions.list(
(ext: PostgresExtension) => ext.name.toLowerCase() === 'pgsodium'
)
const isPgSodiumInstalled = pgsodiumExtension?.installed_version !== null
+ const isNewRecord = column === undefined
+ const originalForeignKey = column
+ ? getColumnForeignKey(column, selectedTable, foreignKeyMeta)
+ : undefined
+
useEffect(() => {
if (visible) {
setErrors({})
const columnFields = isNewRecord
? { ...generateColumnField(), keyId: keys.length > 0 ? keys[0].id : 'create-new' }
- : generateColumnFieldFromPostgresColumn(column!, selectedTable)
+ : generateColumnFieldFromPostgresColumn(column!, selectedTable, foreignKeyMeta)
setColumnFields(columnFields)
}
}, [visible])
@@ -111,23 +126,27 @@ const ColumnEditor: FC<Props> = ({
setErrors(updatedErrors)
}
- const saveColumnForeignKey = (
- foreignKeyConfiguration: { table: PostgresTable; column: PostgresColumn } | undefined
- ) => {
+ const saveColumnForeignKey = (foreignKeyConfiguration?: {
+ table: PostgresTable
+ column: PostgresColumn
+ deletionAction: string
+ }) => {
onUpdateField({
- foreignKey: !isUndefined(foreignKeyConfiguration)
- ? {
- 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,
- }
- : undefined,
- ...(!isUndefined(foreignKeyConfiguration) && {
+ 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,
+ }
+ : undefined,
+ ...(foreignKeyConfiguration !== undefined && {
format: foreignKeyConfiguration.column.format,
defaultValue: null,
}),
@@ -218,6 +237,7 @@ const ColumnEditor: FC<Props> = ({
originalForeignKey={originalForeignKey}
onSelectEditRelation={() => setIsEditingRelation(true)}
onSelectRemoveRelation={() => onUpdateField({ foreignKey: undefined })}
+ onSelectCancelRemoveRelation={() => onUpdateField({ foreignKey: originalForeignKey })}
/>
</div>
</FormSectionContent>
@@ -254,10 +274,10 @@ const ColumnEditor: FC<Props> = ({
layout="vertical"
enumTypes={enumTypes}
error={errors.format}
- disabled={!isUndefined(columnFields?.foreignKey)}
+ disabled={columnFields?.foreignKey !== undefined}
onOptionSelect={(format: string) => onUpdateField({ format, defaultValue: null })}
/>
- {isUndefined(columnFields.foreignKey) && (
+ {columnFields.foreignKey === undefined && (
<div className="space-y-4">
{columnFields.format.includes('int') && (
<div className="w-full">
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index 2467d36a736..a4791589a4f 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -8,7 +8,14 @@ import type {
} from '@supabase/postgres-meta'
import { uuidv4 } from 'lib/helpers'
-import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from '../SidePanelEditor.types'
+import {
+ ColumnField,
+ CreateColumnPayload,
+ ExtendedPostgresRelationship,
+ UpdateColumnPayload,
+} from '../SidePanelEditor.types'
+import { FOREIGN_KEY_DELETION_ACTION } from 'data/database/database-query-constants'
+import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
const isSQLExpression = (input: string) => {
if (['CURRENT_DATE'].includes(input)) return true
@@ -49,12 +56,13 @@ export const generateColumnField = (field: any = {}): ColumnField => {
export const generateColumnFieldFromPostgresColumn = (
column: PostgresColumn,
- table: PostgresTable
+ table: PostgresTable,
+ foreignKeys: ForeignKeyConstraint[]
): ColumnField => {
const { primary_keys } = table
// @ts-ignore
const primaryKeyColumns = primary_keys.map((key) => key.name)
- const foreignKey = getColumnForeignKey(column, table)
+ const foreignKey = getColumnForeignKey(column, table, foreignKeys)
const isArray = column?.data_type === 'ARRAY'
return {
@@ -175,8 +183,8 @@ export const validateFields = (field: ColumnField) => {
}
export const getForeignKeyUIState = (
- originalConfig: PostgresRelationship | undefined,
- updatedConfig: PostgresRelationship | undefined
+ originalConfig: ExtendedPostgresRelationship | undefined,
+ updatedConfig: ExtendedPostgresRelationship | undefined
): 'Info' | 'Add' | 'Remove' | 'Update' => {
if (isUndefined(originalConfig) && !isUndefined(updatedConfig)) {
return 'Add'
@@ -189,7 +197,8 @@ export const getForeignKeyUIState = (
if (
!isEqual(originalConfig?.target_table_schema, updatedConfig?.target_table_schema) ||
!isEqual(originalConfig?.target_table_name, updatedConfig?.target_table_name) ||
- !isEqual(originalConfig?.target_column_name, updatedConfig?.target_column_name)
+ !isEqual(originalConfig?.target_column_name, updatedConfig?.target_column_name) ||
+ originalConfig?.deletion_action !== updatedConfig?.deletion_action
) {
return 'Update'
}
@@ -197,15 +206,24 @@ export const getForeignKeyUIState = (
return 'Info'
}
-export const getColumnForeignKey = (column: PostgresColumn, table: PostgresTable) => {
+export const getColumnForeignKey = (
+ column: PostgresColumn,
+ table: PostgresTable,
+ foreignKeys: ForeignKeyConstraint[]
+) => {
const { relationships } = table
- return find(relationships, (relationship) => {
+ const foreignKey = find(relationships, (relationship) => {
return (
relationship.source_schema === column.schema &&
relationship.source_table_name === column.table &&
relationship.source_column_name === column.name
)
})
+ if (foreignKey === undefined) return foreignKey
+ else {
+ const foreignKeyMeta = foreignKeys.find((fk) => fk.id === foreignKey?.id)
+ return { ...foreignKey, deletion_action: foreignKeyMeta?.deletion_action ?? 'a' }
+ }
}
// Assumes arrayString is a stringified array (e.g "[1, 2, 3]")
@@ -213,3 +231,18 @@ const formatArrayToPostgresArray = (arrayString: string) => {
if (!arrayString) return null
return arrayString.replaceAll('[', '{').replaceAll(']', '}')
}
+
+export const getForeignKeyDeletionAction = (deletionAction?: string) => {
+ switch (deletionAction) {
+ case FOREIGN_KEY_DELETION_ACTION.CASCADE:
+ return 'Cascade'
+ case FOREIGN_KEY_DELETION_ACTION.RESTRICT:
+ return 'Restrict'
+ case FOREIGN_KEY_DELETION_ACTION.SET_DEFAULT:
+ return 'Set default'
+ case FOREIGN_KEY_DELETION_ACTION.SET_NULL:
+ return 'Set null'
+ default:
+ return undefined
+ }
+}
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
index 50d0778c246..93289f96640 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
@@ -1,17 +1,18 @@
import { FC } from 'react'
import { isUndefined } from 'lodash'
-import { Button, IconArrowRight } from 'ui'
+import { Badge, Button, IconArrowRight } from 'ui'
import { ColumnField } from '../SidePanelEditor.types'
import InformationBox from 'components/ui/InformationBox'
-import { getForeignKeyUIState } from './ColumnEditor.utils'
-import type { PostgresRelationship } from '@supabase/postgres-meta'
+import { getForeignKeyDeletionAction, getForeignKeyUIState } from './ColumnEditor.utils'
+import type { ExtendedPostgresRelationship } from '../SidePanelEditor.types'
interface Props {
column: ColumnField
- originalForeignKey: PostgresRelationship | undefined
+ originalForeignKey: ExtendedPostgresRelationship | undefined
onSelectEditRelation: () => void
onSelectRemoveRelation: () => void
+ onSelectCancelRemoveRelation: () => void
}
const ColumnForeignKey: FC<Props> = ({
@@ -19,6 +20,7 @@ const ColumnForeignKey: FC<Props> = ({
originalForeignKey,
onSelectEditRelation = () => {},
onSelectRemoveRelation = () => {},
+ onSelectCancelRemoveRelation,
}) => {
const hasNoForeignKey = isUndefined(originalForeignKey) && isUndefined(column?.foreignKey)
if (hasNoForeignKey) {
@@ -47,6 +49,7 @@ const ColumnForeignKey: FC<Props> = ({
columnName={column.name}
originalForeignKey={originalForeignKey}
onSelectEditRelation={onSelectEditRelation}
+ onSelectCancelRemoveRelation={onSelectCancelRemoveRelation}
/>
)
case 'Update':
@@ -79,24 +82,26 @@ export default ColumnForeignKey
const ColumnForeignKeyInformation: FC<{
columnName: string
- foreignKey?: PostgresRelationship
+ foreignKey?: ExtendedPostgresRelationship
onSelectEditRelation: () => void
onSelectRemoveRelation: () => void
}> = ({ columnName, foreignKey, onSelectEditRelation, onSelectRemoveRelation }) => {
+ const deletionAction = getForeignKeyDeletionAction(foreignKey?.deletion_action)
return (
<InformationBox
block
title={
- <div className="flex flex-col space-y-4 text-scale-900">
+ <div className="flex flex-col space-y-4">
<div className="space-y-2">
- <span>This column has the following foreign key relation:</span>
- <div className="flex items-center space-x-2">
- <span className="text-code">{columnName}</span>
+ <p className="text-scale-1100">This column has the following foreign key relation:</p>
+ <div className="flex items-center space-x-2 text-scale-1200">
+ <span className="text-xs text-code font-mono">{columnName}</span>
<IconArrowRight size={14} strokeWidth={2} />
- <span className="text-code">
+ <span className="text-xs text-code font-mono">
{foreignKey?.target_table_schema}.{foreignKey?.target_table_name}.
{foreignKey?.target_column_name}
</span>
+ {deletionAction !== undefined && <Badge color="gray">Delete: {deletionAction}</Badge>}
</div>
</div>
<div className="flex items-center space-x-2">
@@ -115,10 +120,11 @@ const ColumnForeignKeyInformation: FC<{
const ColumnForeignKeyAdded: FC<{
columnName: string
- foreignKey?: PostgresRelationship
+ foreignKey?: ExtendedPostgresRelationship
onSelectEditRelation: () => void
onSelectRemoveRelation: () => void
}> = ({ columnName, foreignKey, onSelectEditRelation, onSelectRemoveRelation }) => {
+ const deletionAction = getForeignKeyDeletionAction(foreignKey?.deletion_action)
return (
<InformationBox
block
@@ -142,6 +148,7 @@ const ColumnForeignKeyAdded: FC<{
{foreignKey?.target_table_schema}.{foreignKey?.target_table_name}.
{foreignKey?.target_column_name}
</span>
+ {deletionAction !== undefined && <Badge color="gray">Delete: {deletionAction}</Badge>}
</div>
</div>
<div className="flex items-center space-x-2">
@@ -160,23 +167,24 @@ const ColumnForeignKeyAdded: FC<{
const ColumnForeignKeyRemoved: FC<{
columnName: string
- originalForeignKey?: PostgresRelationship
+ originalForeignKey?: ExtendedPostgresRelationship
onSelectEditRelation: () => void
-}> = ({ columnName, originalForeignKey, onSelectEditRelation }) => {
+ onSelectCancelRemoveRelation: () => void
+}> = ({ columnName, originalForeignKey, onSelectEditRelation, onSelectCancelRemoveRelation }) => {
return (
<InformationBox
block
title={
<div className="flex flex-col space-y-4">
<div className="space-y-2">
- <p>
+ <p className="text-scale-1100">
The following foreign key relation will be{' '}
- <span className="text-amber-900">removed</span> from this column:
+ <span className="text-amber-900">removed</span>:
</p>
<div className="flex items-center space-x-2">
- <code className="text-sm">{columnName}</code>
+ <code className="text-xs font-mono">{columnName}</code>
<IconArrowRight size={14} strokeWidth={2} />
- <code className="text-sm">
+ <code className="text-xs font-mono">
{originalForeignKey?.target_table_schema}.{originalForeignKey?.target_table_name}.
{originalForeignKey?.target_column_name}
</code>
@@ -186,6 +194,9 @@ const ColumnForeignKeyRemoved: FC<{
<Button type="outline" onClick={onSelectEditRelation}>
Edit relation
</Button>
+ <Button type="outline" onClick={onSelectCancelRemoveRelation}>
+ Cancel remove
+ </Button>
</div>
</div>
}
@@ -195,8 +206,8 @@ const ColumnForeignKeyRemoved: FC<{
const ColumnForeignKeyUpdated: FC<{
columnName: string
- originalForeignKey?: PostgresRelationship
- updatedForeignKey?: PostgresRelationship
+ originalForeignKey?: ExtendedPostgresRelationship
+ updatedForeignKey?: ExtendedPostgresRelationship
onSelectEditRelation: () => void
onSelectRemoveRelation: () => void
}> = ({
@@ -206,6 +217,12 @@ const ColumnForeignKeyUpdated: FC<{
onSelectEditRelation,
onSelectRemoveRelation,
}) => {
+ 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 originalDeletionAction = getForeignKeyDeletionAction(originalForeignKey?.deletion_action)
+ const updatedDeletionAction = getForeignKeyDeletionAction(updatedForeignKey?.deletion_action)
+
return (
<InformationBox
block
@@ -217,19 +234,25 @@ const ColumnForeignKeyUpdated: FC<{
such:
</p>
<div className="flex items-start space-x-2">
- <code className="text-sm">{columnName}</code>
+ <code className="text-xs font-mono">{columnName}</code>
<IconArrowRight className="mt-1" size={14} strokeWidth={2} />
<div className="flex flex-col space-y-2">
- <p className="line-through">
- <code className="text-sm">
- {originalForeignKey?.target_table_schema}.
- {originalForeignKey?.target_table_name}.{originalForeignKey?.target_column_name}
- </code>
- </p>
- <code className="text-sm">
- {updatedForeignKey?.target_table_schema}.{updatedForeignKey?.target_table_name}.
- {updatedForeignKey?.target_column_name}
- </code>
+ {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 className="flex flex-col space-y-2">
+ {originalDeletionAction !== updatedDeletionAction && (
+ <Badge color="gray" className="line-through">
+ Delete: {originalDeletionAction}
+ </Badge>
+ )}
+ {updatedDeletionAction !== undefined && (
+ <Badge color="green">Delete: {updatedDeletionAction}</Badge>
+ )}
</div>
</div>
</div>
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
index 823ad2382d4..bae877b5204 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
@@ -1,7 +1,7 @@
import React, { FC, useEffect, useState } from 'react'
import { get, find, isEmpty, sortBy } from 'lodash'
import { Dictionary } from 'components/grid'
-import { SidePanel, Input, Listbox, IconHelpCircle, IconDatabase } from 'ui'
+import { SidePanel, Input, Listbox, IconHelpCircle, IconDatabase, Toggle } from 'ui'
import type { PostgresTable, PostgresColumn, PostgresSchema } from '@supabase/postgres-meta'
import { useStore } from 'hooks'
@@ -9,15 +9,21 @@ import ActionBar from '../ActionBar'
import { ForeignKey } from './ForeignKeySelector.types'
import { ColumnField } from '../SidePanelEditor.types'
import InformationBox from 'components/ui/InformationBox'
+import { FOREIGN_KEY_DELETION_ACTION } from 'data/database/database-query-constants'
interface Props {
column: ColumnField
metadata?: any
visible: boolean
closePanel: () => void
- saveChanges: (value: { table: PostgresTable; column: PostgresColumn } | undefined) => void
+ saveChanges: (
+ value: { table: PostgresTable; column: PostgresColumn; deletionAction: string } | undefined
+ ) => void
}
+// [Joshen] In the future, we can easily extend to other deletion actions as well by replacing
+// enableCascadeDelete with deletionAction
+
const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, saveChanges }) => {
const { meta } = useStore()
const [errors, setErrors] = useState<any>({})
@@ -25,6 +31,7 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
schema: 'public',
table: '',
column: '',
+ enableCascadeDelete: false,
})
const schemas = meta.schemas.list()
@@ -51,12 +58,14 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
schema: foreignKey.target_table_schema,
table: foreignKey.target_table_name,
column: foreignKey.target_column_name,
+ enableCascadeDelete: foreignKey.deletion_action === FOREIGN_KEY_DELETION_ACTION.CASCADE,
})
} else {
setSelectedForeignKey({
schema: 'public',
table: '',
column: '',
+ enableCascadeDelete: false,
})
}
}
@@ -64,7 +73,7 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
const updateSelectedSchema = (schema: string) => {
meta.tables.loadBySchema(schema)
- const updatedForeignKey = { ...selectedForeignKey, schema, table: '', column: '' } as ForeignKey
+ const updatedForeignKey = { schema, table: '', column: '', enableCascadeDelete: false }
setSelectedForeignKey(updatedForeignKey)
}
@@ -75,6 +84,7 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
schema: '',
table: '',
column: '',
+ enableCascadeDelete: false,
})
}
const table = find(tables, { id: tableId })
@@ -83,6 +93,7 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
schema: table.schema,
table: table.name,
column: table.columns?.length ? table.columns[0].name : undefined,
+ enableCascadeDelete: false,
})
}
}
@@ -96,6 +107,11 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
}
}
+ const updateEnableCascadeDelete = (value: boolean) => {
+ setErrors({})
+ setSelectedForeignKey({ ...selectedForeignKey, enableCascadeDelete: value })
+ }
+
const onSaveChanges = (resolve: () => void) => {
const errors = {} as Dictionary<any>
if (!selectedForeignKey?.table) {
@@ -110,7 +126,13 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
// Remove foreign key since no table selected
saveChanges(undefined)
} else {
- saveChanges({ table: selectedTable, column: selectedColumn })
+ saveChanges({
+ table: selectedTable,
+ column: selectedColumn,
+ deletionAction: selectedForeignKey.enableCascadeDelete
+ ? FOREIGN_KEY_DELETION_ACTION.CASCADE
+ : FOREIGN_KEY_DELETION_ACTION.NO_ACTION,
+ })
}
}
resolve()
@@ -240,6 +262,13 @@ const ForeignKeySelector: FC<Props> = ({ column, visible = false, closePanel, sa
))}
</Listbox>
)}
+ <Toggle
+ label="Enable cascade deletes"
+ // @ts-ignore
+ onChange={(value: boolean) => updateEnableCascadeDelete(value)}
+ checked={selectedForeignKey.enableCascadeDelete}
+ descriptionText={`Deleting a record from ${selectedForeignKey.schema}.${selectedForeignKey.table} will also delete the referencing records from this table`}
+ />
</>
)}
</div>
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
index a5a73bf717f..119cff3f5e7 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types.ts
@@ -2,4 +2,5 @@ export interface ForeignKey {
schema: string
table: string
column?: string
+ enableCascadeDelete: boolean
}
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 93411f0a8cf..998954457a3 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -1,15 +1,20 @@
import { FC, useState } from 'react'
import { find, isEmpty, isUndefined } from 'lodash'
-import { Query, Dictionary } from 'components/grid'
+import { Dictionary } from 'components/grid'
import { Modal } from 'ui'
-import type { PostgresRelationship, PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
+import type { PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
import { useStore } from 'hooks'
import { useTableRowCreateMutation } from 'data/table-rows/table-row-create-mutation'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { RowEditor, ColumnEditor, TableEditor } from '.'
import { ImportContent } from './TableEditor/TableEditor.types'
-import { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
+import {
+ ColumnField,
+ CreateColumnPayload,
+ ExtendedPostgresRelationship,
+ UpdateColumnPayload,
+} from './SidePanelEditor.types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import JsonEdit from './RowEditor/JsonEditor/JsonEditor'
@@ -150,7 +155,7 @@ const SidePanelEditor: FC<Props> = ({
const saveColumn = async (
payload: CreateColumnPayload | UpdateColumnPayload,
- foreignKey: Partial<PostgresRelationship> | undefined,
+ foreignKey: ExtendedPostgresRelationship | undefined,
isNewRecord: boolean,
configuration: { columnId?: string; isEncrypted: boolean; keyId?: string; keyName?: string },
resolve: any
@@ -304,7 +309,6 @@ const SidePanelEditor: FC<Props> = ({
)}
{!isUndefined(selectedTable) && (
<ColumnEditor
- tables={tables}
column={selectedColumnToEdit}
selectedTable={selectedTable}
visible={sidePanelKey === 'column'}
diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
index 59d260113c0..2a7605c9bfb 100644
--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types.ts
@@ -56,13 +56,17 @@ export interface Field {
foreignKey?: { table: string; column: string }
}
+export interface ExtendedPostgresRelationship extends PostgresRelationship {
+ deletion_action: string
+}
+
export interface ColumnField {
id: string
name: string
comment?: string
format: string
defaultValue: string | null
- foreignKey: PostgresRelationship | undefined
+ foreignKey: ExtendedPostgresRelationship | undefined
isNullable: boolean
isUnique: boolean
isArray: boolean
diff --git a/studio/data/database/database-query-constants.ts b/studio/data/database/database-query-constants.ts
new file mode 100644
index 00000000000..216279061fa
--- /dev/null
+++ b/studio/data/database/database-query-constants.ts
@@ -0,0 +1,18 @@
+// https://www.postgresql.org/docs/current/catalog-pg-constraint.html
+
+export enum FOREIGN_KEY_DELETION_ACTION {
+ NO_ACTION = 'a',
+ RESTRICT = 'r',
+ CASCADE = 'c',
+ SET_NULL = 's',
+ SET_DEFAULT = 'd',
+}
+
+export enum CONSTRAINT_TYPE {
+ CHECK_CONSTRAINT = 'c',
+ FOREIGN_KEY_CONSTRAINT = 'f',
+ PRIMARY_KEY_CONSTRAINT = 'p',
+ UNIQUE_CONSTRAINT = 'u',
+ CONSTRAINT_TRIGGER = 't',
+ EXCLUSION_CONSTRAINT = 'x',
+}
diff --git a/studio/data/database/foreign-key-constraints-query.ts b/studio/data/database/foreign-key-constraints-query.ts
new file mode 100644
index 00000000000..f11d2f44508
--- /dev/null
+++ b/studio/data/database/foreign-key-constraints-query.ts
@@ -0,0 +1,120 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+
+type getForeignKeyConstraintsVariables = {
+ schema?: string
+}
+
+export type ForeignKeyConstraint = {
+ id: number
+ constraint_name: string
+ deletion_action: string
+ source_schema: string
+ source_table: string
+ source_columns: string
+ target_schema: string
+ target_table: string
+ target_columns: string
+}
+
+export const getForeignKeyConstraintsQuery = ({ schema }: getForeignKeyConstraintsVariables) => {
+ const sql = `
+SELECT
+ con.oid as id,
+ con.conname as constraint_name,
+ con.confdeltype as deletion_action,
+ nsp.nspname as source_schema,
+ rel.relname as source_table,
+ (
+ SELECT
+ array_agg(
+ att.attname
+ ORDER BY
+ un.ord
+ )
+ FROM
+ unnest(con.conkey) WITH ORDINALITY un (attnum, ord)
+ INNER JOIN pg_attribute att ON att.attnum = un.attnum
+ WHERE
+ att.attrelid = rel.oid
+ ) source_columns,
+ fnsp.nspname as target_schema,
+ frel.relname as target_table,
+ (
+ SELECT
+ array_agg(
+ att.attname
+ ORDER BY
+ un.ord
+ )
+ FROM
+ unnest(con.confkey) WITH ORDINALITY un (attnum, ord)
+ INNER JOIN pg_attribute att ON att.attnum = un.attnum
+ WHERE
+ att.attrelid = frel.oid
+ ) target_columns
+FROM
+ pg_constraint con
+ INNER JOIN pg_class rel ON rel.oid = con.conrelid
+ INNER JOIN pg_namespace nsp ON nsp.oid = rel.relnamespace
+ INNER JOIN pg_class frel ON frel.oid = con.confrelid
+ INNER JOIN pg_namespace fnsp ON fnsp.oid = frel.relnamespace
+WHERE
+ con.contype = 'f'
+ ${schema !== undefined ? `AND nsp.nspname = '${schema}'` : ''};
+`.trim()
+
+ return sql
+}
+
+export type ForeignKeyConstraintsVariables = getForeignKeyConstraintsVariables & {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type ForeignKeyConstraintsData = ForeignKeyConstraint[]
+export type ForeignKeyConstraintsError = unknown
+
+export const useForeignKeyConstraintsQuery = <
+ TData extends ForeignKeyConstraintsData = ForeignKeyConstraintsData
+>(
+ { projectRef, connectionString, schema }: ForeignKeyConstraintsVariables,
+ options: UseQueryOptions<ExecuteSqlData, ForeignKeyConstraintsError, TData> = {}
+) => {
+ const response = useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getForeignKeyConstraintsQuery({ schema }),
+ queryKey: ['foreignKeyConstraints'],
+ },
+ options
+ )
+
+ // [Joshen] Convert target/source_columns into a string array
+ // This should be safe as the returned data is rather scoped
+ const formattedResults = ((response?.data as any)?.result ?? []).map(
+ (foreignKey: ForeignKeyConstraint) => {
+ return {
+ ...foreignKey,
+ source_columns: foreignKey.source_columns.replace('{', '').replace('}', '').split(','),
+ target_columns: foreignKey.target_columns.replace('{', '').replace('}', '').split(','),
+ }
+ }
+ )
+
+ return { ...response, data: { ...response.data, result: formattedResults } }
+}
+
+export const useForeignKeyConstraintsPrefetch = ({
+ projectRef,
+ connectionString,
+ schema,
+}: ForeignKeyConstraintsVariables) => {
+ return useExecuteSqlPrefetch({
+ projectRef,
+ connectionString,
+ sql: getForeignKeyConstraintsQuery({ schema }),
+ queryKey: ['foreignKeyConstraints'],
+ })
+}
diff --git a/studio/stores/pgmeta/MetaStore.ts b/studio/stores/pgmeta/MetaStore.ts
index a24c5f365f0..3a2ee0709ea 100644
--- a/studio/stores/pgmeta/MetaStore.ts
+++ b/studio/stores/pgmeta/MetaStore.ts
@@ -26,6 +26,7 @@ import { IPostgresMetaInterface } from '../common/PostgresMetaInterface'
import {
ColumnField,
CreateColumnPayload,
+ ExtendedPostgresRelationship,
UpdateColumnPayload,
} from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types'
import {
@@ -43,6 +44,7 @@ import ExtensionsStore from './ExtensionsStore'
import TypesStore from './TypesStore'
import ForeignTableStore from './ForeignTableStore'
import ViewStore from './ViewStore'
+import { FOREIGN_KEY_DELETION_ACTION } from 'data/database/database-query-constants'
const BATCH_SIZE = 1000
const CHUNK_SIZE = 1024 * 1024 * 0.1 // 0.1MB
@@ -81,7 +83,7 @@ export interface IMetaStore {
) => Promise<any | { error: ResponseError }>
removePrimaryKey: (schema: string, table: string) => Promise<any | { error: ResponseError }>
addForeignKey: (
- relationship: Partial<PostgresRelationship>
+ relationship: ExtendedPostgresRelationship
) => Promise<any | { error: ResponseError }>
removeForeignKey: (
relationship: Partial<PostgresRelationship>
@@ -92,14 +94,14 @@ export interface IMetaStore {
createColumn: (
payload: CreateColumnPayload,
selectedTable: PostgresTable,
- foreignKey?: Partial<PostgresRelationship>,
+ foreignKey?: ExtendedPostgresRelationship,
securityConfiguration?: { isEncrypted: boolean; keyId?: string; keyName?: string }
) => any
updateColumn: (
id: string,
payload: UpdateColumnPayload,
selectedTable: PostgresTable,
- foreignKey?: Partial<PostgresRelationship>,
+ foreignKey?: ExtendedPostgresRelationship,
skipPKCreation?: boolean
) => any
duplicateTable: (
@@ -276,12 +278,25 @@ export default class MetaStore implements IMetaStore {
return await this.query(query)
}
- async addForeignKey(relationship: Partial<PostgresRelationship>) {
+ // [Joshen TODO] Eventually need to extend this to composite foreign keys
+ async addForeignKey(relationship: ExtendedPostgresRelationship) {
+ const { deletion_action } = relationship
+ const deletionAction =
+ deletion_action === FOREIGN_KEY_DELETION_ACTION.CASCADE
+ ? 'ON DELETE CASCADE'
+ : deletion_action === FOREIGN_KEY_DELETION_ACTION.RESTRICT
+ ? 'ON DELETE RESTRICT'
+ : deletion_action === FOREIGN_KEY_DELETION_ACTION.SET_DEFAULT
+ ? 'ON DELETE SET DEFAULT'
+ : deletion_action === FOREIGN_KEY_DELETION_ACTION.SET_NULL
+ ? 'ON DELETE SET NULL'
+ : ''
+
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}");
+ REFERENCES "${relationship.target_table_schema}"."${relationship.target_table_name}" ("${relationship.target_column_name}") ${deletionAction};
`
.replace(/\s+/g, ' ')
.trim()
@@ -360,7 +375,7 @@ export default class MetaStore implements IMetaStore {
async createColumn(
payload: CreateColumnPayload,
selectedTable: PostgresTable,
- foreignKey?: Partial<PostgresRelationship>,
+ foreignKey?: ExtendedPostgresRelationship,
securityConfiguration?: { isEncrypted: boolean; keyId?: string; keyName?: string }
) {
const toastId = this.rootStore.ui.setNotification({
@@ -444,7 +459,7 @@ export default class MetaStore implements IMetaStore {
id: string,
payload: UpdateColumnPayload,
selectedTable: PostgresTable,
- foreignKey?: Partial<PostgresRelationship>,
+ foreignKey?: ExtendedPostgresRelationship,
skipPKCreation?: boolean
) {
try {
@@ -516,6 +531,7 @@ export default class MetaStore implements IMetaStore {
const relation = await this.rootStore.meta.addForeignKey({
...relationship,
source_table_name: duplicatedTableName,
+ deletion_action: FOREIGN_KEY_DELETION_ACTION.NO_ACTION,
})
if (relation.error) throw relation.error
})