Skip to content

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

Chore/support showing all entities in database tables page (#27749)

Joshen Lim54320ddb7319
diff --git a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
index de1d1753549..f00ab767ea5 100644
--- a/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/ColumnList.tsx
@@ -1,21 +1,10 @@
import * as Tooltip from '@radix-ui/react-tooltip'
+import { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop } from 'lodash'
+import { ChevronLeft, Edit, MoreVertical, Plus, Search, Trash } from 'lucide-react'
import Link from 'next/link'
import { useState } from 'react'
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- IconEdit,
- IconMoreVertical,
- IconPlus,
- IconSearch,
- IconTrash,
- Input,
-} from 'ui'
import { useParams } from 'common'
import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'
@@ -25,7 +14,14 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useCheckPermissions } from 'hooks'
import useTable from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
-import { ChevronLeft } from 'lucide-react'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Input,
+} from 'ui'
import ProtectedSchemaWarning from '../ProtectedSchemaWarning'
interface ColumnListProps {
@@ -42,6 +38,7 @@ const ColumnList = ({
const { id, ref } = useParams()
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 =
(filterString.length === 0
@@ -68,18 +65,14 @@ const ColumnList = ({
placeholder="Filter columns"
value={filterString}
onChange={(e: any) => setFilterString(e.target.value)}
- icon={<IconSearch size="tiny" />}
+ icon={<Search size={12} />}
/>
</div>
- {!isLocked && (
+ {!isLocked && isTableEntity && (
<div>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
- <Button
- disabled={!canUpdateColumns}
- icon={<IconPlus />}
- onClick={() => onAddColumn()}
- >
+ <Button disabled={!canUpdateColumns} icon={<Plus />} onClick={() => onAddColumn()}>
New column
</Button>
</Tooltip.Trigger>
@@ -155,12 +148,10 @@ const ColumnList = ({
<code className="text-xs">{x.format}</code>
</Table.td>
<Table.td className="text-right">
- {!isLocked && (
+ {!isLocked && isTableEntity && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" className="px-1">
- <IconMoreVertical />
- </Button>
+ <Button type="default" className="px-1" icon={<MoreVertical />} />
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end" className="w-32">
<DropdownMenuItem
@@ -169,7 +160,7 @@ const ColumnList = ({
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger className="flex items-center space-x-2">
- <IconEdit size="tiny" />
+ <Edit size={12} />
<p>Edit column</p>
</Tooltip.Trigger>
{!canUpdateColumns && (
@@ -198,7 +189,7 @@ const ColumnList = ({
>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger className="flex items-center space-x-2">
- <IconTrash stroke="red" size="tiny" />
+ <Trash stroke="red" size={12} />
<p>Delete column</p>
</Tooltip.Trigger>
{!canUpdateColumns && (
diff --git a/apps/studio/components/interfaces/Database/Tables/TableList.tsx b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
index 7ceb67bf32e..ef29514a520 100644
--- a/apps/studio/components/interfaces/Database/Tables/TableList.tsx
+++ b/apps/studio/components/interfaces/Database/Tables/TableList.tsx
@@ -1,7 +1,20 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { noop, partition } from 'lodash'
-import { Columns } from 'lucide-react'
+import {
+ Check,
+ Columns,
+ Copy,
+ Edit,
+ Eye,
+ Filter,
+ MoreVertical,
+ Plus,
+ Search,
+ Table2,
+ Trash,
+ X,
+} from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useState } from 'react'
@@ -10,32 +23,40 @@ import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import SchemaSelector from 'components/ui/SchemaSelector'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useDatabasePublicationsQuery } from 'data/database-publications/database-publications-query'
import { useSchemasQuery } from 'data/database/schemas-query'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+import { useMaterializedViewsQuery } from 'data/materialized-views/materialized-views-query'
import { useTablesQuery } from 'data/tables/tables-query'
+import { useViewsQuery } from 'data/views/views-query'
import { useCheckPermissions } from 'hooks'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import {
Button,
+ Checkbox_Shadcn_,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
- IconCheck,
- IconEdit,
- IconEye,
- IconMoreVertical,
- IconPlus,
- IconSearch,
- IconTrash,
- IconX,
Input,
- IconCopy,
+ Label_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+ Tooltip_Shadcn_,
+ cn,
} from 'ui'
import ProtectedSchemaWarning from '../ProtectedSchemaWarning'
+import { formatAllEntities } from './Tables.utils'
+import { useForeignTableQuery } from 'data/foreign-tables/foreign-table-query'
+import { useForeignTablesQuery } from 'data/foreign-tables/foreign-tables-query'
interface TableListProps {
onAddTable: () => void
@@ -54,6 +75,7 @@ const TableList = ({
const snap = useTableEditorStateSnapshot()
const [filterString, setFilterString] = useState<string>('')
+ const [visibleTypes, setVisibleTypes] = useState<string[]>(Object.values(ENTITY_TYPE))
const canUpdateTables = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
const { data: schemas } = useSchemasQuery({
@@ -66,10 +88,10 @@ const TableList = ({
const {
data: tables,
- isLoading,
- isSuccess,
- isError,
- error,
+ error: tablesError,
+ isError: isErrorTables,
+ isLoading: isLoadingTables,
+ isSuccess: isSuccessTables,
} = useTablesQuery(
{
projectRef: project?.ref,
@@ -87,6 +109,73 @@ const TableList = ({
}
)
+ const {
+ data: views,
+ error: viewsError,
+ isError: isErrorViews,
+ isLoading: isLoadingViews,
+ isSuccess: isSuccessViews,
+ } = useViewsQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: snap.selectedSchemaName,
+ },
+ {
+ select(views) {
+ return filterString.length === 0
+ ? views
+ : views.filter((view) => view.name.toLowerCase().includes(filterString.toLowerCase()))
+ },
+ }
+ )
+
+ const {
+ data: materializedViews,
+ error: materializedViewsError,
+ isError: isErrorMaterializedViews,
+ isLoading: isLoadingMaterializedViews,
+ isSuccess: isSuccessMaterializedViews,
+ } = useMaterializedViewsQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: snap.selectedSchemaName,
+ },
+ {
+ select(materializedViews) {
+ return filterString.length === 0
+ ? materializedViews
+ : materializedViews.filter((view) =>
+ view.name.toLowerCase().includes(filterString.toLowerCase())
+ )
+ },
+ }
+ )
+
+ const {
+ data: foreignTables,
+ error: foreignTablesError,
+ isError: isErrorForeignTables,
+ isLoading: isLoadingForeignTables,
+ isSuccess: isSuccessForeignTables,
+ } = useForeignTablesQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: snap.selectedSchemaName,
+ },
+ {
+ select(foreignTables) {
+ return filterString.length === 0
+ ? foreignTables
+ : foreignTables.filter((table) =>
+ table.name.toLowerCase().includes(filterString.toLowerCase())
+ )
+ },
+ }
+ )
+
const { data: publications } = useDatabasePublicationsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
@@ -96,60 +185,105 @@ const TableList = ({
)
const schema = schemas?.find((schema) => schema.name === snap.selectedSchemaName)
+ const entities = formatAllEntities({ tables, views, materializedViews, foreignTables }).filter(
+ (x) => visibleTypes.includes(x.type)
+ )
const isLocked = protectedSchemas.some((s) => s.id === schema?.id)
+ const error = tablesError || viewsError || materializedViewsError || foreignTablesError
+ const isError = isErrorTables || isErrorViews || isErrorMaterializedViews || isErrorForeignTables
+ const isLoading =
+ isLoadingTables || isLoadingViews || isLoadingMaterializedViews || isLoadingForeignTables
+ const isSuccess =
+ (isSuccessTables && isSuccessViews) || isSuccessMaterializedViews || isSuccessForeignTables
+
+ const formatTooltipText = (entityType: string) => {
+ return Object.entries(ENTITY_TYPE)
+ .find(([, value]) => value === entityType)?.[0]
+ ?.toLowerCase()
+ ?.split('_')
+ ?.join(' ')
+ }
+
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
- <div className="flex items-center space-x-4">
- <SchemaSelector
- className="w-[260px]"
- size="small"
- showError={false}
- selectedSchemaName={snap.selectedSchemaName}
- onSelectSchema={snap.setSelectedSchemaName}
- />
+ <div className="flex items-center gap-x-4">
+ <div className="flex items-center gap-x-2">
+ <SchemaSelector
+ className="w-[260px]"
+ size="small"
+ showError={false}
+ selectedSchemaName={snap.selectedSchemaName}
+ onSelectSchema={snap.setSelectedSchemaName}
+ />
+ <Popover_Shadcn_>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ type={visibleTypes.length !== 5 ? 'default' : 'dashed'}
+ className="py-4 px-2"
+ icon={<Filter />}
+ />
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0 w-56" side="bottom" align="center">
+ <div className="px-3 pt-3 pb-2 flex flex-col gap-y-2">
+ <p className="text-xs">Show entity types</p>
+ <div className="flex flex-col">
+ {Object.entries(ENTITY_TYPE).map(([key, value]) => (
+ <div key={key} className="group flex items-center justify-between py-0.5">
+ <div className="flex items-center gap-x-2">
+ <Checkbox_Shadcn_
+ id={key}
+ name={key}
+ checked={visibleTypes.includes(value)}
+ onCheckedChange={() => {
+ if (visibleTypes.includes(value)) {
+ setVisibleTypes(visibleTypes.filter((y) => y !== value))
+ } else {
+ setVisibleTypes(visibleTypes.concat([value]))
+ }
+ }}
+ />
+ <Label_Shadcn_ htmlFor={key} className="capitalize text-xs">
+ {key.toLowerCase().replace('_', ' ')}
+ </Label_Shadcn_>
+ </div>
+ <Button
+ size="tiny"
+ type="default"
+ onClick={() => setVisibleTypes([value])}
+ className="transition opacity-0 group-hover:opacity-100 h-auto px-1 py-0.5"
+ >
+ Select only
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ </div>
<Input
size="small"
className="w-64"
placeholder="Search for a table"
value={filterString}
onChange={(e: any) => setFilterString(e.target.value)}
- icon={<IconSearch size="tiny" />}
+ icon={<Search size={12} />}
/>
</div>
{!isLocked && (
- <div>
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- disabled={!canUpdateTables}
- icon={<IconPlus />}
- onClick={() => onAddTable()}
- >
- New table
- </Button>
- </Tooltip.Trigger>
- {!canUpdateTables && (
- <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">
- You need additional permissions to create tables
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
- </div>
+ <ButtonTooltip
+ icon={<Plus />}
+ disabled={!canUpdateTables}
+ onClick={() => onAddTable()}
+ tooltip={{
+ content: { side: 'bottom', text: 'You need additional permissions to create tables' },
+ }}
+ >
+ New table
+ </ButtonTooltip>
)}
</div>
@@ -163,6 +297,7 @@ const TableList = ({
<div className="my-4 w-full">
<Table
head={[
+ <Table.th key="icon" className="!px-0" />,
<Table.th key="name">Name</Table.th>,
<Table.th key="description" className="hidden lg:table-cell">
Description
@@ -180,19 +315,43 @@ const TableList = ({
]}
body={
<>
- {tables.length === 0 && filterString.length === 0 && (
+ {entities.length === 0 && filterString.length === 0 && (
<Table.tr key={snap.selectedSchemaName}>
- <Table.td colSpan={6}>
- <p className="text-sm text-foreground">No tables created yet</p>
- <p className="text-sm text-foreground-light">
- There are no tables found in the schema "{snap.selectedSchemaName}"
- </p>
+ <Table.td colSpan={7}>
+ {visibleTypes.length === 0 ? (
+ <>
+ <p className="text-sm text-foreground">
+ Please select at least one entity type to filter with
+ </p>
+ <p className="text-sm text-foreground-light">
+ There are currently no results based on the filter that you have applied
+ </p>
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-foreground">No tables created yet</p>
+ <p className="text-sm text-foreground-light">
+ There are no{' '}
+ {visibleTypes.length === 5
+ ? 'tables'
+ : visibleTypes.length === 1
+ ? `${formatTooltipText(visibleTypes[0])}s`
+ : `${visibleTypes
+ .slice(0, -1)
+ .map((x) => `${formatTooltipText(x)}s`)
+ .join(
+ ', '
+ )}, and ${formatTooltipText(visibleTypes[visibleTypes.length - 1])}s`}{' '}
+ found in the schema "{snap.selectedSchemaName}"
+ </p>
+ </>
+ )}
</Table.td>
</Table.tr>
)}
- {tables.length === 0 && filterString.length > 0 && (
+ {entities.length === 0 && filterString.length > 0 && (
<Table.tr key={snap.selectedSchemaName}>
- <Table.td colSpan={6}>
+ <Table.td colSpan={7}>
<p className="text-sm text-foreground">No results found</p>
<p className="text-sm text-foreground-light">
Your search for "{filterString}" did not return any results
@@ -200,9 +359,47 @@ const TableList = ({
</Table.td>
</Table.tr>
)}
- {tables.length > 0 &&
- tables.map((x: any, i: any) => (
+ {entities.length > 0 &&
+ entities.map((x) => (
<Table.tr key={x.id}>
+ <Table.td className="!pl-5 !pr-1">
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ {x.type === ENTITY_TYPE.TABLE ? (
+ <Table2
+ size={15}
+ strokeWidth={1.5}
+ className="text-foreground-lighter"
+ />
+ ) : x.type === ENTITY_TYPE.VIEW ? (
+ <Eye
+ size={15}
+ strokeWidth={1.5}
+ className="text-foreground-lighter"
+ />
+ ) : (
+ <div
+ className={cn(
+ 'flex items-center justify-center text-xs h-4 w-4 rounded-[2px] font-bold',
+ x.type === ENTITY_TYPE.FOREIGN_TABLE &&
+ 'text-yellow-900 bg-yellow-500',
+ x.type === ENTITY_TYPE.MATERIALIZED_VIEW &&
+ 'text-purple-1000 bg-purple-500',
+ x.type === ENTITY_TYPE.PARTITIONED_TABLE &&
+ 'text-foreground-light bg-border-stronger'
+ )}
+ >
+ {Object.entries(ENTITY_TYPE)
+ .find(([, value]) => value === x.type)?.[0]?.[0]
+ ?.toUpperCase()}
+ </div>
+ )}
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom" className="capitalize">
+ {formatTooltipText(x.type)}
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ </Table.td>
<Table.td>
{/* only show tooltips if required, to reduce noise */}
{x.name.length > 20 ? (
@@ -241,21 +438,21 @@ const TableList = ({
)}
</Table.td>
<Table.td className="hidden text-right xl:table-cell">
- {(x.live_rows_estimate ?? x.live_row_count).toLocaleString()}
+ {x.rows !== undefined ? x.rows.toLocaleString() : '-'}
</Table.td>
<Table.td className="hidden text-right xl:table-cell">
- <code className="text-xs">{x.size}</code>
+ {x.size !== undefined ? <code className="text-xs">{x.size}</code> : '-'}
</Table.td>
<Table.td className="hidden xl:table-cell text-center">
{(realtimePublication?.tables ?? []).find(
(table: any) => table.id === x.id
) ? (
<div className="flex justify-center">
- <IconCheck strokeWidth={2} className="text-brand" />
+ <Check size={18} strokeWidth={2} className="text-brand" />
</div>
) : (
<div className="flex justify-center">
- <IconX strokeWidth={2} className="text-foreground-lighter" />
+ <X size={18} strokeWidth={2} className="text-foreground-lighter" />
</div>
)}
</Table.td>
@@ -269,95 +466,85 @@ const TableList = ({
style={{ paddingTop: 3, paddingBottom: 3 }}
>
<Link href={`/project/${ref}/database/tables/${x.id}`}>
- {x.columns?.length} columns
+ {x.columns.length} columns
</Link>
</Button>
{!isLocked && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" className="px-1">
- <IconMoreVertical />
- </Button>
+ <Button type="default" className="px-1" icon={<MoreVertical />} />
</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" align="end" className="w-36">
- <DropdownMenuItem
- disabled={!canUpdateTables}
- onClick={() => onEditTable(x)}
- >
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger className="flex items-center space-x-2">
- <IconEdit size="tiny" />
- <p>Edit table</p>
- </Tooltip.Trigger>
- {!canUpdateTables && (
- <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">
- Additional permissions required to edit table
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
- </DropdownMenuItem>
-
+ <DropdownMenuContent side="bottom" align="end" className="w-40">
<DropdownMenuItem
className="flex items-center space-x-2"
onClick={() =>
router.push(`/project/${project?.ref}/editor/${x.id}`)
}
>
- <IconEye size="tiny" />
- <p>View table</p>
- </DropdownMenuItem>
- <DropdownMenuItem
- key="duplicate-table"
- className="space-x-2"
- onClick={(e) => {
- e.stopPropagation()
- snap.onDuplicateTable()
- }}
- >
- <IconCopy size="tiny" />
- <span>Duplicate Table</span>
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canUpdateTables || isLocked}
- onClick={() => onDeleteTable(x)}
- >
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger className="flex items-center space-x-2">
- <IconTrash stroke="red" size="tiny" />
- <p>Delete table</p>
- </Tooltip.Trigger>
- {!canUpdateTables && (
- <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">
- Additional permissions required to delete table
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
+ <Eye size={12} />
+ <p>View in Table Editor</p>
</DropdownMenuItem>
+
+ {x.type === ENTITY_TYPE.TABLE && (
+ <>
+ <DropdownMenuSeparator />
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <DropdownMenuItem
+ className="!pointer-events-auto gap-x-2"
+ disabled={!canUpdateTables}
+ onClick={() => {
+ if (canUpdateTables) onEditTable(x)
+ }}
+ >
+ <Edit size={12} />
+ <p>Edit table</p>
+ </DropdownMenuItem>
+ </TooltipTrigger_Shadcn_>
+ {!canUpdateTables && (
+ <TooltipContent_Shadcn_ side="left">
+ You need additional permissions to edit this table
+ </TooltipContent_Shadcn_>
+ )}
+ </Tooltip_Shadcn_>
+ <DropdownMenuItem
+ key="duplicate-table"
+ className="space-x-2"
+ onClick={(e) => {
+ e.stopPropagation()
+ snap.onDuplicateTable()
+ }}
+ >
+ <Copy size={12} />
+ <span>Duplicate Table</span>
+ </DropdownMenuItem>
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <DropdownMenuItem
+ disabled={!canUpdateTables || isLocked}
+ className="!pointer-events-auto gap-x-2"
+ onClick={() => {
+ if (canUpdateTables && !isLocked) {
+ onDeleteTable({
+ ...x,
+ schema: snap.selectedSchemaName,
+ })
+ }
+ }}
+ >
+ <Trash stroke="red" size={12} />
+ <p>Delete table</p>
+ </DropdownMenuItem>
+ </TooltipTrigger_Shadcn_>
+ {!canUpdateTables && (
+ <TooltipContent_Shadcn_ side="left">
+ You need additional permissions to delete tables
+ </TooltipContent_Shadcn_>
+ )}
+ </Tooltip_Shadcn_>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
)}
diff --git a/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts b/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts
new file mode 100644
index 00000000000..43f910509e2
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Tables/Tables.utils.ts
@@ -0,0 +1,69 @@
+import { PostgresMaterializedView, PostgresTable, PostgresView } from '@supabase/postgres-meta'
+import { PostgresForeignTable } from '@supabase/postgres-meta/dist/lib/types'
+import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+
+// [Joshen] We just need name, description, rows, size, and the number of columns
+// Just missing partitioned tables as missing pg-meta support
+export const formatAllEntities = ({
+ tables = [],
+ views = [],
+ materializedViews = [],
+ foreignTables = [],
+}: {
+ tables?: PostgresTable[]
+ views?: PostgresView[]
+ materializedViews?: PostgresMaterializedView[]
+ foreignTables?: PostgresForeignTable[]
+}) => {
+ const formattedTables = tables.map((x) => {
+ return {
+ ...x,
+ type: ENTITY_TYPE.TABLE,
+ rows: x.live_rows_estimate,
+ columns: x.columns ?? [],
+ }
+ })
+
+ const formattedViews = views.map((x) => {
+ return {
+ type: ENTITY_TYPE.VIEW,
+ id: x.id,
+ name: x.name,
+ comment: x.comment,
+ rows: undefined,
+ size: undefined,
+ columns: x.columns ?? [],
+ }
+ })
+
+ const formattedMaterializedViews = materializedViews.map((x) => {
+ return {
+ type: ENTITY_TYPE.MATERIALIZED_VIEW,
+ id: x.id,
+ name: x.name,
+ comment: x.comment,
+ rows: undefined,
+ size: undefined,
+ columns: x.columns ?? [],
+ }
+ })
+
+ const formattedForeignTables = foreignTables.map((x) => {
+ return {
+ type: ENTITY_TYPE.FOREIGN_TABLE,
+ id: x.id,
+ name: x.name,
+ comment: x.comment,
+ rows: undefined,
+ size: undefined,
+ columns: x.columns ?? [],
+ }
+ })
+
+ return [
+ ...formattedTables,
+ ...formattedViews,
+ ...formattedMaterializedViews,
+ ...formattedForeignTables,
+ ].sort((a, b) => a.name.localeCompare(b.name))
+}
diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
index 45f41fe04ad..85a46724f96 100644
--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx
@@ -1,15 +1,27 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import saveAs from 'file-saver'
-import { Eye, MoreHorizontal, Table2, Unlock } from 'lucide-react'
+import {
+ Copy,
+ Download,
+ Edit,
+ Eye,
+ Lock,
+ MoreHorizontal,
+ Table2,
+ Trash,
+ Unlock,
+} from 'lucide-react'
import Link from 'next/link'
import Papa from 'papaparse'
import toast from 'react-hot-toast'
import { IS_PLATFORM } from 'common'
import { parseSupaTable } from 'components/grid'
+import { 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 { fetchAllTableRows } from 'data/table-rows/table-rows-query'
import { getTable } from 'data/tables/table-query'
import { useTableEditorStateSnapshot } from 'state/table-editor'
@@ -19,16 +31,9 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
- IconCopy,
- IconDownload,
- IconEdit,
- IconLock,
- IconTrash,
cn,
} from 'ui'
import { useProjectContext } from '../ProjectLayout/ProjectContext'
-import { useProjectLintsQuery } from 'data/lint/lint-query'
-import { getEntityLintDetails } from 'components/interfaces/TableGridEditor/TableEntity.utils'
export interface EntityListItemProps {
id: number
@@ -280,7 +285,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
snap.onEditTable()
}}
>
- <IconEdit size="tiny" />
+ <Edit size={12} />
<span>Edit Table</span>
</DropdownMenuItem>
<DropdownMenuItem
@@ -291,7 +296,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
snap.onDuplicateTable()
}}
>
- <IconCopy size="tiny" />
+ <Copy size={12} />
<span>Duplicate Table</span>
</DropdownMenuItem>
<DropdownMenuItem key="view-policies" className="space-x-2" asChild>
@@ -299,7 +304,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
key="view-policies"
href={`/project/${projectRef}/auth/policies?schema=${snap.selectedSchemaName}&search=${entity.id}`}
>
- <IconLock size="tiny" />
+ <Lock size={12} />
<span>View Policies</span>
</Link>
</DropdownMenuItem>
@@ -311,7 +316,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
exportTableAsCSV()
}}
>
- <IconDownload size="tiny" />
+ <Download size={12} />
<span>Export as CSV</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
@@ -323,7 +328,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({
snap.onDeleteTable()
}}
>
- <IconTrash size="tiny" />
+ <Trash size={12} />
<span>Delete Table</span>
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/apps/studio/data/foreign-tables/foreign-tables-query.ts b/apps/studio/data/foreign-tables/foreign-tables-query.ts
new file mode 100644
index 00000000000..32bad871e7f
--- /dev/null
+++ b/apps/studio/data/foreign-tables/foreign-tables-query.ts
@@ -0,0 +1,55 @@
+import { UseQueryOptions, useQuery } from '@tanstack/react-query'
+
+import { PostgresView } from '@supabase/postgres-meta'
+import { get, handleError } from 'data/fetchers'
+import type { ResponseError } from 'types'
+import { foreignTableKeys } from './keys'
+
+export type ForeignTablesVariables = {
+ projectRef?: string
+ connectionString?: string
+ schema?: string
+}
+
+export async function getForeignTables(
+ { projectRef, connectionString, schema }: ForeignTablesVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ let headers = new Headers()
+ if (connectionString) headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await get('/platform/pg-meta/{ref}/foreign-tables', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString! },
+ path: { ref: projectRef },
+ query: {
+ included_schemas: schema || '',
+ include_columns: true,
+ } as any,
+ },
+ headers,
+ signal,
+ })
+
+ if (error) handleError(error)
+ return data as PostgresView[]
+}
+
+export type ForeignTablesData = Awaited<ReturnType<typeof getForeignTables>>
+export type ForeignTablesError = ResponseError
+
+export const useForeignTablesQuery = <TData = ForeignTablesData>(
+ { projectRef, connectionString, schema }: ForeignTablesVariables,
+ { enabled = true, ...options }: UseQueryOptions<ForeignTablesData, ForeignTablesError, TData> = {}
+) =>
+ useQuery<ForeignTablesData, ForeignTablesError, TData>(
+ schema ? foreignTableKeys.listBySchema(projectRef, schema) : foreignTableKeys.list(projectRef),
+ ({ signal }) => getForeignTables({ projectRef, connectionString, schema }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ staleTime: 0,
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/foreign-tables/keys.ts b/apps/studio/data/foreign-tables/keys.ts
index 869cd2ccfad..52f040ee36e 100644
--- a/apps/studio/data/foreign-tables/keys.ts
+++ b/apps/studio/data/foreign-tables/keys.ts
@@ -1,5 +1,7 @@
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/materialized-views/keys.ts b/apps/studio/data/materialized-views/keys.ts
index 6e34f29b960..600a905b78a 100644
--- a/apps/studio/data/materialized-views/keys.ts
+++ b/apps/studio/data/materialized-views/keys.ts
@@ -1,5 +1,7 @@
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-views-query.ts b/apps/studio/data/materialized-views/materialized-views-query.ts
new file mode 100644
index 00000000000..fc100cdb420
--- /dev/null
+++ b/apps/studio/data/materialized-views/materialized-views-query.ts
@@ -0,0 +1,60 @@
+import { UseQueryOptions, useQuery } from '@tanstack/react-query'
+
+import { PostgresMaterializedView } from '@supabase/postgres-meta'
+import { get, handleError } from 'data/fetchers'
+import type { ResponseError } from 'types'
+import { materializedViewKeys } from './keys'
+
+export type MaterializedViewsVariables = {
+ projectRef?: string
+ connectionString?: string
+ schema?: string
+}
+
+export async function getMaterializedViews(
+ { projectRef, connectionString, schema }: MaterializedViewsVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ let headers = new Headers()
+ if (connectionString) headers.set('x-connection-encrypted', connectionString)
+
+ const { data, error } = await get('/platform/pg-meta/{ref}/materialized-views', {
+ params: {
+ header: { 'x-connection-encrypted': connectionString! },
+ path: { ref: projectRef },
+ query: {
+ included_schemas: schema || '',
+ include_columns: true,
+ } as any,
+ },
+ headers,
+ signal,
+ })
+
+ if (error) handleError(error)
+ return data as PostgresMaterializedView[]
+}
+
+export type MaterializedViewsData = Awaited<ReturnType<typeof getMaterializedViews>>
+export type MaterializedViewsError = ResponseError
+
+export const useMaterializedViewsQuery = <TData = MaterializedViewsData>(
+ { projectRef, connectionString, schema }: MaterializedViewsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<MaterializedViewsData, MaterializedViewsError, TData> = {}
+) =>
+ useQuery<MaterializedViewsData, MaterializedViewsError, TData>(
+ schema
+ ? materializedViewKeys.listBySchema(projectRef, schema)
+ : materializedViewKeys.list(projectRef),
+ ({ signal }) => getMaterializedViews({ projectRef, connectionString, schema }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ staleTime: 0,
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/tables/keys.ts b/apps/studio/data/tables/keys.ts
index 760be314924..f0c15e661d5 100644
--- a/apps/studio/data/tables/keys.ts
+++ b/apps/studio/data/tables/keys.ts
@@ -1,9 +1,6 @@
export const tableKeys = {
- list: (
- projectRef: string | undefined,
- schema: string | undefined,
- includeColumns?: boolean | undefined
- ) => ['projects', projectRef, 'tables', { schema, includeColumns: !!includeColumns }] as const,
+ 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 42de4ddbc98..1f445aca64d 100644
--- a/apps/studio/data/tables/table-delete-mutation.ts
+++ b/apps/studio/data/tables/table-delete-mutation.ts
@@ -55,8 +55,7 @@ export const useTableDeleteMutation = ({
async onSuccess(data, variables, context) {
const { id, projectRef, schema } = variables
await Promise.all([
- queryClient.invalidateQueries(tableKeys.list(projectRef, schema, true)),
- queryClient.invalidateQueries(tableKeys.list(projectRef, schema, false)),
+ queryClient.invalidateQueries(tableKeys.list(projectRef, schema)),
queryClient.invalidateQueries(tableKeys.table(projectRef, id)),
queryClient.invalidateQueries(entityTypeKeys.list(projectRef)),
// invalidate all views from this schema
diff --git a/apps/studio/data/tables/tables-query.ts b/apps/studio/data/tables/tables-query.ts
index 8e1ebf85199..f93fdf5ccb4 100644
--- a/apps/studio/data/tables/tables-query.ts
+++ b/apps/studio/data/tables/tables-query.ts
@@ -68,12 +68,13 @@ export type TablesError = ResponseError
export const useTablesQuery = <TData = TablesData>(
{ projectRef, connectionString, schema, includeColumns }: TablesVariables,
{ enabled = true, ...options }: UseQueryOptions<TablesData, TablesError, TData> = {}
-) =>
- useQuery<TablesData, TablesError, TData>(
+) => {
+ return useQuery<TablesData, TablesError, TData>(
tableKeys.list(projectRef, schema, includeColumns),
({ signal }) => getTables({ projectRef, connectionString, schema, includeColumns }, signal),
{ enabled: enabled && typeof projectRef !== 'undefined', staleTime: 0, ...options }
)
+}
/**
* useGetTables
diff --git a/apps/studio/data/views/views-query.ts b/apps/studio/data/views/views-query.ts
index b5c884f06f0..fd46365532d 100644
--- a/apps/studio/data/views/views-query.ts
+++ b/apps/studio/data/views/views-query.ts
@@ -1,6 +1,6 @@
-import { UseQueryOptions, useQuery, useQueryClient } from '@tanstack/react-query'
-import { useCallback } from 'react'
+import { UseQueryOptions, useQuery } from '@tanstack/react-query'
+import { PostgresView } from '@supabase/postgres-meta'
import { get, handleError } from 'data/fetchers'
import type { ResponseError } from 'types'
import { viewKeys } from './keys'
@@ -33,7 +33,7 @@ export async function getViews(
})
if (error) handleError(error)
- return data
+ return data as PostgresView[]
}
export type ViewsData = Awaited<ReturnType<typeof getViews>>
@@ -52,16 +52,3 @@ export const useViewsQuery = <TData = ViewsData>(
...options,
}
)
-
-export const useViewsPrefetch = ({ projectRef, connectionString, schema }: ViewsVariables) => {
- const client = useQueryClient()
-
- return useCallback(() => {
- if (projectRef) {
- client.prefetchQuery(
- schema ? viewKeys.listBySchema(projectRef, schema) : viewKeys.list(projectRef),
- ({ signal }) => getViews({ projectRef, connectionString, schema }, signal)
- )
- }
- }, [projectRef, schema])
-}
diff --git a/apps/studio/pages/project/[ref]/database/tables/index.tsx b/apps/studio/pages/project/[ref]/database/tables/index.tsx
index beeb36237cf..daf7c8fcd08 100644
--- a/apps/studio/pages/project/[ref]/database/tables/index.tsx
+++ b/apps/studio/pages/project/[ref]/database/tables/index.tsx
@@ -9,8 +9,10 @@ import { FormHeader } from 'components/ui/Forms'
import type { Table } from 'data/tables/table-query'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { NextPageWithLayout } from 'types'
+import { useQueryClient } from '@tanstack/react-query'
const DatabaseTables: NextPageWithLayout = () => {
+ const queryClient = useQueryClient()
const snap = useTableEditorStateSnapshot()
const [selectedTableToEdit, setSelectedTableToEdit] = useState<Table>()