Skip to content

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

Joshen/fe 2187 disable default sorting in table editor for large tables (#40976)

Joshen Lim1692393e09a1
diff --git a/apps/studio/components/grid/SupabaseGrid.tsx b/apps/studio/components/grid/SupabaseGrid.tsx
index 6862463414f..20e0fa3a291 100644
--- a/apps/studio/components/grid/SupabaseGrid.tsx
+++ b/apps/studio/components/grid/SupabaseGrid.tsx
@@ -44,7 +44,7 @@ export const SupabaseGrid = ({
const gridRef = useRef<DataGridHandle>(null)
const [mounted, setMounted] = useState(false)
- const { filters, onApplyFilters } = useTableFilter()
+ const { filters } = useTableFilter()
const { sorts, onApplySorts } = useTableSort()
const roleImpersonationState = useRoleImpersonationStateSnapshot()
@@ -104,8 +104,6 @@ export const SupabaseGrid = ({
isLoading={isLoading}
isSuccess={isSuccess}
isError={isError}
- filters={filters}
- onApplyFilters={onApplyFilters}
/>
<Footer enableForeignRowsQuery={tableQueriesEnabled} />
<Shortcuts gridRef={gridRef} rows={rows} />
diff --git a/apps/studio/components/grid/components/footer/Footer.tsx b/apps/studio/components/grid/components/footer/Footer.tsx
index 38bafa91679..44259704994 100644
--- a/apps/studio/components/grid/components/footer/Footer.tsx
+++ b/apps/studio/components/grid/components/footer/Footer.tsx
@@ -1,10 +1,11 @@
+import { parseAsString, useQueryState } from 'nuqs'
+
import { useParams } from 'common'
import { GridFooter } from 'components/ui/GridFooter'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
import { useTableEditorQuery } from 'data/table-editor/table-editor-query'
import { isTableLike, isViewLike } from 'data/table-editor/table-editor-types'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { useUrlState } from 'hooks/ui/useUrlState'
import { Pagination } from './pagination/Pagination'
type FooterProps = {
@@ -15,23 +16,13 @@ export const Footer: React.FC<FooterProps> = ({ enableForeignRowsQuery = true }:
const { id: _id } = useParams()
const id = _id ? Number(_id) : undefined
const { data: project } = useSelectedProjectQuery()
+ const [selectedView, setSelectedView] = useQueryState('view', parseAsString.withDefault('data'))
const { data: entity } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id,
})
-
- const [{ view: selectedView = 'data' }, setUrlState] = useUrlState()
-
- const setSelectedView = (view: string) => {
- if (view === 'data') {
- setUrlState({ view: undefined })
- } else {
- setUrlState({ view })
- }
- }
-
const isViewSelected = isViewLike(entity)
const isTableSelected = isTableLike(entity)
diff --git a/apps/studio/components/grid/components/grid/Grid.tsx b/apps/studio/components/grid/components/grid/Grid.tsx
index 09905154e25..31eab0cdcb5 100644
--- a/apps/studio/components/grid/components/grid/Grid.tsx
+++ b/apps/studio/components/grid/components/grid/Grid.tsx
@@ -2,6 +2,7 @@ import { forwardRef, memo, Ref, useRef } from 'react'
import DataGrid, { CalculatedColumn, DataGridHandle } from 'react-data-grid'
import { ref as valtioRef } from 'valtio'
+import { useTableFilter } from 'components/grid/hooks/useTableFilter'
import { handleCopyCell } from 'components/grid/SupabaseGrid.utils'
import { formatForeignKeys } from 'components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.utils'
import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'
@@ -14,7 +15,7 @@ import { useTableEditorStateSnapshot } from 'state/table-editor'
import { useTableEditorTableStateSnapshot } from 'state/table-editor-table'
import { Button, cn } from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import type { Filter, GridProps, SupaRow } from '../../types'
+import type { GridProps, SupaRow } from '../../types'
import { useOnRowsChange } from './Grid.utils'
import { GridError } from './GridError'
import RowRenderer from './RowRenderer'
@@ -30,8 +31,6 @@ interface IGrid extends GridProps {
isLoading: boolean
isSuccess: boolean
isError: boolean
- filters: Filter[]
- onApplyFilters: (appliedFilters: Filter[]) => void
}
// [Joshen] Just for visibility this is causing some hook errors in the browser
@@ -50,13 +49,12 @@ export const Grid = memo(
isLoading,
isSuccess,
isError,
- filters,
- onApplyFilters,
},
ref: Ref<DataGridHandle> | undefined
) => {
const tableEditorSnap = useTableEditorStateSnapshot()
const snap = useTableEditorTableStateSnapshot()
+ const { filters, onApplyFilters } = useTableFilter()
const { data: org } = useSelectedOrganizationQuery()
const { data: project } = useSelectedProjectQuery()
diff --git a/apps/studio/components/grid/components/header/Header.tsx b/apps/studio/components/grid/components/header/Header.tsx
index 2cc06c56aef..95982e4d22f 100644
--- a/apps/studio/components/grid/components/header/Header.tsx
+++ b/apps/studio/components/grid/components/header/Header.tsx
@@ -73,7 +73,7 @@ export const Header = ({ customHeader, isRefetching, tableQueriesEnabled = true
) : snap.selectedRows.size > 0 ? (
<RowHeader tableQueriesEnabled={tableQueriesEnabled} />
) : (
- <DefaultHeader />
+ <DefaultHeader tableQueriesEnabled={tableQueriesEnabled} />
)}
<GridHeaderActions table={snap.originalTable} isRefetching={isRefetching} />
</div>
@@ -81,7 +81,9 @@ export const Header = ({ customHeader, isRefetching, tableQueriesEnabled = true
)
}
-const DefaultHeader = () => {
+const DefaultHeader = ({
+ tableQueriesEnabled = true,
+}: Pick<HeaderProps, 'tableQueriesEnabled'>) => {
const { ref: projectRef } = useParams()
const { data: org } = useSelectedOrganizationQuery()
@@ -104,7 +106,7 @@ const DefaultHeader = () => {
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<FilterPopover />
- <SortPopover />
+ <SortPopover tableQueriesEnabled={tableQueriesEnabled} />
</div>
{canAddNew && (
<>
@@ -231,7 +233,6 @@ type RowHeaderProps = {
}
const RowHeader = ({ tableQueriesEnabled = true }: RowHeaderProps) => {
- debugger
const { data: project } = useSelectedProjectQuery()
const tableEditorSnap = useTableEditorStateSnapshot()
const snap = useTableEditorTableStateSnapshot()
diff --git a/apps/studio/components/grid/components/header/sort/SortPopover.tsx b/apps/studio/components/grid/components/header/sort/SortPopover.tsx
index f7cc7e20400..70afe576c34 100644
--- a/apps/studio/components/grid/components/header/sort/SortPopover.tsx
+++ b/apps/studio/components/grid/components/header/sort/SortPopover.tsx
@@ -7,17 +7,26 @@ import { SortPopoverPrimitive } from './SortPopoverPrimitive'
export interface SortPopoverProps {
portal?: boolean
+ tableQueriesEnabled?: boolean
}
-export const SortPopover = ({ portal = true }: SortPopoverProps) => {
+export const SortPopover = ({ portal = true, tableQueriesEnabled }: SortPopoverProps) => {
const { urlSorts, onApplySorts } = useTableSort()
- const tableState = useTableEditorTableStateSnapshot()
- const tableName = tableState?.table?.name || ''
+
+ const snap = useTableEditorTableStateSnapshot()
+ const tableName = snap.table?.name || ''
// Convert string[] to Sort[]
const sorts = useMemo(() => {
return tableName && urlSorts ? formatSortURLParams(tableName, urlSorts) : []
}, [tableName, urlSorts])
- return <SortPopoverPrimitive portal={portal} sorts={sorts} onApplySorts={onApplySorts} />
+ return (
+ <SortPopoverPrimitive
+ portal={portal}
+ sorts={sorts}
+ onApplySorts={onApplySorts}
+ tableQueriesEnabled={tableQueriesEnabled}
+ />
+ )
}
diff --git a/apps/studio/components/grid/components/header/sort/SortPopoverPrimitive.tsx b/apps/studio/components/grid/components/header/sort/SortPopoverPrimitive.tsx
index 3a5f1d9510c..5c6e124a130 100644
--- a/apps/studio/components/grid/components/header/sort/SortPopoverPrimitive.tsx
+++ b/apps/studio/components/grid/components/header/sort/SortPopoverPrimitive.tsx
@@ -1,8 +1,18 @@
+import { THRESHOLD_COUNT } from '@supabase/pg-meta/src/query/table-row-query'
import { isEqual } from 'lodash'
import { ChevronDown, List } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useParams } from 'common'
+import { useTableFilter } from 'components/grid/hooks/useTableFilter'
import type { Sort } from 'components/grid/types'
+import { InlineLink } from 'components/ui/InlineLink'
+import { useTableRowsCountQuery } from 'data/table-rows/table-rows-count-query'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import {
+ type RoleImpersonationState,
+ useRoleImpersonationStateSnapshot,
+} from 'state/role-impersonation-state'
import { useTableEditorTableStateSnapshot } from 'state/table-editor-table'
import {
Button,
@@ -11,6 +21,7 @@ import {
PopoverTrigger_Shadcn_,
Popover_Shadcn_,
} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { DropdownControl } from '../../common/DropdownControl'
import SortRow from './SortRow'
@@ -19,6 +30,8 @@ export interface SortPopoverPrimitiveProps {
sorts: Sort[]
onApplySorts: (sorts: Sort[]) => void
portal?: boolean
+ defaultOpen?: boolean
+ tableQueriesEnabled?: boolean
}
/**
@@ -35,10 +48,20 @@ export const SortPopoverPrimitive = ({
sorts,
onApplySorts,
portal = true,
+ defaultOpen = false,
+ tableQueriesEnabled = true,
}: SortPopoverPrimitiveProps) => {
- const [open, setOpen] = useState(false)
+ const { ref } = useParams()
+ const { filters } = useTableFilter()
+ const { data: project } = useSelectedProjectQuery()
+ const roleImpersonationState = useRoleImpersonationStateSnapshot()
+
const snap = useTableEditorTableStateSnapshot()
+ const tableName = snap.table?.name || ''
+ const tableSchema = snap.table.schema || ''
+ const [open, setOpen] = useState(defaultOpen)
+ const [showWarning, setShowWarning] = useState(false)
// Local state for draft sorts
const [localSorts, setLocalSorts] = useState<Sort[]>(sorts)
@@ -47,21 +70,18 @@ export const SortPopoverPrimitive = ({
// Track if we're in the middle of applying our own changes
const isApplyingRef = useRef(false)
- // Sync with props when they change, but in a smarter way
- useEffect(() => {
- // If we're in the middle of applying changes, don't sync from props
- if (isApplyingRef.current) {
- isApplyingRef.current = false
- return
- }
-
- // If the props changed unexpectedly (not due to our own actions)
- // then we should update our local state
- if (!isEqual(sorts, lastSortsRef.current)) {
- setLocalSorts(sorts)
- lastSortsRef.current = sorts
- }
- }, [sorts])
+ const { data: countData } = useTableRowsCountQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ tableId: snap.table.id,
+ filters,
+ enforceExactCount: snap.enforceExactCount,
+ roleImpersonationState: roleImpersonationState as RoleImpersonationState,
+ },
+ { keepPreviousData: true, enabled: tableQueriesEnabled }
+ )
+ const isLargeTable = (countData?.count ?? 0) > THRESHOLD_COUNT
// Fix: Use localSorts for button text, not sorts
const displayButtonText =
@@ -180,67 +200,128 @@ export const SortPopoverPrimitive = ({
return `sort-${sort.table}-${sort.column}-${index}`
}
- const content = (
- <div className="space-y-2 py-2">
- {localSorts.map((sort, index) => (
- <SortRow
- key={getSortRowKey(sort, index)}
- index={index}
- columnName={sort.column}
- sort={sort}
- onDelete={onDeleteSort}
- onToggle={onToggleSort}
- onDrag={onDragSort}
- />
- ))}
- {localSorts.length === 0 && (
- <div className="space-y-1 px-3">
- <h5 className="text-xs text-foreground-light">No sorts applied to this view</h5>
- <p className="text-xs text-foreground-lighter">Add a column below to sort the view</p>
- </div>
- )}
-
- <PopoverSeparator_Shadcn_ />
- <div className="px-3 flex flex-row justify-between">
- {dropdownOptions && dropdownOptions.length > 0 ? (
- <DropdownControl
- options={dropdownOptions}
- onSelect={onAddSort}
- side="bottom"
- align="start"
- >
- <Button
- asChild
- type="dashed"
- iconRight={<ChevronDown size="14" className="text-foreground-light" />}
- className="sb-grid-dropdown__item-trigger"
- data-testid="table-editor-pick-column-to-sort-button"
- >
- <span>Pick {localSorts.length > 1 ? 'another' : 'a'} column to sort by</span>
- </Button>
- </DropdownControl>
- ) : (
- <p className="text-sm text-foreground-light">All columns have been added</p>
- )}
- <div className="flex items-center">
- <Button disabled={!hasChanges} type="default" onClick={onSelectApplySorts}>
- Apply sorting
- </Button>
- </div>
- </div>
- </div>
- )
+ // Sync with props when they change, but in a smarter way
+ useEffect(() => {
+ // If we're in the middle of applying changes, don't sync from props
+ if (isApplyingRef.current) {
+ isApplyingRef.current = false
+ return
+ }
+
+ // If the props changed unexpectedly (not due to our own actions)
+ // then we should update our local state
+ if (!isEqual(sorts, lastSortsRef.current)) {
+ setLocalSorts(sorts)
+ lastSortsRef.current = sorts
+ }
+ }, [sorts])
return (
- <Popover_Shadcn_ modal={false} open={open} onOpenChange={setOpen}>
- <PopoverTrigger_Shadcn_ asChild>
- <Button type={localSorts.length > 0 ? 'link' : 'text'} icon={<List />}>
- {displayButtonText}
- </Button>
- </PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0 w-96" side="bottom" align="start" portal={portal}>
- {content}
- </PopoverContent_Shadcn_>
- </Popover_Shadcn_>
+ <>
+ <Popover_Shadcn_ modal={false} open={open} onOpenChange={setOpen}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button type={localSorts.length > 0 ? 'link' : 'text'} icon={<List />}>
+ {displayButtonText}
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0 w-96" side="bottom" align="start" portal={portal}>
+ <div className="space-y-2 py-2">
+ {localSorts.map((sort, index) => (
+ <SortRow
+ key={getSortRowKey(sort, index)}
+ index={index}
+ columnName={sort.column}
+ sort={sort}
+ onDelete={onDeleteSort}
+ onToggle={onToggleSort}
+ onDrag={onDragSort}
+ />
+ ))}
+ {localSorts.length === 0 && (
+ <div className="space-y-1 px-3">
+ <h5 className="text-xs text-foreground-light">No sorts applied to this view</h5>
+ <p className="text-xs text-foreground-lighter">
+ Add a column below to sort the view
+ </p>
+ </div>
+ )}
+
+ <PopoverSeparator_Shadcn_ />
+ <div className="px-3 flex flex-row justify-between">
+ {dropdownOptions && dropdownOptions.length > 0 ? (
+ <DropdownControl
+ options={dropdownOptions}
+ onSelect={onAddSort}
+ side="bottom"
+ align="start"
+ >
+ <Button
+ asChild
+ type="dashed"
+ iconRight={<ChevronDown size="14" className="text-foreground-light" />}
+ className="sb-grid-dropdown__item-trigger"
+ data-testid="table-editor-pick-column-to-sort-button"
+ >
+ <span>Pick {localSorts.length > 1 ? 'another' : 'a'} column to sort by</span>
+ </Button>
+ </DropdownControl>
+ ) : (
+ <p className="text-sm text-foreground-light">All columns have been added</p>
+ )}
+ <div className="flex items-center">
+ <Button
+ disabled={!hasChanges}
+ type="default"
+ onClick={() => {
+ if (isLargeTable && localSorts.length > 0) {
+ // [Joshen] Note we're only checking PKs - unable to check indexes properly
+ // as we are not able to deterministically figure out which columns the indexes are applied to
+ const hasSortNotPK = localSorts.some(
+ (x) => !snap.table.columns.find((y) => x.column === y.name)?.isPrimaryKey
+ )
+ if (hasSortNotPK) setShowWarning(true)
+ } else onSelectApplySorts()
+ }}
+ >
+ Apply sorting
+ </Button>
+ </div>
+ </div>
+ </div>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+
+ <ConfirmationModal
+ size="medium"
+ variant="warning"
+ visible={showWarning}
+ confirmLabel="Confirm"
+ title="Sorting on a large table"
+ onConfirm={() => {
+ onSelectApplySorts()
+ setShowWarning(false)
+ }}
+ onCancel={() => {
+ setLocalSorts(sorts)
+ setShowWarning(false)
+ }}
+ alert={{
+ base: { variant: 'warning' },
+ title: 'Be careful with sorting on unindexed columns',
+ description:
+ 'This may adversely impact your database, in particular if your table has a large number of rows - use with caution.',
+ }}
+ >
+ <p className="text-foreground-light text-sm">
+ We highly recommend only sorting on columns which are{' '}
+ <InlineLink
+ href={`/project/${ref}/database/indexes?search=${tableName}&schema=${tableSchema}`}
+ >
+ indexed
+ </InlineLink>
+ , such as your primary key columns.
+ </p>
+ </ConfirmationModal>
+ </>
)
}
diff --git a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
index 51df142e932..2231354a314 100644
--- a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
+++ b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx
@@ -1,7 +1,7 @@
import { sortBy } from 'lodash'
import { AlertCircle, Search, Trash } from 'lucide-react'
-import { parseAsBoolean, useQueryState } from 'nuqs'
-import { useEffect, useRef, useState } from 'react'
+import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
+import { useEffect, useRef } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
@@ -12,14 +12,13 @@ import ShimmeringLoader, { GenericSkeletonLoader } from 'components/ui/Shimmerin
import { useDatabaseIndexDeleteMutation } from 'data/database-indexes/index-delete-mutation'
import { useIndexesQuery, type DatabaseIndex } from 'data/database-indexes/indexes-query'
import { useSchemasQuery } from 'data/database/schemas-query'
+import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'
import {
Button,
Card,
- Input,
SidePanel,
Table,
TableBody,
@@ -28,7 +27,8 @@ import {
TableHeader,
TableRow,
} from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { Input } from 'ui-patterns/DataInputs/Input'
+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
import { ProtectedSchemaWarning } from '../ProtectedSchemaWarning'
import CreateIndexSidePanel from './CreateIndexSidePanel'
@@ -36,7 +36,7 @@ const Indexes = () => {
const { data: project } = useSelectedProjectQuery()
const { schema: urlSchema, table } = useParams()
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useQueryState('search', parseAsString.withDefault(''))
const { selectedSchema, setSelectedSchema } = useQuerySchemaState()
const deletingIndexNameRef = useRef<string | null>(null)
@@ -184,7 +184,7 @@ const Indexes = () => {
</TableRow>
</TableHeader>
<TableBody>
- {sortedIndexes.length === 0 && search.length === 0 && (
+ {indexes.length === 0 && search.length === 0 && (
<TableRow>
<TableCell colSpan={4}>
<p className="text-sm text-foreground">No indexes created yet</p>
@@ -194,7 +194,7 @@ const Indexes = () => {
</TableCell>
</TableRow>
)}
- {sortedIndexes.length === 0 && search.length > 0 && (
+ {indexes.length === 0 && search.length > 0 && (
<TableRow>
<TableCell colSpan={4}>
<p className="text-sm text-foreground">No results found</p>