Skip to content

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

chore: table editor optimisation 2 (#30295)

Alaister Younga5a287330275
diff --git a/apps/studio/components/grid/SupabaseGrid.utils.ts b/apps/studio/components/grid/SupabaseGrid.utils.ts
index 0b842471cfb..e140838a8a5 100644
--- a/apps/studio/components/grid/SupabaseGrid.utils.ts
+++ b/apps/studio/components/grid/SupabaseGrid.utils.ts
@@ -1,11 +1,8 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
import AwesomeDebouncePromise from 'awesome-debounce-promise'
import { compact } from 'lodash'
import type { Filter } from 'components/grid/types'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { TableLike } from 'data/table-editor/table-editor-query'
-import type { Dictionary, SchemaView } from 'types'
+import { Entity, isTableLike } from 'data/table-editor/table-editor-types'
import { FilterOperatorOptions } from './components/header/filter/Filter.constants'
import { STORAGE_KEY_PREFIX } from './constants'
import { InitialStateType } from './store/reducers'
@@ -65,22 +62,16 @@ export function formatFilterURLParams(filter?: string[]): Filter[] {
) as Filter[]
}
-export function parseSupaTable(
- data: {
- table: Dictionary<any>
- columns: Dictionary<any>[]
- primaryKeys: Dictionary<any>[]
- relationships: Dictionary<any>[]
- },
- encryptedColumns: string[] = []
-): SupaTable {
- const { table, columns, primaryKeys, relationships } = data
+export function parseSupaTable(table: Entity): SupaTable {
+ const columns = table.columns
+ const primaryKeys = isTableLike(table) ? table.primary_keys : []
+ const relationships = isTableLike(table) ? table.relationships : []
const supaColumns: SupaColumn[] = columns.map((column) => {
const temp = {
position: column.ordinal_position,
name: column.name,
- defaultValue: column.default_value,
+ defaultValue: column.default_value as string | null | undefined,
dataType: column.data_type,
format: column.format,
isPrimaryKey: false,
@@ -88,15 +79,14 @@ export function parseSupaTable(
isGeneratable: column.identity_generation == 'BY DEFAULT',
isNullable: column.is_nullable,
isUpdatable: column.is_updatable,
- isEncrypted: encryptedColumns.includes(column.name),
enum: column.enums,
comment: column.comment,
foreignKey: {
- targetTableSchema: null,
- targetTableName: null,
- targetColumnName: null,
- deletionAction: undefined,
- updateAction: undefined,
+ targetTableSchema: null as string | null,
+ targetTableName: null as string | null,
+ targetColumnName: null as string | null,
+ deletionAction: undefined as string | undefined,
+ updateAction: undefined as string | undefined,
},
}
const primaryKey = primaryKeys.find((pk) => pk.name == column.name)
@@ -125,41 +115,10 @@ export function parseSupaTable(
comment: table.comment,
schema: table.schema,
columns: supaColumns,
- estimateRowCount: table.live_rows_estimate,
+ estimateRowCount: isTableLike(table) ? table.live_rows_estimate : 0,
}
}
-export function getSupaTable({
- selectedTable,
- entityType,
- encryptedColumns,
-}: {
- selectedTable: TableLike
- entityType?: ENTITY_TYPE
- encryptedColumns?: string[]
-}) {
- const isViewSelected =
- entityType === ENTITY_TYPE.VIEW || entityType === ENTITY_TYPE.MATERIALIZED_VIEW
- const isForeignTableSelected = entityType === ENTITY_TYPE.FOREIGN_TABLE
-
- return !isViewSelected && !isForeignTableSelected
- ? parseSupaTable(
- {
- table: selectedTable as PostgresTable,
- columns: (selectedTable as PostgresTable).columns ?? [],
- primaryKeys: (selectedTable as PostgresTable).primary_keys ?? [],
- relationships: (selectedTable as PostgresTable).relationships ?? [],
- },
- encryptedColumns
- )
- : parseSupaTable({
- table: selectedTable as SchemaView,
- columns: (selectedTable as SchemaView).columns ?? [],
- primaryKeys: [],
- relationships: [],
- })
-}
-
export const saveStorageDebounced = AwesomeDebouncePromise(saveStorage, 500)
function saveStorage(
diff --git a/apps/studio/components/grid/components/editor/JsonEditor.tsx b/apps/studio/components/grid/components/editor/JsonEditor.tsx
index 15ee5ea12ac..152accb8044 100644
--- a/apps/studio/components/grid/components/editor/JsonEditor.tsx
+++ b/apps/studio/components/grid/components/editor/JsonEditor.tsx
@@ -1,4 +1,3 @@
-import { PostgresTable } from '@supabase/postgres-meta'
import { isNil } from 'lodash'
import { Maximize } from 'lucide-react'
import { useCallback, useState } from 'react'
@@ -7,10 +6,8 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { useTrackedState } from 'components/grid/store/Store'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
@@ -61,12 +58,11 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
const id = _id ? Number(_id) : undefined
const project = useSelectedProject()
- const { data } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
const gridColumn = state.gridColumns.find((x) => x.name == column.key)
const initialValue = row[column.key as keyof TRow] as string
@@ -82,12 +78,12 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
const { mutate: getCellValue, isLoading, isSuccess } = useGetCellValueMutation()
const loadFullValue = () => {
- if (selectedTable === undefined || project === undefined) return
- if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ if (selectedTable === undefined || project === undefined || !isTableLike(selectedTable)) return
+ if (selectedTable.primary_keys.length === 0) {
return toast('Unable to load value as table has no primary keys')
}
- const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ const pkMatch = selectedTable.primary_keys.reduce((a, b) => {
return { ...a, [b.name]: (row as any)[b.name] }
}, {})
diff --git a/apps/studio/components/grid/components/editor/TextEditor.tsx b/apps/studio/components/grid/components/editor/TextEditor.tsx
index df260056dbf..32dbf6b4196 100644
--- a/apps/studio/components/grid/components/editor/TextEditor.tsx
+++ b/apps/studio/components/grid/components/editor/TextEditor.tsx
@@ -1,14 +1,11 @@
-import { PostgresTable } from '@supabase/postgres-meta'
import { Maximize } from 'lucide-react'
import { useCallback, useState } from 'react'
import type { RenderEditCellProps } from 'react-data-grid'
import { toast } from 'sonner'
import { useParams } from 'common'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
@@ -45,12 +42,11 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
const id = _id ? Number(_id) : undefined
const project = useSelectedProject()
- const { data } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
const gridColumn = state.gridColumns.find((x) => x.name == column.key)
const initialValue = row[column.key as keyof TRow] as unknown as string
@@ -66,12 +62,12 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
initialValue.length > MAX_CHARACTERS
const loadFullValue = () => {
- if (selectedTable === undefined || project === undefined) return
- if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ if (selectedTable === undefined || project === undefined || !isTableLike(selectedTable)) return
+ if (selectedTable.primary_keys.length === 0) {
return toast('Unable to load value as table has no primary keys')
}
- const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ const pkMatch = selectedTable.primary_keys.reduce((a, b) => {
return { ...a, [b.name]: (row as any)[b.name] }
}, {})
diff --git a/apps/studio/components/grid/components/footer/Footer.tsx b/apps/studio/components/grid/components/footer/Footer.tsx
index 7153dc6b1fd..158f81973b2 100644
--- a/apps/studio/components/grid/components/footer/Footer.tsx
+++ b/apps/studio/components/grid/components/footer/Footer.tsx
@@ -2,11 +2,8 @@ import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { GridFooter } from 'components/ui/GridFooter'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike, isViewLike } from 'data/table-editor/table-editor-types'
import { useUrlState } from 'hooks/ui/useUrlState'
import RefreshButton from '../header/RefreshButton'
import { Pagination } from './pagination'
@@ -20,13 +17,11 @@ const Footer = ({ isRefetching }: FooterProps) => {
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data } = useTableEditorQuery({
+ const { data: entity } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
- const entityType = data?.entity
const [{ view: selectedView = 'data' }, setUrlState] = useUrlState()
@@ -38,17 +33,16 @@ const Footer = ({ isRefetching }: FooterProps) => {
}
}
- const isViewSelected =
- entityType?.type === ENTITY_TYPE.VIEW || entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW
- const isTableSelected = entityType?.type === ENTITY_TYPE.TABLE
+ const isViewSelected = isViewLike(entity)
+ const isTableSelected = isTableLike(entity)
return (
<GridFooter>
{selectedView === 'data' && <Pagination />}
<div className="ml-auto flex items-center gap-x-2">
- {selectedTable && selectedView === 'data' && (
- <RefreshButton table={selectedTable} isRefetching={isRefetching} />
+ {entity && selectedView === 'data' && (
+ <RefreshButton table={entity} isRefetching={isRefetching} />
)}
{(isViewSelected || isTableSelected) && (
diff --git a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
index 8229d30826b..bb32dd1a3e2 100644
--- a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
+++ b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
@@ -1,14 +1,11 @@
-import { PostgresTable } from '@supabase/postgres-meta'
import { ArrowLeft, ArrowRight, HelpCircle } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useParams } from 'common'
import { formatFilterURLParams } from 'components/grid/SupabaseGrid.utils'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { THRESHOLD_COUNT, useTableRowsCountQuery } from 'data/table-rows/table-rows-count-query'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
@@ -35,15 +32,14 @@ const Pagination = () => {
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
- const { data: tableData } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(tableData)
- // [Joshen] Only applicable to table entities
- const rowsCountEstimate = (selectedTable as PostgresTable)?.live_rows_estimate ?? null
+ // rowsCountEstimate is only applicable to table entities
+ const rowsCountEstimate = isTableLike(selectedTable) ? selectedTable.live_rows_estimate : null
const [{ filter }] = useUrlState({ arrayKeys: ['filter'] })
const filters = formatFilterURLParams(filter as string[])
diff --git a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
index ca1dc3ab5a6..82973ff6987 100644
--- a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
+++ b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
@@ -5,6 +5,7 @@ import type { RenderCellProps } from 'react-data-grid'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { EditorTablePageLink } from 'data/prefetchers/project.$ref.editor.$id'
import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useTablesQuery } from 'data/tables/tables-query'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { Button, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
@@ -28,7 +29,7 @@ export const ForeignKeyFormatter = (props: Props) => {
connectionString: project?.connectionString,
id,
})
- const selectedTable = data?.table_info
+ const selectedTable = isTableLike(data) ? data : undefined
const relationship = (selectedTable?.relationships ?? []).find(
(r) =>
diff --git a/apps/studio/components/grid/components/header/RefreshButton.tsx b/apps/studio/components/grid/components/header/RefreshButton.tsx
index 7041b574aae..0b43a2aa0b2 100644
--- a/apps/studio/components/grid/components/header/RefreshButton.tsx
+++ b/apps/studio/components/grid/components/header/RefreshButton.tsx
@@ -4,11 +4,11 @@ import { RefreshCw } from 'lucide-react'
import { useParams } from 'common'
import type { SupaTable } from 'components/grid/types'
import { sqlKeys } from 'data/sql/keys'
-import { TableLike } from 'data/table-editor/table-editor-query'
+import { Entity } from 'data/table-editor/table-editor-types'
import { Button } from 'ui'
export type RefreshButtonProps = {
- table: TableLike | SupaTable
+ table: Entity | SupaTable
isRefetching?: boolean
}
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
index d3677dd2d25..b64738dfa99 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
@@ -1,4 +1,4 @@
-import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresPolicy } from '@supabase/postgres-meta'
import { isEmpty } from 'lodash'
import { HelpCircle } from 'lucide-react'
import { useRouter } from 'next/router'
@@ -6,7 +6,9 @@ import { useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
-import PolicyTableRow from 'components/interfaces/Auth/Policies/PolicyTableRow'
+import PolicyTableRow, {
+ PolicyTableRowProps,
+} from 'components/interfaces/Auth/Policies/PolicyTableRow'
import ProtectedSchemaWarning from 'components/interfaces/Database/ProtectedSchemaWarning'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'
@@ -18,7 +20,7 @@ import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
interface PoliciesProps {
schema: string
- tables: PostgresTable[]
+ tables: PolicyTableRowProps['table'][]
hasTables: boolean
isLocked: boolean
onSelectCreatePolicy: (table: string) => void
@@ -37,7 +39,12 @@ const Policies = ({
const { ref } = useParams()
const { project } = useProjectContext()
- const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<any>({})
+ const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<{
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }>()
const [selectedPolicyToDelete, setSelectedPolicyToDelete] = useState<any>({})
const { mutate: updateTable } = useTableUpdateMutation({
@@ -59,10 +66,15 @@ const Policies = ({
const closeConfirmModal = () => {
setSelectedPolicyToDelete({})
- setSelectedTableToToggleRLS({})
+ setSelectedTableToToggleRLS(undefined)
}
- const onSelectToggleRLS = (table: PostgresTable) => {
+ const onSelectToggleRLS = (table: {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }) => {
setSelectedTableToToggleRLS(table)
}
@@ -76,6 +88,8 @@ const Policies = ({
// Methods that involve some API
const onToggleRLS = async () => {
+ if (!selectedTableToToggleRLS) return console.error('Table is required')
+
const payload = {
id: selectedTableToToggleRLS.id,
rls_enabled: !selectedTableToToggleRLS.rls_enabled,
@@ -85,7 +99,7 @@ const Policies = ({
projectRef: project?.ref!,
connectionString: project?.connectionString,
id: payload.id,
- schema: (selectedTableToToggleRLS as PostgresTable).schema,
+ schema: selectedTableToToggleRLS.schema,
payload: payload,
})
}
@@ -170,14 +184,14 @@ const Policies = ({
/>
<ConfirmModal
- danger={selectedTableToToggleRLS.rls_enabled}
- visible={!isEmpty(selectedTableToToggleRLS)}
+ danger={selectedTableToToggleRLS?.rls_enabled}
+ visible={selectedTableToToggleRLS !== undefined}
title={`Confirm to ${
- selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'
+ selectedTableToToggleRLS?.rls_enabled ? 'disable' : 'enable'
} Row Level Security`}
description={`Are you sure you want to ${
- selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'
- } Row Level Security for the table "${selectedTableToToggleRLS.name}"?`}
+ selectedTableToToggleRLS?.rls_enabled ? 'disable' : 'enable'
+ } Row Level Security for the table "${selectedTableToToggleRLS?.name}"?`}
buttonLabel="Confirm"
buttonLoadingLabel="Saving"
onSelectCancel={closeConfirmModal}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
index 4823c3bc72e..9c4edfa0dd2 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRowHeader.tsx
@@ -2,7 +2,6 @@ import { noop } from 'lodash'
import { Lock, Unlock } from 'lucide-react'
import { useQueryState } from 'nuqs'
-import type { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
@@ -18,9 +17,19 @@ import {
} from 'ui'
interface PolicyTableRowHeaderProps {
- table: PostgresTable
+ table: {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }
isLocked: boolean
- onSelectToggleRLS: (table: PostgresTable) => void
+ onSelectToggleRLS: (table: {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }) => void
onSelectCreatePolicy: () => void
}
diff --git a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
index fd895d66bda..3e76ab0df6a 100644
--- a/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/PolicyTableRow/index.tsx
@@ -1,4 +1,4 @@
-import type { PostgresPolicy, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresPolicy } from '@supabase/postgres-meta'
import { noop } from 'lodash'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
@@ -9,10 +9,20 @@ import { cn, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } f
import PolicyRow from './PolicyRow'
import PolicyTableRowHeader from './PolicyTableRowHeader'
-interface PolicyTableRowProps {
- table: PostgresTable
+export interface PolicyTableRowProps {
+ table: {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }
isLocked: boolean
- onSelectToggleRLS: (table: PostgresTable) => void
+ onSelectToggleRLS: (table: {
+ id: number
+ schema: string
+ name: string
+ rls_enabled: boolean
+ }) => void
onSelectCreatePolicy: () => void
onSelectEditPolicy: (policy: PostgresPolicy) => void
onSelectDeletePolicy: (policy: PostgresPolicy) => void
diff --git a/apps/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx b/apps/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
index 5e9b259eecd..90729724dea 100644
--- a/apps/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/DeleteHookModal.tsx
@@ -41,7 +41,7 @@ const DeleteHookModal = ({ selectedHook, visible, onClose }: DeleteHookModalProp
return (
<TextConfirmModal
- variant={'warning'}
+ variant="destructive"
visible={visible}
size="medium"
onCancel={() => onClose()}
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index f10aa57a08b..527e37981ba 100644
--- a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
@@ -12,7 +12,7 @@ import {
EdgeFunctionsResponse,
useEdgeFunctionsQuery,
} from 'data/edge-functions/edge-functions-query'
-import { getTable } from 'data/tables/get-table'
+import { getTableEditor } from 'data/table-editor/table-editor-query'
import { useTablesQuery } from 'data/tables/tables-query'
import { isValidHttpUrl, tryParseJson, uuidv4 } from 'lib/helpers'
import { Button, Checkbox, Form, Input, Listbox, Radio, SidePanel } from 'ui'
@@ -182,7 +182,7 @@ const EditHookPanel = ({ visible, selectedHook, onClose }: EditHookPanelProps) =
return setEventsError('Please select at least one event')
}
- const selectedTable = await getTable({
+ const selectedTable = await getTableEditor({
id: values.table_id,
projectRef: project?.ref,
connectionString: project?.connectionString,
diff --git a/apps/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx b/apps/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
index 1af40990b0a..7515d413114 100644
--- a/apps/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/HooksList/HookList.tsx
@@ -95,9 +95,7 @@ const HookList = ({ schema, filterString, editHook = noop, deleteHook = noop }:
{canUpdateWebhook ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" className="px-1">
- <MoreVertical />
- </Button>
+ <Button type="default" className="px-1" icon={<MoreVertical />} />
</DropdownMenuTrigger>
<DropdownMenuContent side="left">
diff --git a/apps/studio/components/interfaces/Database/Privileges/PrivilegesHead.tsx b/apps/studio/components/interfaces/Database/Privileges/PrivilegesHead.tsx
index 6d425a25f82..963a9083ea3 100644
--- a/apps/studio/components/interfaces/Database/Privileges/PrivilegesHead.tsx
+++ b/apps/studio/components/interfaces/Database/Privileges/PrivilegesHead.tsx
@@ -1,4 +1,3 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
import SchemaSelector from 'components/ui/SchemaSelector'
import {
@@ -15,7 +14,7 @@ export interface PrivilegesHeadProps {
disabled: boolean
selectedSchema: string
selectedRole: string
- selectedTable?: PostgresTable
+ selectedTable?: { name: string }
tables: string[]
roles: string[]
onChangeSchema: (schema: string) => void
@@ -118,7 +117,9 @@ const TablesSelect = ({
tables,
onChangeTable,
}: {
- selectedTable?: PostgresTable
+ selectedTable?: {
+ name: string
+ }
tables: string[]
onChangeTable: (table: string) => void
}) => {
diff --git a/apps/studio/components/interfaces/Database/Publications/PublicationsTables.tsx b/apps/studio/components/interfaces/Database/Publications/PublicationsTables.tsx
index 73a20238c1a..dff11cc7ba0 100644
--- a/apps/studio/components/interfaces/Database/Publications/PublicationsTables.tsx
+++ b/apps/studio/components/interfaces/Database/Publications/PublicationsTables.tsx
@@ -119,7 +119,7 @@ const PublicationsTables = ({ selectedPublication, onSelectBack }: PublicationsT
</div> */}
</Table.th>,
]}
- body={tables.map((table: any, i: number) => (
+ body={tables.map((table) => (
<PublicationsTableItem
key={table.id}
table={table}
diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
index 83610ce74b7..9fca6e7978d 100644
--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx
@@ -1,4 +1,4 @@
-import type { PostgresSchema, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresSchema } from '@supabase/postgres-meta'
import { Loader2 } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useEffect, useMemo, useState } from 'react'
@@ -14,9 +14,9 @@ import { useTablesQuery } from 'data/tables/tables-query'
import { useLocalStorage } from 'hooks/misc/useLocalStorage'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
import { Button, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
-import { TableNode } from './SchemaTableNode'
import { SchemaGraphLegend } from './SchemaGraphLegend'
import { getGraphDataFromTables, getLayoutedElementsViaDagre } from './Schemas.utils'
+import { TableNode } from './SchemaTableNode'
// [Joshen] Persisting logic: Only save positions to local storage WHEN a node is moved OR when explicitly clicked to reset layout
@@ -95,13 +95,11 @@ export const SchemaGraph = () => {
useEffect(() => {
if (isSuccessTables && isSuccessSchemas && tables.length > 0) {
const schema = schemas.find((s) => s.name === selectedSchema) as PostgresSchema
- getGraphDataFromTables(ref as string, schema, tables as PostgresTable[]).then(
- ({ nodes, edges }) => {
- reactFlowInstance.setNodes(nodes)
- reactFlowInstance.setEdges(edges)
- setTimeout(() => reactFlowInstance.fitView({})) // it needs to happen during next event tick
- }
- )
+ getGraphDataFromTables(ref as string, schema, tables).then(({ nodes, edges }) => {
+ reactFlowInstance.setNodes(nodes)
+ reactFlowInstance.setEdges(edges)
+ setTimeout(() => reactFlowInstance.fitView({})) // it needs to happen during next event tick
+ })
}
}, [isSuccessTables, isSuccessSchemas, tables, resolvedTheme])
diff --git a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
index ccecfb7c8e4..e23b406b17c 100644
--- a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
@@ -1,5 +1,4 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
import { ChevronLeft, Edit, MoreVertical, Plus, Search, Trash } from 'lucide-react'
@@ -13,10 +12,8 @@ import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import {
@@ -44,15 +41,20 @@ const ColumnList = ({
const id = _id ? Number(_id) : undefined
const { project } = useProjectContext()
- const { data, error, isError, isLoading, isSuccess } = useTableEditorQuery({
+ const {
+ data: selectedTable,
+ error,
+ isError,
+ isLoading,
+ isSuccess,
+ } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
const [filterString, setFilterString] = useState<string>('')
- const isTableEntity = 'live_rows_estimate' in ((selectedTable as PostgresTable) || {})
+ const isTableEntity = isTableLike(selectedTable)
const columns =
(filterString.length === 0
diff --git a/apps/studio/components/interfaces/Database/Tables/TableList.tsx b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
index d7245c85ec8..8ff037d2ca5 100644
--- a/apps/studio/components/interfaces/Database/Tables/TableList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
@@ -1,4 +1,5 @@
import * as Tooltip from '@radix-ui/react-tooltip'
+import type { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
import {
@@ -59,9 +60,9 @@ import { formatAllEntities } from './Tables.utils'
interface TableListProps {
onAddTable: () => void
- onEditTable: (table: any) => void
- onDeleteTable: (table: any) => void
- onDuplicateTable: (table: any) => void
+ onEditTable: (table: PostgresTable) => void
+ onDeleteTable: (table: PostgresTable) => void
+ onDuplicateTable: (table: PostgresTable) => void
}
const TableList = ({
@@ -262,7 +263,7 @@ const TableList = ({
className="w-64"
placeholder="Search for a table"
value={filterString}
- onChange={(e: any) => setFilterString(e.target.value)}
+ onChange={(e) => setFilterString(e.target.value)}
icon={<Search size={12} />}
/>
@@ -383,9 +384,11 @@ const TableList = ({
x.type === ENTITY_TYPE.FOREIGN_TABLE &&
'text-yellow-900 bg-yellow-500',
x.type === ENTITY_TYPE.MATERIALIZED_VIEW &&
- 'text-purple-1000 bg-purple-500',
- x.type === ENTITY_TYPE.PARTITIONED_TABLE &&
- 'text-foreground-light bg-border-stronger'
+ 'text-purple-1000 bg-purple-500'
+ // [Alaister]: tables endpoint doesn't distinguish between tables and partitioned tables
+ // once we update the endpoint to include partitioned tables, we can uncomment this
+ // x.type === ENTITY_TYPE.PARTITIONED_TABLE &&
+ // 'text-foreground-light bg-border-stronger'
)}
>
{Object.entries(ENTITY_TYPE)
@@ -443,9 +446,7 @@ const TableList = ({
{x.size !== undefined ? <code className="text-xs">{x.size}</code> : '-'}
</Table.td>
<Table.td className="hidden xl:table-cell text-center">
- {(realtimePublication?.tables ?? []).find(
- (table: any) => table.id === x.id
- ) ? (
+ {(realtimePublication?.tables ?? []).find((table) => table.id === x.id) ? (
<div className="flex justify-center">
<Check size={18} strokeWidth={2} className="text-brand" />
</div>
diff --git a/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts b/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts
index 43f910509e2..d9acbb4e0f6 100644
--- a/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts
+++ b/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts
@@ -18,7 +18,7 @@ export const formatAllEntities = ({
const formattedTables = tables.map((x) => {
return {
...x,
- type: ENTITY_TYPE.TABLE,
+ type: ENTITY_TYPE.TABLE as const,
rows: x.live_rows_estimate,
columns: x.columns ?? [],
}
@@ -26,7 +26,7 @@ export const formatAllEntities = ({
const formattedViews = views.map((x) => {
return {
- type: ENTITY_TYPE.VIEW,
+ type: ENTITY_TYPE.VIEW as const,
id: x.id,
name: x.name,
comment: x.comment,
@@ -38,7 +38,7 @@ export const formatAllEntities = ({
const formattedMaterializedViews = materializedViews.map((x) => {
return {
- type: ENTITY_TYPE.MATERIALIZED_VIEW,
+ type: ENTITY_TYPE.MATERIALIZED_VIEW as const,
id: x.id,
name: x.name,
comment: x.comment,
@@ -50,7 +50,7 @@ export const formatAllEntities = ({
const formattedForeignTables = foreignTables.map((x) => {
return {
- type: ENTITY_TYPE.FOREIGN_TABLE,
+ type: ENTITY_TYPE.FOREIGN_TABLE as const,
id: x.id,
name: x.name,
comment: x.comment,
diff --git a/apps/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx b/apps/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx
index 6dc505446c8..ac81ccbad08 100644
--- a/apps/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx
+++ b/apps/studio/components/interfaces/Database/Wrappers/WrapperRow.tsx
@@ -119,7 +119,7 @@ const WrapperRow = ({
</p>
<div className="flex flex-wrap gap-2">
{wrapper.tables ? (
- wrapper.tables.map((table: any) => (
+ wrapper.tables.map((table) => (
<EditorTablePageLink
key={table.id}
projectRef={ref}
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
index 896e7882dc7..859971e6fd8 100644
--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
@@ -1,3 +1,4 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { ExternalLink } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
@@ -6,12 +7,12 @@ import { formatFilterURLParams } from 'components/grid/SupabaseGrid.utils'
import type { SupaRow } from 'components/grid/types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useDatabaseColumnDeleteMutation } from 'data/database-columns/database-column-delete-mutation'
-import { TableLike } from 'data/table-editor/table-editor-query'
+import { Entity } from 'data/table-editor/table-editor-types'
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 { TablesData, useGetTables } from 'data/tables/tables-query'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useUrlState } from 'hooks/ui/useUrlState'
import { noop } from 'lib/void'
@@ -21,8 +22,8 @@ import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, Ch
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
export type DeleteConfirmationDialogsProps = {
- selectedTable?: TableLike
- onAfterDeleteTable?: (tables: TableLike[]) => void
+ selectedTable?: Entity | PostgresTable
+ onAfterDeleteTable?: (tables: TablesData) => void
}
const DeleteConfirmationDialogs = ({
diff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index 68a397a6be9..3562f5a8f2e 100644
--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -14,9 +14,14 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
import { useDatabasePublicationUpdateMutation } from 'data/database-publications/database-publications-update-mutation'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import { useProjectLintsQuery } from 'data/lint/lint-query'
-import { Entity, TableLike } from 'data/table-editor/table-editor-query'
+import {
+ Entity,
+ isTableLike,
+ isForeignTable as isTableLikeForeignTable,
+ isMaterializedView as isTableLikeMaterializedView,
+ isView as isTableLikeView,
+} from 'data/table-editor/table-editor-types'
import { useTableUpdateMutation } from 'data/tables/table-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
@@ -36,12 +41,11 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { RoleImpersonationPopover } from '../RoleImpersonationSelector'
export interface GridHeaderActionsProps {
- table: TableLike
- entityType: Entity
+ table: Entity
canEditViaTableEditor: boolean
}
-const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
+const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
const { ref } = useParams()
const { project } = useProjectContext()
@@ -50,13 +54,10 @@ const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
projectRef: project?.ref,
})
- const isTable = entityType?.type === ENTITY_TYPE.TABLE
- const isMaterializedView = entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW
- const isView = entityType?.type === ENTITY_TYPE.VIEW
-
- // check if current entity is a view and has an associated security definer lint
-
- const isForeignTable = entityType?.type === ENTITY_TYPE.FOREIGN_TABLE
+ const isTable = isTableLike(table)
+ const isForeignTable = isTableLikeForeignTable(table)
+ const isView = isTableLikeView(table)
+ const isMaterializedView = isTableLikeMaterializedView(table)
const realtimeEnabled = useIsFeatureEnabled('realtime:all')
const isLocked = EXCLUDED_SCHEMAS.includes(table.schema)
@@ -157,7 +158,7 @@ const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
const onToggleRLS = async () => {
const payload = {
id: table.id,
- rls_enabled: !(table as PostgresTable).rls_enabled,
+ rls_enabled: !(isTable && table.rls_enabled),
}
updateTable({
@@ -186,7 +187,7 @@ const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
</Tooltip_Shadcn_>
)}
{isTable ? (
- (table as PostgresTable).rls_enabled ? (
+ table.rls_enabled ? (
<>
{policies.length < 1 && !isLocked ? (
<ButtonTooltip
@@ -350,7 +351,7 @@ const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
</PopoverContent_Shadcn_>
</Popover_Shadcn_>
)}
- {isForeignTable && entityType.schema === 'public' && (
+ {isForeignTable && table.schema === 'public' && (
<Popover_Shadcn_ open={open} onOpenChange={() => setOpen(!open)} modal={false}>
<PopoverTrigger_Shadcn_ asChild>
<Button type="warning" icon={<Unlock strokeWidth={1.5} />}>
@@ -424,9 +425,9 @@ const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
)}
</div>
</ConfirmationModal>
- {entityType?.type === ENTITY_TYPE.TABLE && (
+ {isTable && (
<ConfirmModal
- danger={(table as PostgresTable).rls_enabled}
+ danger={table.rls_enabled}
visible={rlsConfirmModalOpen}
title="Confirm to enable Row Level Security"
description="Are you sure you want to enable Row Level Security for this table?"
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index 0d87702d8e3..423fc6843c0 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -19,17 +19,7 @@ import {
import { useEnumeratedTypesQuery } from 'data/enumerated-types/enumerated-types-query'
import { EXCLUDED_SCHEMAS_WITHOUT_EXTENSIONS } from 'lib/constants/schemas'
import type { Dictionary } from 'types'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Button,
- Checkbox,
- Input,
- SidePanel,
- Toggle,
- WarningIcon,
-} from 'ui'
+import { Button, Checkbox, Input, SidePanel, Toggle } from 'ui'
import ActionBar from '../ActionBar'
import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'
@@ -52,7 +42,7 @@ import ColumnType from './ColumnType'
import HeaderTitle from './HeaderTitle'
export interface ColumnEditorProps {
- column?: PostgresColumn
+ column?: Readonly<PostgresColumn>
selectedTable: PostgresTable
visible: boolean
closePanel: () => void
@@ -155,7 +145,7 @@ const ColumnEditor = ({
)
}
- const updatedColumnFields = { ...columnFields, ...changes } as ColumnField
+ const updatedColumnFields: ColumnField = { ...columnFields, ...changes }
setColumnFields(updatedColumnFields)
updateEditorDirty()
@@ -361,45 +351,6 @@ const ColumnEditor = ({
/>
</FormSectionContent>
</FormSection>
-
- {isNewRecord && (
- <>
- <SidePanel.Separator />
- <FormSection
- header={<FormSectionLabel className="lg:!col-span-4">Security</FormSectionLabel>}
- >
- <FormSectionContent loading={false} className="lg:!col-span-8">
- <Alert_Shadcn_>
- <WarningIcon />
- <AlertTitle_Shadcn_>
- Column encryption has been removed from the GUI
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- <p className="!leading-normal">
- You may still encrypt new columns through the SQL editor using{' '}
- <Link
- href={`/project/${ref}/database/extensions?filter=pgsodium`}
- className="text-brand hover:underline"
- >
- pgsodium's
- </Link>{' '}
- Transparent Column Encryption (TCE).
- </p>
- <Button asChild type="default" icon={<ExternalLink />} className="mt-2">
- <Link
- target="_blank"
- rel="noreferrer"
- href="https://github.com/orgs/supabase/discussions/18849"
- >
- Learn more
- </Link>
- </Button>
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- </FormSectionContent>
- </FormSection>
- </>
- )}
</SidePanel>
)
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
index 43b2511f260..60319888c7a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils.ts
@@ -1,9 +1,10 @@
import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
-import { find, isEqual, isNull } from 'lodash'
+import { isEqual, isNull } from 'lodash'
import type { Dictionary } from 'types'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
+import type { PartitionedTable, Table } from 'data/table-editor/table-editor-types'
import { uuidv4 } from 'lib/helpers'
import {
ColumnField,
@@ -210,7 +211,8 @@ export const getColumnForeignKey = (
foreignKeys: ForeignKeyConstraint[]
) => {
const { relationships } = table
- const foreignKey = find(relationships, (relationship) => {
+
+ const foreignKey = relationships.find((relationship) => {
return (
relationship.source_schema === column.schema &&
relationship.source_table_name === column.table &&
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
index 6bd3b22437d..978708152af 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
@@ -4,10 +4,7 @@ import { Button } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { ForeignKeySelector } from '../ForeignKeySelector/ForeignKeySelector'
import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'
import type { ColumnField } from '../SidePanelEditor.types'
@@ -41,12 +38,11 @@ const ColumnForeignKey = ({
})
const id = _id ? Number(_id) : undefined
- const { data: tableData } = useTableEditorQuery({
+ const { data: table } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const table = getTableLikeFromTableEditor(tableData)
const formattedColumnsForFkSelector = (table?.columns ?? []).map((c) => {
return { id: c.id, name: c.name, format: column.format, isNewColumn: false }
})
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 18a4a2f8d1a..85de3f09930 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
@@ -1,4 +1,3 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
import { Loader2 } from 'lucide-react'
import { useState } from 'react'
import { DndProvider } from 'react-dnd'
@@ -13,10 +12,7 @@ import RefreshButton from 'components/grid/components/header/RefreshButton'
import FilterPopover from 'components/grid/components/header/filter/FilterPopover'
import { SortPopover } from 'components/grid/components/header/sort'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { SidePanel } from 'ui'
@@ -43,24 +39,13 @@ const ForeignRowSelector = ({
const { tableId: _tableId, schema: schemaName, table: tableName, columns } = foreignKey ?? {}
const tableId = _tableId ? Number(_tableId) : undefined
- const { data: tableData } = useTableEditorQuery({
+ const { data: table } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id: tableId,
})
- const table = getTableLikeFromTableEditor(tableData)
-
- const supaTable =
- table &&
- parseSupaTable(
- {
- table: table as PostgresTable,
- columns: (table as PostgresTable).columns ?? [],
- primaryKeys: (table as PostgresTable).primary_keys,
- relationships: (table as PostgresTable).relationships,
- },
- tableData?.encrypted_columns ?? undefined
- )
+
+ const supaTable = table && parseSupaTable(table)
const [params, setParams] = useState<any>({ filter: [], sort: [] })
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
index 2c5ab27ef11..4919ee73ab3 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
@@ -1,15 +1,12 @@
import * as Tooltip from '@radix-ui/react-tooltip'
-import { PostgresTable } from '@supabase/postgres-meta'
import { AlignLeft } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
@@ -45,12 +42,11 @@ const JsonEdit = ({
const id = _id ? Number(_id) : undefined
const project = useSelectedProject()
- const { data } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
const [view, setView] = useState<'edit' | 'view'>('edit')
const [jsonStr, setJsonStr] = useState('')
@@ -78,12 +74,18 @@ const JsonEdit = ({
}
const loadFullValue = () => {
- if (selectedTable === undefined || project === undefined || row === undefined) return
- if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ if (
+ selectedTable === undefined ||
+ project === undefined ||
+ row === undefined ||
+ !isTableLike(selectedTable)
+ )
+ return
+ if (selectedTable.primary_keys.length === 0) {
return toast('Unable to load value as table has no primary keys')
}
- const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ const pkMatch = selectedTable.primary_keys.reduce((a, b) => {
return { ...a, [b.name]: (row as any)[b.name] }
}, {})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
index 8716600b7e9..b8be1f7414a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
@@ -1,5 +1,4 @@
import { Editor } from '@monaco-editor/react'
-import { PostgresTable } from '@supabase/postgres-meta'
import { Loader } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import remarkGfm from 'remark-gfm'
@@ -8,10 +7,8 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { Markdown } from 'components/interfaces/Markdown'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
@@ -40,12 +37,11 @@ export const TextEditor = ({
const id = _id ? Number(_id) : undefined
const project = useSelectedProject()
- const { data } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
const [strValue, setStrValue] = useState('')
const [view, setView] = useState<'edit' | 'view'>('edit')
@@ -55,12 +51,18 @@ export const TextEditor = ({
const { mutate: getCellValue, isLoading, isSuccess, reset } = useGetCellValueMutation()
const loadFullValue = () => {
- if (selectedTable === undefined || project === undefined || row === undefined) return
- if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ if (
+ selectedTable === undefined ||
+ project === undefined ||
+ row === undefined ||
+ !isTableLike(selectedTable)
+ )
+ return
+ if (selectedTable.primary_keys.length === 0) {
return toast('Unable to load value as table has no primary keys')
}
- const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ const pkMatch = selectedTable.primary_keys.reduce((a, b) => {
return { ...a, [b.name]: (row as any)[b.name] }
}, {})
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 9055ac1005c..b1c2dfca30d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -12,6 +12,8 @@ import type { Constraint } from 'data/database/constraints-query'
import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { entityTypeKeys } from 'data/entity-types/keys'
import { sqlKeys } from 'data/sql/keys'
+import { tableEditorKeys } from 'data/table-editor/keys'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useTableRowCreateMutation } from 'data/table-rows/table-row-create-mutation'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { tableKeys } from 'data/tables/keys'
@@ -111,7 +113,7 @@ const SidePanelEditor = ({
await createTableRows({
projectRef: project.ref,
connectionString: project.connectionString,
- table: selectedTable as any,
+ table: selectedTable,
payload,
enumArrayColumns,
impersonatedRole: getImpersonatedRole(),
@@ -127,7 +129,7 @@ const SidePanelEditor = ({
await updateTableRow({
projectRef: project.ref,
connectionString: project.connectionString,
- table: selectedTable as any,
+ table: selectedTable,
configuration,
payload,
enumArrayColumns,
@@ -216,12 +218,16 @@ const SidePanelEditor = ({
const selectedColumnToEdit = snap.sidePanel?.type === 'column' && snap.sidePanel.column
const { columnId, primaryKey, foreignKeyRelations, existingForeignKeyRelations } = configuration
+ if (!project || selectedTable === undefined) {
+ return console.error('no project or table selected')
+ }
+
const response = isNewRecord
? await createColumn({
projectRef: project?.ref!,
connectionString: project?.connectionString,
payload: payload as CreateColumnPayload,
- selectedTable: selectedTable as PostgresTable,
+ selectedTable,
primaryKey,
foreignKeyRelations,
})
@@ -230,7 +236,7 @@ const SidePanelEditor = ({
connectionString: project?.connectionString,
id: columnId as string,
payload: payload as UpdateColumnPayload,
- selectedTable: selectedTable as PostgresTable,
+ selectedTable,
primaryKey,
foreignKeyRelations,
existingForeignKeyRelations,
@@ -249,9 +255,7 @@ const SidePanelEditor = ({
}
await Promise.all([
- queryClient.invalidateQueries(
- sqlKeys.query(project?.ref, ['table-editor', selectedTable?.id])
- ),
+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(project?.ref, selectedTable?.id)),
queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints'])),
queryClient.invalidateQueries(
sqlKeys.query(project?.ref, [
@@ -434,7 +438,7 @@ const SidePanelEditor = ({
isRLSEnabled,
importContent,
})
- if (isRealtimeEnabled) await updateTableRealtime(table as PostgresTable, true)
+ if (isRealtimeEnabled) await updateTableRealtime(table, true)
await Promise.all([
queryClient.invalidateQueries(tableKeys.list(project?.ref, table.schema, includeColumns)),
@@ -442,7 +446,7 @@ const SidePanelEditor = ({
])
toast.success(`Table ${table.name} is good to go!`, { id: toastId })
- onTableCreated(table as PostgresTable)
+ onTableCreated(table)
} else if (selectedTable) {
toastId = toast.loading(`Updating table: ${selectedTable?.name}...`)
@@ -458,14 +462,19 @@ const SidePanelEditor = ({
primaryKey,
})
- await updateTableRealtime(table, isRealtimeEnabled)
+ if (table === undefined) {
+ return toast.error('Failed to update table')
+ }
+ if (isTableLike(table)) {
+ await updateTableRealtime(table, isRealtimeEnabled)
+ }
if (hasError) {
toast(`Table ${table.name} has been updated, but there were some errors`, { id: toastId })
} else {
queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints']))
await Promise.all([
- queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['table-editor', table.id])),
+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(project?.ref, table.id)),
queryClient.invalidateQueries(
sqlKeys.query(project?.ref, [selectedTable.schema, selectedTable.name])
),
@@ -589,7 +598,7 @@ const SidePanelEditor = ({
<ColumnEditor
column={
snap.sidePanel?.type === 'column'
- ? (snap.sidePanel.column as PostgresColumn)
+ ? (snap.sidePanel.column as unknown as PostgresColumn)
: undefined
}
selectedTable={selectedTable}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 5216a29c9d1..12aa1adf6ca 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -15,10 +15,10 @@ import { entityTypeKeys } from 'data/entity-types/keys'
import { getQueryClient } from 'data/query-client'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
+import { getTableEditor } from 'data/table-editor/table-editor-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/get-table'
import { updateTable as updateTableMutation } from 'data/tables/table-update-mutation'
import { getTables } from 'data/tables/tables-query'
import { timeout, tryParseJson } from 'lib/helpers'
@@ -497,8 +497,8 @@ export const createTable = async ({
// Then add the primary key constraints here to support composite keys
const primaryKeyColumns = columns
- .filter((column: ColumnField) => column.isPrimaryKey)
- .map((column: ColumnField) => column.name)
+ .filter((column) => column.isPrimaryKey)
+ .map((column) => column.name)
if (primaryKeyColumns.length > 0) {
await addPrimaryKey(projectRef, connectionString, table.schema, table.name, primaryKeyColumns)
}
@@ -521,7 +521,7 @@ export const createTable = async ({
projectRef,
connectionString,
importContent.file,
- table as PostgresTable,
+ table,
importContent.selectedHeaders,
(progress: number) => {
toast.loading(
@@ -564,7 +564,7 @@ export const createTable = async ({
await insertTableRows(
projectRef,
connectionString,
- table as PostgresTable,
+ table,
importContent.rows,
importContent.selectedHeaders,
(progress: number) => {
@@ -688,16 +688,12 @@ export const updateTable = async ({
projectRef: projectRef,
connectionString: connectionString,
payload: columnPayload,
- selectedTable: updatedTable as PostgresTable,
+ selectedTable: updatedTable,
})
} else {
const originalColumn = find(originalColumns, { id: column.id })
if (originalColumn) {
- const columnPayload = generateUpdateColumnPayload(
- originalColumn,
- updatedTable as PostgresTable,
- column
- )
+ const columnPayload = generateUpdateColumnPayload(originalColumn, updatedTable, column)
if (!isEmpty(columnPayload)) {
toast.loading(`Updating column ${column.name} from ${updatedTable.name}`, { id: toastId })
const skipPKCreation = true
@@ -707,7 +703,7 @@ export const updateTable = async ({
connectionString: connectionString,
id: column.id,
payload: columnPayload,
- selectedTable: updatedTable as PostgresTable,
+ selectedTable: updatedTable,
skipPKCreation,
skipSuccessMessage,
})
@@ -754,7 +750,7 @@ export const updateTable = async ({
])
return {
- table: await getTable({
+ table: await getTableEditor({
projectRef,
connectionString,
id: table.id,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
index 65f493d9856..b6ecb3313a1 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImport.tsx
@@ -1,5 +1,6 @@
import type { PostgresTable } from '@supabase/postgres-meta'
import { debounce, includes, noop } from 'lodash'
+import { ExternalLink } from 'lucide-react'
import Link from 'next/link'
import { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
@@ -18,7 +19,6 @@ import {
parseSpreadsheetText,
} from './SpreadsheetImport.utils'
import SpreadsheetImportPreview from './SpreadsheetImportPreview'
-import { ExternalLink } from 'lucide-react'
const MAX_CSV_SIZE = 1024 * 1024 * 100 // 100 MB
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImportPreview.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImportPreview.tsx
index 8eb4973494f..88b5a67649f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImportPreview.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SpreadsheetImport/SpreadsheetImportPreview.tsx
@@ -1,17 +1,16 @@
import clsx from 'clsx'
+import { AlertCircle, ArrowRight, ChevronDown, ChevronRight } from 'lucide-react'
import { useEffect, useState } from 'react'
-import { Badge, Button, Collapsible, SidePanel } from 'ui'
-import type { PostgresTable } from '@supabase/postgres-meta'
+import { Badge, Button, Collapsible, SidePanel } from 'ui'
import type { SpreadsheetData } from './SpreadsheetImport.types'
import SpreadsheetPreviewGrid from './SpreadsheetPreviewGrid'
-import { ChevronDown, AlertCircle, ChevronRight, ArrowRight } from 'lucide-react'
const MAX_ROWS = 20
const MAX_HEADERS = 20
interface SpreadsheetImportPreviewProps {
- selectedTable?: PostgresTable
+ selectedTable?: { name: string }
spreadsheetData: SpreadsheetData
errors?: any[]
selectedHeaders: string[]
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index 637f4497429..4b471a8014d 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -320,6 +320,7 @@ const TableEditor = ({
>
<DocsButton
abbrev={false}
+ className="mt-2"
href="https://supabase.com/docs/guides/auth/row-level-security"
/>
</Admonition>
@@ -337,6 +338,7 @@ const TableEditor = ({
>
<DocsButton
abbrev={false}
+ className="mt-2"
href="https://supabase.com/docs/guides/auth/row-level-security"
/>
</Admonition>
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
index 95aeb2358ee..76f3201fb0a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
@@ -1,14 +1,14 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { some } from 'lodash'
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
-import type { ImportContent, TableField } from './TableEditor.types'
-import { DEFAULT_COLUMNS } from './TableEditor.constants'
-import type { ColumnField } from '../SidePanelEditor.types'
+import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import {
generateColumnField,
generateColumnFieldFromPostgresColumn,
} from '../ColumnEditor/ColumnEditor.utils'
-import type { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
+import type { ColumnField } from '../SidePanelEditor.types'
+import { DEFAULT_COLUMNS } from './TableEditor.constants'
+import type { ImportContent, TableField } from './TableEditor.types'
export const validateFields = (field: TableField) => {
const errors = {} as any
@@ -45,7 +45,7 @@ export const generateTableFieldFromPostgresTable = (
id: table.id,
name: isDuplicating ? `${table.name}_duplicate` : table.name,
comment: isDuplicating ? `This is a duplicate of ${table.name}` : table?.comment ?? '',
- columns: (table.columns ?? []).map((column: PostgresColumn) => {
+ columns: (table.columns ?? []).map((column) => {
return generateColumnFieldFromPostgresColumn(column, table, foreignKeys)
}),
isRLSEnabled: table.rls_enabled,
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx b/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
index 609a3b23237..db15bafe083 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
@@ -10,16 +10,21 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useTableDefinitionQuery } from 'data/database/table-definition-query'
import { useViewDefinitionQuery } from 'data/database/view-definition-query'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { Entity } from 'data/table-editor/table-editor-query'
+import {
+ Entity,
+ isMaterializedView,
+ isTableLike,
+ isView,
+ isViewLike,
+} from 'data/table-editor/table-editor-types'
import { timeout } from 'lib/helpers'
import { Button } from 'ui'
export interface TableDefinitionProps {
- entityType?: Entity
+ entity?: Entity
}
-const TableDefinition = ({ entityType }: TableDefinitionProps) => {
+const TableDefinition = ({ entity }: TableDefinitionProps) => {
const { ref } = useParams()
const editorRef = useRef(null)
const monacoRef = useRef(null)
@@ -28,40 +33,35 @@ const TableDefinition = ({ entityType }: TableDefinitionProps) => {
const viewResult = useViewDefinitionQuery(
{
- schema: entityType?.schema,
- name: entityType?.name,
+ schema: entity?.schema,
+ name: entity?.name,
projectRef: project?.ref,
connectionString: project?.connectionString,
},
{
- enabled:
- entityType?.type === ENTITY_TYPE.VIEW || entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW,
+ enabled: isViewLike(entity),
}
)
const tableResult = useTableDefinitionQuery(
{
- schema: entityType?.schema,
- name: entityType?.name,
+ schema: entity?.schema,
+ name: entity?.name,
projectRef: project?.ref,
connectionString: project?.connectionString,
},
{
- enabled: entityType?.type === ENTITY_TYPE.TABLE,
+ enabled: isTableLike(entity),
}
)
- const { data: definition, isLoading } =
- entityType?.type === ENTITY_TYPE.VIEW || entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW
- ? viewResult
- : tableResult
-
- const prepend =
- entityType?.type === ENTITY_TYPE.VIEW
- ? `create view ${entityType.schema}.${entityType.name} as\n`
- : entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW
- ? `create materialized view ${entityType.schema}.${entityType.name} as\n`
- : ''
+ const { data: definition, isLoading } = isViewLike(entity) ? viewResult : tableResult
+
+ const prepend = isView(entity)
+ ? `create view ${entity.schema}.${entity.name} as\n`
+ : isMaterializedView(entity)
+ ? `create materialized view ${entity.schema}.${entity.name} as\n`
+ : ''
const formatDefinition = (value: string) => {
try {
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index bd5416bf64f..9b1887d9081 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -1,4 +1,3 @@
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { QueryKey, useQueryClient } from '@tanstack/react-query'
import { find, isUndefined } from 'lodash'
@@ -7,13 +6,16 @@ import { toast } from 'sonner'
import { useParams } from 'common'
import { SupabaseGrid } from 'components/grid/SupabaseGrid'
-import { getSupaTable } from 'components/grid/SupabaseGrid.utils'
-import { SupaTable } from 'components/grid/types'
+import { parseSupaTable } from 'components/grid/SupabaseGrid.utils'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { DocsButton } from 'components/ui/DocsButton'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import { sqlKeys } from 'data/sql/keys'
-import type { Entity, TableLike } from 'data/table-editor/table-editor-query'
+import {
+ Entity,
+ isMaterializedView,
+ isTableLike,
+ isView,
+} from 'data/table-editor/table-editor-types'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import useLatest from 'hooks/misc/useLatest'
@@ -34,17 +36,13 @@ export interface TableGridEditorProps {
theme?: 'dark' | 'light'
isLoadingSelectedTable?: boolean
- selectedTable?: TableLike
- entityType?: Entity
- encryptedColumns?: string[]
+ selectedTable?: Entity
}
const TableGridEditor = ({
theme = 'dark',
isLoadingSelectedTable = false,
selectedTable,
- entityType,
- encryptedColumns,
}: TableGridEditorProps) => {
const router = useRouter()
const { ref: projectRef, id } = useParams()
@@ -128,21 +126,16 @@ const TableGridEditor = ({
return <NotFoundState id={Number(id)} />
}
- const isViewSelected =
- entityType?.type === ENTITY_TYPE.VIEW || entityType?.type === ENTITY_TYPE.MATERIALIZED_VIEW
- const isTableSelected = entityType?.type === ENTITY_TYPE.TABLE
- const isLocked = EXCLUDED_SCHEMAS.includes(entityType?.schema ?? '')
+ const isViewSelected = isView(selectedTable) || isMaterializedView(selectedTable)
+ const isTableSelected = isTableLike(selectedTable)
+ const isLocked = EXCLUDED_SCHEMAS.includes(selectedTable?.schema ?? '')
const canEditViaTableEditor = isTableSelected && !isLocked
- const gridTable = getSupaTable({
- encryptedColumns,
- selectedTable,
- entityType: entityType?.type,
- })
+ const gridTable = parseSupaTable(selectedTable)
const gridKey = `${selectedTable.schema}_${selectedTable.name}`
- const onTableCreated = (table: PostgresTable) => {
+ const onTableCreated = (table: { id: number }) => {
router.push(`/project/${projectRef}/editor/${table.id}`)
}
@@ -150,7 +143,7 @@ const TableGridEditor = ({
// stale as they are accessed via some react-tracked madness
// [TODO]: refactor out all of react-tracked
const onSelectEditColumn = (name: string) => {
- const column = find(columnsRef.current, { name }) as PostgresColumn
+ const column = find(columnsRef.current, { name })
if (column) {
snap.onEditColumn(column)
} else {
@@ -159,7 +152,7 @@ const TableGridEditor = ({
}
const onSelectDeleteColumn = (name: string) => {
- const column = find(columnsRef.current ?? [], { name }) as PostgresColumn
+ const column = find(columnsRef.current ?? [], { name })
if (column) {
snap.onDeleteColumn(column)
} else {
@@ -174,19 +167,17 @@ const TableGridEditor = ({
const updateTableRow = (previousRow: any, updatedData: any) => {
if (!project) return
- const enumArrayColumns =
- ('columns' in selectedTable &&
- selectedTable.columns
- ?.filter((column) => {
- return (column?.enums ?? []).length > 0 && column.data_type.toLowerCase() === 'array'
- })
- .map((column) => column.name)) ||
- []
+ const enumArrayColumns = selectedTable.columns
+ ?.filter((column) => {
+ return (column?.enums ?? []).length > 0 && column.data_type.toLowerCase() === 'array'
+ })
+ .map((column) => column.name)
const identifiers = {} as Dictionary<any>
- ;(selectedTable as PostgresTable).primary_keys.forEach(
- (column) => (identifiers[column.name] = previousRow[column.name])
- )
+ isTableLike(selectedTable) &&
+ selectedTable.primary_keys.forEach(
+ (column) => (identifiers[column.name] = previousRow[column.name])
+ )
const configuration = { identifiers }
if (Object.keys(identifiers).length === 0) {
@@ -208,7 +199,7 @@ const TableGridEditor = ({
mutateUpdateTableRow({
projectRef: project.ref,
connectionString: project.connectionString,
- table: gridTable as SupaTable,
+ table: selectedTable,
configuration,
payload: updatedData,
enumArrayColumns,
@@ -232,11 +223,7 @@ const TableGridEditor = ({
schema={selectedTable.schema}
table={gridTable}
headerActions={
- <GridHeaderActions
- entityType={entityType as Entity}
- table={selectedTable as TableLike}
- canEditViaTableEditor={canEditViaTableEditor}
- />
+ <GridHeaderActions table={selectedTable} canEditViaTableEditor={canEditViaTableEditor} />
}
onAddColumn={snap.onAddColumn}
onEditColumn={onSelectEditColumn}
@@ -265,12 +252,12 @@ const TableGridEditor = ({
) : null
}
>
- {(isViewSelected || isTableSelected) && <TableDefinition entityType={entityType} />}
+ {(isViewSelected || isTableSelected) && <TableDefinition entity={selectedTable} />}
</SupabaseGrid>
<SidePanelEditor
editable={!isReadOnly && canEditViaTableEditor}
- selectedTable={selectedTable as PostgresTable}
+ selectedTable={isTableLike(selectedTable) ? selectedTable : undefined}
onTableCreated={onTableCreated}
/>
</>
diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
index 2c1bc04dd10..6b265070ee2 100644
--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
@@ -28,11 +28,12 @@ import {
} from 'components/interfaces/TableGridEditor/TableEntity.utils'
import type { ItemRenderer } from 'components/ui/InfiniteList'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+import { Entity } from 'data/entity-types/entity-types-infinite-query'
import { useProjectLintsQuery } from 'data/lint/lint-query'
import { EditorTablePageLink } from 'data/prefetchers/project.$ref.editor.$id'
-import { Entity } from 'data/table-editor/table-editor-query'
+import { getTableEditor } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { fetchAllTableRows } from 'data/table-rows/table-rows-query'
-import { getTable } from 'data/tables/get-table'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
@@ -109,29 +110,23 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
const toastId = toast.loading(`Exporting ${entity.name} as CSV...`)
try {
- const table = await getTable({
+ const table = await getTableEditor({
id: entity.id,
projectRef,
connectionString: project?.connectionString,
})
- if (table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
+ if (isTableLike(table) && table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
return toast.error(
<Markdown content={MAX_EXPORT_ROW_COUNT_MESSAGE} className="text-foreground" />,
{ id: toastId }
)
}
- const supaTable =
- table &&
- parseSupaTable(
- {
- table: table,
- columns: table.columns ?? [],
- primaryKeys: table.primary_keys,
- relationships: table.relationships,
- },
- []
- )
+ const supaTable = table && parseSupaTable(table)
+
+ if (!supaTable) {
+ return toast.error(`Failed to export table: ${entity.name}`, { id: toastId })
+ }
const rows = await fetchAllTableRows({
projectRef,
@@ -168,30 +163,24 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
const toastId = toast.loading(`Exporting ${entity.name} as SQL...`)
try {
- const table = await getTable({
+ const table = await getTableEditor({
id: entity.id,
projectRef,
connectionString: project?.connectionString,
})
- if (table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
+ if (isTableLike(table) && table.live_rows_estimate > MAX_EXPORT_ROW_COUNT) {
return toast.error(
<Markdown content={MAX_EXPORT_ROW_COUNT_MESSAGE} className="text-foreground" />,
{ id: toastId }
)
}
- const supaTable =
- table &&
- parseSupaTable(
- {
- table: table,
- columns: table.columns ?? [],
- primaryKeys: table.primary_keys,
- relationships: table.relationships,
- },
- []
- )
+ const supaTable = table && parseSupaTable(table)
+
+ if (!supaTable) {
+ return toast.error(`Failed to export table: ${entity.name}`, { id: toastId })
+ }
const rows = await fetchAllTableRows({
projectRef,
diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
index 75d93b6363e..eef43fb93f9 100644
--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
@@ -12,10 +12,7 @@ import SchemaSelector from 'components/ui/SchemaSelector'
import { useSchemasQuery } from 'data/database/schemas-query'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorage } from 'hooks/misc/useLocalStorage'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
@@ -100,14 +97,12 @@ const TableEditorMenu = () => {
)
const isLocked = protectedSchemas.some((s) => s.id === schema?.id)
- const { data: tableData } = useTableEditorQuery({
+ const { data: selectedTable } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(tableData)
-
useEffect(() => {
if (selectedTable?.schema) {
setSelectedSchema(selectedTable.schema)
diff --git a/apps/studio/data/database-columns/database-column-delete-mutation.ts b/apps/studio/data/database-columns/database-column-delete-mutation.ts
index dbb6b8e5bac..2572f5fa673 100644
--- a/apps/studio/data/database-columns/database-column-delete-mutation.ts
+++ b/apps/studio/data/database-columns/database-column-delete-mutation.ts
@@ -4,8 +4,7 @@ import { toast } from 'sonner'
import { entityTypeKeys } from 'data/entity-types/keys'
import { del, handleError } from 'data/fetchers'
import { sqlKeys } from 'data/sql/keys'
-import { TableLike } from 'data/table-editor/table-editor-query'
-import { tableKeys } from 'data/tables/keys'
+import { tableEditorKeys } from 'data/table-editor/keys'
import { viewKeys } from 'data/views/keys'
import type { ResponseError } from 'types'
@@ -14,7 +13,7 @@ export type DatabaseColumnDeleteVariables = {
connectionString?: string
id: string
cascade?: boolean
- table?: TableLike
+ table?: { id: number; schema: string; name: string }
}
export async function deleteDatabaseColumn({
@@ -62,9 +61,7 @@ export const useDatabaseColumnDeleteMutation = ({
queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
...(table !== undefined
? [
- queryClient.invalidateQueries(
- sqlKeys.query(projectRef, ['table-editor', table.id])
- ),
+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, table.id)),
queryClient.invalidateQueries(
sqlKeys.query(projectRef, [table.schema, table.name])
),
diff --git a/apps/studio/data/entity-types/entity-types-infinite-query.ts b/apps/studio/data/entity-types/entity-types-infinite-query.ts
index 7d32a82f985..49d1090844e 100644
--- a/apps/studio/data/entity-types/entity-types-infinite-query.ts
+++ b/apps/studio/data/entity-types/entity-types-infinite-query.ts
@@ -1,6 +1,5 @@
import { QueryClient, useInfiniteQuery, UseInfiniteQueryOptions } from '@tanstack/react-query'
import { executeSql, ExecuteSqlVariables } from 'data/sql/execute-sql-query'
-import { Entity } from 'data/table-editor/table-editor-query'
import { ENTITY_TYPE } from './entity-type-constants'
import { entityTypeKeys } from './keys'
@@ -14,6 +13,15 @@ export type EntityTypesVariables = {
filterTypes?: string[]
} & Pick<ExecuteSqlVariables, 'connectionString'>
+export interface Entity {
+ id: number
+ schema: string
+ name: string
+ type: ENTITY_TYPE
+ comment: string | null
+ rls_enabled: boolean
+}
+
export type EntityTypesResponse = {
data: {
entities: Entity[]
diff --git a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
index 63e08a6288a..74e2269059e 100644
--- a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
+++ b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
@@ -7,14 +7,11 @@ import { loadTableEditorSortsAndFiltersFromLocalStorage } from 'components/grid/
import {
formatFilterURLParams,
formatSortURLParams,
- getSupaTable,
+ parseSupaTable,
} from 'components/grid/SupabaseGrid.utils'
import { Filter, Sort } from 'components/grid/types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import {
- getTableLikeFromTableEditor,
- prefetchTableEditor,
-} from 'data/table-editor/table-editor-query'
+import { prefetchTableEditor } from 'data/table-editor/table-editor-query'
import { prefetchTableRows } from 'data/table-rows/table-rows-query'
import { useFlag } from 'hooks/ui/useFlag'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
@@ -42,16 +39,9 @@ export function usePrefetchEditorTablePage() {
projectRef: project.ref,
connectionString: project.connectionString,
id,
- }).then((tableData) => {
- const entity = tableData.entity
- const table = getTableLikeFromTableEditor(tableData)
-
- if (entity && table) {
- const supaTable = getSupaTable({
- selectedTable: table,
- encryptedColumns: tableData.encrypted_columns ?? undefined,
- entityType: entity.type,
- })
+ }).then((entity) => {
+ if (entity) {
+ const supaTable = parseSupaTable(entity)
const { sorts: localSorts = [], filters: localFilters = [] } =
loadTableEditorSortsAndFiltersFromLocalStorage(
diff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.ts
index 97f9b2d0795..6048a90d97c 100644
--- a/apps/studio/data/sql/execute-sql-query.ts
+++ b/apps/studio/data/sql/execute-sql-query.ts
@@ -55,7 +55,11 @@ export async function executeSql(
header: { 'x-connection-encrypted': connectionString ?? '' },
path: { ref: projectRef },
// @ts-ignore: This is just a client side thing to identify queries better
- query: { key: queryKey?.filter((seg) => typeof seg === 'string').join('-') ?? '' },
+ query: {
+ key:
+ queryKey?.filter((seg) => typeof seg === 'string' || typeof seg === 'number').join('-') ??
+ '',
+ },
},
body: { query: sql },
headers: Object.fromEntries(headers),
diff --git a/apps/studio/data/table-editor/keys.ts b/apps/studio/data/table-editor/keys.ts
new file mode 100644
index 00000000000..6ce556c9754
--- /dev/null
+++ b/apps/studio/data/table-editor/keys.ts
@@ -0,0 +1,4 @@
+export const tableEditorKeys = {
+ tableEditor: (projectRef: string | undefined, id: number | undefined) =>
+ ['projects', projectRef, 'table-editor', id] as const,
+}
diff --git a/apps/studio/data/table-editor/table-editor-query-sql.ts b/apps/studio/data/table-editor/table-editor-query-sql.ts
index 9476a97331e..bb5087656c5 100644
--- a/apps/studio/data/table-editor/table-editor-query-sql.ts
+++ b/apps/studio/data/table-editor/table-editor-query-sql.ts
@@ -4,347 +4,251 @@ export function getTableEditorSql(id?: number) {
if (!id) return ''
return minify(/* SQL */ `
- with entity as (
- select
- c.oid::int8 as "id",
- nc.nspname as "schema",
- c.relname as "name",
- c.relkind as "type",
- obj_description(c.oid) as "comment",
- count(*) over () as "count"
- from
- pg_namespace nc
- join pg_class c on nc.oid = c.relnamespace
- where
- c.relkind in ('r', 'v', 'm', 'f', 'p')
- and not pg_is_other_temp_schema(nc.oid)
- and (
- pg_has_role(c.relowner, 'USAGE')
- or has_table_privilege(
- c.oid,
- 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
- )
- or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
- )
- and c.oid = ${id}
- limit
- 1
- ),
- encrypted_columns as (
- select
- column_name as name
- from
- information_schema.columns
- where
- table_schema = (
- select
- e.schema
- from
- entity e
- )
- and table_name = concat(
- 'decrypted_',
- (
- select
- e.name
- from
- entity e
- )
- )
- and column_name like 'decrypted_%'
- ),
- table_info as (
- select
- c.oid::int8 as id,
- nc.nspname as schema,
- c.relname as name,
- c.relrowsecurity as rls_enabled,
- c.relforcerowsecurity as rls_forced,
- case
- when c.relreplident = 'd' then 'DEFAULT'
- when c.relreplident = 'i' then 'INDEX'
- when c.relreplident = 'f' then 'FULL'
- else 'NOTHING'
- end as replica_identity,
- pg_total_relation_size(format('%I.%I', nc.nspname, c.relname))::int8 as bytes,
- pg_size_pretty(
- pg_total_relation_size(format('%I.%I', nc.nspname, c.relname))
- ) as size,
- pg_stat_get_live_tuples (c.oid) as live_rows_estimate,
- pg_stat_get_dead_tuples (c.oid) as dead_rows_estimate,
- obj_description(c.oid) as
- comment,
- coalesce(pk.primary_keys, '[]') as primary_keys,
- coalesce(
- jsonb_agg(relationships) filter (
- where
- relationships is not null
- ),
- '[]'
- ) as relationships
- from
- pg_namespace nc
- join pg_class c on nc.oid = c.relnamespace
- left join (
- select
- table_id,
- jsonb_agg(_pk.*) as primary_keys
- from
- (
- select
- n.nspname as schema,
- c.relname as table_name,
- a.attname as name,
- c.oid::int8 as table_id
- from
- pg_index i,
- pg_class c,
- pg_attribute a,
- pg_namespace n
- where
- i.indrelid = c.oid
- and c.relnamespace = n.oid
- and a.attrelid = c.oid
- and a.attnum = any (i.indkey)
- and i.indisprimary
- ) as _pk
- group by
- table_id
- ) as pk on pk.table_id = c.oid
- left join (
- select
+ with base_table_info as (
+ select
c.oid::int8 as id,
- c.conname as constraint_name,
- c.confdeltype as deletion_action,
- c.confupdtype as update_action,
- nsa.nspname as source_schema,
- csa.relname as source_table_name,
- sa.attname as source_column_name,
- nta.nspname as target_table_schema,
- cta.relname as target_table_name,
- ta.attname as target_column_name
- from
- pg_constraint c
- join (
- pg_attribute sa
- join pg_class csa on sa.attrelid = csa.oid
- join pg_namespace nsa on csa.relnamespace = nsa.oid
- ) on sa.attrelid = c.conrelid
- and sa.attnum = any (c.conkey)
- join (
- pg_attribute ta
- join pg_class cta on ta.attrelid = cta.oid
- join pg_namespace nta on cta.relnamespace = nta.oid
- ) on ta.attrelid = c.confrelid
- and ta.attnum = any (c.confkey)
- where
- c.contype = 'f'
- ) as relationships on (
- relationships.source_schema = nc.nspname
- and relationships.source_table_name = c.relname
- )
- or (
- relationships.target_table_schema = nc.nspname
- and relationships.target_table_name = c.relname
- )
- where
- c.relkind in ('r', 'p')
- and not pg_is_other_temp_schema(nc.oid)
- and (
- pg_has_role(c.relowner, 'USAGE')
- or has_table_privilege(
- c.oid,
- 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
- )
- or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
- )
- and c.oid = ${id}
- group by
- c.oid,
- c.relname,
- c.relrowsecurity,
- c.relforcerowsecurity,
- c.relreplident,
- nc.nspname,
- pk.primary_keys
+ nc.nspname as schema,
+ c.relname as name,
+ c.relkind,
+ c.relrowsecurity as rls_enabled,
+ c.relforcerowsecurity as rls_forced,
+ c.relreplident,
+ c.relowner,
+ obj_description(c.oid) as comment
+ from pg_class c
+ join pg_namespace nc on nc.oid = c.relnamespace
+ where c.oid = ${id}
+ and not pg_is_other_temp_schema(nc.oid)
+ and (
+ pg_has_role(c.relowner, 'USAGE')
+ or has_table_privilege(
+ c.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ )
+ or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
),
- view_info as (
- select
- c.oid::int8 as id,
- n.nspname as schema,
- c.relname as name,
- -- See definition of information_schema.views
- (pg_relation_is_updatable (c.oid, false) & 20) = 20 as is_updatable,
- obj_description(c.oid) as
- comment
- from
- pg_class c
- join pg_namespace n on n.oid = c.relnamespace
- where
- c.relkind = 'v'
- and c.oid = ${id}
+ table_stats as (
+ select
+ b.id,
+ case
+ when b.relreplident = 'd' then 'DEFAULT'
+ when b.relreplident = 'i' then 'INDEX'
+ when b.relreplident = 'f' then 'FULL'
+ else 'NOTHING'
+ end as replica_identity,
+ pg_total_relation_size(format('%I.%I', b.schema, b.name))::int8 as bytes,
+ pg_size_pretty(pg_total_relation_size(format('%I.%I', b.schema, b.name))) as size,
+ pg_stat_get_live_tuples(b.id) as live_rows_estimate,
+ pg_stat_get_dead_tuples(b.id) as dead_rows_estimate
+ from base_table_info b
+ where b.relkind in ('r', 'p')
),
- materialized_view_info as (
- select
- c.oid::int8 as id,
- n.nspname as schema,
- c.relname as name,
- c.relispopulated as is_populated,
- obj_description(c.oid) as
- comment
- from
- pg_class c
- join pg_namespace n on n.oid = c.relnamespace
- where
- c.relkind = 'm'
- and c.oid = ${id}
+ primary_keys as (
+ select
+ i.indrelid as table_id,
+ jsonb_agg(jsonb_build_object(
+ 'schema', n.nspname,
+ 'table_name', c.relname,
+ 'table_id', i.indrelid::int8,
+ 'name', a.attname
+ )) as primary_keys
+ from pg_index i
+ join pg_class c on i.indrelid = c.oid
+ join pg_attribute a on (a.attrelid = c.oid and a.attnum = any(i.indkey))
+ join pg_namespace n on c.relnamespace = n.oid
+ where i.indisprimary
+ group by i.indrelid
),
- foreign_table_info as (
- select
- c.oid::int8 as id,
- n.nspname as schema,
- c.relname as name,
- obj_description(c.oid) as
- comment
- from
- pg_class c
- join pg_namespace n on n.oid = c.relnamespace
- where
- c.relkind = 'f'
- and c.oid = ${id}
+ relationships as (
+ select
+ c.conrelid as source_id,
+ c.confrelid as target_id,
+ jsonb_build_object(
+ 'id', c.oid::int8,
+ 'constraint_name', c.conname,
+ 'deletion_action', c.confdeltype,
+ 'update_action', c.confupdtype,
+ 'source_schema', nsa.nspname,
+ 'source_table_name', csa.relname,
+ 'source_column_name', sa.attname,
+ 'target_table_schema', nta.nspname,
+ 'target_table_name', cta.relname,
+ 'target_column_name', ta.attname
+ ) as rel_info
+ from pg_constraint c
+ join pg_class csa on c.conrelid = csa.oid
+ join pg_namespace nsa on csa.relnamespace = nsa.oid
+ join pg_attribute sa on (sa.attrelid = c.conrelid and sa.attnum = any(c.conkey))
+ join pg_class cta on c.confrelid = cta.oid
+ join pg_namespace nta on cta.relnamespace = nta.oid
+ join pg_attribute ta on (ta.attrelid = c.confrelid and ta.attnum = any(c.confkey))
+ where c.contype = 'f'
),
- column_info as (
- select
- c.oid::int8 as table_id,
- nc.nspname as schema,
- c.relname as table,
- (c.oid || '.' || a.attnum) as id,
- a.attnum as ordinal_position,
- a.attname as name,
- case
- when a.atthasdef then pg_get_expr(ad.adbin, ad.adrelid)
- else null
- end as default_value,
- case
- when t.typtype = 'd' then case
- when bt.typelem <> 0::oid
- and bt.typlen = -1 then 'ARRAY'
- when nbt.nspname = 'pg_catalog' then format_type(t.typbasetype, null)
- else 'USER-DEFINED'
- end
- else case
- when t.typelem <> 0::oid
- and t.typlen = -1 then 'ARRAY'
- when nt.nspname = 'pg_catalog' then format_type(a.atttypid, null)
- else 'USER-DEFINED'
- end
- end as data_type,
- coalesce(bt.typname, t.typname) as format,
- a.attidentity in ('a', 'd') as is_identity,
- case a.attidentity
- when 'a' then 'ALWAYS'
- when 'd' then 'BY DEFAULT'
- else null
- end as identity_generation,
- a.attgenerated in ('s') as is_generated,
- not (
- a.attnotnull
- or t.typtype = 'd'
- and t.typnotnull
- ) as is_nullable,
- (
- c.relkind in ('r', 'p')
- or c.relkind in ('v', 'f')
- and pg_column_is_updatable (c.oid, a.attnum, false)
- ) as is_updatable,
- uniques.table_id is not null as is_unique,
- check_constraints.definition as "check",
- array_to_json(
- array (
- select
- enumlabel
- from
- pg_catalog.pg_enum enums
- where
- enums.enumtypid = coalesce(bt.oid, t.oid)
- or enums.enumtypid = coalesce(bt.typelem, t.typelem)
- order by
- enums.enumsortorder
- )
- ) as enums,
- col_description(c.oid, a.attnum) as
- comment
- from
- pg_attribute a
- left join pg_attrdef ad on a.attrelid = ad.adrelid
- and a.attnum = ad.adnum
- join (
- pg_class c
- join pg_namespace nc on c.relnamespace = nc.oid
- ) on a.attrelid = c.oid
- join (
- pg_type t
- join pg_namespace nt on t.typnamespace = nt.oid
- ) on a.atttypid = t.oid
- left join (
- pg_type bt
- join pg_namespace nbt on bt.typnamespace = nbt.oid
- ) on t.typtype = 'd'
- and t.typbasetype = bt.oid
+ columns as (
+ select
+ a.attrelid as table_id,
+ jsonb_agg(jsonb_build_object(
+ 'id', (a.attrelid || '.' || a.attnum),
+ 'table_id', c.oid::int8,
+ 'schema', nc.nspname,
+ 'table', c.relname,
+ 'ordinal_position', a.attnum,
+ 'name', a.attname,
+ 'default_value', case
+ when a.atthasdef then pg_get_expr(ad.adbin, ad.adrelid)
+ else null
+ end,
+ 'data_type', case
+ when t.typtype = 'd' then
+ case
+ when bt.typelem <> 0::oid and bt.typlen = -1 then 'ARRAY'
+ when nbt.nspname = 'pg_catalog' then format_type(t.typbasetype, null)
+ else 'USER-DEFINED'
+ end
+ else
+ case
+ when t.typelem <> 0::oid and t.typlen = -1 then 'ARRAY'
+ when nt.nspname = 'pg_catalog' then format_type(a.atttypid, null)
+ else 'USER-DEFINED'
+ end
+ end,
+ 'format', coalesce(bt.typname, t.typname),
+ 'is_identity', a.attidentity in ('a', 'd'),
+ 'identity_generation', case a.attidentity
+ when 'a' then 'ALWAYS'
+ when 'd' then 'BY DEFAULT'
+ else null
+ end,
+ 'is_generated', a.attgenerated in ('s'),
+ 'is_nullable', not (a.attnotnull or t.typtype = 'd' and t.typnotnull),
+ 'is_updatable', (
+ b.relkind in ('r', 'p') or
+ (b.relkind in ('v', 'f') and pg_column_is_updatable(b.id, a.attnum, false))
+ ),
+ 'is_unique', uniques.table_id is not null,
+ 'check', check_constraints.definition,
+ 'comment', col_description(c.oid, a.attnum),
+ 'enums', coalesce(
+ (
+ select jsonb_agg(e.enumlabel order by e.enumsortorder)
+ from pg_catalog.pg_enum e
+ where e.enumtypid = coalesce(bt.oid, t.oid)
+ or e.enumtypid = coalesce(bt.typelem, t.typelem)
+ ),
+ '[]'::jsonb
+ )
+ ) order by a.attnum) as columns
+ from pg_attribute a
+ join base_table_info b on a.attrelid = b.id
+ join pg_class c on a.attrelid = c.oid
+ join pg_namespace nc on c.relnamespace = nc.oid
+ left join pg_attrdef ad on (a.attrelid = ad.adrelid and a.attnum = ad.adnum)
+ join pg_type t on a.atttypid = t.oid
+ join pg_namespace nt on t.typnamespace = nt.oid
+ left join pg_type bt on (t.typtype = 'd' and t.typbasetype = bt.oid)
+ left join pg_namespace nbt on bt.typnamespace = nbt.oid
left join (
- select distinct
- on (table_id, ordinal_position) conrelid as table_id,
- conkey[1] as ordinal_position
- from
- pg_catalog.pg_constraint
- where
- contype = 'u'
- and cardinality(conkey) = 1
- ) as uniques on uniques.table_id = c.oid
- and uniques.ordinal_position = a.attnum
+ select
+ conrelid as table_id,
+ conkey[1] as ordinal_position
+ from pg_catalog.pg_constraint
+ where contype = 'u' and cardinality(conkey) = 1
+ ) as uniques on uniques.table_id = a.attrelid and uniques.ordinal_position = a.attnum
left join (
- -- We only select the first column check
- select distinct
- on (table_id, ordinal_position) conrelid as table_id,
- conkey[1] as ordinal_position,
- substring(
- pg_get_constraintdef(pg_constraint.oid, true),
- 8,
- length(pg_get_constraintdef(pg_constraint.oid, true)) - 8
- ) as "definition"
- from
- pg_constraint
- where
- contype = 'c'
- and cardinality(conkey) = 1
- order by
- table_id,
- ordinal_position,
- oid asc
- ) as check_constraints on check_constraints.table_id = c.oid
- and check_constraints.ordinal_position = a.attnum
- where
- not pg_is_other_temp_schema(nc.oid)
- and a.attnum > 0
+ select distinct on (conrelid, conkey[1])
+ conrelid as table_id,
+ conkey[1] as ordinal_position,
+ substring(
+ pg_get_constraintdef(oid, true),
+ 8,
+ length(pg_get_constraintdef(oid, true)) - 8
+ ) as definition
+ from pg_constraint
+ where contype = 'c' and cardinality(conkey) = 1
+ order by conrelid, conkey[1], oid asc
+ ) as check_constraints on check_constraints.table_id = a.attrelid
+ and check_constraints.ordinal_position = a.attnum
+ where a.attnum > 0
and not a.attisdropped
- and (c.relkind in ('r', 'v', 'm', 'f', 'p'))
- and (
- pg_has_role(c.relowner, 'USAGE')
- or has_column_privilege(
- c.oid,
- a.attnum,
- 'SELECT, INSERT, UPDATE, REFERENCES'
- )
- )
- and c.oid = ${id}
+ group by a.attrelid
)
- select
- (select to_jsonb(entity.*) from entity) as "entity",
- (select jsonb_agg(encrypted_columns.*) from encrypted_columns) as "encrypted_columns",
- (select to_jsonb(table_info.*) from table_info) as "table_info",
- (select to_jsonb(view_info.*) from view_info) as "view_info",
- (select to_jsonb(materialized_view_info.*) from materialized_view_info) as "materialized_view_info",
- (select to_jsonb(foreign_table_info.*) from foreign_table_info) as "foreign_table_info",
- (select jsonb_agg(column_info.*) from column_info) as "column_info"
+ select
+ case b.relkind
+ when 'r' then jsonb_build_object(
+ 'entity_type', b.relkind,
+ 'id', b.id,
+ 'schema', b.schema,
+ 'name', b.name,
+ 'rls_enabled', b.rls_enabled,
+ 'rls_forced', b.rls_forced,
+ 'replica_identity', ts.replica_identity,
+ 'bytes', ts.bytes,
+ 'size', ts.size,
+ 'live_rows_estimate', ts.live_rows_estimate,
+ 'dead_rows_estimate', ts.dead_rows_estimate,
+ 'comment', b.comment,
+ 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),
+ 'relationships', coalesce(
+ (select jsonb_agg(r.rel_info)
+ from relationships r
+ where r.source_id = b.id or r.target_id = b.id),
+ '[]'::jsonb
+ ),
+ 'columns', coalesce(c.columns, '[]'::jsonb)
+ )
+ when 'p' then jsonb_build_object(
+ 'entity_type', b.relkind,
+ 'id', b.id,
+ 'schema', b.schema,
+ 'name', b.name,
+ 'rls_enabled', b.rls_enabled,
+ 'rls_forced', b.rls_forced,
+ 'replica_identity', ts.replica_identity,
+ 'bytes', ts.bytes,
+ 'size', ts.size,
+ 'live_rows_estimate', ts.live_rows_estimate,
+ 'dead_rows_estimate', ts.dead_rows_estimate,
+ 'comment', b.comment,
+ 'primary_keys', coalesce(pk.primary_keys, '[]'::jsonb),
+ 'relationships', coalesce(
+ (select jsonb_agg(r.rel_info)
+ from relationships r
+ where r.source_id = b.id or r.target_id = b.id),
+ '[]'::jsonb
+ ),
+ 'columns', coalesce(c.columns, '[]'::jsonb)
+ )
+ when 'v' then jsonb_build_object(
+ 'entity_type', b.relkind,
+ 'id', b.id,
+ 'schema', b.schema,
+ 'name', b.name,
+ 'is_updatable', (pg_relation_is_updatable(b.id, false) & 20) = 20,
+ 'comment', b.comment,
+ 'columns', coalesce(c.columns, '[]'::jsonb)
+ )
+ when 'm' then jsonb_build_object(
+ 'entity_type', b.relkind,
+ 'id', b.id,
+ 'schema', b.schema,
+ 'name', b.name,
+ 'is_populated', true,
+ 'comment', b.comment,
+ 'columns', coalesce(c.columns, '[]'::jsonb)
+ )
+ when 'f' then jsonb_build_object(
+ 'entity_type', b.relkind,
+ 'id', b.id,
+ 'schema', b.schema,
+ 'name', b.name,
+ 'comment', b.comment,
+ 'columns', coalesce(c.columns, '[]'::jsonb)
+ )
+ end as entity
+ from base_table_info b
+ left join table_stats ts on b.id = ts.id
+ left join primary_keys pk on b.id = pk.table_id
+ left join columns c on b.id = c.table_id;
`)
}
diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.ts
index d8d364bd887..9cb98d4bb08 100644
--- a/apps/studio/data/table-editor/table-editor-query.ts
+++ b/apps/studio/data/table-editor/table-editor-query.ts
@@ -1,74 +1,52 @@
-import type {
- PostgresColumn,
- PostgresMaterializedView,
- PostgresTable,
- PostgresView,
-} from '@supabase/postgres-meta'
-import { QueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { sqlKeys } from 'data/sql/keys'
-import {
- executeSql,
- ExecuteSqlData,
- ExecuteSqlError,
- useExecuteSqlQuery,
-} from '../sql/execute-sql-query'
+import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
+import { tableEditorKeys } from './keys'
import { getTableEditorSql } from './table-editor-query-sql'
+import { Entity } from './table-editor-types'
type TableEditorArgs = {
id?: number
}
-export type Table = PostgresTable
-export type View = PostgresView
-export type MaterializedView = PostgresMaterializedView
-export type ForeignTable = PostgresTable
-export type TableLike = Table | View | MaterializedView | ForeignTable
-
-export type Entity = {
- id: number
- schema: string
- name: string
- type: ENTITY_TYPE
- comment: string | null
- rls_enabled: boolean
-}
-
-export type TableEditor = {
- entity: Entity
- // [Joshen] We can probably deprecate this one since we're deprecating pg sodium and TCE
- // https://supabase.com/docs/guides/database/extensions/pgsodium#encryption-key-location
- encrypted_columns: string[] | null
- table_info: Table | null
- view_info: View | null
- materialized_view_info: MaterializedView | null
- foreign_table_info: ForeignTable | null
- column_info: PostgresColumn[]
-}
export type TableEditorVariables = TableEditorArgs & {
projectRef?: string
connectionString?: string
}
-export type TableEditorData = TableEditor
-export type TableEditorError = ExecuteSqlError
-
-export const useTableEditorQuery = <TData extends TableEditorData = TableEditorData>(
+export async function getTableEditor(
{ projectRef, connectionString, id }: TableEditorVariables,
- { enabled = true, ...options }: UseQueryOptions<ExecuteSqlData, TableEditorError, TData> = {}
-) =>
- useExecuteSqlQuery(
+ signal?: AbortSignal
+) {
+ if (!id) {
+ throw new Error('id is required')
+ }
+
+ const sql = getTableEditorSql(id)
+ const { result } = await executeSql(
{
projectRef,
connectionString,
- sql: getTableEditorSql(id),
+ sql,
queryKey: ['table-editor', id],
},
+ signal
+ )
+
+ return result[0]?.entity as Entity | undefined
+}
+
+export type TableEditorData = Awaited<ReturnType<typeof getTableEditor>>
+export type TableEditorError = ExecuteSqlError
+
+export const useTableEditorQuery = <TData = TableEditorData>(
+ { projectRef, connectionString, id }: TableEditorVariables,
+ { enabled = true, ...options }: UseQueryOptions<TableEditorData, TableEditorError, TData> = {}
+) =>
+ useQuery<TableEditorData, TableEditorError, TData>(
+ tableEditorKeys.tableEditor(projectRef, id),
+ ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal),
{
- select(data) {
- return (data.result[0] ?? null) as TData
- },
enabled:
enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),
staleTime: 5 * 60 * 1000, // 5 minutes
@@ -76,55 +54,18 @@ export const useTableEditorQuery = <TData extends TableEditorData = TableEditorD
}
)
-export function getTableLikeFromTableEditor(data?: TableEditor): TableLike | undefined {
- // 404
- if (!data || !data.entity) return undefined
-
- const { entity, table_info, view_info, materialized_view_info, foreign_table_info, column_info } =
- data
-
- switch (entity.type) {
- case ENTITY_TYPE.TABLE:
- case ENTITY_TYPE.PARTITIONED_TABLE:
- return {
- ...table_info,
- columns: column_info,
- } as Table
- case ENTITY_TYPE.VIEW:
- return {
- ...view_info,
- columns: column_info,
- } as View
- case ENTITY_TYPE.MATERIALIZED_VIEW:
- return {
- ...materialized_view_info,
- columns: column_info,
- } as MaterializedView
- case ENTITY_TYPE.FOREIGN_TABLE:
- return {
- ...foreign_table_info,
- columns: column_info,
- } as ForeignTable
- default:
- return undefined
- }
-}
-
export function prefetchTableEditor(
client: QueryClient,
{ projectRef, connectionString, id }: Required<TableEditorVariables>
) {
- return client
- .fetchQuery(sqlKeys.query(projectRef, ['table-editor', id]), ({ signal }) =>
- executeSql(
- {
- projectRef,
- connectionString,
- sql: getTableEditorSql(id),
- queryKey: ['table-editor', id],
- },
- signal
- )
+ return client.fetchQuery(tableEditorKeys.tableEditor(projectRef, id), ({ signal }) =>
+ getTableEditor(
+ {
+ projectRef,
+ connectionString,
+ id,
+ },
+ signal
)
- .then((data) => (data?.result?.[0] as unknown as TableEditor) ?? null)
+ )
}
diff --git a/apps/studio/data/table-editor/table-editor-types.ts b/apps/studio/data/table-editor/table-editor-types.ts
new file mode 100644
index 00000000000..1014acac8cd
--- /dev/null
+++ b/apps/studio/data/table-editor/table-editor-types.ts
@@ -0,0 +1,81 @@
+import type {
+ PostgresColumn,
+ PostgresMaterializedView,
+ PostgresRelationship,
+ PostgresTable,
+ PostgresView,
+} from '@supabase/postgres-meta'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+
+interface TableRelationship extends PostgresRelationship {
+ deletion_action: 'a' | 'r' | 'c' | 'n' | 'd'
+ update_action: 'a' | 'r' | 'c' | 'n' | 'd'
+}
+
+export interface Table extends PostgresTable {
+ entity_type: ENTITY_TYPE.TABLE
+ columns: PostgresColumn[]
+ relationships: TableRelationship[]
+}
+
+export interface PartitionedTable extends PostgresTable {
+ entity_type: ENTITY_TYPE.PARTITIONED_TABLE
+ columns: PostgresColumn[]
+ relationships: TableRelationship[]
+}
+
+export interface View extends PostgresView {
+ entity_type: ENTITY_TYPE.VIEW
+ columns: PostgresColumn[]
+}
+
+export interface MaterializedView extends PostgresMaterializedView {
+ entity_type: ENTITY_TYPE.MATERIALIZED_VIEW
+ columns: PostgresColumn[]
+}
+
+export interface ForeignTable {
+ entity_type: ENTITY_TYPE.FOREIGN_TABLE
+ id: number
+ schema: string
+ name: string
+ comment: string | null
+ columns: PostgresColumn[]
+}
+
+export type Entity = Table | PartitionedTable | View | MaterializedView | ForeignTable
+
+export function isTable(entity?: Entity): entity is Table {
+ return entity?.entity_type === ENTITY_TYPE.TABLE
+}
+
+export function isPartitionedTable(entity?: Entity): entity is PartitionedTable {
+ return entity?.entity_type === ENTITY_TYPE.PARTITIONED_TABLE
+}
+
+/**
+ * Returns true if the entity is a Table or a PartitionedTable.
+ * Foreign tables are not considered table-like.
+ */
+export function isTableLike(entity?: Entity): entity is Table | PartitionedTable {
+ return isTable(entity) || isPartitionedTable(entity)
+}
+
+export function isForeignTable(entity?: Entity): entity is ForeignTable {
+ return entity?.entity_type === ENTITY_TYPE.FOREIGN_TABLE
+}
+
+export function isView(entity?: Entity): entity is View {
+ return entity?.entity_type === ENTITY_TYPE.VIEW
+}
+
+export function isMaterializedView(entity?: Entity): entity is MaterializedView {
+ return entity?.entity_type === ENTITY_TYPE.MATERIALIZED_VIEW
+}
+
+/**
+ * Returns true if the entity is a View or a MaterializedView.
+ */
+export function isViewLike(entity?: Entity): entity is View | MaterializedView {
+ return isView(entity) || isMaterializedView(entity)
+}
diff --git a/apps/studio/data/table-rows/table-row-create-mutation.ts b/apps/studio/data/table-rows/table-row-create-mutation.ts
index d74111d52fe..7624ca09ccd 100644
--- a/apps/studio/data/table-rows/table-row-create-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-create-mutation.ts
@@ -2,7 +2,6 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { toast } from 'sonner'
import { Query } from 'components/grid/query/Query'
-import type { SupaTable } from 'components/grid/types'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
@@ -12,7 +11,7 @@ import type { ResponseError } from 'types'
export type TableRowCreateVariables = {
projectRef: string
connectionString?: string
- table: SupaTable
+ table: { name: string; schema?: string }
payload: any
enumArrayColumns: string[]
returning?: boolean
diff --git a/apps/studio/data/table-rows/table-row-delete-mutation.tsx b/apps/studio/data/table-rows/table-row-delete-mutation.tsx
index 64c102c92df..afb9cbfec88 100644
--- a/apps/studio/data/table-rows/table-row-delete-mutation.tsx
+++ b/apps/studio/data/table-rows/table-row-delete-mutation.tsx
@@ -7,7 +7,7 @@ import { Markdown } from 'components/interfaces/Markdown'
import { DocsButton } from 'components/ui/DocsButton'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
-import type { Table } from 'data/tables/get-table'
+import { Entity } from 'data/table-editor/table-editor-types'
import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'
import type { ResponseError } from 'types'
@@ -16,7 +16,7 @@ import { getPrimaryKeys } from './utils'
export type TableRowDeleteVariables = {
projectRef: string
connectionString?: string
- table: Table
+ table: Entity
rows: SupaRow[]
impersonatedRole?: ImpersonationRole
}
@@ -29,7 +29,7 @@ export function getTableRowDeleteSql({
if (error) throw error
let queryChains = new Query().from(table.name, table.schema ?? undefined).delete()
- primaryKeys!.forEach((key) => {
+ primaryKeys?.forEach((key) => {
const primaryKeyValues = rows.map((x) => x[key])
queryChains = queryChains.filter(key, 'in', primaryKeyValues)
})
diff --git a/apps/studio/data/table-rows/table-row-truncate-mutation.ts b/apps/studio/data/table-rows/table-row-truncate-mutation.ts
index 1fe593a63bf..051b5d216ce 100644
--- a/apps/studio/data/table-rows/table-row-truncate-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-truncate-mutation.ts
@@ -2,7 +2,6 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { toast } from 'sonner'
import { Query } from 'components/grid/query/Query'
-import type { SupaTable } from 'components/grid/types'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
import type { ResponseError } from 'types'
@@ -10,7 +9,7 @@ import type { ResponseError } from 'types'
export type TableRowTruncateVariables = {
projectRef: string
connectionString?: string
- table: SupaTable
+ table: { name: string; schema?: string }
}
export function getTableRowTruncateSql({ table }: Pick<TableRowTruncateVariables, 'table'>) {
diff --git a/apps/studio/data/table-rows/table-row-update-mutation.ts b/apps/studio/data/table-rows/table-row-update-mutation.ts
index cd6fdc8e403..5c5d49783c1 100644
--- a/apps/studio/data/table-rows/table-row-update-mutation.ts
+++ b/apps/studio/data/table-rows/table-row-update-mutation.ts
@@ -2,7 +2,6 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { toast } from 'sonner'
import { Query } from 'components/grid/query/Query'
-import type { SupaTable } from 'components/grid/types'
import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
@@ -12,7 +11,7 @@ import type { ResponseError } from 'types'
export type TableRowUpdateVariables = {
projectRef: string
connectionString?: string
- table: SupaTable
+ table: { name: string; schema?: string }
configuration: { identifiers: any }
payload: any
enumArrayColumns: string[]
diff --git a/apps/studio/data/table-rows/utils.ts b/apps/studio/data/table-rows/utils.ts
index d517bf97025..1cd131be63a 100644
--- a/apps/studio/data/table-rows/utils.ts
+++ b/apps/studio/data/table-rows/utils.ts
@@ -1,6 +1,6 @@
import type { Filter, ServiceError, SupaTable } from 'components/grid/types'
import { isNumericalColumn } from 'components/grid/utils/types'
-import type { Table } from 'data/tables/get-table'
+import { Entity, isTableLike } from 'data/table-editor/table-editor-types'
/**
* temporary fix until we implement a better filter UI
@@ -17,10 +17,16 @@ export function formatFilterValue(table: SupaTable, filter: Filter) {
return filter.value
}
-export function getPrimaryKeys({ table }: { table: Table }): {
+export function getPrimaryKeys({ table }: { table: Entity }): {
primaryKeys?: string[]
error?: ServiceError
} {
+ if (!isTableLike(table)) {
+ return {
+ error: { message: 'Only table rows can be updated or deleted' },
+ }
+ }
+
const pkColumns = table.primary_keys
if (!pkColumns || pkColumns.length == 0) {
return {
diff --git a/apps/studio/data/tables/get-table.ts b/apps/studio/data/tables/get-table.ts
deleted file mode 100644
index b20f9102fe1..00000000000
--- a/apps/studio/data/tables/get-table.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
-
-import { get, handleError } from 'data/fetchers'
-
-export type TableVariables = {
- id?: number
- projectRef?: string
- connectionString?: string
-}
-
-export type Table = PostgresTable
-
-export type TableResponse = Table | { error?: any }
-
-/**
- * @deprecated use `useTableEditorQuery` instead
- */
-export async function getTable(
- { id, projectRef, connectionString }: TableVariables,
- signal?: AbortSignal
-) {
- if (!projectRef) throw new Error('projectRef is required')
- if (!id) throw new Error('id is required')
-
- let headers = new Headers()
- if (connectionString) headers.set('x-connection-encrypted', connectionString)
-
- const { data, error } = await get('/platform/pg-meta/{ref}/tables', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- // @ts-ignore
- query: { id: id.toString() },
- },
- headers,
- signal,
- })
-
- if (error) handleError(error)
- return data as unknown as PostgresTable
-}
diff --git a/apps/studio/data/tables/table-create-mutation.ts b/apps/studio/data/tables/table-create-mutation.ts
index f4459ba9bd3..0ddd8bcb1b8 100644
--- a/apps/studio/data/tables/table-create-mutation.ts
+++ b/apps/studio/data/tables/table-create-mutation.ts
@@ -1,3 +1,4 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
@@ -29,7 +30,10 @@ export async function createTable({ projectRef, connectionString, payload }: Tab
})
if (error) handleError(error)
- return data
+
+ // [Alaister] we have to manually cast the data to PostgresTable
+ // because the API types are slightly wrong
+ return data as PostgresTable
}
type TableCreateData = Awaited<ReturnType<typeof createTable>>
diff --git a/apps/studio/data/tables/table-delete-mutation.ts b/apps/studio/data/tables/table-delete-mutation.ts
index c2aafa6e457..6414865c957 100644
--- a/apps/studio/data/tables/table-delete-mutation.ts
+++ b/apps/studio/data/tables/table-delete-mutation.ts
@@ -1,12 +1,13 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { entityTypeKeys } from 'data/entity-types/keys'
import { del, handleError } from 'data/fetchers'
+import { tableEditorKeys } from 'data/table-editor/keys'
import { viewKeys } from 'data/views/keys'
import type { ResponseError } from 'types'
import { tableKeys } from './keys'
-import { sqlKeys } from 'data/sql/keys'
export type TableDeleteVariables = {
projectRef: string
@@ -35,7 +36,10 @@ export async function deleteTable({
})
if (error) handleError(error)
- return data
+
+ // [Alaister] we have to manually cast the data to PostgresTable
+ // because the API types are slightly wrong
+ return data as PostgresTable
}
type TableDeleteData = Awaited<ReturnType<typeof deleteTable>>
@@ -56,7 +60,7 @@ export const useTableDeleteMutation = ({
async onSuccess(data, variables, context) {
const { id, projectRef, schema } = variables
await Promise.all([
- queryClient.invalidateQueries(sqlKeys.query(projectRef, ['table-editor', id])),
+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)),
queryClient.invalidateQueries(tableKeys.list(projectRef, schema)),
queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
// invalidate all views from this schema
diff --git a/apps/studio/data/tables/table-update-mutation.ts b/apps/studio/data/tables/table-update-mutation.ts
index 8c05451def5..b379a0ba256 100644
--- a/apps/studio/data/tables/table-update-mutation.ts
+++ b/apps/studio/data/tables/table-update-mutation.ts
@@ -1,10 +1,11 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { components } from 'data/api'
import { handleError, patch } from 'data/fetchers'
import { lintKeys } from 'data/lint/keys'
-import { sqlKeys } from 'data/sql/keys'
+import { tableEditorKeys } from 'data/table-editor/keys'
import type { ResponseError } from 'types'
import { tableKeys } from './keys'
@@ -38,7 +39,10 @@ export async function updateTable({
})
if (error) handleError(error)
- return data
+
+ // [Alaister] we have to manually cast the data to PostgresTable
+ // because the API types are slightly wrong
+ return data as PostgresTable
}
type TableUpdateData = Awaited<ReturnType<typeof updateTable>>
@@ -59,7 +63,7 @@ export const useTableUpdateMutation = ({
async onSuccess(data, variables, context) {
const { projectRef, schema, id } = variables
await Promise.all([
- queryClient.invalidateQueries(sqlKeys.query(projectRef, ['table-editor', id])),
+ queryClient.invalidateQueries(tableEditorKeys.tableEditor(projectRef, id)),
queryClient.invalidateQueries(tableKeys.list(projectRef, schema)),
queryClient.invalidateQueries(lintKeys.lint(projectRef)),
])
diff --git a/apps/studio/pages/project/[ref]/database/tables/[id].tsx b/apps/studio/pages/project/[ref]/database/tables/[id].tsx
index 4370e3f2cdc..683523862f5 100644
--- a/apps/studio/pages/project/[ref]/database/tables/[id].tsx
+++ b/apps/studio/pages/project/[ref]/database/tables/[id].tsx
@@ -1,4 +1,3 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
import { ChevronRight } from 'lucide-react'
import { useParams } from 'common'
@@ -9,10 +8,8 @@ import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import { FormHeader } from 'components/ui/Forms/FormHeader'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
+import { isTableLike } from 'data/table-editor/table-editor-types'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
@@ -24,12 +21,11 @@ const DatabaseTables: NextPageWithLayout = () => {
const id = _id ? Number(_id) : undefined
const { project } = useProjectContext()
- const { data, isLoading } = useTableEditorQuery({
+ const { data: selectedTable, isLoading } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
return (
<>
@@ -55,7 +51,10 @@ const DatabaseTables: NextPageWithLayout = () => {
</ScaffoldContainer>
<DeleteConfirmationDialogs selectedTable={selectedTable} />
- <SidePanelEditor includeColumns selectedTable={selectedTable as PostgresTable} />
+ <SidePanelEditor
+ includeColumns
+ selectedTable={isTableLike(selectedTable) ? selectedTable : undefined}
+ />
</>
)
}
diff --git a/apps/studio/pages/project/[ref]/database/tables/index.tsx b/apps/studio/pages/project/[ref]/database/tables/index.tsx
index 2d5e3d0467d..139056842b3 100644
--- a/apps/studio/pages/project/[ref]/database/tables/index.tsx
+++ b/apps/studio/pages/project/[ref]/database/tables/index.tsx
@@ -1,3 +1,4 @@
+import type { PostgresTable } from '@supabase/postgres-meta'
import { useState } from 'react'
import { TableList } from 'components/interfaces/Database'
@@ -6,13 +7,12 @@ import DeleteConfirmationDialogs from 'components/interfaces/TableGridEditor/Del
import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import { FormHeader } from 'components/ui/Forms/FormHeader'
-import type { Table } from 'data/tables/get-table'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
const DatabaseTables: NextPageWithLayout = () => {
const snap = useTableEditorStateSnapshot()
- const [selectedTableToEdit, setSelectedTableToEdit] = useState<Table>()
+ const [selectedTableToEdit, setSelectedTableToEdit] = useState<PostgresTable>()
return (
<>
diff --git a/apps/studio/pages/project/[ref]/editor/[id].tsx b/apps/studio/pages/project/[ref]/editor/[id].tsx
index 97cd3b11201..a75964a6aa0 100644
--- a/apps/studio/pages/project/[ref]/editor/[id].tsx
+++ b/apps/studio/pages/project/[ref]/editor/[id].tsx
@@ -9,10 +9,7 @@ import {
useProjectContext,
} from 'components/layouts/ProjectLayout/ProjectContext'
import TableEditorLayout from 'components/layouts/TableEditorLayout/TableEditorLayout'
-import {
- getTableLikeFromTableEditor,
- useTableEditorQuery,
-} from 'data/table-editor/table-editor-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import type { NextPageWithLayout } from 'types'
const TableEditorPage: NextPageWithLayout = () => {
@@ -22,20 +19,17 @@ const TableEditorPage: NextPageWithLayout = () => {
const id = _id ? Number(_id) : undefined
const { project } = useProjectContext()
- const { data, isLoading } = useTableEditorQuery({
+ const { data: selectedTable, isLoading } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
- const selectedTable = getTableLikeFromTableEditor(data)
return (
<>
<TableGridEditor
isLoadingSelectedTable={isLoading}
selectedTable={selectedTable}
- entityType={data?.entity}
- encryptedColumns={data?.encrypted_columns ?? undefined}
theme={resolvedTheme?.includes('dark') ? 'dark' : 'light'}
/>
<DeleteConfirmationDialogs
diff --git a/apps/studio/pages/project/[ref]/editor/index.tsx b/apps/studio/pages/project/[ref]/editor/index.tsx
index d2138dfae83..a7922e7f570 100644
--- a/apps/studio/pages/project/[ref]/editor/index.tsx
+++ b/apps/studio/pages/project/[ref]/editor/index.tsx
@@ -6,14 +6,13 @@ import EmptyState from 'components/interfaces/TableGridEditor/EmptyState'
import SidePanelEditor from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor'
import { ProjectContextFromParamsProvider } from 'components/layouts/ProjectLayout/ProjectContext'
import TableEditorLayout from 'components/layouts/TableEditorLayout/TableEditorLayout'
-import type { Table } from 'data/tables/get-table'
import type { NextPageWithLayout } from 'types'
const TableEditorPage: NextPageWithLayout = () => {
const { ref: projectRef } = useParams()
const router = useRouter()
- const onTableCreated = (table: Table) => {
+ const onTableCreated = (table: { id: number }) => {
router.push(`/project/${projectRef}/editor/${table.id}`)
}