Skip to content

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

table create performance (#40857)

Saxon Fletcher9d66964b6291
diff --git a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
index c960551a749..738d3605fbd 100644
--- a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
+++ b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
@@ -8,7 +8,7 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { isTableLike } from 'data/table-editor/table-editor-types'
-import { useTablesQuery as useTableRetrieveQuery } from 'data/tables/table-retrieve-query'
+import { useTableQuery } from 'data/tables/table-retrieve-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Popover_Shadcn_, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_ } from 'ui'
import type { SupaRow } from '../../types'
@@ -38,21 +38,18 @@ export const ForeignKeyFormatter = (props: Props) => {
r.source_column_name === column.name
)
- const { data: targetTable, isLoading: isLoadingTargetTable } =
- useTableRetrieveQuery<PostgresTable>(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: relationship?.target_table_schema ?? '',
- name: relationship?.target_table_name ?? '',
- },
- {
- enabled:
- !!project?.ref &&
- !!relationship?.target_table_schema &&
- !!relationship?.target_table_name,
- }
- )
+ const { data: targetTable, isLoading: isLoadingTargetTable } = useTableQuery<PostgresTable>(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: relationship?.target_table_schema ?? '',
+ name: relationship?.target_table_name ?? '',
+ },
+ {
+ enabled:
+ !!project?.ref && !!relationship?.target_table_schema && !!relationship?.target_table_name,
+ }
+ )
const value = row[column.key]
const formattedValue =
diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx
index 92212d51b5f..52f62761795 100644
--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx
+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx
@@ -1,9 +1,10 @@
import { Check, ChevronsUpDown, Database, Plus } from 'lucide-react'
import { useEffect, useState } from 'react'
-import ActionBar from 'components/interfaces/TableGridEditor/SidePanelEditor/ActionBar'
+import { ActionBar } from 'components/interfaces/TableGridEditor/SidePanelEditor/ActionBar'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useSchemasQuery } from 'data/database/schemas-query'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import {
Button,
cn,
@@ -27,7 +28,6 @@ import {
import WrapperDynamicColumns from './WrapperDynamicColumns'
import type { Table, TableOption } from './Wrappers.types'
import { makeValidateRequired } from './Wrappers.utils'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
export type WrapperTableEditorProps = {
visible: boolean
diff --git a/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx
index 7d982581e39..4aa8e54520c 100644
--- a/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx
+++ b/apps/studio/components/interfaces/Storage/ImportForeignSchemaDialog.tsx
@@ -15,7 +15,7 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Button, Form_Shadcn_, FormField_Shadcn_, Input_Shadcn_, Modal, Separator } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { formatWrapperTables } from '../Integrations/Wrappers/Wrappers.utils'
-import SchemaEditor from '../TableGridEditor/SidePanelEditor/SchemaEditor'
+import { SchemaEditor } from '../TableGridEditor/SidePanelEditor/SchemaEditor'
import { getAnalyticsBucketFDWServerName } from './AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils'
import { useAnalyticsBucketAssociatedEntities } from './AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketAssociatedEntities'
import { getDecryptedParameters } from './ImportForeignSchemaDialog.utils'
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
index 67cd2bdb999..fd66522f00c 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
@@ -13,7 +13,7 @@ interface ActionBarProps {
formId?: string
}
-const ActionBar = ({
+export const ActionBar = ({
loading = false,
disableApply = false,
hideApply = false,
@@ -70,4 +70,3 @@ const ActionBar = ({
</div>
)
}
-export default ActionBar
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index 06a6c3f27d8..462ad22f131 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -21,7 +21,7 @@ import { useProtectedSchemas } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
import type { Dictionary } from 'types'
import { Button, Checkbox, Input, SidePanel, Toggle } from 'ui'
-import ActionBar from '../ActionBar'
+import { ActionBar } from '../ActionBar'
import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
import { TEXT_TYPES } from '../SidePanelEditor.constants'
@@ -62,7 +62,7 @@ export interface ColumnEditorProps {
updateEditorDirty: () => void
}
-const ColumnEditor = ({
+export const ColumnEditor = ({
column,
selectedTable,
visible = false,
@@ -373,5 +373,3 @@ const ColumnEditor = ({
</SidePanel>
)
}
-
-export default ColumnEditor
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
index c7bb451b9df..273e3315df8 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx
@@ -15,13 +15,13 @@ import { DocsButton } from 'components/ui/DocsButton'
import InformationBox from 'components/ui/InformationBox'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { useSchemasQuery } from 'data/database/schemas-query'
-import { useTablesQuery as useTableRetrieveQuery } from 'data/tables/table-retrieve-query'
+import { useTableQuery } from 'data/tables/table-retrieve-query'
import { useTablesQuery } from 'data/tables/tables-query'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { DOCS_URL } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
-import ActionBar from '../ActionBar'
+import { ActionBar } from '../ActionBar'
import { NUMERICAL_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'
import type { ColumnField } from '../SidePanelEditor.types'
import { FOREIGN_KEY_CASCADE_OPTIONS } from './ForeignKeySelector.constants'
@@ -77,18 +77,17 @@ export const ForeignKeySelector = ({
includeColumns: false,
})
- const { data: selectedTable, isLoading: isLoadingSelectedTable } =
- useTableRetrieveQuery<PostgresTable>(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: fk.schema,
- name: fk.table,
- },
- {
- enabled: !!project?.ref && !!fk.schema && !!fk.table,
- }
- )
+ const { data: selectedTable, isLoading: isLoadingSelectedTable } = useTableQuery<PostgresTable>(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: fk.schema,
+ name: fk.table,
+ },
+ {
+ enabled: !!project?.ref && !!fk.schema && !!fk.table,
+ }
+ )
const disableApply = isLoadingSelectedTable || selectedTable === undefined || hasTypeErrors
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
index b5ea64cd868..ab07199af1d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
@@ -23,7 +23,7 @@ import {
} from 'state/role-impersonation-state'
import { TableEditorTableStateContextProvider } from 'state/table-editor-table'
import { Button, SidePanel } from 'ui'
-import ActionBar from '../../ActionBar'
+import { ActionBar } from '../../ActionBar'
import { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'
import { convertByteaToHex } from '../RowEditor.utils'
import Pagination from './Pagination'
@@ -38,7 +38,7 @@ export interface ForeignRowSelectorProps {
closePanel: () => void
}
-const ForeignRowSelector = ({
+export const ForeignRowSelector = ({
visible,
foreignKey,
onSelect,
@@ -269,5 +269,3 @@ const ForeignRowSelector = ({
</SidePanel>
)
}
-
-export default ForeignRowSelector
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/HeaderTitle.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/HeaderTitle.tsx
index cfa43f090fd..4bbc0b5f3ee 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/HeaderTitle.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/HeaderTitle.tsx
@@ -3,7 +3,7 @@ interface HeaderTitleProps {
tableName?: string
}
-const HeaderTitle = ({ isNewRecord, tableName }: HeaderTitleProps) => {
+export const HeaderTitle = ({ isNewRecord, tableName }: HeaderTitleProps) => {
let header = `${isNewRecord ? 'Add new' : 'Update'} row ${isNewRecord ? 'to' : 'from'} `
return (
@@ -13,5 +13,3 @@ const HeaderTitle = ({ isNewRecord, tableName }: HeaderTitleProps) => {
</>
)
}
-
-export default HeaderTitle
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
index 1c13e580b23..7c72debe95d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
@@ -35,7 +35,7 @@ export interface InputFieldProps {
onSelectForeignKey?: () => void
}
-const InputField = ({
+export const InputField = ({
field,
errors,
isEditable = true,
@@ -353,5 +353,3 @@ const InputField = ({
/>
)
}
-
-export default InputField
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx
index ca0f3aa7576..f591d6e6028 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/index.tsx
@@ -12,7 +12,7 @@ import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { minifyJSON, prettifyJSON, removeJSONTrailingComma, tryParseJson } from 'lib/helpers'
import { Button, SidePanel, cn } from 'ui'
-import ActionBar from '../../ActionBar'
+import { ActionBar } from '../../ActionBar'
import { isValueTruncated } from '../RowEditor.utils'
import { DrilldownViewer } from './DrilldownViewer/DrilldownViewer'
import { JsonCodeEditor } from './JsonCodeEditor'
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
index 935915f6e7e..e8f74f46718 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
@@ -6,11 +6,11 @@ import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constra
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import type { Dictionary } from 'types'
import { SidePanel } from 'ui'
-import ActionBar from '../ActionBar'
+import { ActionBar } from '../ActionBar'
import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
-import ForeignRowSelector from './ForeignRowSelector/ForeignRowSelector'
-import HeaderTitle from './HeaderTitle'
-import InputField from './InputField'
+import { ForeignRowSelector } from './ForeignRowSelector/ForeignRowSelector'
+import { HeaderTitle } from './HeaderTitle'
+import { InputField } from './InputField'
import { JsonEditor } from './JsonEditor'
import type { EditValue, RowField } from './RowEditor.types'
import {
@@ -32,7 +32,9 @@ export interface RowEditorProps {
updateEditorDirty: () => void
}
-const RowEditor = ({
+const formId = 'row-editor-panel'
+
+export const RowEditor = ({
row,
selectedTable,
visible = false,
@@ -158,7 +160,7 @@ const RowEditor = ({
return (
<SidePanel
data-testid="side-panel-row-editor"
- hideFooter
+ // hideFooter
size="large"
key="RowEditor"
visible={visible}
@@ -167,8 +169,18 @@ const RowEditor = ({
isEditingText || isEditingJson || isSelectingForeignKey ? ' mr-32' : ''
}`}
onCancel={closePanel}
+ customFooter={
+ <ActionBar
+ loading={loading}
+ formId={formId}
+ backButtonLabel="Cancel"
+ applyButtonLabel="Save"
+ closePanel={closePanel}
+ hideApply={!editable}
+ />
+ }
>
- <form onSubmit={(e) => onSaveChanges(e)} className="h-full">
+ <form id={formId} onSubmit={(e) => onSaveChanges(e)} className="h-full">
<div className="flex h-full flex-col">
<div className="flex flex-grow flex-col">
{requiredFields.length > 0 && (
@@ -244,15 +256,6 @@ const RowEditor = ({
readOnly={!editable}
/>
</div>
- <div className="flex-shrink">
- <ActionBar
- loading={loading}
- backButtonLabel="Cancel"
- applyButtonLabel="Save"
- closePanel={closePanel}
- hideApply={!editable}
- />
- </div>
</div>
</form>
@@ -269,5 +272,3 @@ const RowEditor = ({
</SidePanel>
)
}
-
-export default RowEditor
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
index 2915aaf4dcf..7191536347b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
@@ -13,7 +13,7 @@ import { isTableLike } from 'data/table-editor/table-editor-types'
import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Button, SidePanel, cn } from 'ui'
-import ActionBar from '../ActionBar'
+import { ActionBar } from '../ActionBar'
import { isValueTruncated } from './RowEditor.utils'
interface TextEditorProps {
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx
index bc4d2fbb696..0b5a06fedc6 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SchemaEditor.tsx
@@ -11,7 +11,7 @@ interface SchemaEditorProps {
closePanel: () => void
}
-const SchemaEditor = ({ visible, onSuccess, closePanel }: SchemaEditorProps) => {
+export const SchemaEditor = ({ visible, onSuccess, closePanel }: SchemaEditorProps) => {
const { data: project } = useSelectedProjectQuery()
const [errors, setErrors] = useState<{ name?: string }>({ name: undefined })
@@ -77,5 +77,3 @@ const SchemaEditor = ({ visible, onSuccess, closePanel }: SchemaEditorProps) =>
</SidePanel>
)
}
-
-export default SchemaEditor
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index b13becd2889..12d2f525bc2 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -31,15 +31,15 @@ import { useTableEditorStateSnapshot } from 'state/table-editor'
import { createTabId, useTabsStateSnapshot } from 'state/tabs'
import type { Dictionary } from 'types'
import { SonnerProgress } from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import ColumnEditor from './ColumnEditor/ColumnEditor'
+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
+import { ColumnEditor } from './ColumnEditor/ColumnEditor'
import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
-import ForeignRowSelector from './RowEditor/ForeignRowSelector/ForeignRowSelector'
+import { ForeignRowSelector } from './RowEditor/ForeignRowSelector/ForeignRowSelector'
import { JsonEditor } from './RowEditor/JsonEditor'
-import RowEditor from './RowEditor/RowEditor'
+import { RowEditor } from './RowEditor/RowEditor'
import { convertByteaToHex } from './RowEditor/RowEditor.utils'
import { TextEditor } from './RowEditor/TextEditor'
-import SchemaEditor from './SchemaEditor'
+import { SchemaEditor } from './SchemaEditor'
import type { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
import {
createColumn,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts
new file mode 100644
index 00000000000..9041b931c92
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.createTable.test.ts
@@ -0,0 +1,518 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
+import type { ColumnField } from './SidePanelEditor.types'
+
+// Define mock functions at module level
+const mockExecuteSql = vi.fn()
+const mockGetTable = vi.fn()
+const mockSendEvent = vi.fn()
+const mockPrefetchEditorTablePage = vi.fn()
+const mockToastLoading = vi.fn()
+const mockToastSuccess = vi.fn()
+const mockToastError = vi.fn()
+const mockFetchQuery = vi.fn()
+
+// Setup mocks before imports
+vi.mock('data/query-client', () => ({
+ getQueryClient: () => ({
+ fetchQuery: mockFetchQuery,
+ }),
+}))
+
+vi.mock('data/sql/execute-sql-query', () => ({
+ executeSql: (...args: unknown[]) => mockExecuteSql(...args),
+}))
+
+vi.mock('data/tables/table-retrieve-query', () => ({
+ getTable: (...args: unknown[]) => mockGetTable(...args),
+ getTableQuery: (...args: unknown[]) => mockGetTable(...args),
+}))
+
+vi.mock('data/telemetry/send-event-mutation', () => ({
+ sendEvent: (...args: unknown[]) => mockSendEvent(...args),
+}))
+
+vi.mock('data/prefetchers/project.$ref.editor.$id', () => ({
+ prefetchEditorTablePage: (...args: unknown[]) => mockPrefetchEditorTablePage(...args),
+}))
+
+vi.mock('sonner', () => ({
+ toast: {
+ loading: (...args: unknown[]) => mockToastLoading(...args),
+ success: (...args: unknown[]) => mockToastSuccess(...args),
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+// Mock SparkBar component used in toast
+vi.mock('components/ui/SparkBar', () => ({
+ default: () => null,
+}))
+
+// Import after mocks are set up
+import { createTable } from './SidePanelEditor.utils'
+
+// Helper to create a column field with defaults
+const createColumnField = (overrides: Partial<ColumnField> = {}): ColumnField => ({
+ id: 'col-1',
+ name: 'column',
+ table: 'test_table',
+ schema: 'public',
+ format: 'text',
+ check: null,
+ comment: null,
+ defaultValue: null,
+ isNullable: true,
+ isUnique: false,
+ isArray: false,
+ isIdentity: false,
+ isPrimaryKey: false,
+ isNewColumn: true,
+ isEncrypted: false,
+ ...overrides,
+})
+
+describe('createTable', () => {
+ const projectRef = 'test-project-ref'
+ const connectionString = 'postgresql://localhost:5432/test'
+ const toastId = 'test-toast-id'
+
+ const basePayload = {
+ name: 'test_table',
+ schema: 'public',
+ comment: 'A test table',
+ }
+
+ const mockTableResult = {
+ id: 123,
+ name: 'test_table',
+ schema: 'public',
+ comment: 'A test table',
+ columns: [],
+ primary_keys: [],
+ relationships: [],
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+
+ // Default mock implementations
+ mockExecuteSql.mockResolvedValue({ result: [] })
+ mockGetTable.mockResolvedValue(mockTableResult)
+ mockSendEvent.mockResolvedValue({})
+ mockPrefetchEditorTablePage.mockResolvedValue(undefined)
+ mockFetchQuery.mockImplementation(({ queryFn }) => {
+ if (queryFn) {
+ return queryFn({ signal: new AbortController().signal })
+ }
+ return Promise.resolve(mockTableResult)
+ })
+ })
+
+ it('should create a basic table with no columns', async () => {
+ const result = await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledTimes(1)
+ expect(mockExecuteSql).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectRef,
+ connectionString,
+ queryKey: ['table', 'create-with-columns'],
+ })
+ )
+
+ // Should show loading toast
+ expect(mockToastLoading).toHaveBeenCalledWith(`Creating table ${basePayload.name}...`, {
+ id: toastId,
+ })
+
+ // Should track table creation event
+ expect(mockSendEvent).toHaveBeenCalledWith({
+ event: {
+ action: 'table_created',
+ properties: {
+ method: 'table_editor',
+ schema_name: 'public',
+ table_name: 'test_table',
+ },
+ groups: {
+ project: projectRef,
+ },
+ },
+ })
+
+ // Should prefetch the editor table page
+ expect(mockPrefetchEditorTablePage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectRef,
+ connectionString,
+ id: mockTableResult.id,
+ })
+ )
+
+ expect(result).toStrictEqual(mockTableResult)
+ })
+
+ it('should create a table with RLS enabled', async () => {
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: true,
+ })
+
+ const sqlCall = mockExecuteSql.mock.calls[0][0]
+ expect(sqlCall.sql).toContain('ENABLE ROW LEVEL SECURITY')
+
+ expect(mockSendEvent).toHaveBeenCalledWith({
+ event: {
+ action: 'table_rls_enabled',
+ properties: {
+ method: 'table_editor',
+ schema_name: 'public',
+ table_name: 'test_table',
+ },
+ groups: {
+ project: projectRef,
+ },
+ },
+ })
+ })
+
+ it('should create a table with columns', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ id: 'col-1',
+ name: 'id',
+ format: 'int8',
+ isNullable: false,
+ isIdentity: true,
+ isPrimaryKey: true,
+ }),
+ createColumnField({
+ id: 'col-2',
+ name: 'name',
+ format: 'text',
+ comment: 'User name',
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ const sqlCall = mockExecuteSql.mock.calls[0][0]
+ expect(sqlCall.sql).toContain('ALTER TABLE')
+ expect(sqlCall.sql).toContain('ADD COLUMN')
+ expect(sqlCall.sql).toContain('ADD PRIMARY KEY')
+ expect(sqlCall.sql).toContain('id')
+ })
+
+ it('should create a table with composite primary key', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ id: 'col-1',
+ name: 'user_id',
+ format: 'int8',
+ isNullable: false,
+ isPrimaryKey: true,
+ }),
+ createColumnField({
+ id: 'col-2',
+ name: 'order_id',
+ format: 'int8',
+ isNullable: false,
+ isPrimaryKey: true,
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ const sqlCall = mockExecuteSql.mock.calls[0][0]
+ expect(sqlCall.sql).toContain('ADD PRIMARY KEY')
+ expect(sqlCall.sql).toContain('user_id')
+ expect(sqlCall.sql).toContain('order_id')
+ })
+
+ it('should create a table with foreign key relations', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ id: 'col-1',
+ name: 'id',
+ format: 'int8',
+ isNullable: false,
+ isIdentity: true,
+ isPrimaryKey: true,
+ }),
+ createColumnField({
+ id: 'col-2',
+ name: 'user_id',
+ format: 'int8',
+ isNullable: false,
+ }),
+ ]
+
+ const foreignKeyRelations: ForeignKey[] = [
+ {
+ schema: 'public',
+ table: 'users',
+ columns: [{ source: 'user_id', target: 'id' }],
+ deletionAction: FOREIGN_KEY_CASCADE_ACTION.CASCADE,
+ updateAction: FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
+ },
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations,
+ isRLSEnabled: false,
+ })
+
+ const sqlCall = mockExecuteSql.mock.calls[0][0]
+ expect(sqlCall.sql).toContain('ADD FOREIGN KEY')
+ expect(sqlCall.sql).toContain('REFERENCES')
+ expect(sqlCall.sql).toContain('"users"')
+ expect(sqlCall.sql).toContain('ON DELETE CASCADE')
+ })
+
+ it('should include organization slug in telemetry when provided', async () => {
+ const organizationSlug = 'test-org'
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: true,
+ organizationSlug,
+ })
+
+ expect(mockSendEvent).toHaveBeenCalledWith({
+ event: expect.objectContaining({
+ action: 'table_created',
+ groups: {
+ project: projectRef,
+ organization: organizationSlug,
+ },
+ }),
+ })
+
+ expect(mockSendEvent).toHaveBeenCalledWith({
+ event: expect.objectContaining({
+ action: 'table_rls_enabled',
+ groups: {
+ project: projectRef,
+ organization: organizationSlug,
+ },
+ }),
+ })
+ })
+
+ it('should handle telemetry errors gracefully', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockSendEvent.mockRejectedValue(new Error('Telemetry failed'))
+
+ const result = await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(result).toStrictEqual(mockTableResult)
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Failed to track table creation event:',
+ expect.any(Error)
+ )
+
+ consoleErrorSpy.mockRestore()
+ })
+
+ it('should create a table with nullable connectionString', async () => {
+ await createTable({
+ projectRef,
+ connectionString: null,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectRef,
+ connectionString: null,
+ })
+ )
+ })
+
+ it('should create table with column having default value', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ name: 'status',
+ defaultValue: "'pending'",
+ isNullable: false,
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledTimes(1)
+ })
+
+ it('should create table with unique column', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ name: 'email',
+ isNullable: false,
+ isUnique: true,
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledTimes(1)
+ })
+
+ it('should create table with array column', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ name: 'tags',
+ isArray: true,
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledTimes(1)
+ })
+
+ it('should create table with check constraint', async () => {
+ const columns: ColumnField[] = [
+ createColumnField({
+ name: 'age',
+ format: 'int4',
+ check: 'age >= 0',
+ isNullable: false,
+ }),
+ ]
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns,
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ expect(mockExecuteSql).toHaveBeenCalledTimes(1)
+ })
+
+ it('should propagate SQL execution errors', async () => {
+ mockExecuteSql.mockRejectedValue(new Error('SQL execution failed'))
+
+ await expect(
+ createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: basePayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+ ).rejects.toThrow('SQL execution failed')
+ })
+
+ it('should create table in non-public schema', async () => {
+ const customSchemaPayload = {
+ name: 'custom_table',
+ schema: 'private',
+ comment: 'A private table',
+ }
+
+ await createTable({
+ projectRef,
+ connectionString,
+ toastId,
+ payload: customSchemaPayload,
+ columns: [],
+ foreignKeyRelations: [],
+ isRLSEnabled: false,
+ })
+
+ const sqlCall = mockExecuteSql.mock.calls[0][0]
+ expect(sqlCall.sql).toMatch(/private\.custom_table|"private"\."custom_table"/)
+
+ expect(mockSendEvent).toHaveBeenCalledWith({
+ event: expect.objectContaining({
+ properties: expect.objectContaining({
+ schema_name: 'private',
+ }),
+ }),
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 9fb9ab70ea7..e1d7821eb73 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -1,3 +1,4 @@
+import pgMeta from '@supabase/pg-meta'
import type { PostgresPrimaryKey } from '@supabase/postgres-meta'
import { chunk, find, isEmpty, isEqual } from 'lodash'
import Papa from 'papaparse'
@@ -22,10 +23,9 @@ import { prefetchTableEditor } from 'data/table-editor/table-editor-query'
import { tableRowKeys } from 'data/table-rows/keys'
import { executeWithRetry } from 'data/table-rows/table-rows-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,
+ getTableQuery,
RetrievedTableColumn,
RetrieveTableResult,
} from 'data/tables/table-retrieve-query'
@@ -52,15 +52,27 @@ const CHUNK_SIZE = 1024 * 1024 * 0.1 // 0.1MB
* The functions below are basically just queries but may be supported directly
* from the pg-meta library in the future
*/
-export const addPrimaryKey = async (
+const getAddPrimaryKeySQL = ({
+ schema,
+ table,
+ columns,
+}: {
+ schema: string
+ table: string
+ columns: string[]
+}) => {
+ const primaryKeyColumns = columns.join('","')
+ return `ALTER TABLE "${schema}"."${table}" ADD PRIMARY KEY (${primaryKeyColumns})`
+}
+
+const addPrimaryKey = async (
projectRef: string,
connectionString: string | undefined | null,
schema: string,
table: string,
columns: string[]
) => {
- const primaryKeyColumns = columns.join('","')
- const query = `ALTER TABLE "${schema}"."${table}" ADD PRIMARY KEY ("${primaryKeyColumns}")`
+ const query = getAddPrimaryKeySQL({ schema, table, columns })
return await executeSql({
projectRef: projectRef,
connectionString: connectionString,
@@ -69,7 +81,7 @@ export const addPrimaryKey = async (
})
}
-export const dropConstraint = async (
+const dropConstraint = async (
projectRef: string,
connectionString: string | undefined | null,
schema: string,
@@ -85,7 +97,7 @@ export const dropConstraint = async (
})
}
-export const getAddForeignKeySQL = ({
+const getAddForeignKeySQL = ({
table,
foreignKeys,
}: {
@@ -128,7 +140,7 @@ export const getAddForeignKeySQL = ({
)
}
-export const addForeignKey = async ({
+const addForeignKey = async ({
projectRef,
connectionString,
table,
@@ -148,7 +160,7 @@ export const addForeignKey = async ({
})
}
-export const getRemoveForeignKeySQL = ({
+const getRemoveForeignKeySQL = ({
table,
foreignKeys,
}: {
@@ -169,7 +181,7 @@ DROP CONSTRAINT IF EXISTS "${relation.name}"
)
}
-export const removeForeignKey = async ({
+const removeForeignKey = async ({
projectRef,
connectionString,
table,
@@ -189,7 +201,7 @@ export const removeForeignKey = async ({
})
}
-export const updateForeignKey = async ({
+const updateForeignKey = async ({
projectRef,
connectionString,
table,
@@ -214,10 +226,28 @@ export const updateForeignKey = async ({
})
}
+const getUpdateIdentitySequenceSQL = ({
+ schema,
+ table,
+ column,
+}: {
+ schema: string
+ table: string
+ column: string
+}) => {
+ return `SELECT setval('"${schema}"."${table}_${column}_seq"', (SELECT COALESCE(MAX("${column}"), 1) FROM "${schema}"."${table}"))`
+}
+
+const getEnableRLSSQL = ({ schema, table }: { schema: string; table: string }) => {
+ return `ALTER TABLE "${schema}"."${table}" ENABLE ROW LEVEL SECURITY`
+}
+
/**
* The methods below involve several contexts due to the UI flow of the
* dashboard and hence do not sit within their own stores
*/
+
+/** TODO: Refactor to do in a single transaction */
export const createColumn = async ({
projectRef,
connectionString,
@@ -293,6 +323,7 @@ export const createColumn = async ({
}
}
+/** TODO: Refactor to do in a single transaction */
export const updateColumn = async ({
projectRef,
connectionString,
@@ -372,6 +403,7 @@ export const updateColumn = async ({
}
}
+/** TODO: Refactor to do in a single transaction */
export const duplicateTable = async (
projectRef: string,
connectionString: string | undefined | null,
@@ -481,18 +513,99 @@ export const createTable = async ({
}) => {
const queryClient = getQueryClient()
- // Create the table first. Error may be thrown.
- await createTableMutation({
- projectRef: projectRef,
- connectionString: connectionString,
- payload: payload,
+ // Build all SQL statements for table creation, columns, and constraints
+ // to execute in a single transaction for better performance and atomicity
+ const sqlStatements: string[] = []
+
+ // 1. Create table SQL
+ const { sql: createTableSql } = pgMeta.tables.create(payload)
+ sqlStatements.push(createTableSql)
+
+ // 2. Enable RLS if configured
+ if (isRLSEnabled) {
+ const enableRLSSQL = getEnableRLSSQL({ schema: payload.schema, table: payload.name })
+ sqlStatements.push(enableRLSSQL)
+ }
+
+ // 3. Add columns SQL (without primary keys - those are added as constraints)
+ for (const column of columns) {
+ const columnPayload = generateCreateColumnPayload(
+ { schema: payload.schema, name: payload.name } as RetrieveTableResult,
+ { ...column, isPrimaryKey: false }
+ )
+ const { sql: columnSQL } = pgMeta.columns.create({
+ schema: columnPayload.schema,
+ table: columnPayload.table,
+ name: columnPayload.name,
+ type: columnPayload.type,
+ default_value: columnPayload.defaultValue,
+ default_value_format: columnPayload.defaultValueFormat,
+ is_identity: columnPayload.isIdentity,
+ is_nullable: columnPayload.isNullable,
+ is_primary_key: columnPayload.isPrimaryKey,
+ is_unique: columnPayload.isUnique,
+ comment: columnPayload.comment,
+ check: columnPayload.check,
+ })
+ sqlStatements.push(columnSQL)
+ }
+
+ // 4. Add primary key constraint (supports composite keys)
+ const primaryKeyColumns = columns
+ .filter((column) => column.isPrimaryKey)
+ .map((column) => column.name)
+ if (primaryKeyColumns.length > 0) {
+ const primaryKeySQL = getAddPrimaryKeySQL({
+ schema: payload.schema,
+ table: payload.name,
+ columns: primaryKeyColumns,
+ })
+ sqlStatements.push(primaryKeySQL)
+ }
+
+ // 5. Add foreign key constraints
+ if (foreignKeyRelations.length > 0) {
+ const fkSql = getAddForeignKeySQL({
+ table: { schema: payload.schema, name: payload.name },
+ foreignKeys: foreignKeyRelations,
+ })
+ // Remove trailing semicolon since we join with semicolons
+ sqlStatements.push(fkSql.replace(/;+$/, ''))
+ }
+
+ // Execute all table creation SQL in a single transaction
+ toast.loading(`Creating table ${payload.name}...`, { id: toastId })
+
+ await executeSql({
+ projectRef,
+ connectionString,
+ sql: sqlStatements.join(';\n'),
+ queryKey: ['table', 'create-with-columns'],
})
- // Track table creation event
- try {
- await sendEvent({
+ // Track table creation event (fire-and-forget to avoid blocking)
+ sendEvent({
+ event: {
+ action: 'table_created',
+ properties: {
+ method: 'table_editor',
+ schema_name: payload.schema,
+ table_name: payload.name,
+ },
+ groups: {
+ project: projectRef,
+ ...(organizationSlug && { organization: organizationSlug }),
+ },
+ },
+ }).catch((error) => {
+ console.error('Failed to track table creation event:', error)
+ })
+
+ // Track RLS enablement event if enabled (fire-and-forget)
+ if (isRLSEnabled) {
+ sendEvent({
event: {
- action: 'table_created',
+ action: 'table_rls_enabled',
properties: {
method: 'table_editor',
schema_name: payload.schema,
@@ -503,199 +616,115 @@ export const createTable = async ({
...(organizationSlug && { organization: organizationSlug }),
},
},
+ }).catch((error) => {
+ console.error('Failed to track RLS enablement event:', error)
})
- } catch (error) {
- console.error('Failed to track table creation event:', error)
}
- const table = await queryClient.fetchQuery({
- queryKey: tableKeys.retrieve(projectRef, payload.name, payload.schema),
- queryFn: ({ signal }) =>
- getTable(
- { projectRef, connectionString, name: payload.name, schema: payload.schema },
- signal
- ),
+ // Fetch the created table
+ const table = await getTableQuery({
+ projectRef,
+ connectionString,
+ name: payload.name,
+ schema: payload.schema,
})
- // 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({
+ // 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,
- id: table.id,
- name: table.name,
- schema: table.schema,
- payload: { rls_enabled: isRLSEnabled },
- })
+ importContent.file,
+ table,
+ 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 }
+ )
+ }
+ )
- // Track RLS enablement event
- try {
- await sendEvent({
- event: {
- action: 'table_rls_enabled',
- properties: {
- method: 'table_editor',
- schema_name: table.schema,
- table_name: table.name,
- },
- groups: {
- project: projectRef,
- ...(organizationSlug && { organization: organizationSlug }),
- },
- },
- })
- } catch (error) {
- console.error('Failed to track RLS enablement event:', error)
+ 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 })
}
- }
-
- // 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, {
- ...column,
- isPrimaryKey: false,
- })
- await createDatabaseColumn({
+ } else {
+ // Via text copy and paste
+ await insertTableRows(
projectRef,
connectionString,
- payload: columnPayload,
- })
- }
-
- // Then add the primary key constraints here to support composite keys
- const primaryKeyColumns = columns
- .filter((column) => column.isPrimaryKey)
- .map((column) => column.name)
- if (primaryKeyColumns.length > 0) {
- await addPrimaryKey(projectRef, connectionString, table.schema, table.name, primaryKeyColumns)
+ table,
+ 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 }
+ )
+ }
+ )
}
- // Then add the foreign key constraints here
- if (foreignKeyRelations.length > 0) {
- await addForeignKey({
+ // For identity columns, manually raise the sequences (batched for performance)
+ const identityColumns = columns.filter((column) => column.isIdentity)
+ if (identityColumns.length > 0) {
+ const updateSequenceSQL = identityColumns
+ .map((column) =>
+ getUpdateIdentitySequenceSQL({
+ schema: table.schema,
+ table: table.name,
+ column: column.name,
+ })
+ )
+ .join(';\n')
+ await executeSql({
projectRef,
connectionString,
- table: { schema: table.schema, name: table.name },
- foreignKeys: foreignKeyRelations,
+ sql: updateSequenceSQL,
+ queryKey: ['sequences', 'update-batch'],
})
}
+ }
- // 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,
- 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,
- 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}"));`,
- })
- }
- }
- }
-
- await prefetchEditorTablePage({
- queryClient,
- projectRef,
- connectionString,
- id: table.id,
- })
+ await prefetchEditorTablePage({
+ queryClient,
+ projectRef,
+ connectionString,
+ id: table.id,
+ })
- // Finally, return the created table
- return table
- } catch (error) {
- deleteTableMutation({
- projectRef,
- connectionString,
- id: table.id,
- name: table.name,
- schema: table.schema,
- })
- throw error
- }
+ // Finally, return the created table
+ return table
}
+/** TODO: Refactor to do in a single transaction */
export const updateTable = async ({
projectRef,
connectionString,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
index fcee1686210..515e7df85ca 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
@@ -5,13 +5,13 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { useChanged } from 'hooks/misc/useChanged'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { SidePanel, Tabs } from 'ui'
-import ActionBar from '../ActionBar'
+import { ActionBar } from '../ActionBar'
import type { ImportContent } from '../TableEditor/TableEditor.types'
import SpreadSheetFileUpload from './SpreadSheetFileUpload'
-import { SpreadsheetImportPreview } from './SpreadsheetImportPreview'
import SpreadsheetImportConfiguration from './SpreadSheetImportConfiguration'
import SpreadSheetTextInput from './SpreadSheetTextInput'
import { EMPTY_SPREADSHEET_DATA } from './SpreadsheetImport.constants'
@@ -21,7 +21,7 @@ import {
parseSpreadsheet,
parseSpreadsheetText,
} from './SpreadsheetImport.utils'
-import { useChanged } from 'hooks/misc/useChanged'
+import { SpreadsheetImportPreview } from './SpreadsheetImportPreview'
interface SpreadsheetImportProps {
debounceDuration?: number
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/HeaderTitle.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/HeaderTitle.tsx
index 2c433e3c8b1..c3c56c2063e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/HeaderTitle.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/HeaderTitle.tsx
@@ -4,7 +4,7 @@ interface HeaderTitleProps {
isDuplicating: boolean
}
-const HeaderTitle = ({ schema, table, isDuplicating }: HeaderTitleProps) => {
+export const HeaderTitle = ({ schema, table, isDuplicating }: HeaderTitleProps) => {
if (!table) {
return (
<>
@@ -25,5 +25,3 @@ const HeaderTitle = ({ schema, table, isDuplicating }: HeaderTitleProps) => {
</>
)
}
-
-export default HeaderTitle
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index ab61d1a6be5..0533e95c1ba 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -8,22 +8,22 @@ import { useDatabasePublicationsQuery } from 'data/database-publications/databas
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 { useTrack } from 'lib/telemetry/track'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
import { useChanged } from 'hooks/misc/useChanged'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
+import { RealtimeButtonVariant, useRealtimeExperiment } from 'hooks/misc/useRealtimeExperiment'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
-import { useRealtimeExperiment, RealtimeButtonVariant } from 'hooks/misc/useRealtimeExperiment'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useProtectedSchemas } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
+import { useTrack } from 'lib/telemetry/track'
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 { 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'
@@ -31,7 +31,7 @@ import type { ColumnField } from '../SidePanelEditor.types'
import { SpreadsheetImport } from '../SpreadsheetImport/SpreadsheetImport'
import ColumnManagement from './ColumnManagement'
import { ForeignKeysManagement } from './ForeignKeysManagement/ForeignKeysManagement'
-import HeaderTitle from './HeaderTitle'
+import { HeaderTitle } from './HeaderTitle'
import RLSDisableModalContent from './RLSDisableModal'
import { DEFAULT_COLUMNS } from './TableEditor.constants'
import type { ImportContent, TableField } from './TableEditor.types'
@@ -319,6 +319,7 @@ export const TableEditor = ({
const importedColumns = formatImportedContentToColumnFields(importContent)
onUpdateField({ columns: importedColumns })
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [importContent])
if (!tableFields) return null
diff --git a/apps/studio/data/tables/table-retrieve-query.ts b/apps/studio/data/tables/table-retrieve-query.ts
index 219860136e1..ddda1c817b7 100644
--- a/apps/studio/data/tables/table-retrieve-query.ts
+++ b/apps/studio/data/tables/table-retrieve-query.ts
@@ -1,6 +1,7 @@
import pgMeta from '@supabase/pg-meta'
import { useQuery } from '@tanstack/react-query'
+import { getQueryClient } from 'data/query-client'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { tableKeys } from './keys'
@@ -34,7 +35,7 @@ export type RetrieveTableResult = Awaited<ReturnType<typeof getTable>>
export type RetrieveTableError = ResponseError
export type RetrievedTableColumn = NonNullable<RetrieveTableResult['columns']>[number]
-export const useTablesQuery = <TData = RetrieveTableResult>(
+export const useTableQuery = <TData = RetrieveTableResult>(
{ projectRef, connectionString, name, schema }: TablesVariables,
{
enabled = true,
@@ -48,3 +49,26 @@ export const useTablesQuery = <TData = RetrieveTableResult>(
...options,
})
}
+
+/**
+ * Non-hook usage to fetch data + caching it into the store
+ */
+export const getTableQuery = async ({
+ projectRef,
+ name,
+ schema,
+ connectionString,
+}: {
+ projectRef: string
+ name: string
+ schema: string
+ connectionString?: string | null
+}) => {
+ const queryClient = getQueryClient()
+ const table = await queryClient.fetchQuery({
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps
+ queryKey: tableKeys.retrieve(projectRef, name, schema),
+ queryFn: ({ signal }) => getTable({ projectRef, connectionString, name, schema }, signal),
+ })
+ return table
+}