Skip to content

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

chore(perf): table editor query optimisation (#30184)

Alaister Young3a27070dc2b4
diff --git a/apps/studio/components/grid/SupabaseGrid.utils.ts b/apps/studio/components/grid/SupabaseGrid.utils.ts
index 25fddc31895..e69fae2d3fb 100644
--- a/apps/studio/components/grid/SupabaseGrid.utils.ts
+++ b/apps/studio/components/grid/SupabaseGrid.utils.ts
@@ -1,15 +1,11 @@
-import type { PostgresRelationship, PostgresTable } from '@supabase/postgres-meta'
+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 { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
-import {
- ForeignKeyConstraint,
- ForeignKeyConstraintsData,
-} from 'data/database/foreign-key-constraints-query'
+import { ForeignKeyConstraintsData } from 'data/database/foreign-key-constraints-query'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { TableLike } from 'hooks/misc/useTable'
+import { TableLike } from 'data/table-editor/table-editor-query'
import type { Dictionary, SchemaView } from 'types'
import { FilterOperatorOptions } from './components/header/filter/Filter.constants'
import { STORAGE_KEY_PREFIX } from './constants'
@@ -101,6 +97,7 @@ export function parseSupaTable(
targetTableName: null,
targetColumnName: null,
deletionAction: undefined,
+ updateAction: undefined,
},
}
const primaryKey = primaryKeys.find((pk) => pk.name == column.name)
@@ -118,6 +115,7 @@ export function parseSupaTable(
temp.foreignKey.targetTableName = relationship.target_table_name
temp.foreignKey.targetColumnName = relationship.target_column_name
temp.foreignKey.deletionAction = relationship.deletion_action
+ temp.foreignKey.updateAction = relationship.update_action
}
return temp
})
@@ -135,29 +133,12 @@ export function parseSupaTable(
export function getSupaTable({
selectedTable,
entityType,
- foreignKeyMeta,
encryptedColumns,
}: {
selectedTable: TableLike
entityType?: ENTITY_TYPE
- foreignKeyMeta: ForeignKeyConstraintsData
- encryptedColumns: string[]
+ encryptedColumns?: string[]
}) {
- // [Joshen] We can tweak below to eventually support composite keys as the data
- // returned from foreignKeyMeta should be easy to deal with, rather than pg-meta
- const formattedRelationships = (
- ('relationships' in selectedTable && selectedTable.relationships) ||
- []
- ).map((relationship: PostgresRelationship) => {
- const relationshipMeta = foreignKeyMeta.find(
- (fk: ForeignKeyConstraint) => fk.id === relationship.id
- )
- return {
- ...relationship,
- deletion_action: relationshipMeta?.deletion_action ?? FOREIGN_KEY_CASCADE_ACTION.NO_ACTION,
- }
- })
-
const isViewSelected =
entityType === ENTITY_TYPE.VIEW || entityType === ENTITY_TYPE.MATERIALIZED_VIEW
const isForeignTableSelected = entityType === ENTITY_TYPE.FOREIGN_TABLE
@@ -168,7 +149,7 @@ export function getSupaTable({
table: selectedTable as PostgresTable,
columns: (selectedTable as PostgresTable).columns ?? [],
primaryKeys: (selectedTable as PostgresTable).primary_keys ?? [],
- relationships: formattedRelationships,
+ relationships: (selectedTable as PostgresTable).relationships ?? [],
},
encryptedColumns
)
diff --git a/apps/studio/components/grid/components/editor/JsonEditor.tsx b/apps/studio/components/grid/components/editor/JsonEditor.tsx
index 8a815486632..15ee5ea12ac 100644
--- a/apps/studio/components/grid/components/editor/JsonEditor.tsx
+++ b/apps/studio/components/grid/components/editor/JsonEditor.tsx
@@ -7,10 +7,13 @@ 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 { 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'
-import useTable from 'hooks/misc/useTable'
import { prettifyJSON, removeJSONTrailingComma, tryParseJson } from 'lib/helpers'
import { Popover, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_ } from 'ui'
import { BlockKeys } from '../common/BlockKeys'
@@ -56,9 +59,15 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
const state = useTrackedState()
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable } = useTable(id)
const project = useSelectedProject()
+ const { data } = 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
const jsonString = prettifyJSON(!isNil(initialValue) ? tryFormatInitialValue(initialValue) : '')
diff --git a/apps/studio/components/grid/components/editor/TextEditor.tsx b/apps/studio/components/grid/components/editor/TextEditor.tsx
index 14c111adea1..df260056dbf 100644
--- a/apps/studio/components/grid/components/editor/TextEditor.tsx
+++ b/apps/studio/components/grid/components/editor/TextEditor.tsx
@@ -5,10 +5,13 @@ 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 { 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'
-import useTable from 'hooks/misc/useTable'
import {
Button,
Popover,
@@ -17,13 +20,13 @@ import {
Tooltip_Shadcn_,
cn,
} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { useTrackedState } from '../../store/Store'
import { BlockKeys } from '../common/BlockKeys'
import { EmptyValue } from '../common/EmptyValue'
import { MonacoEditor } from '../common/MonacoEditor'
import { NullValue } from '../common/NullValue'
import { TruncatedWarningOverlay } from './TruncatedWarningOverlay'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
export const TextEditor = <TRow, TSummaryRow = unknown>({
row,
@@ -40,9 +43,15 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
const state = useTrackedState()
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable } = useTable(id)
const project = useSelectedProject()
+ const { data } = 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
const [isPopoverOpen, setIsPopoverOpen] = useState(true)
diff --git a/apps/studio/components/grid/components/footer/Footer.tsx b/apps/studio/components/grid/components/footer/Footer.tsx
index f3a4881622a..7153dc6b1fd 100644
--- a/apps/studio/components/grid/components/footer/Footer.tsx
+++ b/apps/studio/components/grid/components/footer/Footer.tsx
@@ -1,9 +1,12 @@
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 useEntityType from 'hooks/misc/useEntityType'
-import useTable from 'hooks/misc/useTable'
+import {
+ getTableLikeFromTableEditor,
+ useTableEditorQuery,
+} from 'data/table-editor/table-editor-query'
import { useUrlState } from 'hooks/ui/useUrlState'
import RefreshButton from '../header/RefreshButton'
import { Pagination } from './pagination'
@@ -13,10 +16,17 @@ export interface FooterProps {
}
const Footer = ({ isRefetching }: FooterProps) => {
+ const { project } = useProjectContext()
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable } = useTable(id)
- const entityType = useEntityType(selectedTable?.id)
+
+ const { data } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const selectedTable = getTableLikeFromTableEditor(data)
+ const entityType = data?.entity
const [{ view: selectedView = 'data' }, setUrlState] = useUrlState()
diff --git a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
index d8110559a05..8229d30826b 100644
--- a/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
+++ b/apps/studio/components/grid/components/footer/pagination/Pagination.tsx
@@ -1,27 +1,24 @@
+import { PostgresTable } from '@supabase/postgres-meta'
import { ArrowLeft, ArrowRight, HelpCircle } from 'lucide-react'
import { useEffect, useState } from 'react'
-import { PostgresTable } from '@supabase/postgres-meta'
+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 { THRESHOLD_COUNT, useTableRowsCountQuery } from 'data/table-rows/table-rows-count-query'
-import useTable from 'hooks/misc/useTable'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
-import {
- Button,
- InputNumber,
- TooltipContent_Shadcn_,
- TooltipTrigger_Shadcn_,
- Tooltip_Shadcn_,
-} from 'ui'
+import { Button, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_ } from 'ui'
+import { Input } from 'ui-patterns/DataInputs/Input'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { useParams } from 'common'
import { useDispatch, useTrackedState } from '../../../store/Store'
import { DropdownControl } from '../../common/DropdownControl'
import { formatEstimatedCount } from './Pagination.utils'
-import { Input } from 'ui-patterns/DataInputs/Input'
const rowsPerPageOptions = [
{ value: 100, label: '100 rows' },
@@ -38,7 +35,13 @@ const Pagination = () => {
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
- const { data: selectedTable } = useTable(id)
+ const { data: tableData } = 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
diff --git a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
index 2948e7ff0f5..ca1dc3ab5a6 100644
--- a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
+++ b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx
@@ -4,7 +4,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 { useTableQuery } from 'data/tables/table-query'
+import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { useTablesQuery } from 'data/tables/tables-query'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { Button, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
@@ -23,11 +23,13 @@ export const ForeignKeyFormatter = (props: Props) => {
const { projectRef, tableId, row, column } = props
const id = tableId ? Number(tableId) : undefined
- const { data: selectedTable } = useTableQuery({
+ const { data } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
+ const selectedTable = data?.table_info
+
const relationship = (selectedTable?.relationships ?? []).find(
(r) =>
r.source_schema === selectedTable?.schema &&
diff --git a/apps/studio/components/grid/components/grid/ColumnHeader.tsx b/apps/studio/components/grid/components/grid/ColumnHeader.tsx
index db17d57ac9b..92c7cfb152a 100644
--- a/apps/studio/components/grid/components/grid/ColumnHeader.tsx
+++ b/apps/studio/components/grid/components/grid/ColumnHeader.tsx
@@ -1,4 +1,3 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
import type { XYCoord } from 'dnd-core'
import { ArrowRight, Key, Link, Lock } from 'lucide-react'
import { useEffect, useRef } from 'react'
@@ -6,6 +5,7 @@ import { useDrag, useDrop } from 'react-dnd'
import { getForeignKeyCascadeAction } from 'components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.utils'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
+import { Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
import { useDispatch, useTrackedState } from '../../store/Store'
import type { ColumnHeaderProps, ColumnType, DragItem, GridForeignKey } from '../../types'
import { ColumnMenu } from '../menu'
@@ -126,50 +126,30 @@ export function ColumnHeader<R>({
<div className="sb-grid-column-header__inner">
{renderColumnIcon(columnType, { name: column.name as string, foreignKey })}
{isPrimaryKey && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger>
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_>
<div className="sb-grid-column-header__inner__primary-key">
<Key size={14} strokeWidth={2} />
</div>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Primary key</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom" className="font-normal">
+ Primary key
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
)}
<span className="sb-grid-column-header__inner__name" title={hoverValue}>
{column.name}
</span>
<span className="sb-grid-column-header__inner__format">{columnFormat}</span>
{isEncrypted && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger>
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_>
<Lock size={14} strokeWidth={2} />
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Encrypted column</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom" className="font-normal">
+ Encrypted column
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
)}
</div>
<ColumnMenu column={column} isEncrypted={isEncrypted} />
@@ -185,40 +165,36 @@ function renderColumnIcon(
const { name, foreignKey } = columnMeta
switch (type) {
case 'foreign_key':
+ // [Joshen] Look into this separately but this should be a hover card instead
return (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger>
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_>
<Link size={14} strokeWidth={2} />
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <div>
- <p className="text-xs text-foreground-light">Foreign key relation:</p>
- <div className="flex items-center space-x-1">
- <p className="text-xs text-foreground">{name}</p>
- <ArrowRight size={14} strokeWidth={1.5} />
- <p className="text-xs text-foreground">
- {foreignKey?.targetTableSchema}.{foreignKey?.targetTableName}.
- {foreignKey?.targetColumnName}
- </p>
- </div>
- {foreignKey?.deletionAction !== FOREIGN_KEY_CASCADE_ACTION.NO_ACTION && (
- <p className="text-xs text-foreground mt-1">
- On delete: {getForeignKeyCascadeAction(foreignKey?.deletionAction)}
- </p>
- )}
- </div>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom">
+ <div className="font-normal">
+ <p className="text-xs text-foreground-light">Foreign key relation:</p>
+ <div className="flex items-center space-x-1">
+ <p className="text-xs !text-foreground">{name}</p>
+ <ArrowRight size={14} strokeWidth={1.5} className="!text-foreground-light" />
+ <p className="text-xs !text-foreground">
+ {foreignKey?.targetTableSchema}.{foreignKey?.targetTableName}.
+ {foreignKey?.targetColumnName}
+ </p>
</div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
+ {foreignKey?.updateAction !== FOREIGN_KEY_CASCADE_ACTION.NO_ACTION && (
+ <p className="text-xs !text-foreground mt-1">
+ On update: {getForeignKeyCascadeAction(foreignKey?.updateAction)}
+ </p>
+ )}
+ {foreignKey?.deletionAction !== FOREIGN_KEY_CASCADE_ACTION.NO_ACTION && (
+ <p className="text-xs !text-foreground mt-1">
+ On delete: {getForeignKeyCascadeAction(foreignKey?.deletionAction)}
+ </p>
+ )}
+ </div>
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
)
default:
return null
diff --git a/apps/studio/components/grid/components/header/RefreshButton.tsx b/apps/studio/components/grid/components/header/RefreshButton.tsx
index 9c557e2b43c..7041b574aae 100644
--- a/apps/studio/components/grid/components/header/RefreshButton.tsx
+++ b/apps/studio/components/grid/components/header/RefreshButton.tsx
@@ -4,7 +4,7 @@ import { RefreshCw } from 'lucide-react'
import { useParams } from 'common'
import type { SupaTable } from 'components/grid/types'
import { sqlKeys } from 'data/sql/keys'
-import type { TableLike } from 'hooks/misc/useTable'
+import { TableLike } from 'data/table-editor/table-editor-query'
import { Button } from 'ui'
export type RefreshButtonProps = {
diff --git a/apps/studio/components/grid/types/base.ts b/apps/studio/components/grid/types/base.ts
index 262d4c81e3c..29e899223c8 100644
--- a/apps/studio/components/grid/types/base.ts
+++ b/apps/studio/components/grid/types/base.ts
@@ -58,6 +58,7 @@ export interface GridForeignKey {
targetTableName?: string | null
targetColumnName?: string | null
deletionAction?: string
+ updateAction?: string
}
export interface ColumnHeaderProps<R> extends RenderHeaderCellProps<R> {
diff --git a/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx b/apps/studio/components/interfaces/Database/Hooks/EditHookPanel.tsx
index 7ba9cff0fbb..f10aa57a08b 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/table-query'
+import { getTable } from 'data/tables/get-table'
import { useTablesQuery } from 'data/tables/tables-query'
import { isValidHttpUrl, tryParseJson, uuidv4 } from 'lib/helpers'
import { Button, Checkbox, Form, Input, Listbox, Radio, SidePanel } from 'ui'
diff --git a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
index b3c3482ee26..ccecfb7c8e4 100644
--- a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
@@ -7,13 +7,17 @@ import Link from 'next/link'
import { useState } from 'react'
import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'
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 { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import useTable from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import {
Button,
@@ -36,9 +40,18 @@ const ColumnList = ({
onEditColumn = noop,
onDeleteColumn = noop,
}: ColumnListProps) => {
- const { id, ref } = useParams()
+ const { id: _id, ref } = useParams()
+ const id = _id ? Number(_id) : undefined
+
+ const { project } = useProjectContext()
+ const { data, error, isError, isLoading, isSuccess } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const selectedTable = getTableLikeFromTableEditor(data)
+
const [filterString, setFilterString] = useState<string>('')
- const { data: selectedTable, error, isError, isLoading, isSuccess } = useTable(Number(id))
const isTableEntity = 'live_rows_estimate' in ((selectedTable as PostgresTable) || {})
const columns =
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
index 45c99ca76cb..896e7882dc7 100644
--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx
@@ -6,13 +6,13 @@ 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 { 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 { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
-import type { TableLike } from 'hooks/misc/useTable'
import { useUrlState } from 'hooks/ui/useUrlState'
import { noop } from 'lib/void'
import { useGetImpersonatedRole } from 'state/role-impersonation-state'
diff --git a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
index ff99e95d37d..d007c019e02 100644
--- a/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/GridHeaderActions.tsx
@@ -15,11 +15,10 @@ import { useDatabasePublicationsQuery } from 'data/database-publications/databas
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 { useTableUpdateMutation } from 'data/tables/table-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import useEntityType from 'hooks/misc/useEntityType'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
-import { TableLike } from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_, cn } from 'ui'
import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
@@ -28,11 +27,11 @@ import { RoleImpersonationPopover } from '../RoleImpersonationSelector'
export interface GridHeaderActionsProps {
table: TableLike
+ entityType: Entity
canEditViaTableEditor: boolean
}
-const GridHeaderActions = ({ table }: GridHeaderActionsProps) => {
- const entityType = useEntityType(table?.id)
+const GridHeaderActions = ({ table, entityType }: GridHeaderActionsProps) => {
const { ref } = useParams()
const { project } = useProjectContext()
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
index cce27c4d0e3..0d87702d8e3 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
@@ -1,10 +1,10 @@
import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
-import { useParams } from 'common'
import { isEmpty, noop } from 'lodash'
import { ExternalLink, Plus } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useState } from 'react'
+import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
import {
@@ -398,7 +398,6 @@ const ColumnEditor = ({
</Alert_Shadcn_>
</FormSectionContent>
</FormSection>
- <SidePanel.Separator />
</>
)}
</SidePanel>
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
index 0efd4f816d2..2af8df8b08f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnForeignKey.tsx
@@ -4,7 +4,10 @@ import { Button } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
-import useTable from 'hooks/misc/useTable'
+import {
+ getTableLikeFromTableEditor,
+ 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'
@@ -38,7 +41,12 @@ const ColumnForeignKey = ({
})
const id = _id ? Number(_id) : undefined
- const { data: table } = useTable(id)
+ const { data: tableData } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const table = getTableLikeFromTableEditor(tableData)
const getRelationStatus = (fk: ForeignKey) => {
const existingRelation = (data ?? []).find((x) => x.id === fk.id)
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 13f03b53110..18a4a2f8d1a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector.tsx
@@ -13,9 +13,11 @@ 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 { useEncryptedColumnsQuery } from 'data/encrypted-columns/encrypted-columns-query'
+import {
+ getTableLikeFromTableEditor,
+ useTableEditorQuery,
+} from 'data/table-editor/table-editor-query'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
-import { useTableQuery } from 'data/tables/table-query'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { SidePanel } from 'ui'
import ActionBar from '../../ActionBar'
@@ -41,18 +43,12 @@ const ForeignRowSelector = ({
const { tableId: _tableId, schema: schemaName, table: tableName, columns } = foreignKey ?? {}
const tableId = _tableId ? Number(_tableId) : undefined
- const { data: table } = useTableQuery({
+ const { data: tableData } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id: tableId,
})
-
- const { data: encryptedColumns } = useEncryptedColumnsQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: schemaName,
- tableName,
- })
+ const table = getTableLikeFromTableEditor(tableData)
const supaTable =
table &&
@@ -63,7 +59,7 @@ const ForeignRowSelector = ({
primaryKeys: (table as PostgresTable).primary_keys,
relationships: (table as PostgresTable).relationships,
},
- encryptedColumns
+ tableData?.encrypted_columns ?? undefined
)
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 27ebfeaba62..2c5ab27ef11 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
@@ -6,10 +6,13 @@ 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 { 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'
-import useTable from 'hooks/misc/useTable'
import { minifyJSON, prettifyJSON, removeJSONTrailingComma, tryParseJson } from 'lib/helpers'
import { Button, SidePanel, cn } from 'ui'
import ActionBar from '../../ActionBar'
@@ -40,9 +43,15 @@ const JsonEdit = ({
}: JsonEditProps) => {
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable } = useTable(id)
const project = useSelectedProject()
+ const { data } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const selectedTable = getTableLikeFromTableEditor(data)
+
const [view, setView] = useState<'edit' | 'view'>('edit')
const [jsonStr, setJsonStr] = useState('')
// sometimes the value is a JSON object if it was truncated, then fully loaded from the grid.
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
index 6f3c614aee3..8716600b7e9 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
@@ -8,10 +8,13 @@ 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 { 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'
-import useTable from 'hooks/misc/useTable'
import { Button, SidePanel, cn } from 'ui'
import ActionBar from '../ActionBar'
import { isValueTruncated } from './RowEditor.utils'
@@ -35,9 +38,15 @@ export const TextEditor = ({
}: TextEditorProps) => {
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable } = useTable(id)
const project = useSelectedProject()
+ const { data } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const selectedTable = getTableLikeFromTableEditor(data)
+
const [strValue, setStrValue] = useState('')
const [view, setView] = useState<'edit' | 'view'>('edit')
const value = row?.[column as keyof typeof row] as unknown as string
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 93b92eacd6d..9055ac1005c 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -249,7 +249,9 @@ const SidePanelEditor = ({
}
await Promise.all([
- queryClient.invalidateQueries(tableKeys.table(project?.ref, selectedTable!.id)),
+ queryClient.invalidateQueries(
+ sqlKeys.query(project?.ref, ['table-editor', selectedTable?.id])
+ ),
queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints'])),
queryClient.invalidateQueries(
sqlKeys.query(project?.ref, [
@@ -463,6 +465,7 @@ const SidePanelEditor = ({
} 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(
sqlKeys.query(project?.ref, [selectedTable.schema, selectedTable.name])
),
@@ -474,7 +477,6 @@ const SidePanelEditor = ({
])
),
queryClient.invalidateQueries(entityTypeKeys.list(project?.ref)),
- queryClient.invalidateQueries(tableKeys.table(project?.ref, table.id)),
])
toast.success(`Successfully updated ${table.name}!`, { id: toastId })
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 37c28bcd263..5216a29c9d1 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -18,7 +18,7 @@ import { sqlKeys } from 'data/sql/keys'
import { tableKeys } from 'data/tables/keys'
import { createTable as createTableMutation } from 'data/tables/table-create-mutation'
import { deleteTable as deleteTableMutation } from 'data/tables/table-delete-mutation'
-import { getTable } from 'data/tables/table-query'
+import { 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'
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx b/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
index e09e347138f..609a3b23237 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
@@ -11,20 +11,19 @@ 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 useEntityType from 'hooks/misc/useEntityType'
+import { Entity } from 'data/table-editor/table-editor-query'
import { timeout } from 'lib/helpers'
import { Button } from 'ui'
export interface TableDefinitionProps {
- id?: number
+ entityType?: Entity
}
-const TableDefinition = ({ id }: TableDefinitionProps) => {
+const TableDefinition = ({ entityType }: TableDefinitionProps) => {
const { ref } = useParams()
const editorRef = useRef(null)
const monacoRef = useRef(null)
const { resolvedTheme } = useTheme()
- const entityType = useEntityType(id)
const { project } = useProjectContext()
const viewResult = useViewDefinitionQuery(
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 62ad59ad1b6..bd5416bf64f 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -11,15 +11,12 @@ import { getSupaTable } from 'components/grid/SupabaseGrid.utils'
import { SupaTable } from 'components/grid/types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { DocsButton } from 'components/ui/DocsButton'
-import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
-import { useEncryptedColumnsQuery } from 'data/encrypted-columns/encrypted-columns-query'
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 { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import useEntityType from 'hooks/misc/useEntityType'
import useLatest from 'hooks/misc/useLatest'
-import type { TableLike } from 'hooks/misc/useTable'
import { useUrlState } from 'hooks/ui/useUrlState'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { EMPTY_ARR } from 'lib/void'
@@ -38,12 +35,16 @@ export interface TableGridEditorProps {
isLoadingSelectedTable?: boolean
selectedTable?: TableLike
+ entityType?: Entity
+ encryptedColumns?: string[]
}
const TableGridEditor = ({
theme = 'dark',
isLoadingSelectedTable = false,
selectedTable,
+ entityType,
+ encryptedColumns,
}: TableGridEditorProps) => {
const router = useRouter()
const { ref: projectRef, id } = useParams()
@@ -57,13 +58,6 @@ const TableGridEditor = ({
const canEditColumns = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'columns')
const isReadOnly = !canEditTables && !canEditColumns
- const { data: encryptedColumns } = useEncryptedColumnsQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: selectedTable?.schema,
- tableName: selectedTable?.name,
- })
-
const queryClient = useQueryClient()
const { mutate: mutateUpdateTableRow } = useTableRowUpdateMutation({
async onMutate({ projectRef, table, configuration, payload }) {
@@ -123,14 +117,6 @@ const TableGridEditor = ({
},
})
- const { data } = useForeignKeyConstraintsQuery({
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- schema: selectedTable?.schema,
- })
- const foreignKeyMeta = data || []
-
- const entityType = useEntityType(selectedTable?.id)
const columnsRef = useLatest(selectedTable?.columns ?? EMPTY_ARR)
// NOTE: DO NOT PUT HOOKS AFTER THIS LINE
@@ -150,7 +136,6 @@ const TableGridEditor = ({
const gridTable = getSupaTable({
encryptedColumns,
- foreignKeyMeta,
selectedTable,
entityType: entityType?.type,
})
@@ -248,6 +233,7 @@ const TableGridEditor = ({
table={gridTable}
headerActions={
<GridHeaderActions
+ entityType={entityType as Entity}
table={selectedTable as TableLike}
canEditViaTableEditor={canEditViaTableEditor}
/>
@@ -279,7 +265,7 @@ const TableGridEditor = ({
) : null
}
>
- {(isViewSelected || isTableSelected) && <TableDefinition id={selectedTable?.id} />}
+ {(isViewSelected || isTableSelected) && <TableDefinition entityType={entityType} />}
</SupabaseGrid>
<SidePanelEditor
diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
index 98cd65ec2b4..2c1bc04dd10 100644
--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
@@ -21,16 +21,18 @@ import {
MAX_EXPORT_ROW_COUNT_MESSAGE,
} from 'components/grid/components/header/Header'
import { parseSupaTable } from 'components/grid/SupabaseGrid.utils'
+import { Markdown } from 'components/interfaces/Markdown'
import {
formatTableRowsToSQL,
getEntityLintDetails,
} from 'components/interfaces/TableGridEditor/TableEntity.utils'
import type { ItemRenderer } from 'components/ui/InfiniteList'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import type { Entity } from 'data/entity-types/entity-type-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 { fetchAllTableRows } from 'data/table-rows/table-rows-query'
-import { getTable } from 'data/tables/table-query'
+import { getTable } from 'data/tables/get-table'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
@@ -45,8 +47,6 @@ import {
DropdownMenuTrigger,
} from 'ui'
import { useProjectContext } from '../ProjectLayout/ProjectContext'
-import { Markdown } from 'components/interfaces/Markdown'
-import { EditorTablePageLink } from 'data/prefetchers/project.$ref.editor.$id'
export interface EntityListItemProps {
id: number
diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
index 215893ac1d3..75d93b6363e 100644
--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
@@ -12,10 +12,13 @@ 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 { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorage } from 'hooks/misc/useLocalStorage'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
-import useTable from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
@@ -41,7 +44,8 @@ import { useProjectContext } from '../ProjectLayout/ProjectContext'
import EntityListItem from './EntityListItem'
const TableEditorMenu = () => {
- const { id } = useParams()
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
const snap = useTableEditorStateSnapshot()
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
@@ -96,13 +100,19 @@ const TableEditorMenu = () => {
)
const isLocked = protectedSchemas.some((s) => s.id === schema?.id)
- const { data: selectedTable } = useTable(id !== undefined ? Number(id) : undefined)
+ const { data: tableData } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+
+ const selectedTable = getTableLikeFromTableEditor(tableData)
useEffect(() => {
- if (selectedTable) {
+ if (selectedTable?.schema) {
setSelectedSchema(selectedTable.schema)
}
- }, [selectedTable])
+ }, [selectedTable?.schema])
return (
<>
diff --git a/apps/studio/data/config/pgbouncer-enabled-query.ts b/apps/studio/data/config/pgbouncer-enabled-query.ts
index c1f4658585f..74606a2eace 100644
--- a/apps/studio/data/config/pgbouncer-enabled-query.ts
+++ b/apps/studio/data/config/pgbouncer-enabled-query.ts
@@ -26,7 +26,10 @@ export type PgBouncerStatusError = ResponseError
export const usePgBouncerStatus = <TData = PgBouncerStatusData>(
{ projectRef }: PgBouncerVariables,
- { enabled, ...options }: UseQueryOptions<PgBouncerStatusData, PgBouncerStatusError, TData> = {}
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<PgBouncerStatusData, PgBouncerStatusError, TData> = {}
) =>
useQuery<PgBouncerStatusData, PgBouncerStatusError, TData>(
configKeys.pgBouncerStatus(projectRef),
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 cad881f0611..dbb6b8e5bac 100644
--- a/apps/studio/data/database-columns/database-column-delete-mutation.ts
+++ b/apps/studio/data/database-columns/database-column-delete-mutation.ts
@@ -4,9 +4,9 @@ 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 { viewKeys } from 'data/views/keys'
-import type { TableLike } from 'hooks/misc/useTable'
import type { ResponseError } from 'types'
export type DatabaseColumnDeleteVariables = {
@@ -62,7 +62,9 @@ export const useDatabaseColumnDeleteMutation = ({
queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
...(table !== undefined
? [
- queryClient.invalidateQueries(tableKeys.table(projectRef, table.id)),
+ queryClient.invalidateQueries(
+ sqlKeys.query(projectRef, ['table-editor', table.id])
+ ),
queryClient.invalidateQueries(
sqlKeys.query(projectRef, [table.schema, table.name])
),
@@ -72,9 +74,6 @@ export const useDatabaseColumnDeleteMutation = ({
// invalidate all views from this schema, not sure if this is needed since you can't actually delete a column
// which has a view dependent on it
queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, table.schema)),
- // invalidate the view if there's a view with this id, not sure if this is needed because you can't delete a
- // column from a view
- queryClient.invalidateQueries(viewKeys.view(projectRef, table.id)),
]
: []),
])
diff --git a/apps/studio/data/encrypted-columns/encrypted-columns-query.ts b/apps/studio/data/encrypted-columns/encrypted-columns-query.ts
deleted file mode 100644
index e21e2685631..00000000000
--- a/apps/studio/data/encrypted-columns/encrypted-columns-query.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
-
-import { executeSql } from 'data/sql/execute-sql-query'
-import type { ResponseError } from 'types'
-import { encryptedColumnKeys } from './keys'
-
-export type EncryptedColumnsVariables = {
- projectRef?: string
- connectionString?: string
- schema?: string
- tableName?: string
-}
-
-export async function getEncryptedColumns(
- { projectRef, connectionString, schema, tableName }: EncryptedColumnsVariables,
- signal?: AbortSignal
-) {
- if (!tableName) return []
-
- try {
- const encryptedColumns = await executeSql(
- {
- projectRef,
- connectionString,
- sql: `select column_name as name from information_schema.columns where table_schema = '${schema}' and table_name = 'decrypted_${tableName}' and column_name like 'decrypted_%'`,
- queryKey: ['encrypted-columns', tableName],
- },
- signal
- )
- return encryptedColumns.result.map((column: any) => column.name.split('decrypted_')[1])
- } catch (error) {
- console.error('Error fetching encrypted columns', error)
- return []
- }
-}
-
-export type EncryptedColumnsData = Awaited<ReturnType<typeof getEncryptedColumns>>
-export type EncryptedColumnsError = ResponseError
-
-export const useEncryptedColumnsQuery = <TData = EncryptedColumnsData>(
- { projectRef, connectionString, schema, tableName }: EncryptedColumnsVariables,
- {
- enabled = true,
- ...options
- }: UseQueryOptions<EncryptedColumnsData, EncryptedColumnsError, TData> = {}
-) =>
- useQuery<EncryptedColumnsData, EncryptedColumnsError, TData>(
- encryptedColumnKeys.list(projectRef, schema, tableName),
- ({ signal }) =>
- getEncryptedColumns({ projectRef, connectionString, schema, tableName }, signal),
- { enabled: enabled && typeof projectRef !== 'undefined', ...options }
- )
-
-export function prefetchEncryptedColumns(
- client: QueryClient,
- { projectRef, connectionString, schema, tableName }: EncryptedColumnsVariables
-) {
- return client.fetchQuery(encryptedColumnKeys.list(projectRef, schema, tableName), ({ signal }) =>
- getEncryptedColumns(
- {
- projectRef,
- connectionString,
- schema,
- tableName,
- },
- signal
- )
- )
-}
diff --git a/apps/studio/data/encrypted-columns/keys.ts b/apps/studio/data/encrypted-columns/keys.ts
deleted file mode 100644
index e73d19d7a53..00000000000
--- a/apps/studio/data/encrypted-columns/keys.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const encryptedColumnKeys = {
- list: (
- projectRef: string | undefined,
- schema: string | undefined,
- tableName: string | undefined
- ) => ['projects', projectRef, 'encrypted-columns', schema, tableName] as const,
-}
diff --git a/apps/studio/data/entity-types/entity-type-query.ts b/apps/studio/data/entity-types/entity-type-query.ts
deleted file mode 100644
index b0e26577073..00000000000
--- a/apps/studio/data/entity-types/entity-type-query.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { QueryClient, UseQueryOptions } from '@tanstack/react-query'
-
-import { sqlKeys } from 'data/sql/keys'
-import {
- executeSql,
- ExecuteSqlData,
- ExecuteSqlError,
- useExecuteSqlQuery,
-} from '../sql/execute-sql-query'
-import { ENTITY_TYPE } from './entity-type-constants'
-
-type EntityTypeArgs = {
- id?: number
-}
-
-export const entityTypeSqlQuery = ({ id }: EntityTypeArgs) => {
- const sql = /* SQL */ `
- 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;
- `
-
- return sql
-}
-
-export type Entity = {
- id: number
- schema: string
- name: string
- type: ENTITY_TYPE
- comment: string | null
- rls_enabled: boolean
-}
-
-export type EntityType = Entity | null
-
-export type EntityTypeVariables = EntityTypeArgs & {
- projectRef?: string
- connectionString?: string
-}
-
-export type EntityTypeData = EntityType
-export type EntityTypeError = ExecuteSqlError
-
-export const useEntityTypeQuery = <TData extends EntityTypeData = EntityTypeData>(
- { projectRef, connectionString, id, ...args }: EntityTypeVariables,
- { enabled, ...options }: UseQueryOptions<ExecuteSqlData, EntityTypeError, TData> = {}
-) =>
- useExecuteSqlQuery(
- {
- projectRef,
- connectionString,
- sql: entityTypeSqlQuery({ id, ...args }),
- queryKey: ['entity-type', id],
- },
- {
- select(data) {
- return (data.result[0] ?? null) as TData
- },
- enabled:
- enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),
- ...options,
- }
- )
-
-export function prefetchEntityType(
- client: QueryClient,
- { projectRef, connectionString, id }: EntityTypeVariables
-) {
- return client
- .fetchQuery(sqlKeys.query(projectRef, ['entity-type', id]), ({ signal }) =>
- executeSql(
- {
- projectRef,
- connectionString,
- sql: entityTypeSqlQuery({ id }),
- queryKey: ['entity-type', id],
- },
- signal
- )
- )
- .then((data: { result: EntityTypeData[] }) => data?.result?.[0] ?? null)
-}
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 91d1b549bd9..7d32a82f985 100644
--- a/apps/studio/data/entity-types/entity-types-infinite-query.ts
+++ b/apps/studio/data/entity-types/entity-types-infinite-query.ts
@@ -1,8 +1,8 @@
import { QueryClient, useInfiniteQuery, UseInfiniteQueryOptions } from '@tanstack/react-query'
import { executeSql, ExecuteSqlVariables } from 'data/sql/execute-sql-query'
-import type { Entity } from './entity-type-query'
-import { entityTypeKeys } from './keys'
+import { Entity } from 'data/table-editor/table-editor-query'
import { ENTITY_TYPE } from './entity-type-constants'
+import { entityTypeKeys } from './keys'
export type EntityTypesVariables = {
projectRef?: string
diff --git a/apps/studio/data/foreign-tables/foreign-table-query.ts b/apps/studio/data/foreign-tables/foreign-table-query.ts
deleted file mode 100644
index cc7370d4ff8..00000000000
--- a/apps/studio/data/foreign-tables/foreign-table-query.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type { PostgresTable } from '@supabase/postgres-meta'
-import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { foreignTableKeys } from './keys'
-
-export type ForeignTableVariables = {
- id?: number
- projectRef?: string
- connectionString?: string
-}
-
-export type ForeignTable = PostgresTable
-
-export type ForeignTableResponse = ForeignTable | { error?: any }
-
-export async function getForeignTable(
- { id, projectRef, connectionString }: ForeignTableVariables,
- 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 response = (await get(`${API_URL}/pg-meta/${projectRef}/foreign-tables?id=${id}`, {
- headers: Object.fromEntries(headers),
- signal,
- })) as ForeignTableResponse
-
- if ('error' in response) {
- throw response.error
- }
-
- return response as PostgresTable
-}
-
-export type ForeignTableData = Awaited<ReturnType<typeof getForeignTable>>
-export type ForeignTableError = unknown
-
-export const useForeignTableQuery = <TData = ForeignTableData>(
- { projectRef, connectionString, id }: ForeignTableVariables,
- { enabled = true, ...options }: UseQueryOptions<ForeignTableData, ForeignTableError, TData> = {}
-) =>
- useQuery<ForeignTableData, ForeignTableError, TData>(
- foreignTableKeys.foreignTable(projectRef, id),
- ({ signal }) => getForeignTable({ projectRef, connectionString, id }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
- staleTime: 0,
- ...options,
- }
- )
-
-export function prefetchForeignTable(
- client: QueryClient,
- { projectRef, connectionString, id }: ForeignTableVariables
-) {
- return client.fetchQuery(foreignTableKeys.foreignTable(projectRef, id), ({ signal }) =>
- getForeignTable({ id, projectRef, connectionString }, signal)
- )
-}
diff --git a/apps/studio/data/foreign-tables/keys.ts b/apps/studio/data/foreign-tables/keys.ts
index 52f040ee36e..1d92f2a2046 100644
--- a/apps/studio/data/foreign-tables/keys.ts
+++ b/apps/studio/data/foreign-tables/keys.ts
@@ -2,6 +2,4 @@ export const foreignTableKeys = {
list: (projectRef: string | undefined) => ['projects', projectRef, 'foreignTables'] as const,
listBySchema: (projectRef: string | undefined, schema: string) =>
[...foreignTableKeys.list(projectRef), schema] as const,
- foreignTable: (projectRef: string | undefined, id: number | undefined) =>
- ['projects', projectRef, 'foreignTables', id] as const,
}
diff --git a/apps/studio/data/log-drains/log-drains-query.ts b/apps/studio/data/log-drains/log-drains-query.ts
index e874534a6ca..41cf0284eb5 100644
--- a/apps/studio/data/log-drains/log-drains-query.ts
+++ b/apps/studio/data/log-drains/log-drains-query.ts
@@ -30,7 +30,7 @@ export type LogDrainsyError = ResponseError
export const useLogDrainsQuery = <TData = LogDrainsData>(
{ ref }: LogDrainsVariables,
- { enabled, ...options }: UseQueryOptions<LogDrainsData, LogDrainsyError, TData> = {}
+ { enabled = true, ...options }: UseQueryOptions<LogDrainsData, LogDrainsyError, TData> = {}
) =>
useQuery<LogDrainsData, LogDrainsyError, TData>(
logDrainsKeys.list(ref),
diff --git a/apps/studio/data/materialized-views/keys.ts b/apps/studio/data/materialized-views/keys.ts
index 600a905b78a..52471531801 100644
--- a/apps/studio/data/materialized-views/keys.ts
+++ b/apps/studio/data/materialized-views/keys.ts
@@ -2,6 +2,4 @@ export const materializedViewKeys = {
list: (projectRef: string | undefined) => ['projects', projectRef, 'materializedViews'] as const,
listBySchema: (projectRef: string | undefined, schema: string) =>
[...materializedViewKeys.list(projectRef), schema] as const,
- materializedView: (projectRef: string | undefined, id: number | undefined) =>
- ['projects', projectRef, 'materializedViews', id] as const,
}
diff --git a/apps/studio/data/materialized-views/materialized-view-query.ts b/apps/studio/data/materialized-views/materialized-view-query.ts
deleted file mode 100644
index 1d6e2411e24..00000000000
--- a/apps/studio/data/materialized-views/materialized-view-query.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { PostgresMaterializedView } from '@supabase/postgres-meta'
-import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
-
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { materializedViewKeys } from './keys'
-
-export type MaterializedViewVariables = {
- id?: number
- projectRef?: string
- connectionString?: string
-}
-
-export type MaterializedView = PostgresMaterializedView
-
-export type MaterializedViewResponse = MaterializedView | { error?: any }
-
-export async function getMaterializedView(
- { id, projectRef, connectionString }: MaterializedViewVariables,
- 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 response = (await get(`${API_URL}/pg-meta/${projectRef}/materialized-views?id=${id}`, {
- headers: Object.fromEntries(headers),
- signal,
- })) as MaterializedViewResponse
-
- if ('error' in response) {
- throw response.error
- }
-
- return response as PostgresMaterializedView
-}
-
-export type MaterializedViewData = Awaited<ReturnType<typeof getMaterializedView>>
-export type MaterializedViewError = unknown
-
-export const useMaterializedViewQuery = <TData = MaterializedViewData>(
- { projectRef, connectionString, id }: MaterializedViewVariables,
- {
- enabled = true,
- ...options
- }: UseQueryOptions<MaterializedViewData, MaterializedViewError, TData> = {}
-) =>
- useQuery<MaterializedViewData, MaterializedViewError, TData>(
- materializedViewKeys.materializedView(projectRef, id),
- ({ signal }) => getMaterializedView({ projectRef, connectionString, id }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
- staleTime: 0,
- ...options,
- }
- )
-
-export function prefetchMaterializedView(
- client: QueryClient,
- { projectRef, connectionString, id }: MaterializedViewVariables
-) {
- return client.fetchQuery(materializedViewKeys.materializedView(projectRef, id), ({ signal }) =>
- getMaterializedView({ id, projectRef, connectionString }, signal)
- )
-}
diff --git a/apps/studio/data/permissions/permissions-query.ts b/apps/studio/data/permissions/permissions-query.ts
index 61614607aa5..abb751cf5c5 100644
--- a/apps/studio/data/permissions/permissions-query.ts
+++ b/apps/studio/data/permissions/permissions-query.ts
@@ -26,7 +26,7 @@ export const usePermissionsQuery = <TData = PermissionsData>(
({ signal }) => getPermissions(signal),
{
...options,
- enabled: IS_PLATFORM && options.enabled,
+ enabled: IS_PLATFORM && (options.enabled ?? true),
staleTime: 30 * 60 * 1000,
}
)
diff --git a/apps/studio/data/pg-sodium-keys/pg-sodium-keys-query.ts b/apps/studio/data/pg-sodium-keys/pg-sodium-keys-query.ts
index 23e9ab21cdb..517ecac0332 100644
--- a/apps/studio/data/pg-sodium-keys/pg-sodium-keys-query.ts
+++ b/apps/studio/data/pg-sodium-keys/pg-sodium-keys-query.ts
@@ -49,7 +49,7 @@ export type PgSodiumKeysError = unknown
export const usePgSodiumKeysQuery = <TData = PgSodiumKeysData>(
{ projectRef, connectionString }: PgSodiumKeysVariables,
- { enabled, ...options }: UseQueryOptions<PgSodiumKeysData, PgSodiumKeysError, TData> = {}
+ { enabled = true, ...options }: UseQueryOptions<PgSodiumKeysData, PgSodiumKeysError, TData> = {}
) =>
useQuery<PgSodiumKeysData, PgSodiumKeysError, TData>(
pgSodiumKeys.list(projectRef),
diff --git a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
index ad4ed80b1fe..63e08a6288a 100644
--- a/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
+++ b/apps/studio/data/prefetchers/project.$ref.editor.$id.tsx
@@ -12,20 +12,10 @@ import {
import { Filter, Sort } from 'components/grid/types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import {
- ForeignKeyConstraintsData,
- prefetchForeignKeyConstraints,
-} from 'data/database/foreign-key-constraints-query'
-import { prefetchEncryptedColumns } from 'data/encrypted-columns/encrypted-columns-query'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { Entity, prefetchEntityType } from 'data/entity-types/entity-type-query'
-import { ForeignTableData, prefetchForeignTable } from 'data/foreign-tables/foreign-table-query'
-import {
- MaterializedViewData,
- prefetchMaterializedView,
-} from 'data/materialized-views/materialized-view-query'
+ getTableLikeFromTableEditor,
+ prefetchTableEditor,
+} from 'data/table-editor/table-editor-query'
import { prefetchTableRows } from 'data/table-rows/table-rows-query'
-import { prefetchTable, TableData } from 'data/tables/table-query'
-import { prefetchView, ViewData } from 'data/views/view-query'
import { useFlag } from 'hooks/ui/useFlag'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE } from 'state/table-editor'
@@ -48,104 +38,43 @@ export function usePrefetchEditorTablePage() {
router.prefetch(`/project/${project.ref}/editor/${id}`)
// Prefetch the data
- prefetchEntityType(queryClient, {
+ prefetchTableEditor(queryClient, {
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,
+ })
+
+ const { sorts: localSorts = [], filters: localFilters = [] } =
+ loadTableEditorSortsAndFiltersFromLocalStorage(
+ project.ref,
+ entity.name,
+ entity.schema
+ ) ?? {}
+
+ prefetchTableRows(queryClient, {
+ queryKey: [supaTable.schema, supaTable.name],
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ table: supaTable,
+ sorts: sorts ?? formatSortURLParams(supaTable.name, localSorts),
+ filters: filters ?? formatFilterURLParams(localFilters),
+ page: 1,
+ limit: TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE,
+ impersonatedRole: roleImpersonationState.role,
+ })
+ }
})
- .then((entity) => {
- let promises: [
- Promise<Entity | null>,
- Promise<ForeignKeyConstraintsData>,
- Promise<string[]>,
- (
- | Promise<TableData | ViewData | MaterializedViewData | ForeignTableData | undefined>
- | undefined
- ),
- ] = [
- Promise.resolve(entity),
- prefetchForeignKeyConstraints(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- schema: entity?.schema,
- }),
- prefetchEncryptedColumns(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- schema: entity?.schema,
- tableName: entity?.name,
- }),
- undefined,
- ]
-
- switch (entity?.type) {
- case ENTITY_TYPE.TABLE:
- case ENTITY_TYPE.PARTITIONED_TABLE:
- promises[3] = prefetchTable(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- id,
- })
- break
-
- case ENTITY_TYPE.VIEW:
- promises[3] = prefetchView(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- id,
- })
- break
-
- case ENTITY_TYPE.MATERIALIZED_VIEW:
- promises[3] = prefetchMaterializedView(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- id,
- })
- break
-
- case ENTITY_TYPE.FOREIGN_TABLE:
- promises[3] = prefetchForeignTable(queryClient, {
- projectRef: project.ref,
- connectionString: project.connectionString,
- id,
- })
- break
- }
-
- return Promise.all(promises)
- })
- .then(([entity, foreignKeyConstraints, encryptedColumns, table]) => {
- if (entity && table) {
- const supaTable = getSupaTable({
- selectedTable: table,
- encryptedColumns,
- foreignKeyMeta: foreignKeyConstraints,
- entityType: entity.type,
- })
-
- const { sorts: localSorts = [], filters: localFilters = [] } =
- loadTableEditorSortsAndFiltersFromLocalStorage(
- project.ref,
- entity.name,
- entity.schema
- ) ?? {}
-
- prefetchTableRows(queryClient, {
- queryKey: [supaTable.schema, supaTable.name],
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- table: supaTable,
- sorts: sorts ?? formatSortURLParams(supaTable.name, localSorts),
- filters: filters ?? formatFilterURLParams(localFilters),
- page: 1,
- limit: TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE,
- impersonatedRole: roleImpersonationState.role,
- })
- }
- })
},
- [project, queryClient, router]
+ [project, queryClient, roleImpersonationState.role, router, tableEditorPrefetchingEnabled]
)
}
diff --git a/apps/studio/data/read-replicas/replica-lag-query.ts b/apps/studio/data/read-replicas/replica-lag-query.ts
index 9585e9eba42..9d0cf3fbf1d 100644
--- a/apps/studio/data/read-replicas/replica-lag-query.ts
+++ b/apps/studio/data/read-replicas/replica-lag-query.ts
@@ -25,7 +25,7 @@ export type ReplicationLagError = ExecuteSqlError
export const useReplicationLagQuery = <TData extends ReplicationLagData = ReplicationLagData>(
{ projectRef, connectionString, id }: ReplicationLagVariables,
- { enabled, ...options }: UseQueryOptions<ExecuteSqlData, ReplicationLagError, TData> = {}
+ { enabled = true, ...options }: UseQueryOptions<ExecuteSqlData, ReplicationLagError, TData> = {}
) =>
useExecuteSqlQuery(
{
diff --git a/apps/studio/data/table-editor/table-editor-query-sql.ts b/apps/studio/data/table-editor/table-editor-query-sql.ts
new file mode 100644
index 00000000000..9476a97331e
--- /dev/null
+++ b/apps/studio/data/table-editor/table-editor-query-sql.ts
@@ -0,0 +1,350 @@
+import minify from 'pg-minify'
+
+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
+ 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
+ ),
+ 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}
+ ),
+ 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}
+ ),
+ 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}
+ ),
+ 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
+ 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
+ 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
+ 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}
+ )
+ 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"
+ `)
+}
diff --git a/apps/studio/data/table-editor/table-editor-query.ts b/apps/studio/data/table-editor/table-editor-query.ts
new file mode 100644
index 00000000000..d8d364bd887
--- /dev/null
+++ b/apps/studio/data/table-editor/table-editor-query.ts
@@ -0,0 +1,130 @@
+import type {
+ PostgresColumn,
+ PostgresMaterializedView,
+ PostgresTable,
+ PostgresView,
+} from '@supabase/postgres-meta'
+import { QueryClient, 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 { getTableEditorSql } from './table-editor-query-sql'
+
+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>(
+ { projectRef, connectionString, id }: TableEditorVariables,
+ { enabled = true, ...options }: UseQueryOptions<ExecuteSqlData, TableEditorError, TData> = {}
+) =>
+ useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getTableEditorSql(id),
+ queryKey: ['table-editor', id],
+ },
+ {
+ 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
+ ...options,
+ }
+ )
+
+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
+ )
+ )
+ .then((data) => (data?.result?.[0] as unknown as TableEditor) ?? null)
+}
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 2a5ecf25865..64c102c92df 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/table-query'
+import type { Table } from 'data/tables/get-table'
import { ImpersonationRole, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'
import type { ResponseError } from 'types'
diff --git a/apps/studio/data/table-rows/utils.ts b/apps/studio/data/table-rows/utils.ts
index 7e45b8a53e1..d517bf97025 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/table-query'
+import type { Table } from 'data/tables/get-table'
/**
* temporary fix until we implement a better filter UI
diff --git a/apps/studio/data/tables/table-query.ts b/apps/studio/data/tables/get-table.ts
similarity index 50%
rename from apps/studio/data/tables/table-query.ts
rename to apps/studio/data/tables/get-table.ts
index 36b5d4195a3..b20f9102fe1 100644
--- a/apps/studio/data/tables/table-query.ts
+++ b/apps/studio/data/tables/get-table.ts
@@ -1,8 +1,6 @@
import type { PostgresTable } from '@supabase/postgres-meta'
-import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get, handleError } from 'data/fetchers'
-import { tableKeys } from './keys'
export type TableVariables = {
id?: number
@@ -14,6 +12,9 @@ export type Table = PostgresTable
export type TableResponse = Table | { error?: any }
+/**
+ * @deprecated use `useTableEditorQuery` instead
+ */
export async function getTable(
{ id, projectRef, connectionString }: TableVariables,
signal?: AbortSignal
@@ -38,29 +39,3 @@ export async function getTable(
if (error) handleError(error)
return data as unknown as PostgresTable
}
-
-export type TableData = Awaited<ReturnType<typeof getTable>>
-export type TableError = unknown
-
-export const useTableQuery = <TData = TableData>(
- { projectRef, connectionString, id }: TableVariables,
- { enabled = true, ...options }: UseQueryOptions<TableData, TableError, TData> = {}
-) =>
- useQuery<TableData, TableError, TData>(
- tableKeys.table(projectRef, id),
- ({ signal }) => getTable({ projectRef, connectionString, id }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
- staleTime: 0,
- ...options,
- }
- )
-
-export function prefetchTable(
- client: QueryClient,
- { projectRef, connectionString, id }: TableVariables
-) {
- return client.fetchQuery(tableKeys.table(projectRef, id), ({ signal }) =>
- getTable({ id, projectRef, connectionString }, signal)
- )
-}
diff --git a/apps/studio/data/tables/keys.ts b/apps/studio/data/tables/keys.ts
index f0c15e661d5..4b6bbca70fc 100644
--- a/apps/studio/data/tables/keys.ts
+++ b/apps/studio/data/tables/keys.ts
@@ -1,6 +1,4 @@
export const tableKeys = {
list: (projectRef: string | undefined, schema: string | undefined, includeColumns?: boolean) =>
['projects', projectRef, 'tables', schema, includeColumns].filter(Boolean),
- table: (projectRef: string | undefined, id: number | undefined) =>
- ['projects', projectRef, 'tables', id] as const,
}
diff --git a/apps/studio/data/tables/table-delete-mutation.ts b/apps/studio/data/tables/table-delete-mutation.ts
index 2c4d98089d5..c2aafa6e457 100644
--- a/apps/studio/data/tables/table-delete-mutation.ts
+++ b/apps/studio/data/tables/table-delete-mutation.ts
@@ -6,6 +6,7 @@ import { del, handleError } from 'data/fetchers'
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
@@ -55,13 +56,11 @@ 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(tableKeys.list(projectRef, schema)),
- queryClient.invalidateQueries(tableKeys.table(projectRef, id)),
queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
// invalidate all views from this schema
queryClient.invalidateQueries(viewKeys.listBySchema(projectRef, schema)),
- // invalidate the view if there's a view with this id
- queryClient.invalidateQueries(viewKeys.view(projectRef, id)),
])
await onSuccess?.(data, variables, context)
diff --git a/apps/studio/data/tables/table-update-mutation.ts b/apps/studio/data/tables/table-update-mutation.ts
index bffdf683d7c..8c05451def5 100644
--- a/apps/studio/data/tables/table-update-mutation.ts
+++ b/apps/studio/data/tables/table-update-mutation.ts
@@ -4,6 +4,7 @@ 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 type { ResponseError } from 'types'
import { tableKeys } from './keys'
@@ -58,8 +59,8 @@ 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(tableKeys.list(projectRef, schema)),
- queryClient.invalidateQueries(tableKeys.table(projectRef, id)),
queryClient.invalidateQueries(lintKeys.lint(projectRef)),
])
await onSuccess?.(data, variables, context)
diff --git a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts
index 7421073b18d..1626084d5c6 100644
--- a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts
+++ b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts
@@ -42,7 +42,7 @@ export type VaultSecretsDecryptedValueError = unknown
export const useVaultSecretDecryptedValueQuery = <TData = VaultSecretsDecryptedValueData>(
{ projectRef, connectionString, id }: VaultSecretsDecryptedValueVariables,
{
- enabled,
+ enabled = true,
...options
}: UseQueryOptions<VaultSecretsDecryptedValueData, VaultSecretsDecryptedValueError, TData> = {}
) =>
diff --git a/apps/studio/data/vault/vault-secrets-query.ts b/apps/studio/data/vault/vault-secrets-query.ts
index ff3bf827be8..345481cba43 100644
--- a/apps/studio/data/vault/vault-secrets-query.ts
+++ b/apps/studio/data/vault/vault-secrets-query.ts
@@ -23,7 +23,7 @@ export type VaultSecretsError = ExecuteSqlError
export const useVaultSecretsQuery = <TData extends VaultSecretsData = VaultSecretsData>(
{ projectRef, connectionString }: VaultSecretsVariables,
- { enabled, ...options }: UseQueryOptions<ExecuteSqlData, VaultSecretsError, TData> = {}
+ { enabled = true, ...options }: UseQueryOptions<ExecuteSqlData, VaultSecretsError, TData> = {}
) => {
return useExecuteSqlQuery(
{
diff --git a/apps/studio/data/views/keys.ts b/apps/studio/data/views/keys.ts
index 24c879ae256..df314bb23af 100644
--- a/apps/studio/data/views/keys.ts
+++ b/apps/studio/data/views/keys.ts
@@ -2,6 +2,4 @@ export const viewKeys = {
list: (projectRef: string | undefined) => ['projects', projectRef, 'views'] as const,
listBySchema: (projectRef: string | undefined, schema: string) =>
[...viewKeys.list(projectRef), schema] as const,
- view: (projectRef: string | undefined, id: number | undefined) =>
- [...viewKeys.list(projectRef), id] as const,
}
diff --git a/apps/studio/data/views/view-query.ts b/apps/studio/data/views/view-query.ts
deleted file mode 100644
index 9fc16cf2299..00000000000
--- a/apps/studio/data/views/view-query.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { PostgresView } from '@supabase/postgres-meta'
-import { QueryClient, useQuery, UseQueryOptions } from '@tanstack/react-query'
-
-import { get, handleError } from 'data/fetchers'
-import type { ResponseError } from 'types'
-import { viewKeys } from './keys'
-
-export type ViewVariables = {
- id?: number
- projectRef?: string
- connectionString?: string
-}
-
-export type View = PostgresView
-
-export type ViewResponse = View | { error?: any }
-
-export async function getView(
- { id, projectRef, connectionString }: ViewVariables,
- 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}/views', {
- params: {
- header: { 'x-connection-encrypted': connectionString! },
- path: { ref: projectRef },
- query: { id: `${id}` } as any,
- },
- headers,
- signal,
- })
-
- if (error) handleError(error)
- return data as unknown as PostgresView
-}
-
-export type ViewData = Awaited<ReturnType<typeof getView>>
-export type ViewError = ResponseError
-
-export const useViewQuery = <TData = ViewData>(
- { projectRef, connectionString, id }: ViewVariables,
- { enabled = true, ...options }: UseQueryOptions<ViewData, ViewError, TData> = {}
-) =>
- useQuery<ViewData, ViewError, TData>(
- viewKeys.view(projectRef, id),
- ({ signal }) => getView({ projectRef, connectionString, id }, signal),
- {
- enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
- staleTime: 0,
- ...options,
- }
- )
-
-export function prefetchView(
- client: QueryClient,
- { projectRef, connectionString, id }: ViewVariables
-) {
- return client.fetchQuery(viewKeys.view(projectRef, id), ({ signal }) =>
- getView({ id, projectRef, connectionString }, signal)
- )
-}
diff --git a/apps/studio/hooks/misc/useEntityType.ts b/apps/studio/hooks/misc/useEntityType.ts
deleted file mode 100644
index 336b83fb5df..00000000000
--- a/apps/studio/hooks/misc/useEntityType.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useQueryClient } from '@tanstack/react-query'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { type Entity, useEntityTypeQuery } from 'data/entity-types/entity-type-query'
-import { entityTypeKeys } from 'data/entity-types/keys'
-import { useMemo } from 'react'
-
-/**
- * Tries to load an entity type from the cached list of entity types, or fetches it from the server.
- */
-function useEntityType(id?: number, onNotFound?: (id: number) => void) {
- const queryClient = useQueryClient()
- const { project } = useProjectContext()
-
- const existingEntity = useMemo(
- () =>
- (
- queryClient.getQueryCache().find(entityTypeKeys.list(project?.ref))?.state.data as any
- )?.pages
- ?.flatMap((page: any) => page.data.entities)
- ?.find((entity: any) => entity.id === id) as Entity | undefined,
- [project?.ref, id]
- )
-
- const { data: entity } = useEntityTypeQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id,
- },
- {
- enabled: !existingEntity,
- onSettled(data) {
- if (!data && id !== undefined) {
- onNotFound?.(id)
- }
- },
- }
- )
-
- return existingEntity ?? entity
-}
-
-export default useEntityType
diff --git a/apps/studio/hooks/misc/useTable.ts b/apps/studio/hooks/misc/useTable.ts
deleted file mode 100644
index 891d25fe9df..00000000000
--- a/apps/studio/hooks/misc/useTable.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
-import { ForeignTable, useForeignTableQuery } from 'data/foreign-tables/foreign-table-query'
-import {
- MaterializedView,
- useMaterializedViewQuery,
-} from 'data/materialized-views/materialized-view-query'
-import { Table, useTableQuery } from 'data/tables/table-query'
-import { View, useViewQuery } from 'data/views/view-query'
-import useEntityType from './useEntityType'
-
-export type TableLike = Table | View | MaterializedView | ForeignTable
-
-/**
- * A hook that loads all table-like objects. e.g. tables, views, materialized views, etc...
- */
-function useTable(id?: number) {
- const { project } = useProjectContext()
- const entity = useEntityType(id)
-
- const tableResult = useTableQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id: entity?.id,
- },
- {
- enabled: entity?.type === ENTITY_TYPE.TABLE || entity?.type === ENTITY_TYPE.PARTITIONED_TABLE,
- }
- )
-
- const viewResult = useViewQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id: entity?.id,
- },
- {
- enabled: entity?.type === ENTITY_TYPE.VIEW,
- }
- )
-
- const materializedViewResult = useMaterializedViewQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id: entity?.id,
- },
- {
- enabled: entity?.type === ENTITY_TYPE.MATERIALIZED_VIEW,
- }
- )
-
- const foreignTableResult = useForeignTableQuery(
- {
- projectRef: project?.ref,
- connectionString: project?.connectionString,
- id: entity?.id,
- },
- {
- enabled: entity?.type === ENTITY_TYPE.FOREIGN_TABLE,
- }
- )
-
- switch (entity?.type) {
- case ENTITY_TYPE.TABLE:
- case ENTITY_TYPE.PARTITIONED_TABLE:
- return tableResult
- case ENTITY_TYPE.VIEW:
- return viewResult
- case ENTITY_TYPE.MATERIALIZED_VIEW:
- return materializedViewResult
- case ENTITY_TYPE.FOREIGN_TABLE:
- return foreignTableResult
- default:
- // While entity is loading, we can fallback
- // to the loading state of the table query.
- return tableResult
- }
-}
-
-export default useTable
diff --git a/apps/studio/pages/project/[ref]/database/tables/[id].tsx b/apps/studio/pages/project/[ref]/database/tables/[id].tsx
index 0bf8713790c..4370e3f2cdc 100644
--- a/apps/studio/pages/project/[ref]/database/tables/[id].tsx
+++ b/apps/studio/pages/project/[ref]/database/tables/[id].tsx
@@ -6,17 +6,30 @@ import { ColumnList } from 'components/interfaces/Database'
import { SidePanelEditor } from 'components/interfaces/TableGridEditor'
import DeleteConfirmationDialogs from 'components/interfaces/TableGridEditor/DeleteConfirmationDialogs'
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 useTable from 'hooks/misc/useTable'
+import {
+ getTableLikeFromTableEditor,
+ useTableEditorQuery,
+} from 'data/table-editor/table-editor-query'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
const DatabaseTables: NextPageWithLayout = () => {
- const { id } = useParams()
const snap = useTableEditorStateSnapshot()
- const { data: selectedTable, isLoading } = useTable(Number(id))
+
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
+
+ const { project } = useProjectContext()
+ const { data, isLoading } = useTableEditorQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ id,
+ })
+ const selectedTable = getTableLikeFromTableEditor(data)
return (
<>
diff --git a/apps/studio/pages/project/[ref]/database/tables/index.tsx b/apps/studio/pages/project/[ref]/database/tables/index.tsx
index cb4473b09e4..2d5e3d0467d 100644
--- a/apps/studio/pages/project/[ref]/database/tables/index.tsx
+++ b/apps/studio/pages/project/[ref]/database/tables/index.tsx
@@ -6,7 +6,7 @@ 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/table-query'
+import type { Table } from 'data/tables/get-table'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
diff --git a/apps/studio/pages/project/[ref]/editor/[id].tsx b/apps/studio/pages/project/[ref]/editor/[id].tsx
index 9c232bb3883..97cd3b11201 100644
--- a/apps/studio/pages/project/[ref]/editor/[id].tsx
+++ b/apps/studio/pages/project/[ref]/editor/[id].tsx
@@ -4,9 +4,15 @@ import { useRouter } from 'next/router'
import { useParams } from 'common/hooks'
import { TableGridEditor } from 'components/interfaces/TableGridEditor'
import DeleteConfirmationDialogs from 'components/interfaces/TableGridEditor/DeleteConfirmationDialogs'
-import { ProjectContextFromParamsProvider } from 'components/layouts/ProjectLayout/ProjectContext'
+import {
+ ProjectContextFromParamsProvider,
+ useProjectContext,
+} from 'components/layouts/ProjectLayout/ProjectContext'
import TableEditorLayout from 'components/layouts/TableEditorLayout/TableEditorLayout'
-import useTable from 'hooks/misc/useTable'
+import {
+ getTableLikeFromTableEditor,
+ useTableEditorQuery,
+} from 'data/table-editor/table-editor-query'
import type { NextPageWithLayout } from 'types'
const TableEditorPage: NextPageWithLayout = () => {
@@ -15,13 +21,21 @@ const TableEditorPage: NextPageWithLayout = () => {
const { id: _id, ref: projectRef } = useParams()
const id = _id ? Number(_id) : undefined
- const { data: selectedTable, isLoading } = useTable(id)
+ const { project } = useProjectContext()
+ const { data, 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 675d67aa7f7..d2138dfae83 100644
--- a/apps/studio/pages/project/[ref]/editor/index.tsx
+++ b/apps/studio/pages/project/[ref]/editor/index.tsx
@@ -6,7 +6,7 @@ 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/table-query'
+import type { Table } from 'data/tables/get-table'
import type { NextPageWithLayout } from 'types'
const TableEditorPage: NextPageWithLayout = () => {