Skip to content

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

feat: adds infinite scroll to tables list

Alaister Young289b0531b076
diff --git a/packages/ui/src/components/Menu/Menu.tsx b/packages/ui/src/components/Menu/Menu.tsx
index b57d781ddd5..9c5f510592f 100644
--- a/packages/ui/src/components/Menu/Menu.tsx
+++ b/packages/ui/src/components/Menu/Menu.tsx
@@ -1,5 +1,4 @@
import React from 'react'
-import { Space } from '../Space'
import Typography from '../Typography'
import { MenuContextProvider, useMenuContext } from './MenuContext'
@@ -8,11 +7,12 @@ import styleHandler from '../../lib/theme/styleHandler'
interface MenuProps {
children: React.ReactNode
className?: string
+ ulClassName?: string
style?: React.CSSProperties
type?: 'text' | 'pills' | 'border'
}
-function Menu({ children, className, style, type = 'text' }: MenuProps) {
+function Menu({ children, className, ulClassName, style, type = 'text' }: MenuProps) {
return (
<nav
role="menu"
@@ -23,7 +23,7 @@ function Menu({ children, className, style, type = 'text' }: MenuProps) {
style={style}
>
<MenuContextProvider type={type}>
- <ul>{children}</ul>
+ <ul className={ulClassName}>{children}</ul>
</MenuContextProvider>
</nav>
)
@@ -86,7 +86,7 @@ export function Item({
onClick={onClick}
aria-current={active ? 'page' : undefined}
>
- {icon && <span className={iconClasses.join(' ')}>{icon}</span>}
+ {icon && <div className={`${iconClasses.join(' ')} min-w-fit`}>{icon}</div>}
<span className={contentClasses.join(' ')}>{children}</span>
</a>
</li>
@@ -103,9 +103,7 @@ export function Group({ children, icon, title }: GroupProps) {
const __styles = styleHandler('menu')
const { type } = useMenuContext()
return (
- <div
- className={[__styles.group.base, __styles.group.variants[type]].join(' ')}
- >
+ <div className={[__styles.group.base, __styles.group.variants[type]].join(' ')}>
{icon && <span className={__styles.group.icon}>{icon}</span>}
<span className={__styles.group.content}>{title}</span>
{children}
diff --git a/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx b/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
index 9d8b552385f..984d6709b46 100644
--- a/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
+++ b/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
@@ -1,39 +1,35 @@
-import { FC, ReactNode, useState, useEffect } from 'react'
-import { isUndefined } from 'lodash'
+import { PropsWithChildren, useEffect } from 'react'
+import { isUndefined, noop } from 'lodash'
import { observer } from 'mobx-react-lite'
-import type { PostgresTable } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { checkPermissions, useParams, useStore } from 'hooks'
-import Error from 'components/ui/Error'
+import { Entity } from 'data/entity-types/entity-types-infinite-query'
import ProjectLayout from '../ProjectLayout/ProjectLayout'
import TableEditorMenu from './TableEditorMenu'
import NoPermission from 'components/ui/NoPermission'
-interface Props {
+export interface TableEditorLayoutProps {
selectedSchema?: string
onSelectSchema: (schema: string) => void
onAddTable: () => void
- onEditTable: (table: PostgresTable) => void
- onDeleteTable: (table: PostgresTable) => void
- onDuplicateTable: (table: PostgresTable) => void
- children: ReactNode
+ onEditTable: (table: Entity) => void
+ onDeleteTable: (table: Entity) => void
+ onDuplicateTable: (table: Entity) => void
}
-const TableEditorLayout: FC<Props> = ({
+const TableEditorLayout = ({
selectedSchema,
- onSelectSchema = () => {},
- onAddTable = () => {},
- onEditTable = () => {},
- onDeleteTable = () => {},
- onDuplicateTable = () => {},
+ onSelectSchema = noop,
+ onAddTable = noop,
+ onEditTable = noop,
+ onDeleteTable = noop,
+ onDuplicateTable = noop,
children,
-}) => {
+}: PropsWithChildren<TableEditorLayoutProps>) => {
const { vault, meta, ui } = useStore()
const { id, type } = useParams()
- const { isInitialized, isLoading, error } = meta.tables
- const [loaded, setLoaded] = useState<boolean>(isInitialized)
const canReadTables = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'tables')
const vaultExtension = meta.extensions.byId('supabase_vault')
@@ -56,12 +52,12 @@ const TableEditorLayout: FC<Props> = ({
}
}, [ui.selectedProject?.ref])
- useEffect(() => {
- if (selectedSchema && ui.selectedProject?.ref) {
- meta.tables.loadBySchema(selectedSchema)
- meta.views.loadBySchema(selectedSchema)
- }
- }, [ui.selectedProject?.ref, selectedSchema])
+ // useEffect(() => {
+ // if (selectedSchema && ui.selectedProject?.ref) {
+ // meta.tables.loadBySchema(selectedSchema)
+ // meta.views.loadBySchema(selectedSchema)
+ // }
+ // }, [ui.selectedProject?.ref, selectedSchema])
useEffect(() => {
if (ui.selectedProject?.ref && id) {
@@ -79,16 +75,6 @@ const TableEditorLayout: FC<Props> = ({
}
}, [ui.selectedProject?.ref, isVaultEnabled])
- useEffect(() => {
- let cancel = false
- if (!isLoading && !loaded) {
- if (!cancel) setLoaded(true)
- }
- return () => {
- cancel = true
- }
- }, [isLoading])
-
if (!canReadTables) {
return (
<ProjectLayout>
@@ -97,17 +83,9 @@ const TableEditorLayout: FC<Props> = ({
)
}
- if (error) {
- return (
- <ProjectLayout>
- <Error error={error} />
- </ProjectLayout>
- )
- }
-
return (
<ProjectLayout
- isLoading={!loaded || isUndefined(selectedSchema)}
+ isLoading={isUndefined(selectedSchema)}
product="Table editor"
productMenu={
<TableEditorMenu
diff --git a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
index dcdfc12bd0d..6fa70d4ea1d 100644
--- a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
+++ b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
@@ -1,6 +1,6 @@
-import { FC, useEffect, useState } from 'react'
+import { useMemo, useState } from 'react'
import Link from 'next/link'
-import { partition } from 'lodash'
+import { noop, partition } from 'lodash'
import { observer } from 'mobx-react-lite'
import {
Button,
@@ -20,80 +20,62 @@ import {
} from 'ui'
import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import type { PostgresSchema, PostgresTable } from '@supabase/postgres-meta'
+import type { PostgresSchema } from '@supabase/postgres-meta'
-import { SchemaView } from 'types'
import { checkPermissions, useStore, useParams } from 'hooks'
import ProductMenuItem from 'components/ui/ProductMenu/ProductMenuItem'
+import { Entity, useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'
+import { useProjectContext } from '../ProjectLayout/ProjectContext'
+import InfiniteList from 'components/ui/InfiniteList'
-interface Props {
+export interface TableEditorMenuProps {
selectedSchema?: string
onSelectSchema: (schema: string) => void
onAddTable: () => void
- onEditTable: (table: PostgresTable) => void
- onDeleteTable: (table: PostgresTable) => void
- onDuplicateTable: (table: PostgresTable) => void
+ onEditTable: (table: Entity) => void
+ onDeleteTable: (table: Entity) => void
+ onDuplicateTable: (table: Entity) => void
}
-const TableEditorMenu: FC<Props> = ({
+const TableEditorMenu = ({
selectedSchema,
- onSelectSchema = () => {},
- onAddTable = () => {},
- onEditTable = () => {},
- onDeleteTable = () => {},
- onDuplicateTable = () => {},
-}) => {
+ onSelectSchema = noop,
+ onAddTable = noop,
+ onEditTable = noop,
+ onDeleteTable = noop,
+ onDuplicateTable = noop,
+}: TableEditorMenuProps) => {
const { meta } = useStore()
- const { id, ref } = useParams()
+ const { id } = useParams()
- const schemas: PostgresSchema[] = meta.schemas.list()
- const tables: PostgresTable[] = meta.tables.list(
- (table: PostgresTable) => table.schema === selectedSchema
- )
- const views: SchemaView[] = meta.views.list((view: SchemaView) => view.schema === selectedSchema)
- const foreignTables: Partial<PostgresTable>[] = meta.foreignTables.list(
- (table: Partial<PostgresTable>) => table.schema === selectedSchema
+ const [searchText, setSearchText] = useState<string>('')
+
+ const { project } = useProjectContext()
+ const { data, isLoading, refetch, isRefetching, hasNextPage, isFetchingNextPage, fetchNextPage } =
+ useEntityTypesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ schema: selectedSchema,
+ // search: searchText.trim().toLowerCase()
+ })
+
+ const totalCount = data?.pages?.[0].data.count
+ const entityTypes = useMemo(
+ () => data?.pages.flatMap((page) => page.data.entities),
+ [data?.pages]
)
- const isFetchingTables =
- // @ts-ignore
- tables.filter((t) => t.schema === selectedSchema).length === 0 && meta.tables.isLoading
+ const schemas: PostgresSchema[] = meta.schemas.list()
const schema = schemas.find((schema) => schema.name === selectedSchema)
const canCreateTables = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')
- const [searchText, setSearchText] = useState<string>('')
- const [isRefreshing, setIsRefreshing] = useState<boolean>(false)
+ const isLoadingTableMetadata = id ? !meta.tables.byId(id) : true
const refreshTables = async () => {
- if (selectedSchema) {
- setIsRefreshing(true)
- await meta.tables.loadBySchema(selectedSchema)
- await meta.views.loadBySchema(selectedSchema)
- setIsRefreshing(false)
- }
+ await refetch()
}
- const filteredTables =
- searchText.length === 0
- ? tables
- : // @ts-ignore
- tables.filter((table) => table.name.toLowerCase().includes(searchText.toLowerCase()))
-
- const filteredViews =
- searchText.length === 0
- ? views || []
- : (views || []).filter((view: Partial<PostgresTable>) =>
- (view?.name ?? '').toLowerCase().includes(searchText.toLowerCase())
- )
-
- const filteredForeignTables =
- searchText.length === 0
- ? foreignTables
- : foreignTables.filter((table) =>
- (table?.name ?? '').toLowerCase().includes(searchText.toLowerCase())
- )
-
const [protectedSchemas, openSchemas] = partition(schemas, (schema) =>
meta.excludedSchemas.includes(schema?.name ?? '')
)
@@ -101,7 +83,7 @@ const TableEditorMenu: FC<Props> = ({
return (
<div
- className="pt-6 flex flex-grow flex-col space-y-6"
+ className="pt-6 flex flex-col flex-grow space-y-6 h-full"
style={{ maxHeight: 'calc(100vh - 48px)' }}
>
{/* Schema selection dropdown */}
@@ -115,7 +97,6 @@ const TableEditorMenu: FC<Props> = ({
<Listbox
size="tiny"
value={selectedSchema}
- // @ts-ignore
onChange={(name: string) => {
setSearchText('')
onSelectSchema(name)
@@ -124,7 +105,6 @@ const TableEditorMenu: FC<Props> = ({
<Listbox.Option disabled key="normal-schemas" value="normal-schemas" label="Schemas">
<p className="text-xs text-scale-1100">Schemas</p>
</Listbox.Option>
- {/* @ts-ignore */}
{openSchemas.map((schema) => (
<Listbox.Option
key={schema.id}
@@ -218,172 +198,64 @@ const TableEditorMenu: FC<Props> = ({
</div>
</div>
- {isFetchingTables ? (
+ {isLoading ? (
<div className="mx-7 flex items-center space-x-2">
<IconLoader className="animate-spin" size={14} strokeWidth={1.5} />
- <p className="text-sm text-scale-1000">Loading tables...</p>
+ <p className="text-sm text-scale-1000">Loading entities...</p>
</div>
- ) : searchText.length === 0 && filteredTables.length === 0 && filteredViews.length === 0 ? (
+ ) : searchText.length === 0 && (entityTypes?.length ?? 0) === 0 ? (
<div className="mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
- <p className="text-xs">No tables available</p>
- <p className="text-xs text-scale-1100">This schema has no tables available yet</p>
+ <p className="text-xs">No entities available</p>
+ <p className="text-xs text-scale-1100">This schema has no entities available yet</p>
</div>
) : (
- <div className="flex-auto px-4 overflow-y-auto space-y-6 pb-4">
- {/* List of tables belonging to selected schema */}
- {filteredTables.length > 0 && (
- <Menu type="pills">
- <Menu.Group
- // @ts-ignore
- title={
- <>
- <div className="flex w-full items-center justify-between">
- <div className="flex items-center space-x-1">
- <p>Tables</p>
- <p style={{ fontVariantNumeric: 'tabular-nums' }}>
- ({filteredTables.length})
- </p>
- </div>
- <button className="cursor-pointer" onClick={refreshTables}>
- <IconRefreshCw className={isRefreshing ? 'animate-spin' : ''} size={14} />
- </button>
- </div>
- </>
- }
- />
-
- <div>
- {filteredTables.map((table) => {
- const isActive = Number(id) === table.id
- return (
- <ProductMenuItem
- key={table.name}
- url={`/project/${ref}/editor/${table.id}`}
- name={table.name}
- hoverText={table.comment ? table.comment : table.name}
- isActive={isActive}
- action={
- isActive &&
- !isLocked && (
- <Dropdown
- size="small"
- side="bottom"
- align="start"
- overlay={[
- <Dropdown.Item
- key="edit-table"
- icon={<IconEdit size="tiny" />}
- onClick={() => onEditTable(table)}
- >
- Edit Table
- </Dropdown.Item>,
- <Dropdown.Item
- key="duplicate-table"
- icon={<IconCopy size="tiny" />}
- onClick={() => onDuplicateTable(table)}
- >
- Duplicate Table
- </Dropdown.Item>,
- <Link href={`/project/${ref}/auth/policies?search=${table.id}`}>
- <a>
- <Dropdown.Item key="delete-table" icon={<IconLock size="tiny" />}>
- View Policies
- </Dropdown.Item>
- </a>
- </Link>,
- <Dropdown.Separator key="separator" />,
- <Dropdown.Item
- key="delete-table"
- icon={<IconTrash size="tiny" />}
- onClick={() => onDeleteTable(table)}
- >
- Delete Table
- </Dropdown.Item>,
- ]}
- >
- <div className="text-scale-900 transition-colors hover:text-scale-1200">
- <IconChevronDown size={14} strokeWidth={2} />
- </div>
- </Dropdown>
- )
- }
- />
- )
- })}
- </div>
- </Menu>
- )}
-
- {/* List of views belonging to selected schema */}
- {filteredViews.length > 0 && (
- <Menu type="pills">
- <Menu.Group
- // @ts-ignore
- title={
- <div className="flex w-full items-center space-x-1">
- <p>Views</p>
- <p style={{ fontVariantNumeric: 'tabular-nums' }}>({filteredViews.length})</p>
- </div>
- }
- />
-
- {filteredViews.map((view: SchemaView) => {
- const isActive = Number(id) === view.id
- return (
- <Link key={view.id} href={`/project/${ref}/editor/${view.id}?type=view`}>
- <a>
- <Menu.Item key={view.id} rounded active={isActive}>
- <div className="flex justify-between">
- <p className="truncate">{view.name}</p>
- </div>
- </Menu.Item>
- </a>
- </Link>
- )
- })}
- </Menu>
- )}
-
- {/* List of foreign tables belonging to selected schema */}
- {filteredForeignTables.length > 0 && (
- <Menu type="pills">
- <Menu.Group
- // @ts-ignore
- title={
- <div className="flex w-full items-center space-x-1">
- <p>Foreign Tables</p>
- <p style={{ fontVariantNumeric: 'tabular-nums' }}>
- ({filteredForeignTables.length})
- </p>
+ <Menu
+ type="pills"
+ className="flex flex-auto px-4 space-y-6 pb-4"
+ ulClassName="flex flex-auto flex-col"
+ >
+ <Menu.Group
+ // @ts-ignore
+ title={
+ <>
+ <div className="flex w-full items-center justify-between">
+ <div className="flex items-center space-x-1">
+ <p>Tables</p>
+ <p style={{ fontVariantNumeric: 'tabular-nums' }}>({totalCount})</p>
</div>
- }
- />
+ <button className="cursor-pointer" onClick={refreshTables}>
+ <IconRefreshCw className={isRefetching ? 'animate-spin' : ''} size={14} />
+ </button>
+ </div>
+ </>
+ }
+ />
- {filteredForeignTables.map((table: Partial<PostgresTable>) => {
- const isActive = Number(id) === table.id
- return (
- <Link key={table.id} href={`/project/${ref}/editor/${table.id}?type=foreign`}>
- <a>
- <Menu.Item key={table.id} rounded active={isActive}>
- <div className="flex justify-between">
- <p className="truncate">{table.name}</p>
- </div>
- </Menu.Item>
- </a>
- </Link>
- )
- })}
- </Menu>
- )}
- </div>
+ <div className="flex flex-1">
+ <InfiniteList
+ items={entityTypes}
+ ItemComponent={EntityListItem}
+ itemProps={{
+ projectRef: project?.ref,
+ id: Number(id),
+ onEditTable,
+ onDeleteTable,
+ onDuplicateTable,
+ isLoadingTableMetadata,
+ }}
+ getItemSize={() => 28}
+ hasNextPage={hasNextPage}
+ isLoadingNextPage={isFetchingNextPage}
+ onLoadNextPage={() => fetchNextPage()}
+ />
+ </div>
+ </Menu>
)}
- {searchText.length > 0 && filteredTables.length === 0 && filteredViews.length === 0 && (
+ {searchText.length > 0 && (entityTypes?.length ?? 0) === 0 && (
<div className="!mt-0 mx-7 space-y-1 rounded-md border border-scale-400 bg-scale-300 py-3 px-4">
<p className="text-xs">No results found</p>
- <p className="text-xs text-scale-1100">
- There are no tables or views that match your search
- </p>
+ <p className="text-xs text-scale-1100">There are no entities that match your search</p>
</div>
)}
</div>
@@ -391,3 +263,94 @@ const TableEditorMenu: FC<Props> = ({
}
export default observer(TableEditorMenu)
+
+export interface EntityListItemProps {
+ id: number
+ projectRef: string
+ item: Entity
+ isLocked: boolean
+ onEditTable: (table: Entity) => void
+ onDeleteTable: (table: Entity) => void
+ onDuplicateTable: (table: Entity) => void
+ isLoadingTableMetadata?: boolean
+}
+
+const EntityListItem = ({
+ id,
+ projectRef,
+ item: entity,
+ isLocked,
+ onEditTable,
+ onDeleteTable,
+ onDuplicateTable,
+ isLoadingTableMetadata = false,
+}: EntityListItemProps) => {
+ const isActive = Number(id) === entity.id
+
+ return (
+ <ProductMenuItem
+ url={`/project/${projectRef}/editor/${entity.id}?type=${entity.type}`}
+ name={entity.name}
+ hoverText={entity.comment ? entity.comment : entity.name}
+ isActive={isActive}
+ icon={
+ <div className="flex items-center justify-center text-xs h-4 w-4 rounded-[2px] bg-scale-800">
+ {entity.type[0]?.toUpperCase()}
+ </div>
+ }
+ action={
+ entity.type === 'table' &&
+ isActive &&
+ !isLocked && (
+ <Dropdown
+ size="small"
+ side="bottom"
+ align="start"
+ overlay={
+ entity.type === 'table'
+ ? [
+ <Dropdown.Item
+ key="edit-table"
+ icon={<IconEdit size="tiny" />}
+ onClick={() => onEditTable(entity)}
+ disabled={isLoadingTableMetadata}
+ >
+ Edit Table
+ </Dropdown.Item>,
+ <Dropdown.Item
+ key="duplicate-table"
+ icon={<IconCopy size="tiny" />}
+ onClick={() => onDuplicateTable(entity)}
+ disabled={isLoadingTableMetadata}
+ >
+ Duplicate Table
+ </Dropdown.Item>,
+ <Link href={`/project/${projectRef}/auth/policies?search=${entity.id}`}>
+ <a>
+ <Dropdown.Item key="delete-table" icon={<IconLock size="tiny" />}>
+ View Policies
+ </Dropdown.Item>
+ </a>
+ </Link>,
+ <Dropdown.Separator key="separator" />,
+ <Dropdown.Item
+ key="delete-table"
+ icon={<IconTrash size="tiny" />}
+ onClick={() => onDeleteTable(entity)}
+ disabled={isLoadingTableMetadata}
+ >
+ Delete Table
+ </Dropdown.Item>,
+ ]
+ : null
+ }
+ >
+ <div className="text-scale-900 transition-colors hover:text-scale-1200">
+ <IconChevronDown size={14} strokeWidth={2} />
+ </div>
+ </Dropdown>
+ )
+ }
+ />
+ )
+}
diff --git a/studio/components/ui/InfiniteList.tsx b/studio/components/ui/InfiniteList.tsx
index e469b1a59d4..60619509629 100644
--- a/studio/components/ui/InfiniteList.tsx
+++ b/studio/components/ui/InfiniteList.tsx
@@ -1,4 +1,4 @@
-import { CSSProperties, FC, memo } from 'react'
+import { CSSProperties, memo } from 'react'
import memoize from 'memoize-one'
import { areEqual, VariableSizeList } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
@@ -15,13 +15,13 @@ import ShimmeringLoader from 'components/ui/ShimmeringLoader'
const createItemData = memoize((items, itemProps) => ({ items, ...itemProps }))
-interface ItemProps {
+export interface ItemProps {
data: any
index: number
style: CSSProperties
}
-const Item: FC<ItemProps> = memo(({ data, index, style }) => {
+const Item = memo(({ data, index, style }: ItemProps) => {
const { items, itemProps, ItemComponent } = data
const item = index < items.length ? items[index] : undefined
@@ -38,7 +38,17 @@ const Item: FC<ItemProps> = memo(({ data, index, style }) => {
)
}, areEqual)
-const InfiniteList = ({
+export interface InfiniteListProps<T> {
+ items?: T[]
+ itemProps?: any
+ hasNextPage?: boolean
+ isLoadingNextPage?: boolean
+ getItemSize?: (index: number) => number
+ onLoadNextPage?: () => void
+ ItemComponent?: any
+}
+
+function InfiniteList<T>({
items = [],
itemProps = {},
hasNextPage = false,
@@ -46,7 +56,7 @@ const InfiniteList = ({
getItemSize = () => 40,
onLoadNextPage = () => {},
ItemComponent = () => null,
-}) => {
+}: InfiniteListProps<T>) {
// Only load 1 page of items at a time
// Pass an empty callback to InfiniteLoader in case it asks to load more than once
const loadMoreItems = isLoadingNextPage ? () => {} : onLoadNextPage
diff --git a/studio/data/entity-types/entity-types-infinite-query.ts b/studio/data/entity-types/entity-types-infinite-query.ts
new file mode 100644
index 00000000000..7af9464b7bf
--- /dev/null
+++ b/studio/data/entity-types/entity-types-infinite-query.ts
@@ -0,0 +1,129 @@
+import { useInfiniteQuery, UseInfiniteQueryOptions } from '@tanstack/react-query'
+import { executeSql, ExecuteSqlVariables } from 'data/sql/execute-sql-query'
+import { entityTypeKeys } from './keys'
+
+export type EntityTypesVariables = {
+ projectRef?: string
+ schema?: string
+ limit?: number
+ page?: number
+} & Pick<ExecuteSqlVariables, 'connectionString'>
+
+export type Entity = {
+ id: number
+ schema: string
+ name: string
+ type: string
+ comment: string | null
+}
+
+export type EntityTypesResponse = {
+ data: {
+ entities: Entity[]
+ count: number
+ }
+}
+
+export async function getEntityTypes(
+ { projectRef, connectionString, schema = 'public', limit = 100, page = 0 }: EntityTypesVariables,
+ signal?: AbortSignal
+) {
+ const sql = /* SQL */ `
+ with records as (
+ select
+ c.oid::int8 as "id",
+ nc.nspname as "schema",
+ c.relname as "name",
+ case c.relkind
+ when 'r' then 'table'
+ when 'v' then 'view'
+ when 'm' then 'materialized_view'
+ when 'f' then 'foreign_table'
+ when 'p' then 'partitioned_table'
+ end 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 nc.nspname = '${schema}'
+ order by "name" asc
+ limit ${limit}
+ offset ${page * limit}
+ )
+ select
+ jsonb_build_object(
+ 'entities', jsonb_agg(
+ jsonb_build_object(
+ 'id', r.id,
+ 'schema', r.schema,
+ 'name', r.name,
+ 'type', r.type,
+ 'comment', r.comment
+ )
+ order by r.name asc
+ ),
+ 'count', min(r.count)
+ ) "data"
+ from records r;
+ `
+
+ const { result } = await executeSql<EntityTypesResponse[]>(
+ {
+ projectRef,
+ connectionString,
+ sql,
+ },
+ signal
+ )
+
+ return result[0]
+}
+
+export type EntityTypesData = Awaited<ReturnType<typeof getEntityTypes>>
+export type EntityTypesError = unknown
+
+export const useEntityTypesQuery = <TData = EntityTypesData>(
+ {
+ projectRef,
+ connectionString,
+ schema = 'public',
+ limit = 100,
+ }: Omit<EntityTypesVariables, 'page'>,
+ {
+ enabled = true,
+ ...options
+ }: UseInfiniteQueryOptions<EntityTypesData, EntityTypesError, TData> = {}
+) =>
+ useInfiniteQuery<EntityTypesData, EntityTypesError, TData>(
+ entityTypeKeys.list(projectRef),
+ ({ signal, pageParam }) =>
+ getEntityTypes({ projectRef, connectionString, schema, limit, page: pageParam }, signal),
+ {
+ enabled:
+ enabled && typeof projectRef !== 'undefined' && typeof connectionString !== 'undefined',
+ getNextPageParam(lastPage, pages) {
+ const page = pages.length
+ const currentTotalCount = page * limit
+ const totalCount = lastPage.data.count
+
+ if (currentTotalCount >= totalCount) {
+ return undefined
+ }
+
+ return page
+ },
+ ...options,
+ }
+ )
diff --git a/studio/data/entity-types/keys.ts b/studio/data/entity-types/keys.ts
new file mode 100644
index 00000000000..b58ad8e80a1
--- /dev/null
+++ b/studio/data/entity-types/keys.ts
@@ -0,0 +1,3 @@
+export const entityTypeKeys = {
+ list: (projectRef: string | undefined) => ['projects', projectRef, 'entity-types'] as const,
+}
diff --git a/studio/data/sql/execute-sql-query.ts b/studio/data/sql/execute-sql-query.ts
index 8fc75f28b45..ec4d8b1cd91 100644
--- a/studio/data/sql/execute-sql-query.ts
+++ b/studio/data/sql/execute-sql-query.ts
@@ -12,8 +12,12 @@ export type ExecuteSqlVariables = {
queryKey?: QueryKey
}
-export async function executeSql(
- { projectRef, connectionString, sql }: ExecuteSqlVariables,
+export async function executeSql<T = any>(
+ {
+ projectRef,
+ connectionString,
+ sql,
+ }: Pick<ExecuteSqlVariables, 'projectRef' | 'connectionString' | 'sql'>,
signal?: AbortSignal
) {
if (!projectRef) {
@@ -35,7 +39,7 @@ export async function executeSql(
throw response.error
}
- return { result: response }
+ return { result: response as T }
}
export type ExecuteSqlData = Awaited<ReturnType<typeof executeSql>>
diff --git a/studio/pages/project/[ref]/editor/[id].tsx b/studio/pages/project/[ref]/editor/[id].tsx
index 0d33a04be14..bb8f7ea54ab 100644
--- a/studio/pages/project/[ref]/editor/[id].tsx
+++ b/studio/pages/project/[ref]/editor/[id].tsx
@@ -7,6 +7,7 @@ import { Alert, Button, Checkbox, IconExternalLink, Modal } from 'ui'
import type { PostgresTable, PostgresColumn } from '@supabase/postgres-meta'
import { useStore, withAuth, useUrlState, useParams } from 'hooks'
+import { Entity } from 'data/entity-types/entity-types-infinite-query'
import { Dictionary } from 'components/grid'
import { TableEditorLayout } from 'components/layouts'
import { TableGridEditor } from 'components/interfaces'
@@ -96,21 +97,27 @@ const TableEditorPage: NextPageWithLayout = () => {
setSelectedTableToEdit(undefined)
}
- const onEditTable = (table: PostgresTable) => {
+ const onEditTable = (entity: Entity) => {
setSidePanelKey('table')
setIsDuplicating(false)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToEdit(table)
}
- const onDeleteTable = (table: PostgresTable) => {
+ const onDeleteTable = (entity: Entity) => {
setIsDeleting(true)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToDelete(table)
setIsDeleteWithCascade(false)
}
- const onDuplicateTable = (table: PostgresTable) => {
+ const onDuplicateTable = (entity: Entity) => {
setSidePanelKey('table')
setIsDuplicating(true)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToEdit(table)
}
diff --git a/studio/pages/project/[ref]/editor/index.tsx b/studio/pages/project/[ref]/editor/index.tsx
index f6e8d064eb4..7d20614af77 100644
--- a/studio/pages/project/[ref]/editor/index.tsx
+++ b/studio/pages/project/[ref]/editor/index.tsx
@@ -6,6 +6,7 @@ import type { PostgresTable } from '@supabase/postgres-meta'
import { NextPageWithLayout } from 'types'
import { useStore, withAuth } from 'hooks'
+import { Entity } from 'data/entity-types/entity-types-infinite-query'
import { TableEditorLayout } from 'components/layouts'
import { EmptyState, SidePanelEditor } from 'components/interfaces/TableGridEditor'
import ConfirmationModal from 'components/ui/ConfirmationModal'
@@ -27,20 +28,26 @@ const TableEditorPage: NextPageWithLayout = () => {
setSelectedTableToEdit(undefined)
}
- const onEditTable = (table: PostgresTable) => {
+ const onEditTable = (entity: Entity) => {
setSidePanelKey('table')
setIsDuplicating(false)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToEdit(table)
}
- const onDeleteTable = (table: PostgresTable) => {
+ const onDeleteTable = (entity: Entity) => {
setIsDeleting(true)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToDelete(table)
}
- const onDuplicateTable = (table: PostgresTable) => {
+ const onDuplicateTable = (entity: Entity) => {
setSidePanelKey('table')
setIsDuplicating(true)
+
+ const table = meta.tables.byId(entity.id)
setSelectedTableToEdit(table)
}