Files
Joshen Lim 6abbb5700d Joshenlim/fe 5274 re database tables reshuffles the (#54521)
## Context

On Database > Tables, schemas with more than 50 relations reshuffle as
you scroll.
- Tables were paged by `oid`, then the merged list was re-sorted by name
on the client
- Views, materialized views and foreign tables came from three separate
unpaginated queries and were merged into the same sorted list, so the
list was never stable across pages

## Changes involved

Am hence opting to use the same query that we fetch entities in the
Table Editor for the Database > Tables page with a few tweaks
- `TableList` now uses `getEntityTypesSQL` instead of 4 separate queries
to fetch tables, views, materialised views and partition tables
- `getEntityTypesSQL` gets a new `enrich` prop which fetches additional
data that the Database > Tables page requires (e.g column count, row
count, size, etc
- Selecting "Edit" or "Duplicate" actions in the Database > Tables page
will fetch the table's details on demand
- Also fixed searching via `getEntityTypesSQL` to escape `%` and `_` in
`search` with `escapeIlikeLiteral`, otherwise searching `my_table` also
matched `myXtable`

## Performance

As with every change to SQL queries in the dashboard, we benchmark the
performance to ensure that the dashboard never runs a heavy query
against the project's DB. This just benchmarks `enrich` off vs on with
`EXPLAIN ANALYZE` on synthetic schemas of 500, 2,000 and 8,000 tables.
Execution time, median of 5 warm runs:

| Schema tables | limit 50 | limit 200 |
|---|---|---|
| 500 | +7.6 ms | +35.2 ms |
| 2,000 | +8.6 ms | +34.9 ms |
| 8,000 | +8.0 ms | +36.0 ms |

The extra cost is about 0.16 ms per row, the same at every schema size,
and the same on deep pages. It follows the page size, not the schema
size.

## To test

Create more than 50 relations in a schema (tables, views, materialized
views, a partitioned table), then on Database > Tables:

- [ ] Scroll through the list. New rows append at the bottom in
alphabetical order, with views mixed in.
- [ ] Untick and tick entity types. The list filters correctly, and
unticking all shows the empty state.
- [ ] Search `alph_` returns nothing when no name contains `alph_`, and
`zz_alpha` finds the matching rows.
- [ ] Create, edit, duplicate and delete a table. The list refreshes.
- [ ] Table Editor sidebar still lists and searches as before.
2026-12-04 14:49:17 +07:00

578 lines
24 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Link, useNavigate } from '@tanstack/react-router'
import { useDebounce, useIntersectionObserver } from '@uidotdev/usehooks'
import { useParams } from 'common'
import { noop } from 'lodash'
import {
CheckIcon,
ChevronDownIcon,
CopyIcon,
EditIcon,
EyeIcon,
MoreVerticalIcon,
PlusIcon,
SearchIcon,
TrashIcon,
XIcon,
} from 'lucide-react'
import { parseAsString, useQueryState } from 'nuqs'
import { useEffect, useRef, useState } from 'react'
import {
Button,
Card,
Checkbox,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
Label,
Popover,
PopoverContent,
PopoverTrigger,
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { ProtectedSchemaWarning } from '../ProtectedSchemaWarning'
import { buildTableEditorUrl } from '@/components/grid/SupabaseGrid.utils'
import { AlertError } from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'
import { EntityTypeIcon } from '@/components/ui/EntityTypeIcon'
import { SchemaSelector } from '@/components/ui/SchemaSelector'
import { Shortcut } from '@/components/ui/Shortcut'
import { TableRowNoResults } from '@/components/ui/TableRowNoResults'
import { useDatabasePublicationsQuery } from '@/data/database-publications/database-publications-query'
import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
import { useEntityTypesQuery } from '@/data/entity-types/entity-types-infinite-query'
import { usePrefetchEditorTablePage } from '@/data/prefetchers/project.$ref.editor.$id'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'
import { onSearchInputEscape } from '@/lib/keyboard'
import { navigateToUrl } from '@/lib/navigation'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
const isTableType = (type: ENTITY_TYPE) =>
type === ENTITY_TYPE.TABLE || type === ENTITY_TYPE.PARTITIONED_TABLE
interface TableListProps {
onAddTable: () => void
onEditTable: (table: { id: number }) => void
onDeleteTable: (table: { id: number }) => void
onDuplicateTable: (table: { id: number }) => void
}
export const TableList = ({
onDuplicateTable,
onAddTable = noop,
onEditTable = noop,
onDeleteTable = noop,
}: TableListProps) => {
const navigate = useNavigate()
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const prefetchEditorTablePage = usePrefetchEditorTablePage()
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
const [filterString, setFilterString] = useQueryState('search', parseAsString.withDefault(''))
const debouncedFilterString = useDebounce(filterString, 300)
const [visibleTypes, setVisibleTypes] = useState<string[]>(Object.values(ENTITY_TYPE))
const [schemaSelectorOpen, setSchemaSelectorOpen] = useState(false)
const searchInputRef = useRef<HTMLInputElement>(null)
const { can: canUpdateTables } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.DATABASE_WRITE
)
// Nothing to list when every type is unticked (and `filterTypes` can't be empty in the SQL)
const hasNoTypesSelected = visibleTypes.length === 0
const {
data: entitiesData,
error,
isError: isErrorEntities,
isPending: isPendingEntities,
isSuccess: isSuccessEntities,
hasNextPage: hasNextEntitiesPage,
isFetchingNextPage: isFetchingNextEntitiesPage,
fetchNextPage: fetchNextEntitiesPage,
} = useEntityTypesQuery(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
schemas: [selectedSchema],
search: debouncedFilterString,
sort: 'alphabetical',
filterTypes: visibleTypes,
limit: 50,
enrich: true,
},
{ enabled: !hasNoTypesSelected }
)
const entities = entitiesData?.pages.flatMap((page) => page.data.entities) ?? []
const [sentinelRef, sentinelEntry] = useIntersectionObserver({
threshold: 0,
rootMargin: '200px 0px 200px 0px',
})
useEffect(() => {
if (sentinelEntry?.isIntersecting && hasNextEntitiesPage && !isFetchingNextEntitiesPage) {
fetchNextEntitiesPage()
}
}, [
sentinelEntry?.isIntersecting,
hasNextEntitiesPage,
isFetchingNextEntitiesPage,
fetchNextEntitiesPage,
])
const { data: publications } = useDatabasePublicationsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
const realtimePublication = (publications ?? []).find(
(publication) => publication.name === 'supabase_realtime'
)
const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedSchema })
const canAddTables = canUpdateTables && !isSchemaLocked
useShortcut(
SHORTCUT_IDS.LIST_PAGE_FOCUS_SEARCH,
() => {
searchInputRef.current?.focus()
searchInputRef.current?.select()
},
{ label: 'Search tables' }
)
useShortcut(SHORTCUT_IDS.LIST_PAGE_RESET_FILTERS, () => {
setVisibleTypes(Object.values(ENTITY_TYPE))
setFilterString('')
})
const isError = isErrorEntities && !hasNoTypesSelected
const isLoading = isPendingEntities && !hasNoTypesSelected
const isSuccess = isSuccessEntities || hasNoTypesSelected
const hasFiltersApplied = visibleTypes.length !== 5
const formatTooltipText = (entityType: string) => {
const text =
Object.entries(ENTITY_TYPE)
.find(([, value]) => value === entityType)?.[0]
?.toLowerCase()
?.split('_')
?.join(' ') || ''
// Return sentence case (capitalize first letter only)
return text.charAt(0).toUpperCase() + text.slice(1)
}
return (
<div className="flex flex-col gap-y-4">
<div className="flex flex-col lg:flex-row lg:items-center gap-2 flex-wrap">
<Shortcut
id={SHORTCUT_IDS.LIST_PAGE_FOCUS_SCHEMA}
onTrigger={() => setSchemaSelectorOpen(true)}
side="bottom"
tooltipOpen={schemaSelectorOpen ? false : undefined}
>
<SchemaSelector
className="grow lg:grow-0 w-[180px]"
size="tiny"
showError={false}
selectedSchemaName={selectedSchema}
onSelectSchema={setSelectedSchema}
open={schemaSelectorOpen}
onOpenChange={setSchemaSelectorOpen}
/>
</Shortcut>
<Input
ref={searchInputRef}
size="tiny"
containerClassName="grow lg:grow-0 w-52"
placeholder="Search for a table"
value={filterString}
onChange={(e) => setFilterString(e.target.value)}
onKeyDown={onSearchInputEscape(filterString, setFilterString)}
icon={<SearchIcon />}
/>
<Popover>
<PopoverTrigger asChild>
<Button
size="tiny"
variant={hasFiltersApplied ? 'default' : 'dashed'}
iconRight={<ChevronDownIcon />}
>
Entity Type
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-60" 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
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 htmlFor={key} className="capitalize text-xs">
{key.toLowerCase().replace('_', ' ')}
</Label>
</div>
<Button
size="tiny"
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>
</Popover>
{!isSchemaLocked &&
(canAddTables ? (
<Shortcut
id={SHORTCUT_IDS.LIST_PAGE_NEW_ITEM}
label="Create new table"
onTrigger={() => onAddTable()}
side="bottom"
>
<Button
variant="primary"
className="w-auto ml-auto"
icon={<PlusIcon />}
onClick={() => onAddTable()}
>
New table
</Button>
</Shortcut>
) : (
<ButtonTooltip
variant="primary"
className="w-auto ml-auto"
icon={<PlusIcon />}
disabled
tooltip={{
content: {
side: 'bottom',
text: 'You need additional permissions to create tables',
},
}}
>
New table
</ButtonTooltip>
))}
</div>
{isSchemaLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="tables" />}
{isLoading && <GenericSkeletonLoader />}
{isError && <AlertError error={error} subject="Failed to retrieve tables" />}
{isSuccess && (
<div className="w-full">
<Card>
<Table>
<TableHeader>
<TableRow>
<TableHead key="icon" className="w-0 px-0!" />
<TableHead key="name" className="max-w-[160px] sm:max-w-[280px]">
Name
</TableHead>
<TableHead key="columns">Columns</TableHead>
<TableHead key="rows">Rows (Estimated)</TableHead>
<TableHead key="size">Size (Estimated)</TableHead>
<TableHead key="realtime">Realtime</TableHead>
<TableHead key="buttons"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
<>
{entities.length === 0 && filterString.length === 0 && (
<TableRow key={selectedSchema}>
<TableCell 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 ? (
<span>tables</span>
) : visibleTypes.length === 1 ? (
<span>{`${formatTooltipText(visibleTypes[0])}s`}</span>
) : (
<span>{`${visibleTypes
.slice(0, -1)
.map((x) => `${formatTooltipText(x)}s`)
.join(
', '
)}, and ${formatTooltipText(visibleTypes[visibleTypes.length - 1])}s`}</span>
)}{' '}
<span>found in the schema "</span>
{selectedSchema}
<span>"</span>
</p>
</>
)}
</TableCell>
</TableRow>
)}
{entities.length === 0 && filterString.length > 0 && (
<TableRowNoResults key={selectedSchema} colSpan={7} search={filterString} />
)}
{entities.length > 0 &&
entities.map((x) => (
<TableRow key={x.id}>
<TableCell className="w-0 pl-5! pr-1!">
<Tooltip>
<TooltipTrigger asChild className="cursor-default">
<div className="flex w-4 justify-center">
<EntityTypeIcon type={x.type} />
</div>
</TooltipTrigger>
<TooltipContent side="bottom">
{formatTooltipText(x.type)}
</TooltipContent>
</Tooltip>
</TableCell>
<TableCell className="max-w-[160px] sm:max-w-[280px]">
<div className="flex min-w-0 flex-col">
{/* only show tooltips if required, to reduce noise */}
{x.name.length > 20 ? (
<Tooltip disableHoverableContent={true}>
<TooltipTrigger
asChild
className="max-w-[95%] overflow-hidden text-ellipsis whitespace-nowrap"
>
<p>{x.name}</p>
</TooltipTrigger>
<TooltipContent side="bottom">{x.name}</TooltipContent>
</Tooltip>
) : (
<p>{x.name}</p>
)}
{x.comment !== null ? (
<span
className="max-w-md truncate text-foreground-lighter"
title={x.comment}
>
{x.comment}
</span>
) : null}
</div>
</TableCell>
<TableCell>
<p className="text-foreground-light">
{(x.columns_count ?? 0).toLocaleString()}
</p>
</TableCell>
<TableCell>
{x.live_rows_estimate != null ? (
<p className="text-foreground-light">
{x.live_rows_estimate.toLocaleString()}
</p>
) : (
<p className="text-foreground-muted">–</p>
)}
</TableCell>
<TableCell>
{x.size != null ? (
<p className="text-foreground-light">{x.size}</p>
) : (
<p className="text-foreground-muted">–</p>
)}
</TableCell>
<TableCell>
{(realtimePublication?.tables ?? []).find(
(table) => table.id === x.id
) ? (
<div className="flex items-center gap-x-2">
<CheckIcon size={16} strokeWidth={2} className="text-primary" />
<p className="text-foreground-light">Enabled</p>
</div>
) : (
<div className="flex items-center gap-x-2">
<XIcon size={16} strokeWidth={2} className="text-foreground-muted" />
<p className="text-foreground-lighter">Disabled</p>
</div>
)}
</TableCell>
<TableCell>
<div className="flex justify-end gap-2">
<Button asChild>
<Link
to="/project/$ref/database/tables/$id"
params={{ ref: ref ?? '_', id: String(x.id) }}
>
View columns
</Link>
</Button>
{!isSchemaLocked && (
<DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button
className="px-1"
icon={<MoreVerticalIcon />}
aria-label={`Table ${x.name} actions`}
/>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom">More options</TooltipContent>
</Tooltip>
<DropdownMenuContent side="bottom" align="end" className="w-40">
<DropdownMenuItem
className="flex items-center space-x-2"
onClick={() =>
void navigateToUrl(
navigate,
buildTableEditorUrl({
projectRef: project?.ref,
tableId: x.id,
schema: x.schema,
})
)
}
onMouseEnter={() =>
prefetchEditorTablePage({
id: x.id ? String(x.id) : undefined,
})
}
>
<EyeIcon size={12} />
<p>View in Table Editor</p>
</DropdownMenuItem>
{isTableType(x.type) && (
<>
<DropdownMenuSeparator />
<DropdownMenuItemTooltip
className="gap-x-2"
disabled={!canUpdateTables}
onClick={() => {
if (canUpdateTables) onEditTable(x)
}}
tooltip={{
content: {
side: 'left',
text: 'You need additional permissions to edit this table',
},
}}
>
<EditIcon size={12} />
<p>Edit table</p>
</DropdownMenuItemTooltip>
<DropdownMenuItemTooltip
key="duplicate-table"
className="gap-x-2"
disabled={!canUpdateTables}
onClick={() => {
if (canUpdateTables) onDuplicateTable(x)
}}
tooltip={{
content: {
side: 'left',
text: 'You need additional permissions to duplicate tables',
},
}}
>
<CopyIcon size={12} />
<span>Duplicate Table</span>
</DropdownMenuItemTooltip>
<DropdownMenuSeparator />
<DropdownMenuItemTooltip
disabled={!canUpdateTables || isSchemaLocked}
className="gap-x-2"
onClick={() => {
if (canUpdateTables && !isSchemaLocked) {
onDeleteTable(x)
}
}}
tooltip={{
content: {
side: 'left',
text: 'You need additional permissions to delete tables',
},
}}
>
<TrashIcon size={12} />
<p>Delete table</p>
</DropdownMenuItemTooltip>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</TableCell>
</TableRow>
))}
</>
</TableBody>
<TableFooter className="font-normal">
<TableRow ref={sentinelRef} className="border-b-0">
<TableCell colSpan={7} className="text-foreground-muted hover:bg-inherit">
{isFetchingNextEntitiesPage
? 'Loading more tables…'
: `${entities.length} ${entities.length === 1 ? 'table' : 'tables'}${
hasNextEntitiesPage ? ' loaded' : ''
}`}
</TableCell>
</TableRow>
</TableFooter>
</Table>
</Card>
</div>
)}
</div>
)
}