Skip to content

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

fix(table editor): prevent unnecessary update requests (#40192)

Charis50a0408e6040
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 48648c6aab4..f4a2feeb496 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -52,6 +52,61 @@ import { SpreadsheetImport } from './SpreadsheetImport/SpreadsheetImport'
import { TableEditor } from './TableEditor/TableEditor'
import type { ImportContent } from './TableEditor/TableEditor.types'
+export type SaveTableParams =
+ | SaveTableParamsNew
+ | SaveTableParamsDuplicate
+ | SaveTableParamsExisting
+
+type SaveTableParamsBase = {
+ configuration: SaveTableConfiguration
+ columns: ColumnField[]
+ foreignKeyRelations: ForeignKey[]
+ resolve: () => void
+}
+
+type SaveTableParamsNew = SaveTableParamsBase & {
+ action: 'create'
+ payload: SaveTablePayloadNew
+}
+
+type SaveTableParamsDuplicate = SaveTableParamsBase & {
+ action: 'duplicate'
+ payload: SaveTablePayloadDuplicate
+}
+
+type SaveTableParamsExisting = SaveTableParamsBase & {
+ action: 'update'
+ payload: SaveTablePayloadExisting
+}
+
+type SaveTablePayloadBase = {
+ comment?: string | null
+}
+
+type SaveTablePayloadNew = SaveTablePayloadBase & {
+ name: string
+ schema: string
+}
+
+type SaveTablePayloadDuplicate = SaveTablePayloadBase & {
+ name: string
+}
+
+type SaveTablePayloadExisting = SaveTablePayloadBase & {
+ name?: string
+ rls_enabled?: boolean
+}
+
+type SaveTableConfiguration = {
+ tableId?: number
+ importContent?: ImportContent
+ isRLSEnabled: boolean
+ isRealtimeEnabled: boolean
+ isDuplicateRows: boolean
+ existingForeignKeyRelations: ForeignKeyConstraint[]
+ primaryKey?: Constraint
+}
+
export interface SidePanelEditorProps {
editable?: boolean
selectedTable?: PostgresTable
@@ -107,6 +162,8 @@ export const SidePanelEditor = ({
const getImpersonatedRoleState = useGetImpersonatedRoleState()
+ const isDuplicating = snap.sidePanel?.type === 'table' && snap.sidePanel.mode === 'duplicate'
+
const saveRow = async (
payload: any,
isNewRecord: boolean,
@@ -387,26 +444,11 @@ export const SidePanelEditor = ({
}
}
- const saveTable = async (
- payload: {
- name: string
- schema: string
- comment?: string | null
- },
- columns: ColumnField[],
- foreignKeyRelations: ForeignKey[],
- isNewRecord: boolean,
- configuration: {
- tableId?: number
- importContent?: ImportContent
- isRLSEnabled: boolean
- isRealtimeEnabled: boolean
- isDuplicateRows: boolean
- existingForeignKeyRelations: ForeignKeyConstraint[]
- primaryKey?: Constraint
- },
- resolve: any
- ) => {
+ const saveTable = async (params: SaveTableParams) => {
+ // action and payload are not destructured here to preserve type
+ // narrowing later on
+ const { configuration, columns, foreignKeyRelations, resolve } = params
+
let toastId
let saveTableError = false
const {
@@ -419,43 +461,14 @@ export const SidePanelEditor = ({
} = configuration
try {
- if (
- snap.sidePanel?.type === 'table' &&
- snap.sidePanel.mode === 'duplicate' &&
- selectedTable
- ) {
- const tableToDuplicate = selectedTable
-
- 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)
-
- await Promise.all([
- queryClient.invalidateQueries({
- queryKey: tableKeys.list(project?.ref, table.schema, includeColumns),
- }),
- queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(project?.ref) }),
- ])
-
- toast.success(
- `Table ${tableToDuplicate.name} has been successfully duplicated into ${table.name}!`,
- { id: toastId }
- )
- onTableCreated(table)
- } else if (isNewRecord) {
- toastId = toast.loading(`Creating new table: ${payload.name}...`)
+ if (params.action === 'create') {
+ toastId = toast.loading(`Creating new table: ${params.payload.name}...`)
const table = await createTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
toastId,
- payload,
+ payload: params.payload,
columns,
foreignKeyRelations,
isRLSEnabled,
@@ -473,15 +486,44 @@ export const SidePanelEditor = ({
toast.success(`Table ${table.name} is good to go!`, { id: toastId })
onTableCreated(table)
- } else if (selectedTable) {
- toastId = toast.loading(`Updating table: ${selectedTable?.name}...`)
+ } else if (params.action === 'duplicate' && !!selectedTable) {
+ const tableToDuplicate = selectedTable
+ toastId = toast.loading(`Duplicating table: ${tableToDuplicate.name}...`)
+
+ const table = await duplicateTable(
+ project?.ref!,
+ project?.connectionString,
+ params.payload,
+ {
+ isRLSEnabled,
+ isDuplicateRows,
+ duplicateTable: tableToDuplicate,
+ foreignKeyRelations,
+ }
+ )
+ if (isRealtimeEnabled) await updateTableRealtime(table, isRealtimeEnabled)
+
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: tableKeys.list(project?.ref, table.schema, includeColumns),
+ }),
+ queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(project?.ref) }),
+ ])
+
+ toast.success(
+ `Table ${tableToDuplicate.name} has been successfully duplicated into ${table.name}!`,
+ { id: toastId }
+ )
+ onTableCreated(table)
+ } else if (params.action === 'update' && selectedTable) {
+ toastId = toast.loading(`Updating table: ${selectedTable.name}...`)
const { table, hasError } = await updateTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
toastId,
table: selectedTable,
- payload,
+ payload: params.payload,
columns,
foreignKeyRelations,
existingForeignKeyRelations,
@@ -501,10 +543,10 @@ export const SidePanelEditor = ({
`Table ${table.name} has been updated but there were some errors. Please check these errors separately.`
)
} else {
- if (ref && payload.name) {
+ if (ref && params.payload.name) {
// [Joshen] Only table entities can be updated via the dashboard
const tabId = createTabId(ENTITY_TYPE.TABLE, { id: selectedTable.id })
- tabsSnap.updateTab(tabId, { label: payload.name })
+ tabsSnap.updateTab(tabId, { label: params.payload.name })
}
toast.success(`Successfully updated ${table.name}!`, { id: toastId })
}
@@ -632,7 +674,7 @@ export const SidePanelEditor = ({
? selectedTable
: undefined
}
- isDuplicating={snap.sidePanel?.type === 'table' && snap.sidePanel.mode === 'duplicate'}
+ isDuplicating={isDuplicating}
templateData={
snap.sidePanel?.type === 'table' && snap.sidePanel.templateData
? {
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 978362ac9c3..aa71ebac03e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -394,7 +394,7 @@ export const duplicateTable = async (
connectionString,
sql: [
`CREATE TABLE "${sourceTableSchema}"."${duplicatedTableName}" (LIKE "${sourceTableSchema}"."${sourceTableName}" INCLUDING ALL);`,
- payload.comment !== undefined
+ payload.comment != undefined
? `comment on table "${sourceTableSchema}"."${duplicatedTableName}" is '${payload.comment}';`
: '',
].join('\n'),
@@ -724,7 +724,6 @@ export const updateTable = async ({
const primaryKeyColumns = columns
.filter((column) => column.isPrimaryKey)
.map((column) => column.name)
-
const existingPrimaryKeyColumns = table.primary_keys.map((pk: PostgresPrimaryKey) => pk.name)
const isPrimaryKeyUpdated = !isEqual(primaryKeyColumns, existingPrimaryKeyColumns)
@@ -738,15 +737,16 @@ export const updateTable = async ({
}
}
- // Update the table
- await updateTableMutation({
- projectRef,
- connectionString,
- id: table.id,
- name: table.name,
- schema: table.schema,
- payload,
- })
+ if (Object.keys(payload).length > 0) {
+ await updateTableMutation({
+ projectRef,
+ connectionString,
+ id: table.id,
+ name: table.name,
+ schema: table.schema,
+ payload,
+ })
+ }
// Track RLS enablement if it's being turned on
if (payload.rls_enabled === true) {
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index dc3a4941978..d0679345f4f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -1,19 +1,12 @@
import type { PostgresTable } from '@supabase/postgres-meta'
import { isEmpty, isUndefined, noop } from 'lodash'
-import { useEffect, useMemo, useState } from 'react'
+import { useContext, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { DocsButton } from 'components/ui/DocsButton'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
-import {
- CONSTRAINT_TYPE,
- Constraint,
- useTableConstraintsQuery,
-} from 'data/database/constraints-query'
-import {
- ForeignKeyConstraint,
- useForeignKeyConstraintsQuery,
-} from 'data/database/foreign-key-constraints-query'
+import { CONSTRAINT_TYPE, useTableConstraintsQuery } from 'data/database/constraints-query'
+import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
import { useEnumeratedTypesQuery } from 'data/enumerated-types/enumerated-types-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
@@ -24,13 +17,15 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useProtectedSchemas } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
-import { useTableEditorStateSnapshot } from 'state/table-editor'
+import { type PlainObject } from 'lib/type-helpers'
+import { TableEditorStateContext, useTableEditorStateSnapshot } from 'state/table-editor'
import { Badge, Checkbox, Input, SidePanel } from 'ui'
import { Admonition } from 'ui-patterns'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import ActionBar from '../ActionBar'
import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
+import type { SaveTableParams } from '../SidePanelEditor'
import type { ColumnField } from '../SidePanelEditor.types'
import { SpreadsheetImport } from '../SpreadsheetImport/SpreadsheetImport'
import ColumnManagement from './ColumnManagement'
@@ -46,32 +41,21 @@ import {
validateFields,
} from './TableEditor.utils'
+type SaveTableParamsFor<Action extends SaveTableParams['action']> = Extract<
+ SaveTableParams,
+ { action: Action }
+>
+
+type SaveTablePayloadFor<Action extends SaveTableParams['action']> =
+ SaveTableParamsFor<Action>['payload']
+
export interface TableEditorProps {
table?: PostgresTable
isDuplicating: boolean
templateData?: Partial<TableField>
visible: boolean
closePanel: () => void
- saveChanges: (
- payload: {
- name: string
- schema: string
- comment?: string | null
- },
- columns: ColumnField[],
- foreignKeyRelations: ForeignKey[],
- isNewRecord: boolean,
- configuration: {
- tableId?: number
- importContent?: ImportContent
- isRLSEnabled: boolean
- isRealtimeEnabled: boolean
- isDuplicateRows: boolean
- existingForeignKeyRelations: ForeignKeyConstraint[]
- primaryKey?: Constraint
- },
- resolve: any
- ) => void
+ saveChanges: (params: SaveTableParams) => void
updateEditorDirty: () => void
}
@@ -84,23 +68,26 @@ export const TableEditor = ({
saveChanges = noop,
updateEditorDirty = noop,
}: TableEditorProps) => {
+ const tableEditorApi = useContext(TableEditorStateContext)
const snap = useTableEditorStateSnapshot()
+
const { data: project } = useSelectedProjectQuery()
const { data: org } = useSelectedOrganizationQuery()
const { selectedSchema } = useQuerySchemaState()
- const isNewRecord = isUndefined(table)
+
const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
+ const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
const { mutate: sendEvent } = useSendEventMutation()
- const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
+ const isNewRecord = isUndefined(table)
const [params, setParams] = useUrlState()
useEffect(() => {
if (params.create === 'table' && snap.ui.open === 'none') {
- snap.onAddTable()
+ tableEditorApi.onAddTable()
setParams({ ...params, create: undefined })
}
- }, [snap, params, setParams])
+ }, [tableEditorApi, setParams, snap.ui.open, params])
const { data: types } = useEnumeratedTypesQuery({
projectRef: project?.ref,
@@ -121,9 +108,9 @@ export const TableEditor = ({
const realtimeEnabledTables = realtimePublication?.tables ?? []
const isRealtimeEnabled = isNewRecord
? false
- : realtimeEnabledTables.some((t: any) => t.id === table?.id)
+ : realtimeEnabledTables.some((t) => t.id === table?.id)
- const [errors, setErrors] = useState<any>({})
+ const [errors, setErrors] = useState<PlainObject>({})
const [tableFields, setTableFields] = useState<TableField>()
const [fkRelations, setFkRelations] = useState<ForeignKey[]>([])
@@ -194,25 +181,22 @@ export const TableEditor = ({
setFkRelations(relations)
}
- const onSaveChanges = (resolve: any) => {
+ const onSaveChanges = (resolve: () => void) => {
if (tableFields) {
- const errors: any = validateFields(tableFields)
+ const errors = validateFields(tableFields)
if (errors.name) {
toast.error(errors.name)
}
-
if (errors.columns) {
toast.error(errors.columns)
}
setErrors(errors)
+ const isNameChanged = tableFields.name.trim() !== table?.name
+ const isCommentChanged = tableFields.comment !== table?.comment
+ const isRlsEnabledChanged = tableFields.isRLSEnabled !== (table?.rls_enabled ?? false)
+
if (isEmpty(errors)) {
- const payload = {
- name: tableFields.name.trim(),
- schema: selectedSchema,
- comment: tableFields.comment?.trim(),
- ...(!isNewRecord && { rls_enabled: tableFields.isRLSEnabled }),
- }
const configuration = {
tableId: table?.id,
importContent,
@@ -226,7 +210,48 @@ export const TableEditor = ({
return { ...column, name: column.name.trim() }
})
- saveChanges(payload, columns, fkRelations, isNewRecord, configuration, resolve)
+ if (isNewRecord) {
+ const payload: SaveTablePayloadFor<'create'> = {
+ name: tableFields.name.trim(),
+ schema: selectedSchema,
+ comment: tableFields.comment?.trim(),
+ }
+ saveChanges({
+ action: 'create',
+ payload,
+ configuration,
+ columns,
+ foreignKeyRelations: fkRelations,
+ resolve,
+ })
+ } else if (isDuplicating) {
+ const payload: SaveTablePayloadFor<'duplicate'> = {
+ name: tableFields.name.trim(),
+ comment: tableFields.comment?.trim(),
+ }
+ saveChanges({
+ action: 'duplicate',
+ payload,
+ configuration,
+ columns,
+ foreignKeyRelations: fkRelations,
+ resolve,
+ })
+ } else {
+ const payload: SaveTablePayloadFor<'update'> = {
+ ...(isNameChanged && { name: tableFields.name.trim() }),
+ ...(isCommentChanged && { comment: tableFields.comment?.trim() ?? '' }),
+ ...(isRlsEnabledChanged && { rls_enabled: tableFields.isRLSEnabled }),
+ }
+ saveChanges({
+ action: 'update',
+ payload,
+ configuration,
+ columns,
+ foreignKeyRelations: fkRelations,
+ resolve,
+ })
+ }
} else {
resolve()
}
@@ -295,7 +320,7 @@ export const TableEditor = ({
label="Name"
layout="horizontal"
type="text"
- error={errors.name}
+ error={errors.name ? String(errors.name) : undefined}
value={tableFields?.name}
onChange={(event: any) => onUpdateField({ name: event.target.value })}
/>
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
index 32e17c65317..2f068d8b259 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types.ts
@@ -4,7 +4,7 @@ import type { ColumnField } from '../SidePanelEditor.types'
export interface TableField {
id: number
name: string
- comment?: string
+ comment?: string | null
columns: ColumnField[]
isRLSEnabled: boolean
isRealtimeEnabled: boolean
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
index 76f3201fb0a..72a4674314e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
@@ -10,8 +10,13 @@ import type { ColumnField } from '../SidePanelEditor.types'
import { DEFAULT_COLUMNS } from './TableEditor.constants'
import type { ImportContent, TableField } from './TableEditor.types'
-export const validateFields = (field: TableField) => {
- const errors = {} as any
+type ValidateFieldsReturn = {
+ name?: string
+ columns?: string
+}
+
+export const validateFields = (field: TableField): ValidateFieldsReturn => {
+ const errors: ValidateFieldsReturn = {}
if (field.name.length === 0) {
errors['name'] = 'Please assign a name for your table'
}
@@ -44,7 +49,7 @@ export const generateTableFieldFromPostgresTable = (
return {
id: table.id,
name: isDuplicating ? `${table.name}_duplicate` : table.name,
- comment: isDuplicating ? `This is a duplicate of ${table.name}` : table?.comment ?? '',
+ comment: isDuplicating ? `This is a duplicate of ${table.name}` : table?.comment,
columns: (table.columns ?? []).map((column) => {
return generateColumnFieldFromPostgresColumn(column, table, foreignKeys)
}),
diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsx
index 97ca0cd5d4b..43623fd2d09 100644
--- a/apps/studio/state/table-editor.tsx
+++ b/apps/studio/state/table-editor.tsx
@@ -1,7 +1,8 @@
import type { PostgresColumn } from '@supabase/postgres-meta'
-import { PropsWithChildren, createContext, useContext, useRef } from 'react'
+import { PropsWithChildren, createContext, useContext } from 'react'
import { proxy, useSnapshot } from 'valtio'
+import { useConstant } from 'common'
import type { SupaRow } from 'components/grid/types'
import { ForeignKey } from 'components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types'
import type { EditValue } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'
@@ -210,7 +211,7 @@ export type TableEditorState = ReturnType<typeof createTableEditorState>
export const TableEditorStateContext = createContext<TableEditorState>(createTableEditorState())
export const TableEditorStateContextProvider = ({ children }: PropsWithChildren<{}>) => {
- const state = useRef(createTableEditorState()).current
+ const state = useConstant(createTableEditorState)
return (
<TableEditorStateContext.Provider value={state}>{children}</TableEditorStateContext.Provider>
diff --git a/packages/pg-meta/src/pg-meta-tables.ts b/packages/pg-meta/src/pg-meta-tables.ts
index 33d47193490..dd1faa265c0 100644
--- a/packages/pg-meta/src/pg-meta-tables.ts
+++ b/packages/pg-meta/src/pg-meta-tables.ts
@@ -144,9 +144,10 @@ type TableCreateParams = {
function create({ name, schema = 'public', comment }: TableCreateParams): { sql: string } {
const tableSql = `CREATE TABLE ${ident(schema)}.${ident(name)} ();`
- const commentSql = comment
- ? `COMMENT ON TABLE ${ident(schema)}.${ident(name)} IS ${literal(comment)};`
- : ''
+ const commentSql =
+ comment != undefined
+ ? `COMMENT ON TABLE ${ident(schema)}.${ident(name)} IS ${literal(comment)};`
+ : ''
const sql = `BEGIN; ${tableSql} ${commentSql} COMMIT;`
return { sql }
}
@@ -230,9 +231,11 @@ $$;
.join(',')});`
}
}
- const commentSql = !!comment
- ? `COMMENT ON TABLE ${ident(old.schema)}.${ident(old.name)} IS ${literal(comment)};`
- : ''
+ const commentSql =
+ comment == undefined
+ ? ''
+ : `COMMENT ON TABLE ${ident(old.schema)}.${ident(old.name)} IS ${literal(comment)};`
+
// nameSql must be last, right below schemaSql
const sql = `
BEGIN;
diff --git a/packages/ui/src/components/SidePanel/SidePanel.tsx b/packages/ui/src/components/SidePanel/SidePanel.tsx
index 2ef745d1f15..b1d9608229f 100644
--- a/packages/ui/src/components/SidePanel/SidePanel.tsx
+++ b/packages/ui/src/components/SidePanel/SidePanel.tsx
@@ -72,7 +72,7 @@ const SidePanel = ({
{cancelText}
</Button>
</div>
- {onConfirm !== undefined && (
+ {!!onConfirm && (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-block">
@@ -80,7 +80,7 @@ const SidePanel = ({
htmlType="submit"
disabled={disabled || loading}
loading={loading}
- onClick={() => (onConfirm ? onConfirm() : null)}
+ onClick={onConfirm}
>
{confirmText}
</Button>