Skip to content

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

chore: Migrate TableStore (#20033)

Ivan Vasilove81442de5625
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
index d77b6e299e5..a7c719afb56 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
@@ -1,8 +1,6 @@
import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
-import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common/hooks'
import { PolicyEditorModal, PolicyTableRow } from 'components/interfaces/Auth/Policies'
-import { useStore } from 'hooks'
import { isEmpty } from 'lodash'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
@@ -19,7 +17,7 @@ import InformationBox from 'components/ui/InformationBox'
import { useDatabasePolicyCreateMutation } from 'data/database-policies/database-policy-create-mutation'
import { useDatabasePolicyDeleteMutation } from 'data/database-policies/database-policy-delete-mutation'
import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
-import { tableKeys } from 'data/tables/keys'
+import { useTableUpdateMutation } from 'data/tables/table-update-mutation'
interface PoliciesProps {
tables: PostgresTable[]
@@ -38,8 +36,6 @@ const Policies = ({
const { ref } = useParams()
const { project } = useProjectContext()
- const { ui, meta } = useStore()
- const queryClient = useQueryClient()
const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const [selectedSchemaAndTable, setSelectedSchemaAndTable] = useState<any>({})
@@ -50,9 +46,19 @@ const Policies = ({
const { mutateAsync: createDatabasePolicy } = useDatabasePolicyCreateMutation()
const { mutateAsync: updateDatabasePolicy } = useDatabasePolicyUpdateMutation()
+ const { mutate: updateTable } = useTableUpdateMutation({
+ onError: (error) => {
+ toast.error(`Failed to toggle RLS: ${error.message}`)
+ },
+ onSettled: () => {
+ closeConfirmModal()
+ },
+ })
const { mutate: deleteDatabasePolicy } = useDatabasePolicyDeleteMutation({
onSuccess: () => {
toast.success('Successfully deleted policy!')
+ },
+ onSettled: () => {
closeConfirmModal()
},
})
@@ -70,7 +76,7 @@ const Policies = ({
setSelectedTableToToggleRLS({})
}
- const onSelectToggleRLS = (table: any) => {
+ const onSelectToggleRLS = (table: PostgresTable) => {
setSelectedTableToToggleRLS(table)
}
@@ -92,7 +98,7 @@ const Policies = ({
}
const onSavePolicySuccess = useCallback(async () => {
- ui.setNotification({ category: 'success', message: 'Policy successfully saved!' })
+ toast.success('Policy successfully saved!')
closePolicyEditorModal()
}, [closePolicyEditorModal])
@@ -103,16 +109,13 @@ const Policies = ({
rls_enabled: !selectedTableToToggleRLS.rls_enabled,
}
- const res: any = await meta.tables.update(payload.id, payload)
- if (res.error) {
- return ui.setNotification({
- category: 'error',
- message: `Failed to toggle RLS: ${res.error.message}`,
- })
- }
-
- await queryClient.invalidateQueries(tableKeys.list(ref, selectedTableToToggleRLS.schema))
- closeConfirmModal()
+ updateTable({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
+ id: payload.id,
+ schema: (selectedTableToToggleRLS as PostgresTable).schema,
+ payload: payload,
+ })
}
const onCreatePolicy = useCallback(
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
index 2e0469f3c06..62b57b56565 100644
--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
@@ -1,4 +1,3 @@
-import { useQueryClient } from '@tanstack/react-query'
import Link from 'next/link'
import toast from 'react-hot-toast'
import { Alert, Button, Checkbox, IconExternalLink, Modal } from 'ui'
@@ -8,13 +7,12 @@ import { formatFilterURLParams } from 'components/grid/SupabaseGrid.utils'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ConfirmationModal from 'components/ui/ConfirmationModal'
import { useDatabaseColumnDeleteMutation } from 'data/database-columns/database-column-delete-mutation'
-import { entityTypeKeys } from 'data/entity-types/keys'
import { useTableRowDeleteAllMutation } from 'data/table-rows/table-row-delete-all-mutation'
import { useTableRowDeleteMutation } from 'data/table-rows/table-row-delete-mutation'
import { useTableRowTruncateMutation } from 'data/table-rows/table-row-truncate-mutation'
+import { useTableDeleteMutation } from 'data/tables/table-delete-mutation'
import { useGetTables } from 'data/tables/tables-query'
-import { viewKeys } from 'data/views/keys'
-import { useStore, useUrlState } from 'hooks'
+import { useUrlState } from 'hooks'
import { TableLike } from 'hooks/misc/useTable'
import { noop } from 'lib/void'
import { useGetImpersonatedRole } from 'state/role-impersonation-state'
@@ -34,8 +32,6 @@ const DeleteConfirmationDialogs = ({
includeColumns = false,
onAfterDeleteTable = noop,
}: DeleteConfirmationDialogsProps) => {
- const { meta } = useStore()
- const queryClient = useQueryClient()
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
@@ -72,12 +68,26 @@ const DeleteConfirmationDialogs = ({
const selectedColumnToDelete = snap.confirmationDialog.column
removeDeletedColumnFromFiltersAndSorts(selectedColumnToDelete.name)
toast.success(`Successfully deleted column "${selectedColumnToDelete.name}"`)
- snap.closeConfirmationDialog()
},
onError: (error) => {
if (!(snap.confirmationDialog?.type === 'column')) return
const selectedColumnToDelete = snap.confirmationDialog.column
toast.error(`Failed to delete ${selectedColumnToDelete!.name}: ${error.message}`)
+ },
+ onSettled: () => {
+ snap.closeConfirmationDialog()
+ },
+ })
+ const { mutateAsync: deleteTable } = useTableDeleteMutation({
+ onSuccess: async () => {
+ const tables = await getTables(snap.selectedSchemaName)
+ onAfterDeleteTable(tables)
+ toast.success(`Successfully deleted table "${selectedTable?.name}"`)
+ },
+ onError: (error) => {
+ toast.error(`Failed to delete ${selectedTable?.name}: ${error.message}`)
+ },
+ onSettled: () => {
snap.closeConfirmationDialog()
},
})
@@ -88,10 +98,11 @@ const DeleteConfirmationDialogs = ({
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted selected row(s)`)
- snap.closeConfirmationDialog()
},
onError: (error) => {
toast.error(`Failed to delete row: ${error.message}`)
+ },
+ onSettled: () => {
snap.closeConfirmationDialog()
},
})
@@ -102,10 +113,11 @@ const DeleteConfirmationDialogs = ({
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted selected rows`)
- snap.closeConfirmationDialog()
},
onError: (error) => {
toast.error(`Failed to delete rows: ${error.message}`)
+ },
+ onSettled: () => {
snap.closeConfirmationDialog()
},
})
@@ -116,10 +128,11 @@ const DeleteConfirmationDialogs = ({
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted all rows from table`)
- snap.closeConfirmationDialog()
},
onError: (error) => {
toast.error(`Failed to delete rows: ${error.message}`)
+ },
+ onSettled: () => {
snap.closeConfirmationDialog()
},
})
@@ -157,36 +170,15 @@ const DeleteConfirmationDialogs = ({
if (!(snap.confirmationDialog?.type === 'table')) return
const selectedTableToDelete = selectedTable
- try {
- if (selectedTableToDelete === undefined) return
-
- const response: any = await meta.tables.del(selectedTableToDelete.id, isDeleteWithCascade)
- if (response.error) throw response.error
-
- const tables = await getTables(snap.selectedSchemaName)
-
- await Promise.all([
- queryClient.invalidateQueries(
- tableKeys.list(project?.ref, selectedTableToDelete.schema, includeColumns)
- ),
- queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
- // invalidate all views from this schema
- snap.selectedSchemaName
- ? queryClient.invalidateQueries(
- viewKeys.listBySchema(projectRef, snap.selectedSchemaName)
- )
- : null,
- // invalidate the view if there's a view with this id
- queryClient.invalidateQueries(viewKeys.view(projectRef, selectedTableToDelete?.id)),
- ])
+ if (selectedTableToDelete === undefined) return
- onAfterDeleteTable(tables)
- toast.success(`Successfully deleted table "${selectedTableToDelete.name}"`)
- } catch (error: any) {
- toast.error(`Failed to delete ${selectedTableToDelete?.name}: ${error.message}`)
- } finally {
- snap.closeConfirmationDialog()
- }
+ deleteTable({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
+ schema: selectedTableToDelete.schema,
+ id: selectedTableToDelete.id,
+ cascade: isDeleteWithCascade,
+ })
}
const getImpersonatedRole = useGetImpersonatedRole()
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 2fec34dc340..37966039e85 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -30,7 +30,15 @@ import {
ExtendedPostgresRelationship,
UpdateColumnPayload,
} from './SidePanelEditor.types'
-import { createColumn, updateColumn } from './SidePanelEditor.utils'
+import {
+ createColumn,
+ createTable,
+ duplicateTable,
+ insertRowsViaSpreadsheet,
+ insertTableRows,
+ updateColumn,
+ updateTable,
+} from './SidePanelEditor.utils'
import { ImportContent } from './TableEditor/TableEditor.types'
import { TextEditor } from './RowEditor/TextEditor'
@@ -53,7 +61,7 @@ const SidePanelEditor = ({
const snap = useTableEditorStateSnapshot()
const [_, setParams] = useUrlState({ arrayKeys: ['filter', 'sort'] })
- const { meta, ui } = useStore()
+ const { ui } = useStore()
const queryClient = useQueryClient()
const { project } = useProjectContext()
@@ -352,7 +360,11 @@ const SidePanelEditor = ({
}
const saveTable = async (
- payload: any,
+ payload: {
+ name: string
+ schema: string
+ comment?: string | undefined
+ },
columns: ColumnField[],
isNewRecord: boolean,
configuration: {
@@ -374,17 +386,17 @@ const SidePanelEditor = ({
snap.sidePanel.mode === 'duplicate' &&
selectedTable
) {
- const duplicateTable = selectedTable
+ const tableToDuplicate = selectedTable
toastId = ui.setNotification({
category: 'loading',
- message: `Duplicating table: ${duplicateTable.name}...`,
+ message: `Duplicating table: ${tableToDuplicate.name}...`,
})
- const table: any = await meta.duplicateTable(payload, {
+ const table = await duplicateTable(project?.ref!, project?.connectionString, payload, {
isRLSEnabled,
isDuplicateRows,
- duplicateTable,
+ duplicateTable: tableToDuplicate,
})
if (isRealtimeEnabled) await updateTableRealtime(table, isRealtimeEnabled)
@@ -396,7 +408,7 @@ const SidePanelEditor = ({
ui.setNotification({
id: toastId,
category: 'success',
- message: `Table ${duplicateTable.name} has been successfully duplicated into ${table.name}!`,
+ message: `Table ${tableToDuplicate.name} has been successfully duplicated into ${table.name}!`,
})
onTableCreated(table)
@@ -406,8 +418,16 @@ const SidePanelEditor = ({
message: `Creating new table: ${payload.name}...`,
})
- const table = await meta.createTable(toastId, payload, columns, isRLSEnabled, importContent)
- if (isRealtimeEnabled) await updateTableRealtime(table, true)
+ const table = await createTable(
+ project?.ref!,
+ project?.connectionString,
+ toastId,
+ payload,
+ columns,
+ isRLSEnabled,
+ importContent
+ )
+ if (isRealtimeEnabled) await updateTableRealtime(table as PostgresTable, true)
await Promise.all([
queryClient.invalidateQueries(tableKeys.list(project?.ref, table.schema, includeColumns)),
@@ -420,14 +440,21 @@ const SidePanelEditor = ({
message: `Table ${table.name} is good to go!`,
})
- onTableCreated(table)
+ onTableCreated(table as PostgresTable)
} else if (selectedTable) {
toastId = ui.setNotification({
category: 'loading',
message: `Updating table: ${selectedTable?.name}...`,
})
- const { table, hasError } = await meta.updateTable(toastId, selectedTable, payload, columns)
+ const { table, hasError } = await updateTable(
+ project?.ref!,
+ project?.connectionString,
+ toastId,
+ selectedTable,
+ payload,
+ columns
+ )
await updateTableRealtime(table, isRealtimeEnabled)
@@ -451,7 +478,7 @@ const SidePanelEditor = ({
])
),
queryClient.invalidateQueries(entityTypeKeys.list(project?.ref)),
- queryClient.invalidateQueries(tableKeys.table(project?.ref, table.schema)),
+ queryClient.invalidateQueries(tableKeys.table(project?.ref, table.id)),
])
ui.setNotification({
@@ -487,53 +514,63 @@ const SidePanelEditor = ({
if (file && rowCount > 0) {
// CSV file upload
- const { error }: any = await meta.insertRowsViaSpreadsheet(
- file,
- selectedTable,
- selectedHeaders,
- (progress: number) => {
+ try {
+ await insertRowsViaSpreadsheet(
+ project.ref!,
+ project.connectionString,
+ file,
+ selectedTable,
+ selectedHeaders,
+ (progress: number) => {
+ ui.setNotification({
+ id: toastId,
+ progress,
+ category: 'loading',
+ message: `Adding ${rowCount.toLocaleString()} rows to ${selectedTable.name}`,
+ })
+ }
+ )
+ } catch (error: any) {
+ if (error) {
ui.setNotification({
+ error,
id: toastId,
- progress,
- category: 'loading',
- message: `Adding ${rowCount.toLocaleString()} rows to ${selectedTable.name}`,
+ category: 'error',
+ message: `Failed to import data: ${error.message}`,
})
+ return resolve()
}
- )
- if (error) {
- ui.setNotification({
- error,
- id: toastId,
- category: 'error',
- message: `Failed to import data: ${error.message}`,
- })
- return resolve()
}
} else {
// Text paste
- const { error } = await meta.insertTableRows(
- selectedTable,
- importContent.rows,
- selectedHeaders,
- (progress: number) => {
+ try {
+ await insertTableRows(
+ project.ref!,
+ project.connectionString,
+ selectedTable,
+ importContent.rows,
+ selectedHeaders,
+ (progress: number) => {
+ ui.setNotification({
+ id: toastId,
+ progress,
+ category: 'loading',
+ message: `Adding ${importContent.rows.length.toLocaleString()} rows to ${
+ selectedTable.name
+ }`,
+ })
+ }
+ )
+ } catch (error: any) {
+ if (error) {
ui.setNotification({
+ error,
id: toastId,
- progress,
- category: 'loading',
- message: `Adding ${importContent.rows.length.toLocaleString()} rows to ${
- selectedTable.name
- }`,
+ category: 'error',
+ message: `Failed to import data: ${error.message}`,
})
+ return resolve()
}
- )
- if (error) {
- ui.setNotification({
- error,
- id: toastId,
- category: 'error',
- message: `Failed to import data: ${error.message}`,
- })
- return resolve()
}
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.ts
deleted file mode 100644
index 55edf993958..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-import { PostgresRelationship, PostgresTable } from '@supabase/postgres-meta'
-import { find } from 'lodash'
-import { useEffect, useState } from 'react'
-import toast from 'react-hot-toast'
-
-import { createDatabaseColumn } from 'data/database-columns/database-column-create-mutation'
-import { updateDatabaseColumn } from 'data/database-columns/database-column-update-mutation'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
-import { executeSql } from 'data/sql/execute-sql-query'
-import { getViews } from 'data/views/views-query'
-import { useStore } from 'hooks'
-import { IMetaStore } from 'stores/pgmeta/MetaStore'
-import {
- CreateColumnPayload,
- ExtendedPostgresRelationship,
- UpdateColumnPayload,
-} from './SidePanelEditor.types'
-
-export interface UseEncryptedColumnsArgs {
- schemaName?: string
- tableName?: string
-}
-
-const listEncryptedColumns = async (meta: IMetaStore, schema: string, table: string) => {
- if (!table) return []
-
- const views = await getViews({
- projectRef: meta.projectRef,
- connectionString: meta.connectionString,
- schema,
- })
- const decryptedView = views.find((view) => view.name === `decrypted_${table}`)
- if (!decryptedView) return []
-
- const encryptedColumns = await meta.query(
- `SELECT column_name as name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'decrypted_${table}' and column_name like 'decrypted_%'`
- )
- if (!encryptedColumns.error) {
- return encryptedColumns.map((column: any) => column.name.split('decrypted_')[1])
- } else {
- console.error('Error fetching encrypted columns', encryptedColumns.error)
- return []
- }
-}
-
-export function useEncryptedColumns({ schemaName, tableName }: UseEncryptedColumnsArgs) {
- const { meta } = useStore()
- const [encryptedColumns, setEncryptedColumns] = useState<string[]>([])
-
- useEffect(() => {
- let isMounted = true
-
- const getEncryptedColumns = async () => {
- if (schemaName !== undefined && tableName !== undefined) {
- const columns = await listEncryptedColumns(meta, schemaName, tableName)
-
- if (isMounted) {
- setEncryptedColumns(columns)
- }
- }
- }
-
- getEncryptedColumns()
-
- return () => {
- isMounted = false
- }
- }, [schemaName, tableName])
-
- return encryptedColumns
-}
-
-/**
- * The functions below are basically just queries but may be supported directly
- * from the pg-meta library in the future
- */
-export const addPrimaryKey = async (
- projectRef: string,
- connectionString: string | undefined,
- schema: string,
- table: string,
- columns: string[]
-) => {
- const primaryKeyColumns = columns.join('","')
- const query = `ALTER TABLE "${schema}"."${table}" ADD PRIMARY KEY ("${primaryKeyColumns}")`
- return await executeSql({
- projectRef: projectRef,
- connectionString: connectionString,
- sql: query,
- queryKey: ['primary-keys'],
- })
-}
-
-export const removePrimaryKey = async (
- projectRef: string,
- connectionString: string | undefined,
- schema: string,
- table: string
-) => {
- const query = `ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${table}_pkey"`
- return await executeSql({
- projectRef: projectRef,
- connectionString: connectionString,
- sql: query,
- queryKey: ['primary-keys'],
- })
-}
-
-// [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
- ? 'ON DELETE CASCADE'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
- ? 'ON DELETE RESTRICT'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
- ? 'ON DELETE SET DEFAULT'
- : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
- ? 'ON DELETE SET NULL'
- : ''
- const updateAction =
- update_action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
- ? 'ON UPDATE CASCADE'
- : update_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
- ? 'ON UPDATE RESTRICT'
- : ''
-
- 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()
- return await executeSql({
- projectRef: projectRef,
- connectionString: connectionString,
- sql: query,
- queryKey: ['foreign-keys'],
- })
-}
-
-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`
- const query = `
- ALTER TABLE "${relationship.source_schema}"."${relationship.source_table_name}"
- DROP CONSTRAINT IF EXISTS "${constraintName}"
- `
- .replace(/\s+/g, ' ')
- .trim()
- return await executeSql({
- projectRef: projectRef,
- connectionString: connectionString,
- sql: query,
- queryKey: ['foreign-keys'],
- })
-}
-
-/**
- * The methods below involve several contexts due to the UI flow of the
- * dashboard and hence do not sit within their own stores
- */
-export const createColumn = async ({
- projectRef,
- connectionString,
- payload,
- selectedTable,
- foreignKey,
-}: {
- projectRef: string
- connectionString: string | undefined
- payload: CreateColumnPayload
- selectedTable: PostgresTable
- foreignKey?: ExtendedPostgresRelationship
-}) => {
- const toastId = toast.loading(`Creating column "${payload.name}"...`)
- try {
- // Once pg-meta supports composite keys, we can remove this logic
- const { isPrimaryKey, ...formattedPayload } = payload
- const column = await createDatabaseColumn({
- projectRef: projectRef,
- connectionString: connectionString,
- payload: formattedPayload,
- })
-
- // Firing createColumn in createTable will bypass this block
- if (isPrimaryKey) {
- toast.loading('Assigning primary key to column...', { id: toastId })
- // Same logic in createTable: Remove any primary key constraints first (we'll add it back later)
- const existingPrimaryKeys = selectedTable.primary_keys.map((x) => x.name)
-
- if (existingPrimaryKeys.length > 0) {
- await removePrimaryKey(projectRef, connectionString, column.schema, column.table)
- }
-
- const primaryKeyColumns = existingPrimaryKeys.concat([column.name])
- await addPrimaryKey(
- projectRef,
- connectionString,
- column.schema,
- column.table,
- 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 })
- return { error }
- }
-}
-
-export const updateColumn = async ({
- projectRef,
- connectionString,
- id,
- payload,
- selectedTable,
- foreignKey,
- skipPKCreation,
- skipSuccessMessage = false,
-}: {
- projectRef: string
- connectionString: string | undefined
- id: string
- payload: UpdateColumnPayload
- selectedTable: PostgresTable
- foreignKey?: ExtendedPostgresRelationship
- skipPKCreation?: boolean
- skipSuccessMessage?: boolean
-}) => {
- try {
- const { isPrimaryKey, ...formattedPayload } = payload
- const column = await updateDatabaseColumn({
- projectRef: projectRef,
- connectionString: connectionString,
- id,
- payload: formattedPayload,
- })
-
- const originalColumn = find(selectedTable.columns, { id })
- const existingForeignKey = find(selectedTable.relationships, {
- source_column_name: originalColumn!.name,
- })
-
- if (!skipPKCreation && isPrimaryKey !== undefined) {
- const existingPrimaryKeys = selectedTable.primary_keys.map((x) => x.name)
-
- // Primary key is getting updated for the column
- if (existingPrimaryKeys.length > 0) {
- await removePrimaryKey(projectRef, connectionString, column.schema, column.table)
- }
-
- const primaryKeyColumns = isPrimaryKey
- ? existingPrimaryKeys.concat([column.name])
- : existingPrimaryKeys.filter((x) => x !== column.name)
-
- if (primaryKeyColumns.length) {
- await addPrimaryKey(
- projectRef,
- connectionString,
- column.schema,
- column.table,
- primaryKeyColumns
- )
- }
- }
-
- // 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}"`)
- }
- } catch (error: any) {
- return { error }
- }
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
new file mode 100644
index 00000000000..cc69c0880ad
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -0,0 +1,827 @@
+import { PostgresPrimaryKey, PostgresRelationship, 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 { 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 { getQueryClient } from 'data/query-client'
+import { executeSql } from 'data/sql/execute-sql-query'
+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'
+import { getTable } from 'data/tables/table-query'
+import { updateTable as updateTableMutation } from 'data/tables/table-update-mutation'
+import { getTables } from 'data/tables/tables-query'
+import { getViews } from 'data/views/views-query'
+import { useStore } from 'hooks'
+import { timeout, tryParseJson } from 'lib/helpers'
+import { IMetaStore } from 'stores/pgmeta/MetaStore'
+import {
+ generateCreateColumnPayload,
+ generateUpdateColumnPayload,
+} from './ColumnEditor/ColumnEditor.utils'
+import {
+ ColumnField,
+ CreateColumnPayload,
+ ExtendedPostgresRelationship,
+ UpdateColumnPayload,
+} from './SidePanelEditor.types'
+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
+
+export interface UseEncryptedColumnsArgs {
+ schemaName?: string
+ tableName?: string
+}
+
+const listEncryptedColumns = async (meta: IMetaStore, schema: string, table: string) => {
+ if (!table) return []
+
+ const views = await getViews({
+ projectRef: meta.projectRef,
+ connectionString: meta.connectionString,
+ schema,
+ })
+ const decryptedView = views.find((view) => view.name === `decrypted_${table}`)
+ if (!decryptedView) return []
+
+ const encryptedColumns = await meta.query(
+ `SELECT column_name as name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'decrypted_${table}' and column_name like 'decrypted_%'`
+ )
+ if (!encryptedColumns.error) {
+ return encryptedColumns.map((column: any) => column.name.split('decrypted_')[1])
+ } else {
+ console.error('Error fetching encrypted columns', encryptedColumns.error)
+ return []
+ }
+}
+
+export function useEncryptedColumns({ schemaName, tableName }: UseEncryptedColumnsArgs) {
+ const { meta } = useStore()
+ const [encryptedColumns, setEncryptedColumns] = useState<string[]>([])
+
+ useEffect(() => {
+ let isMounted = true
+
+ const getEncryptedColumns = async () => {
+ if (schemaName !== undefined && tableName !== undefined) {
+ const columns = await listEncryptedColumns(meta, schemaName, tableName)
+
+ if (isMounted) {
+ setEncryptedColumns(columns)
+ }
+ }
+ }
+
+ getEncryptedColumns()
+
+ return () => {
+ isMounted = false
+ }
+ }, [schemaName, tableName])
+
+ return encryptedColumns
+}
+
+/**
+ * The functions below are basically just queries but may be supported directly
+ * from the pg-meta library in the future
+ */
+export const addPrimaryKey = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ schema: string,
+ table: string,
+ columns: string[]
+) => {
+ const primaryKeyColumns = columns.join('","')
+ const query = `ALTER TABLE "${schema}"."${table}" ADD PRIMARY KEY ("${primaryKeyColumns}")`
+ return await executeSql({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ sql: query,
+ queryKey: ['primary-keys'],
+ })
+}
+
+export const removePrimaryKey = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ schema: string,
+ table: string
+) => {
+ const query = `ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${table}_pkey"`
+ return await executeSql({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ sql: query,
+ queryKey: ['primary-keys'],
+ })
+}
+
+// [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
+ ? 'ON DELETE CASCADE'
+ : deletion_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ ? 'ON DELETE RESTRICT'
+ : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_DEFAULT
+ ? 'ON DELETE SET DEFAULT'
+ : deletion_action === FOREIGN_KEY_CASCADE_ACTION.SET_NULL
+ ? 'ON DELETE SET NULL'
+ : ''
+ const updateAction =
+ update_action === FOREIGN_KEY_CASCADE_ACTION.CASCADE
+ ? 'ON UPDATE CASCADE'
+ : update_action === FOREIGN_KEY_CASCADE_ACTION.RESTRICT
+ ? 'ON UPDATE RESTRICT'
+ : ''
+
+ 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()
+ return await executeSql({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ sql: query,
+ queryKey: ['foreign-keys'],
+ })
+}
+
+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`
+ const query = `
+ ALTER TABLE "${relationship.source_schema}"."${relationship.source_table_name}"
+ DROP CONSTRAINT IF EXISTS "${constraintName}"
+ `
+ .replace(/\s+/g, ' ')
+ .trim()
+ return await executeSql({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ sql: query,
+ queryKey: ['foreign-keys'],
+ })
+}
+
+/**
+ * The methods below involve several contexts due to the UI flow of the
+ * dashboard and hence do not sit within their own stores
+ */
+export const createColumn = async ({
+ projectRef,
+ connectionString,
+ payload,
+ selectedTable,
+ foreignKey,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ payload: CreateColumnPayload
+ selectedTable: PostgresTable
+ foreignKey?: ExtendedPostgresRelationship
+}) => {
+ const toastId = toast.loading(`Creating column "${payload.name}"...`)
+ try {
+ // Once pg-meta supports composite keys, we can remove this logic
+ const { isPrimaryKey, ...formattedPayload } = payload
+ const column = await createDatabaseColumn({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ payload: formattedPayload,
+ })
+
+ // Firing createColumn in createTable will bypass this block
+ if (isPrimaryKey) {
+ toast.loading('Assigning primary key to column...', { id: toastId })
+ // Same logic in createTable: Remove any primary key constraints first (we'll add it back later)
+ const existingPrimaryKeys = selectedTable.primary_keys.map((x) => x.name)
+
+ if (existingPrimaryKeys.length > 0) {
+ await removePrimaryKey(projectRef, connectionString, column.schema, column.table)
+ }
+
+ const primaryKeyColumns = existingPrimaryKeys.concat([column.name])
+ await addPrimaryKey(
+ projectRef,
+ connectionString,
+ column.schema,
+ column.table,
+ 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 })
+ return { error }
+ }
+}
+
+export const updateColumn = async ({
+ projectRef,
+ connectionString,
+ id,
+ payload,
+ selectedTable,
+ foreignKey,
+ skipPKCreation,
+ skipSuccessMessage = false,
+}: {
+ projectRef: string
+ connectionString: string | undefined
+ id: string
+ payload: UpdateColumnPayload
+ selectedTable: PostgresTable
+ foreignKey?: ExtendedPostgresRelationship
+ skipPKCreation?: boolean
+ skipSuccessMessage?: boolean
+}) => {
+ try {
+ const { isPrimaryKey, ...formattedPayload } = payload
+ const column = await updateDatabaseColumn({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ id,
+ 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)
+
+ // Primary key is getting updated for the column
+ if (existingPrimaryKeys.length > 0) {
+ await removePrimaryKey(projectRef, connectionString, column.schema, column.table)
+ }
+
+ const primaryKeyColumns = isPrimaryKey
+ ? existingPrimaryKeys.concat([column.name])
+ : existingPrimaryKeys.filter((x) => x !== column.name)
+
+ if (primaryKeyColumns.length) {
+ await addPrimaryKey(
+ projectRef,
+ connectionString,
+ column.schema,
+ column.table,
+ primaryKeyColumns
+ )
+ }
+ }
+
+ // 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}"`)
+ }
+ } catch (error: any) {
+ return { error }
+ }
+}
+
+export const duplicateTable = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ payload: { name: string },
+ metadata: {
+ duplicateTable: PostgresTable
+ isRLSEnabled: boolean
+ isDuplicateRows: boolean
+ }
+) => {
+ const { duplicateTable, isRLSEnabled, isDuplicateRows } = metadata
+ const { name: sourceTableName, schema: sourceTableSchema } = duplicateTable
+ const duplicatedTableName = payload.name
+
+ // The following query will copy the structure of the table along with indexes, constraints and
+ // triggers. However, foreign key constraints are not duplicated over - has to be done separately
+ await executeSql({
+ projectRef,
+ connectionString,
+ sql: `CREATE TABLE "${sourceTableSchema}"."${duplicatedTableName}" (LIKE "${sourceTableSchema}"."${sourceTableName}" INCLUDING ALL);`,
+ })
+
+ // 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,
+ })
+ })
+ }
+
+ // Duplicate rows if needed
+ if (isDuplicateRows) {
+ const rows = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `INSERT INTO "${sourceTableSchema}"."${duplicatedTableName}" SELECT * FROM "${sourceTableSchema}"."${sourceTableName}";`,
+ })
+
+ // Insert into does not copy over auto increment sequences, so we manually do it next if any
+ const columns = duplicateTable.columns ?? []
+ const identityColumns = columns.filter((column) => column.identity_generation !== null)
+ identityColumns.map(async (column) => {
+ const identity = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT setval('"${sourceTableSchema}"."${duplicatedTableName}_${column.name}_seq"', (SELECT MAX("${column.name}") FROM "${sourceTableSchema}"."${sourceTableName}"));`,
+ })
+ })
+ }
+
+ const queryClient = getQueryClient()
+ const tables = await queryClient.fetchQuery({
+ queryKey: tableKeys.list(projectRef, sourceTableSchema),
+ queryFn: ({ signal }) =>
+ getTables({ projectRef, connectionString, schema: sourceTableSchema }, signal),
+ })
+
+ const duplicatedTable = find(tables, { schema: sourceTableSchema, name: duplicatedTableName })!
+
+ if (isRLSEnabled) {
+ await updateTableMutation({
+ projectRef,
+ connectionString,
+ id: duplicatedTable?.id!,
+ schema: duplicatedTable?.schema!,
+ payload: { rls_enabled: isRLSEnabled },
+ })
+ }
+
+ return duplicatedTable
+}
+
+export const createTable = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ toastId: string,
+ payload: {
+ name: string
+ schema: string
+ comment?: string | undefined
+ },
+ columns: ColumnField[] = [],
+ isRLSEnabled: boolean,
+ importContent?: ImportContent
+) => {
+ // Create the table first. Error may be thrown.
+ const table = await createTableMutation({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ payload: payload,
+ })
+
+ // If we face any errors during this process after the actual table creation
+ // We'll delete the table as a way to clean up and not leave behind bits that
+ // got through successfully. This is so that the user can continue editing in
+ // the table side panel editor conveniently
+ try {
+ // Toggle RLS if configured to be
+ if (isRLSEnabled) {
+ await updateTableMutation({
+ projectRef,
+ connectionString,
+ id: table.id,
+ schema: table.schema,
+ payload: { rls_enabled: isRLSEnabled },
+ })
+ }
+
+ // Then insert the columns - we don't do Promise.all as we want to keep the integrity
+ // of the column order during creation. Note that we add primary key constraints separately
+ // via the query endpoint to support composite primary keys as pg-meta does not support that OOB
+ toast.loading(`Adding ${columns.length} columns to ${table.name}...`, { id: toastId })
+
+ for (const column of columns) {
+ // We create all columns without primary keys first
+ const columnPayload = generateCreateColumnPayload(table.id, {
+ ...column,
+ isPrimaryKey: false,
+ })
+ await createDatabaseColumn({
+ projectRef,
+ connectionString,
+ payload: columnPayload,
+ })
+ }
+
+ // Then add the primary key constraints here to support composite keys
+ const primaryKeyColumns = columns
+ .filter((column: ColumnField) => column.isPrimaryKey)
+ .map((column: ColumnField) => column.name)
+ if (primaryKeyColumns.length > 0) {
+ await addPrimaryKey(projectRef, connectionString, table.schema, table.name, primaryKeyColumns)
+ }
+
+ // Then add the foreign key constraints here
+ for (const column of columns) {
+ if (column.foreignKey !== undefined) {
+ await addForeignKey(projectRef, connectionString, column.foreignKey)
+ }
+ }
+
+ // If the user is importing data via a spreadsheet
+ if (importContent !== undefined) {
+ if (importContent.file && importContent.rowCount > 0) {
+ // Via a CSV file
+ const { error }: any = await insertRowsViaSpreadsheet(
+ projectRef,
+ connectionString,
+ importContent.file,
+ table as PostgresTable,
+ importContent.selectedHeaders,
+ (progress: number) => {
+ toast.loading(
+ <div className="flex flex-col space-y-2" style={{ minWidth: '220px' }}>
+ <SparkBar
+ value={progress}
+ max={100}
+ type="horizontal"
+ barClass="bg-brand"
+ labelBottom={`Adding ${importContent.rowCount.toLocaleString()} rows to ${table.name}`}
+ labelBottomClass=""
+ labelTop={`${progress.toFixed(2)}%`}
+ labelTopClass="tabular-nums"
+ />
+ </div>,
+ { id: toastId }
+ )
+ }
+ )
+
+ // For identity columns, manually raise the sequences
+ const identityColumns = columns.filter((column) => column.isIdentity)
+ for (const column of identityColumns) {
+ await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT setval('${table.name}_${column.name}_seq', (SELECT MAX("${column.name}") FROM "${table.name}"));`,
+ })
+ }
+
+ if (error !== undefined) {
+ toast.error('Do check your spreadsheet if there are any discrepancies.')
+
+ const message = `Table ${table.name} has been created but we ran into an error while inserting rows: ${error.message}`
+ toast.error(message)
+ console.error('Error:', { error, message })
+ }
+ } else {
+ // Via text copy and paste
+ await insertTableRows(
+ projectRef,
+ connectionString,
+ table as PostgresTable,
+ importContent.rows,
+ importContent.selectedHeaders,
+ (progress: number) => {
+ toast.loading(
+ <div className="flex flex-col space-y-2" style={{ minWidth: '220px' }}>
+ <SparkBar
+ value={progress}
+ max={100}
+ type="horizontal"
+ barClass="bg-brand"
+ labelBottom={`Adding ${importContent.rows.length.toLocaleString()} rows to ${table.name}`}
+ labelBottomClass=""
+ labelTop={`${progress.toFixed(2)}%`}
+ labelTopClass="tabular-nums"
+ />
+ </div>,
+ { id: toastId }
+ )
+ }
+ )
+
+ // For identity columns, manually raise the sequences
+ const identityColumns = columns.filter((column) => column.isIdentity)
+ for (const column of identityColumns) {
+ await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT setval('${table.name}_${column.name}_seq', (SELECT MAX("${column.name}") FROM "${table.name}"));`,
+ })
+ }
+ }
+ }
+
+ // Finally, return the created table
+ return table
+ } catch (error) {
+ deleteTableMutation({
+ projectRef,
+ connectionString,
+ id: table.id,
+ schema: table.schema,
+ })
+ throw error
+ }
+}
+
+export const updateTable = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ toastId: string,
+ table: PostgresTable,
+ payload: any,
+ columns: ColumnField[]
+) => {
+ // Prepare a check to see if primary keys to the tables were updated or not
+ 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)
+
+ if (isPrimaryKeyUpdated) {
+ // Remove any primary key constraints first (we'll add it back later)
+ // If we do it later, and if the user deleted a PK column, we'd need to do
+ // an additional check when removing PK if the column in the PK was removed
+ // So doing this one step earlier, lets us skip that additional check.
+ if (table.primary_keys.length > 0) {
+ await removePrimaryKey(projectRef, connectionString, table.schema, table.name)
+ }
+ }
+
+ // Update the table
+ const updatedTable = await updateTableMutation({
+ projectRef,
+ connectionString,
+ id: table.id,
+ schema: table.schema,
+ payload,
+ })
+
+ const originalColumns = table.columns ?? []
+ const columnIds = columns.map((column) => column.id)
+
+ // Delete any removed columns
+ const columnsToRemove = originalColumns.filter((column) => !columnIds.includes(column.id))
+ for (const column of columnsToRemove) {
+ toast.loading(`Removing column ${column.name} from ${updatedTable.name}`, { id: toastId })
+ await deleteDatabaseColumn({
+ projectRef,
+ connectionString,
+ id: column.id,
+ })
+ }
+
+ // Add any new columns / Update any existing columns
+ let hasError = false
+ for (const column of columns) {
+ if (!column.id.includes(table.id.toString())) {
+ toast.loading(`Adding column ${column.name} to ${updatedTable.name}`, { id: toastId })
+ // Ensure that columns do not created as primary key first, cause the primary key will
+ // be added later on further down in the code
+ const columnPayload = generateCreateColumnPayload(updatedTable.id, {
+ ...column,
+ isPrimaryKey: false,
+ })
+ await createColumn({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ payload: columnPayload,
+ selectedTable: updatedTable as PostgresTable,
+ foreignKey: column.foreignKey,
+ })
+ } else {
+ const originalColumn = find(originalColumns, { id: column.id })
+ if (originalColumn) {
+ const columnPayload = generateUpdateColumnPayload(
+ originalColumn,
+ 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) {
+ toast.loading(`Updating column ${column.name} from ${updatedTable.name}`, { id: toastId })
+ const skipPKCreation = true
+ const skipSuccessMessage = true
+ const res = await updateColumn({
+ projectRef: projectRef,
+ connectionString: connectionString,
+ id: column.id,
+ payload: columnPayload,
+ selectedTable: updatedTable as PostgresTable,
+ foreignKey: column.foreignKey,
+ skipPKCreation,
+ skipSuccessMessage,
+ })
+ if (res?.error) {
+ hasError = true
+ toast.error(`Failed to update column "${column.name}": ${res.error.message}`)
+ }
+ }
+ }
+ }
+ }
+
+ // Then add back the primary keys again
+ if (isPrimaryKeyUpdated && primaryKeyColumns.length > 0) {
+ await addPrimaryKey(
+ projectRef,
+ connectionString,
+ updatedTable.schema,
+ updatedTable.name,
+ primaryKeyColumns
+ )
+ }
+
+ const queryClient = getQueryClient()
+
+ await Promise.all([
+ queryClient.invalidateQueries(sqlKeys.query(projectRef, ['foreign-key-constraints'])),
+ // invalidate list of tables, as well as visible individual tables
+ queryClient.invalidateQueries(['projects', projectRef, 'tables']),
+ queryClient.invalidateQueries(sqlKeys.query(projectRef, [table.schema, table.name])),
+ queryClient.invalidateQueries(
+ sqlKeys.query(projectRef, ['table-definition', table.schema, table.name])
+ ),
+ queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
+ ])
+
+ return {
+ table: await getTable({
+ projectRef,
+ connectionString,
+ id: table.id,
+ }),
+ hasError,
+ }
+}
+
+export const insertRowsViaSpreadsheet = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ file: any,
+ table: PostgresTable,
+ selectedHeaders: string[],
+ onProgressUpdate: (progress: number) => void
+) => {
+ let chunkNumber = 0
+ let insertError: any = undefined
+ const t1: any = new Date()
+ return new Promise((resolve) => {
+ Papa.parse(file, {
+ header: true,
+ // dynamicTyping has to be disabled so that "00001" doesn't get parsed as 1.
+ dynamicTyping: false,
+ skipEmptyLines: true,
+ chunkSize: CHUNK_SIZE,
+ quoteChar: file.type === 'text/tab-separated-values' ? '' : '"',
+ chunk: async (results: any, parser: any) => {
+ parser.pause()
+
+ const formattedData = results.data.map((row: any) => {
+ const formattedRow: any = {}
+ selectedHeaders.forEach((header) => {
+ const column = table.columns?.find((c) => c.name === header)
+ if ((column?.data_type ?? '') === 'ARRAY' || (column?.format ?? '').includes('json')) {
+ formattedRow[header] = tryParseJson(row[header])
+ } else if (row[header] === '') {
+ // if the cell is empty string, convert it to NULL
+ formattedRow[header] = null
+ } else {
+ formattedRow[header] = row[header]
+ }
+ })
+ return formattedRow
+ })
+
+ const insertQuery = new Query().from(table.name, table.schema).insert(formattedData).toSql()
+ try {
+ await executeSql({ projectRef, connectionString, sql: insertQuery })
+ } catch (error) {
+ console.warn(error)
+ insertError = error
+ parser.abort()
+ }
+
+ chunkNumber += 1
+ const progress = (chunkNumber * CHUNK_SIZE) / file.size
+ const progressPercentage = progress > 1 ? 100 : progress * 100
+ onProgressUpdate(progressPercentage)
+ parser.resume()
+ },
+ complete: () => {
+ const t2: any = new Date()
+ console.log(`Total time taken for importing spreadsheet: ${(t2 - t1) / 1000} seconds`)
+ resolve({ error: insertError })
+ },
+ })
+ })
+}
+
+export const insertTableRows = async (
+ projectRef: string,
+ connectionString: string | undefined,
+ table: PostgresTable,
+ rows: any,
+ selectedHeaders: string[],
+ onProgressUpdate: (progress: number) => void
+) => {
+ let insertError = undefined
+ let insertProgress = 0
+
+ const formattedRows = rows.map((row: any) => {
+ const formattedRow: any = {}
+ selectedHeaders.forEach((header) => {
+ const column = table.columns?.find((c) => c.name === header)
+ if ((column?.data_type ?? '') === 'ARRAY' || (column?.format ?? '').includes('json')) {
+ formattedRow[header] = tryParseJson(row[header])
+ } else {
+ formattedRow[header] = row[header]
+ }
+ })
+ return formattedRow
+ })
+
+ const batches = chunk(formattedRows, BATCH_SIZE)
+ const promises = batches.map((batch: any) => {
+ return () => {
+ return Promise.race([
+ new Promise(async (resolve, reject) => {
+ const insertQuery = new Query().from(table.name, table.schema).insert(batch).toSql()
+ try {
+ await executeSql({ projectRef, connectionString, sql: insertQuery })
+ } catch (error) {
+ insertError = error
+ reject(error)
+ }
+
+ insertProgress = insertProgress + batch.length / rows.length
+ resolve({})
+ }),
+ timeout(30000),
+ ])
+ }
+ })
+
+ const batchedPromises = chunk(promises, 10)
+ for (const batchedPromise of batchedPromises) {
+ const res = await Promise.allSettled(batchedPromise.map((batch) => batch()))
+ const hasFailedBatch = find(res, { status: 'rejected' })
+ if (hasFailedBatch) break
+ onProgressUpdate(insertProgress * 100)
+ }
+ return { error: insertError }
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index 16793e27741..a05833b938a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -14,7 +14,7 @@ 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 { ColumnField, CreateTablePayload, UpdateTablePayload } from '../SidePanelEditor.types'
+import { ColumnField } from '../SidePanelEditor.types'
import ColumnManagement from './ColumnManagement'
import HeaderTitle from './HeaderTitle'
import RLSDisableModalContent from './RLSDisableModal'
@@ -33,7 +33,11 @@ export interface TableEditorProps {
visible: boolean
closePanel: () => void
saveChanges: (
- payload: any,
+ payload: {
+ name: string
+ schema: string
+ comment?: string | undefined
+ },
columns: ColumnField[],
isNewRecord: boolean,
configuration: {
@@ -144,7 +148,7 @@ const TableEditor = ({
setErrors(errors)
if (isEmpty(errors)) {
- const payload: CreateTablePayload | UpdateTablePayload = {
+ const payload = {
name: tableFields.name,
schema: snap.selectedSchemaName,
comment: tableFields.comment,
diff --git a/apps/studio/data/tables/table-create-mutation.ts b/apps/studio/data/tables/table-create-mutation.ts
new file mode 100644
index 00000000000..62f27e27f58
--- /dev/null
+++ b/apps/studio/data/tables/table-create-mutation.ts
@@ -0,0 +1,66 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { components } from 'data/api'
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { tableKeys } from './keys'
+
+export type CreateTableBody = components['schemas']['CreateTableBody']
+
+export type TableCreateVariables = {
+ projectRef: string
+ connectionString?: string
+ // the schema is required field
+ payload: CreateTableBody & { schema: string }
+}
+
+export async function createTable({ projectRef, connectionString, payload }: TableCreateVariables) {
+ let headers = new Headers()
+ if (connectionString) headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await post('/platform/pg-meta/{ref}/tables', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString! },
+ path: { ref: projectRef },
+ },
+ body: payload,
+ headers,
+ })
+
+ if (error) throw error
+ return data
+}
+
+type TableCreateData = Awaited<ReturnType<typeof createTable>>
+
+export const useTableCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<TableCreateData, ResponseError, TableCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<TableCreateData, ResponseError, TableCreateVariables>(
+ (vars) => createTable(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, payload } = variables
+
+ await queryClient.invalidateQueries(tableKeys.list(projectRef, payload.schema))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to create database table: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/tables/table-delete-mutation.ts b/apps/studio/data/tables/table-delete-mutation.ts
new file mode 100644
index 00000000000..d6937c3efb9
--- /dev/null
+++ b/apps/studio/data/tables/table-delete-mutation.ts
@@ -0,0 +1,79 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { entityTypeKeys } from 'data/entity-types/keys'
+import { del } from 'data/fetchers'
+import { viewKeys } from 'data/views/keys'
+import { ResponseError } from 'types'
+import { tableKeys } from './keys'
+
+export type TableDeleteVariables = {
+ projectRef: string
+ connectionString?: string
+ id: number
+ schema: string
+ cascade?: boolean
+}
+
+export async function deleteTable({
+ projectRef,
+ connectionString,
+ id,
+ cascade = false,
+}: TableDeleteVariables) {
+ let headers = new Headers()
+ if (connectionString) headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await del('/platform/pg-meta/{ref}/tables', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString! },
+ path: { ref: projectRef },
+ query: { id, cascade },
+ },
+ headers,
+ })
+
+ if (error) throw error
+ return data
+}
+
+type TableDeleteData = Awaited<ReturnType<typeof deleteTable>>
+
+export const useTableDeleteMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<TableDeleteData, ResponseError, TableDeleteVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<TableDeleteData, ResponseError, TableDeleteVariables>(
+ (vars) => deleteTable(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { id, projectRef, schema } = variables
+ await Promise.all([
+ queryClient.invalidateQueries(tableKeys.list(projectRef, schema)),
+ queryClient.invalidateQueries(tableKeys.table(projectRef, id)),
+ queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
+ // invalidate all views from this schema
+ queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, schema)),
+ // invalidate the view if there's a view with this id
+ queryClient.invalidateQueries(viewKeys.view(projectRef, id)),
+ ])
+
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to delete database table: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/tables/table-update-mutation.ts b/apps/studio/data/tables/table-update-mutation.ts
new file mode 100644
index 00000000000..3ab10a5521d
--- /dev/null
+++ b/apps/studio/data/tables/table-update-mutation.ts
@@ -0,0 +1,75 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { components } from 'data/api'
+import { patch } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { tableKeys } from './keys'
+
+export type UpdateTableBody = components['schemas']['UpdateTableBody']
+
+export type TableUpdateVariables = {
+ projectRef: string
+ connectionString?: string
+ id: number
+ schema: string
+ payload: UpdateTableBody
+}
+
+export async function updateTable({
+ projectRef,
+ connectionString,
+ id,
+ payload,
+}: TableUpdateVariables) {
+ let headers = new Headers()
+ if (connectionString) headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await patch('/platform/pg-meta/{ref}/tables', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString! },
+ path: { ref: projectRef },
+ query: { id },
+ },
+ body: payload,
+ headers,
+ })
+
+ if (error) throw error
+ return data
+}
+
+type TableUpdateData = Awaited<ReturnType<typeof updateTable>>
+
+export const useTableUpdateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<TableUpdateData, ResponseError, TableUpdateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<TableUpdateData, ResponseError, TableUpdateVariables>(
+ (vars) => updateTable(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, schema, id } = variables
+ await Promise.all([
+ queryClient.invalidateQueries(tableKeys.list(projectRef, schema)),
+ queryClient.invalidateQueries(tableKeys.table(projectRef, id)),
+ ])
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to update database table: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/stores/common/PostgresMetaInterface.ts b/apps/studio/stores/common/PostgresMetaInterface.ts
deleted file mode 100644
index c932165fc2f..00000000000
--- a/apps/studio/stores/common/PostgresMetaInterface.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { action, computed, makeObservable, observable } from 'mobx'
-import { get, patch, post, delete_, isResponseOk } from 'lib/common/fetch'
-import { keyBy } from 'lodash'
-import { IRootStore } from '../RootStore'
-import { ResponseError, SupaResponse } from 'types'
-
-type DataKeys = number | string
-
-export interface IPostgresMetaInterface<T> {
- error: Error | null
-
- count: number
- hasError: boolean
- isLoading: boolean
- isInitialized: boolean
-
- load: () => void
- loadBySchema: (schema: string) => Promise<SupaResponse<T[]>>
- create: (payload: any) => Promise<SupaResponse<T>>
- update: (id: number | string, updates: any) => Promise<SupaResponse<T>>
- del: (id: number | string, cascade?: boolean) => Promise<SupaResponse<boolean>>
- list: (filter?: any) => T[]
- find: (filter?: any) => T | undefined
- byId: (id: number | string) => T | undefined
- initialDataArray: (value: T[]) => void
-
- setUrl: (url: string) => void
- setHeaders: (headers: { [prop: string]: any }) => void
-}
-
-// [TODO] Need to refactor the logic for 'isInitialized'
-// Should avoid page level "loaded" state like TableEditorLayout
-// The logic should be - state should be INITIAL at first, and only
-// taken as initialized after the first trigger of the load method.
-// https://github.com/supabase/supabase/pull/5128#pullrequestreview-860706726
-export default class PostgresMetaInterface<T> implements IPostgresMetaInterface<T> {
- STATES = {
- INITIAL: 'initial',
- LOADING: 'loading',
- ERROR: 'error',
- LOADED: 'loaded',
- }
- rootStore: IRootStore
- url: string
- error: Error | null = null
- identifier: string
- state = this.STATES.INITIAL
- data: { [key in DataKeys]: T } = {}
- headers: any = {}
- isInitialized: boolean = false
-
- constructor(
- rootStore: IRootStore,
- dataUrl: string,
- headers?: {
- [prop: string]: any
- },
- options?: { identifier: string }
- ) {
- this.rootStore = rootStore
- this.url = dataUrl
- this.headers = headers
- this.identifier = options?.identifier ?? 'id'
-
- makeObservable(this, {
- state: observable,
- data: observable,
- error: observable,
- count: computed,
- hasError: computed,
- isLoading: computed,
- isInitialized: observable,
- load: action,
- create: action,
- update: action,
- del: action,
- setState: action,
- setDataArray: action,
- setError: action,
- })
- }
-
- get count() {
- return Object.keys(this.data).length
- }
-
- get hasError() {
- return this.state === this.STATES.ERROR
- }
-
- get isLoading() {
- return this.state === this.STATES.INITIAL || this.state === this.STATES.LOADING
- }
-
- async fetchData() {
- const headers = { 'Content-Type': 'application/json', ...this.headers }
- const response = await get<T[]>(this.url, { headers })
- if (!isResponseOk(response)) {
- throw response.error
- }
-
- this.setDataArray(response)
- return response
- }
-
- async load() {
- let { LOADING, ERROR, LOADED } = this.STATES
- try {
- this.setError(null)
- this.setState(LOADING)
- await this.fetchData()
- this.setState(LOADED)
- } catch (e: any) {
- console.error('Load error message', e.message)
- this.setError(e)
- this.setState(ERROR)
- } finally {
- if (!this.isInitialized) this.isInitialized = true
- }
- }
-
- // [Joshen] Only used for tables and views for now
- async loadBySchema(schema: string) {
- let { LOADING, ERROR, LOADED } = this.STATES
- try {
- this.setError(null)
- this.setState(LOADING)
-
- const url = this.url.includes('?')
- ? `${this.url}&included_schemas=${schema}`
- : `${this.url}?included_schemas=${schema}`
- const response = await get(url, { headers: this.headers })
- if (response.error) throw response.error
-
- const data = response as T[]
- const formattedData = keyBy(data, this.identifier)
-
- // Purge existing data that belongs to given schema, otherwise
- // stale data will persist
- const purgedData = Object.keys(this.data)
- .map((identifier: any) => this.data[identifier])
- .filter((item: any) => item.schema !== schema)
- const formattedPurgedData = keyBy(purgedData, this.identifier)
-
- this.data = { ...formattedPurgedData, ...formattedData } as any
- this.setState(LOADED)
-
- return data
- } catch (error: any) {
- console.error('Error in loadBySchema:', error.message)
- this.setError(error)
- this.setState(ERROR)
- return { error }
- }
- }
-
- initialDataArray(value: T[]) {
- if (this.state === this.STATES.INITIAL) {
- this.data = keyBy(value, this.identifier) as any
- this.state = this.STATES.LOADED
- }
- }
-
- setState(value: string) {
- this.state = value
- }
-
- setDataArray(value: T[]) {
- this.data = keyBy(value, this.identifier) as any
- }
-
- setError(value: any) {
- this.error = value
- }
-
- list(filter?: any) {
- let arr = Object.values(this.data)
- if (!!filter) {
- return arr.filter(filter).sort((a: any, b: any) => a.name.localeCompare(b.name))
- } else {
- return arr.sort((a: any, b: any) => a.name.localeCompare(b.name))
- }
- }
-
- find(filter?: any) {
- let arr = Object.values(this.data)
- if (!!filter) {
- return arr.find(filter)
- } else {
- return undefined
- }
- }
-
- byId(id: number | string) {
- return this.data[id]
- }
-
- async create(payload: any) {
- try {
- const headers = { 'Content-Type': 'application/json', ...this.headers }
- const response = await post(this.url, payload, { headers })
- if (response.error) throw response.error
-
- const data = response as T
- const identity = response[this.identifier]
- this.data[identity] = data
- return data
- } catch (error: any) {
- return { data: null, error }
- }
- }
-
- async update(id: number | string, payload: any) {
- try {
- const headers = { 'Content-Type': 'application/json', ...this.headers }
- const url = `${this.url}?id=${id}`
- const response = await patch<T>(url, payload, { headers })
- if (!isResponseOk(response)) {
- throw response.error
- }
-
- this.data[id] = response
- return response
- } catch (error: any) {
- return { error }
- }
- }
-
- async del(id: number | string, cascade: boolean = false) {
- try {
- const headers = { 'Content-Type': 'application/json', ...this.headers }
- const url = cascade ? `${this.url}?id=${id}&cascade=${cascade}` : `${this.url}?id=${id}`
- const response = await delete_<T>(url, {}, { headers })
- if (!isResponseOk(response)) {
- throw response.error
- }
-
- delete this.data[id]
- return true
- } catch (error: any) {
- return { error }
- }
- }
-
- setUrl(url: string) {
- this.url = url
-
- // if the url changes, we need to reset the state
- this.state = this.STATES.INITIAL
- this.data = {}
- this.error = null
- }
-
- setHeaders(headers: { [prop: string]: any }) {
- this.headers = headers
- }
-}
diff --git a/apps/studio/stores/pgmeta/MetaStore.ts b/apps/studio/stores/pgmeta/MetaStore.ts
index 45bf0cd76e1..7dee87467ad 100644
--- a/apps/studio/stores/pgmeta/MetaStore.ts
+++ b/apps/studio/stores/pgmeta/MetaStore.ts
@@ -1,52 +1,12 @@
-import { Query } from 'components/grid/query/Query'
-import { chunk, find, isEmpty, isEqual } from 'lodash'
import { makeObservable } from 'mobx'
-import Papa from 'papaparse'
-
-import type {
- PostgresPrimaryKey,
- PostgresRelationship,
- PostgresTable,
-} from '@supabase/postgres-meta'
import { post } from 'lib/common/fetch'
import { API_URL, IS_PLATFORM } from 'lib/constants'
-import { timeout, tryParseJson } from 'lib/helpers'
import { ResponseError } from 'types'
import { IRootStore } from '../RootStore'
-import TableStore, { ITableStore } from './TableStore'
-
-import {
- generateCreateColumnPayload,
- generateUpdateColumnPayload,
-} from 'components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'
-import { ColumnField } from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.types'
-import {
- addForeignKey,
- addPrimaryKey,
- createColumn,
- removePrimaryKey,
- updateColumn,
-} from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils'
-import { ImportContent } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types'
-import { createDatabaseColumn } from 'data/database-columns/database-column-create-mutation'
-import { deleteDatabaseColumn } from 'data/database-columns/database-column-delete-mutation'
-import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
-import { entityTypeKeys } from 'data/entity-types/keys'
-import { getCachedProjectDetail } from 'data/projects/project-detail-query'
-import { getQueryClient } from 'data/query-client'
-import { sqlKeys } from 'data/sql/keys'
-import { tableKeys } from 'data/tables/keys'
-import { getTable } from 'data/tables/table-query'
-import { getTables } from 'data/tables/tables-query'
-
-const BATCH_SIZE = 1000
-const CHUNK_SIZE = 1024 * 1024 * 0.1 // 0.1MB
export interface IMetaStore {
- tables: ITableStore
-
projectRef?: string
connectionString?: string
@@ -54,39 +14,10 @@ export interface IMetaStore {
validateQuery: (value: string) => Promise<any | { error: ResponseError }>
formatQuery: (value: string) => Promise<any | { error: ResponseError }>
- duplicateTable: (
- payload: any,
- metadata: {
- duplicateTable: PostgresTable
- isRLSEnabled: boolean
- isDuplicateRows: boolean
- }
- ) => void
- createTable: (
- toastId: string,
- payload: any,
- columns: ColumnField[],
- isRLSEnabled: boolean,
- importContent?: ImportContent
- ) => any
- updateTable: (toastId: string, table: PostgresTable, payload: any, columns: ColumnField[]) => any
- insertRowsViaSpreadsheet: (
- file: any,
- table: PostgresTable,
- selectedHeaders: string[],
- onProgressUpdate: (progress: number) => void
- ) => void
- insertTableRows: (
- table: PostgresTable,
- rows: any,
- selectedHeaders: string[],
- onProgressUpdate: (progress: number) => void
- ) => any
setProjectDetails: (details: { ref: string; connectionString?: string }) => void
}
export default class MetaStore implements IMetaStore {
rootStore: IRootStore
- tables: TableStore
projectRef: string
connectionString?: string
@@ -105,8 +36,6 @@ export default class MetaStore implements IMetaStore {
this.headers['x-connection-encrypted'] = connectionString
}
- this.tables = new TableStore(this.rootStore, `${this.baseUrl}/tables`, this.headers)
-
makeObservable(this, {})
}
@@ -155,479 +84,6 @@ export default class MetaStore implements IMetaStore {
}
}
- async duplicateTable(
- payload: any,
- metadata: {
- duplicateTable: PostgresTable
- isRLSEnabled: boolean
- isDuplicateRows: boolean
- }
- ) {
- const { duplicateTable, isRLSEnabled, isDuplicateRows } = metadata
- const { name: sourceTableName, schema: sourceTableSchema } = duplicateTable
- const duplicatedTableName = payload.name
-
- // The following query will copy the structure of the table along with indexes, constraints and
- // triggers. However, foreign key constraints are not duplicated over - has to be done separately
- const table = await this.rootStore.meta.query(
- `CREATE TABLE "${sourceTableSchema}"."${duplicatedTableName}" (LIKE "${sourceTableSchema}"."${sourceTableName}" INCLUDING ALL);`
- )
- if (table.error) throw table.error
-
- // Duplicate foreign key constraints over
- const relationships = duplicateTable.relationships
- if (relationships.length > 0) {
- relationships.map(async (relationship: PostgresRelationship) => {
- await addForeignKey(this.projectRef, this.connectionString, {
- ...relationship,
- source_table_name: duplicatedTableName,
- deletion_action: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- update_action: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- })
- })
- }
-
- // Duplicate rows if needed
- if (isDuplicateRows) {
- const rows = await this.rootStore.meta.query(
- `INSERT INTO "${sourceTableSchema}"."${duplicatedTableName}" SELECT * FROM "${sourceTableSchema}"."${sourceTableName}";`
- )
- if (rows.error) throw rows.error
-
- // Insert into does not copy over auto increment sequences, so we manually do it next if any
- const columns = duplicateTable.columns ?? []
- const identityColumns = columns.filter((column) => column.identity_generation !== null)
- identityColumns.map(async (column) => {
- const identity = await this.rootStore.meta.query(
- `SELECT setval('"${sourceTableSchema}"."${duplicatedTableName}_${column.name}_seq"', (SELECT MAX("${column.name}") FROM "${sourceTableSchema}"."${sourceTableName}"));`
- )
- if (identity.error) throw identity.error
- })
- }
-
- const queryClient = getQueryClient()
- const project = await getCachedProjectDetail(queryClient, this.rootStore.ui.selectedProjectRef)
- const projectRef = project?.ref
- const connectionString = project?.connectionString
- const tables = await queryClient.fetchQuery({
- queryKey: tableKeys.list(projectRef, sourceTableSchema),
- queryFn: ({ signal }) =>
- getTables({ projectRef, connectionString, schema: sourceTableSchema }, signal),
- })
-
- const duplicatedTable = find(tables, { schema: sourceTableSchema, name: duplicatedTableName })
-
- if (isRLSEnabled) {
- const updateTable: any = await this.tables.update(duplicatedTable!.id, {
- rls_enabled: isRLSEnabled,
- })
- if (updateTable.error) throw updateTable.error
- }
-
- return duplicatedTable
- }
-
- async createTable(
- toastId: string,
- payload: any,
- columns: ColumnField[] = [],
- isRLSEnabled: boolean,
- importContent?: ImportContent
- ) {
- // Create the table first
- const table = await this.tables.create(payload)
- if ('error' in table) throw table.error
-
- // If we face any errors during this process after the actual table creation
- // We'll delete the table as a way to clean up and not leave behind bits that
- // got through successfully. This is so that the user can continue editing in
- // the table side panel editor conveniently
- try {
- // Toggle RLS if configured to be
- if (isRLSEnabled) {
- const updatedTable: any = await this.tables.update(table.id, {
- rls_enabled: isRLSEnabled,
- })
- if (updatedTable.error) throw updatedTable.error
- }
-
- // Then insert the columns - we don't do Promise.all as we want to keep the integrity
- // of the column order during creation. Note that we add primary key constraints separately
- // via the query endpoint to support composite primary keys as pg-meta does not support that OOB
- this.rootStore.ui.setNotification({
- id: toastId,
- category: 'loading',
- message: `Adding ${columns.length} columns to ${table.name}...`,
- })
-
- for (const column of columns) {
- // We create all columns without primary keys first
- const columnPayload = generateCreateColumnPayload(table.id, {
- ...column,
- isPrimaryKey: false,
- })
- await createDatabaseColumn({
- projectRef: this.projectRef,
- connectionString: this.connectionString,
- payload: columnPayload,
- })
- }
-
- // Then add the primary key constraints here to support composite keys
- const primaryKeyColumns = columns
- .filter((column: ColumnField) => column.isPrimaryKey)
- .map((column: ColumnField) => column.name)
- if (primaryKeyColumns.length > 0) {
- await addPrimaryKey(
- this.projectRef,
- this.connectionString,
- table.schema,
- table.name,
- primaryKeyColumns
- )
- }
-
- // Then add the foreign key constraints here
- for (const column of columns) {
- if (column.foreignKey !== undefined) {
- await addForeignKey(this.projectRef, this.connectionString, column.foreignKey)
- }
- }
-
- // If the user is importing data via a spreadsheet
- if (importContent !== undefined) {
- if (importContent.file && importContent.rowCount > 0) {
- // Via a CSV file
- const { error }: any = await this.insertRowsViaSpreadsheet(
- importContent.file,
- table,
- importContent.selectedHeaders,
- (progress: number) => {
- this.rootStore.ui.setNotification({
- id: toastId,
- progress,
- category: 'loading',
- message: `Adding ${importContent.rowCount.toLocaleString()} rows to ${table.name}`,
- })
- }
- )
-
- // For identity columns, manually raise the sequences
- const identityColumns = columns.filter((column) => column.isIdentity)
- for (const column of identityColumns) {
- const identity = await this.rootStore.meta.query(
- `SELECT setval('${table.name}_${column.name}_seq', (SELECT MAX("${column.name}") FROM "${table.name}"));`
- )
- if (identity.error) throw identity.error
- }
-
- if (error !== undefined) {
- this.rootStore.ui.setNotification({
- category: 'error',
- message: 'Do check your spreadsheet if there are any discrepancies.',
- })
- this.rootStore.ui.setNotification({
- category: 'error',
- message: `Table ${table.name} has been created but we ran into an error while inserting rows:
- ${error.message}`,
- error,
- })
- }
- } else {
- // Via text copy and paste
- await this.insertTableRows(
- table,
- importContent.rows,
- importContent.selectedHeaders,
- (progress: number) => {
- this.rootStore.ui.setNotification({
- id: toastId,
- progress,
- category: 'loading',
- message: `Adding ${importContent.rows.length.toLocaleString()} rows to ${
- table.name
- }`,
- })
- }
- )
-
- // For identity columns, manually raise the sequences
- const identityColumns = columns.filter((column) => column.isIdentity)
- for (const column of identityColumns) {
- const identity = await this.rootStore.meta.query(
- `SELECT setval('${table.name}_${column.name}_seq', (SELECT MAX("${column.name}") FROM "${table.name}"));`
- )
- if (identity.error) throw identity.error
- }
- }
- }
-
- // Finally, return the created table
- return table
- } catch (error: any) {
- this.tables.del(table.id)
- throw error
- }
- }
-
- async updateTable(toastId: string, table: PostgresTable, payload: any, columns: ColumnField[]) {
- // Prepare a check to see if primary keys to the tables were updated or not
- 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)
-
- if (isPrimaryKeyUpdated) {
- // Remove any primary key constraints first (we'll add it back later)
- // If we do it later, and if the user deleted a PK column, we'd need to do
- // an additional check when removing PK if the column in the PK was removed
- // So doing this one step earlier, lets us skip that additional check.
- if (table.primary_keys.length > 0) {
- await removePrimaryKey(this.projectRef, this.connectionString, table.schema, table.name)
- }
- }
-
- // Update the table
- const updatedTable: any = await this.tables.update(table.id, payload)
- if (updatedTable.error) throw updatedTable.error
-
- const originalColumns = table.columns ?? []
- const columnIds = columns.map((column) => column.id)
-
- // Delete any removed columns
- const columnsToRemove = originalColumns.filter((column) => !columnIds.includes(column.id))
- for (const column of columnsToRemove) {
- this.rootStore.ui.setNotification({
- id: toastId,
- category: 'loading',
- message: `Removing column ${column.name} from ${updatedTable.name}`,
- })
- await deleteDatabaseColumn({
- projectRef: this.projectRef,
- connectionString: this.connectionString,
- id: column.id,
- })
- }
-
- // Add any new columns / Update any existing columns
- let hasError = false
- for (const column of columns) {
- if (!column.id.includes(table.id.toString())) {
- this.rootStore.ui.setNotification({
- id: toastId,
- category: 'loading',
- message: `Adding column ${column.name} to ${updatedTable.name}`,
- })
- // Ensure that columns do not created as primary key first, cause the primary key will
- // be added later on further down in the code
- const columnPayload = generateCreateColumnPayload(updatedTable.id, {
- ...column,
- isPrimaryKey: false,
- })
- await createColumn({
- projectRef: this.projectRef,
- connectionString: this.connectionString,
- payload: columnPayload,
- selectedTable: updatedTable,
- foreignKey: column.foreignKey,
- })
- } else {
- const originalColumn = find(originalColumns, { id: column.id })
- if (originalColumn) {
- const columnPayload = generateUpdateColumnPayload(originalColumn, updatedTable, 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) {
- this.rootStore.ui.setNotification({
- id: toastId,
- category: 'loading',
- message: `Updating column ${column.name} from ${updatedTable.name}`,
- })
- const skipPKCreation = true
- const skipSuccessMessage = true
- const res = await updateColumn({
- projectRef: this.projectRef,
- connectionString: this.connectionString,
- id: column.id,
- payload: columnPayload,
- selectedTable: updatedTable,
- foreignKey: column.foreignKey,
- skipPKCreation,
- skipSuccessMessage,
- })
- if (res?.error) {
- hasError = true
- this.rootStore.ui.setNotification({
- category: 'error',
- message: `Failed to update column "${column.name}": ${res.error.message}`,
- })
- }
- }
- }
- }
- }
-
- // Then add back the primary keys again
- if (isPrimaryKeyUpdated && primaryKeyColumns.length > 0) {
- await addPrimaryKey(
- this.projectRef,
- this.connectionString,
- updatedTable.schema,
- updatedTable.name,
- primaryKeyColumns
- )
- }
-
- const queryClient = getQueryClient()
- const project = await getCachedProjectDetail(queryClient, this.rootStore.ui.selectedProjectRef)
- const projectRef = project?.ref
- const connectionString = project?.connectionString
-
- await Promise.all([
- queryClient.invalidateQueries(sqlKeys.query(projectRef, ['foreign-key-constraints'])),
- // invalidate list of tables, as well as visible individual tables
- queryClient.invalidateQueries(['projects', projectRef, 'tables']),
- queryClient.invalidateQueries(sqlKeys.query(projectRef, [table.schema, table.name])),
- queryClient.invalidateQueries(
- sqlKeys.query(projectRef, ['table-definition', table.schema, table.name])
- ),
- queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
- ])
-
- return {
- table: await getTable({
- projectRef,
- connectionString,
- id: table.id,
- }),
- hasError,
- }
- }
-
- async insertRowsViaSpreadsheet(
- file: any,
- table: PostgresTable,
- selectedHeaders: string[],
- onProgressUpdate: (progress: number) => void
- ) {
- let chunkNumber = 0
- let insertError: any = undefined
- const t1: any = new Date()
- return new Promise((resolve) => {
- Papa.parse(file, {
- header: true,
- // dynamicTyping has to be disabled so that "00001" doesn't get parsed as 1.
- dynamicTyping: false,
- skipEmptyLines: true,
- chunkSize: CHUNK_SIZE,
- quoteChar: file.type === 'text/tab-separated-values' ? '' : '"',
- chunk: async (results: any, parser: any) => {
- parser.pause()
-
- const formattedData = results.data.map((row: any) => {
- const formattedRow: any = {}
- selectedHeaders.forEach((header) => {
- const column = table.columns?.find((c) => c.name === header)
- if (
- (column?.data_type ?? '') === 'ARRAY' ||
- (column?.format ?? '').includes('json')
- ) {
- formattedRow[header] = tryParseJson(row[header])
- } else if (row[header] === '') {
- // if the cell is empty string, convert it to NULL
- formattedRow[header] = null
- } else {
- formattedRow[header] = row[header]
- }
- })
- return formattedRow
- })
-
- const insertQuery = new Query()
- .from(table.name, table.schema)
- .insert(formattedData)
- .toSql()
- const res = await this.query(insertQuery)
-
- if (res.error) {
- console.warn(res.error)
- insertError = res.error
- parser.abort()
- } else {
- chunkNumber += 1
- const progress = (chunkNumber * CHUNK_SIZE) / file.size
- const progressPercentage = progress > 1 ? 100 : progress * 100
- onProgressUpdate(progressPercentage)
- parser.resume()
- }
- },
- complete: () => {
- const t2: any = new Date()
- console.log(`Total time taken for importing spreadsheet: ${(t2 - t1) / 1000} seconds`)
- resolve({ error: insertError })
- },
- })
- })
- }
-
- async insertTableRows(
- table: PostgresTable,
- rows: any,
- selectedHeaders: string[],
- onProgressUpdate: (progress: number) => void
- ) {
- let insertError = undefined
- let insertProgress = 0
-
- const formattedRows = rows.map((row: any) => {
- const formattedRow: any = {}
- selectedHeaders.forEach((header) => {
- const column = table.columns?.find((c) => c.name === header)
- if ((column?.data_type ?? '') === 'ARRAY' || (column?.format ?? '').includes('json')) {
- formattedRow[header] = tryParseJson(row[header])
- } else {
- formattedRow[header] = row[header]
- }
- })
- return formattedRow
- })
-
- const batches = chunk(formattedRows, BATCH_SIZE)
- const promises = batches.map((batch: any) => {
- return () => {
- return Promise.race([
- new Promise(async (resolve, reject) => {
- const insertQuery = new Query().from(table.name, table.schema).insert(batch).toSql()
- const res = await this.query(insertQuery)
-
- if (res.error) {
- insertError = res.error
- reject(res.error)
- }
- insertProgress = insertProgress + batch.length / rows.length
- resolve({})
- }),
- timeout(30000),
- ])
- }
- })
-
- const batchedPromises = chunk(promises, 10)
- for (const batchedPromise of batchedPromises) {
- const res = await Promise.allSettled(batchedPromise.map((batch) => batch()))
- const hasFailedBatch = find(res, { status: 'rejected' })
- if (hasFailedBatch) break
- onProgressUpdate(insertProgress * 100)
- }
- return { error: insertError }
- }
-
setProjectDetails({ ref, connectionString }: { ref: string; connectionString?: string }) {
this.projectRef = ref
this.baseUrl = `${API_URL}/pg-meta/${ref}`
@@ -635,8 +91,5 @@ export default class MetaStore implements IMetaStore {
this.connectionString = connectionString
this.headers['x-connection-encrypted'] = connectionString
}
-
- this.tables.setUrl(`${this.baseUrl}/tables`)
- this.tables.setHeaders(this.headers)
}
}
diff --git a/apps/studio/stores/pgmeta/TableStore.ts b/apps/studio/stores/pgmeta/TableStore.ts
deleted file mode 100644
index 220920ec0c9..00000000000
--- a/apps/studio/stores/pgmeta/TableStore.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { action, makeObservable } from 'mobx'
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
-
-import PostgresMetaInterface, { IPostgresMetaInterface } from '../common/PostgresMetaInterface'
-import { IRootStore } from '../RootStore'
-import { get } from 'lib/common/fetch'
-
-export interface ITableStore extends IPostgresMetaInterface<PostgresTable> {}
-
-export default class TableStore extends PostgresMetaInterface<PostgresTable> {
- constructor(
- rootStore: IRootStore,
- dataUrl: string,
- headers?: {
- [prop: string]: any
- },
- options?: { identifier: string }
- ) {
- super(rootStore, dataUrl, headers, options)
- }
-
- // Customize TableStore fetchData method to improve request performance
- async fetchData() {
- const headers = { 'Content-Type': 'application/json', ...this.headers }
- // load all tables w/o columns info
- const urlTables = this.url.includes('?')
- ? `${this.url}&include_columns=false`
- : `${this.url}?include_columns=false`
- // load all columns
- const urlColumns = this.url.replace('/tables', '/columns')
- const [tablesResponse, columnsResponse] = await Promise.all([
- get(urlTables, { headers }),
- get(urlColumns, { headers }),
- ])
- if (tablesResponse.error) throw tablesResponse.error
- if (columnsResponse.error) throw columnsResponse.error
-
- // merge 2 response to create the final array
- const columnsByTableId = (columnsResponse as PostgresColumn[]).reduce(
- (acc, curr) => {
- acc[curr.table_id] ??= []
- acc[curr.table_id].push(curr)
- return acc
- },
- {} as Record<string, PostgresColumn[]>
- )
- const tables: PostgresTable[] = []
- tablesResponse.forEach((table: PostgresTable) => {
- const columns = columnsByTableId[table.id]
- tables.push({ ...table, columns })
- })
-
- this.setDataArray(tables)
- return tables as any
- }
-}