Skip to content

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

Set the primary key as the default sort if no other sort exists (#27097)

Terry Suttond6f9cb53f90d
diff --git a/apps/studio/components/grid/constants.ts b/apps/studio/components/grid/constants.ts
index 31559971291..cc99ab00137 100644
--- a/apps/studio/components/grid/constants.ts
+++ b/apps/studio/components/grid/constants.ts
@@ -8,9 +8,6 @@ export const TOTAL_ROWS_RESET = -2
export const SELECT_COLUMN_KEY = 'supabase-grid-select-row'
export const ADD_COLUMN_KEY = 'supabase-grid-add-column'
-export const ERROR_PRIMARY_KEY_NOTFOUND =
- 'Please add a primary key column to your table to update or delete rows'
-
const RLS_ACKNOWLEDGED_KEY = 'supabase-acknowledge-rls-warning'
export const rlsAcknowledgedKey = (tableID?: string | number) =>
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 7f51502a6e7..6dd75fb8690 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -7,7 +7,7 @@ import toast from 'react-hot-toast'
import { useParams } from 'common'
import { parseSupaTable, SupabaseGrid, SupaTable } from 'components/grid'
-import { ERROR_PRIMARY_KEY_NOTFOUND } from 'components/grid/constants'
+import { Markdown } from 'components/interfaces/Markdown'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { Loading } from 'components/ui/Loading'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
@@ -23,9 +23,11 @@ import useEntityType from 'hooks/misc/useEntityType'
import type { TableLike } from 'hooks/misc/useTable'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
import { EMPTY_ARR } from 'lib/void'
+import { ExternalLink } from 'lucide-react'
import { useGetImpersonatedRole } from 'state/role-impersonation-state'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import type { Dictionary, SchemaView } from 'types'
+import { Button, toast as UiToast } from 'ui'
import GridHeaderActions from './GridHeaderActions'
import NotFoundState from './NotFoundState'
import { SidePanelEditor } from './SidePanelEditor'
@@ -230,7 +232,35 @@ const TableGridEditor = ({
const configuration = { identifiers }
if (Object.keys(identifiers).length === 0) {
- toast.error(ERROR_PRIMARY_KEY_NOTFOUND)
+ return UiToast({
+ variant: 'default',
+ style: { flexDirection: 'column' },
+ title: (
+ <Markdown
+ className="text-foreground [&>p]:m-0"
+ content="Unable to update row as table has no primary keys"
+ />
+ ) as any,
+ description: (
+ <Markdown
+ className="[&>p]:m-0"
+ content="Add a primary key column to your table first to serve as a unique identifier for each row before updating or deleting the row."
+ />
+ ),
+ action: (
+ <div className="w-full flex gap-x-2 !mx-0 mt-3">
+ <Button asChild type="outline" icon={<ExternalLink />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://supabase.com/docs/guides/database/tables#primary-keys"
+ >
+ Documentation
+ </a>
+ </Button>
+ </div>
+ ),
+ })
}
mutateUpdateTableRow({
diff --git a/apps/studio/data/table-rows/table-row-delete-mutation.tsx b/apps/studio/data/table-rows/table-row-delete-mutation.tsx
index 1957b5a3330..dc9240ab7cb 100644
--- a/apps/studio/data/table-rows/table-row-delete-mutation.tsx
+++ b/apps/studio/data/table-rows/table-row-delete-mutation.tsx
@@ -82,6 +82,7 @@ export const useTableRowDeleteMutation = ({
async onError(data, variables, context) {
if (onError === undefined) {
const { table, rows } = variables
+ const isPkError = data.message.includes('Please add a primary key column')
const isFkError = data.message.includes('violates foreign key constraint')
const isMultipleRows = rows.length > 1
@@ -124,6 +125,36 @@ export const useTableRowDeleteMutation = ({
</div>
),
})
+ } else if (isPkError) {
+ UiToast({
+ variant: 'default',
+ style: { flexDirection: 'column' },
+ title: (
+ <Markdown
+ className="text-foreground [&>p]:m-0"
+ content="Unable to delete row(s) as table has no primary keys"
+ />
+ ) as any,
+ description: (
+ <Markdown
+ className="[&>p]:m-0"
+ content="Add a primary key column to your table first to serve as a unique identifier for each row before updating or deleting the row."
+ />
+ ),
+ action: (
+ <div className="w-full flex gap-x-2 !mx-0 mt-3">
+ <Button asChild type="outline" icon={<ExternalLink />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://supabase.com/docs/guides/database/tables#primary-keys"
+ >
+ Documentation
+ </a>
+ </Button>
+ </div>
+ ),
+ })
} else {
toast.error(`Failed to delete table row: ${data.message}`)
}
diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.ts
index d04933191c9..5d0e3e56c54 100644
--- a/apps/studio/data/table-rows/table-rows-query.ts
+++ b/apps/studio/data/table-rows/table-rows-query.ts
@@ -34,6 +34,13 @@ type GetTableRowsArgs = {
// [Joshen] We can probably make this reasonably high, but for now max aim to load 10kb
export const MAX_CHARACTERS = 10 * KB
+// return the primary key column if exists, otherwise return the first column
+// to use as a default sort
+const getDefaultOrderByColumn = (table: SupaTable) => {
+ return table.columns.find((column) => column.isPrimaryKey)?.name || table.columns[0]?.name
+}
+
+// Updated fetchAllTableRows function
export const fetchAllTableRows = async ({
projectRef,
connectionString,
@@ -64,9 +71,18 @@ export const fetchAllTableRows = async ({
const value = formatFilterValue(table, filter)
queryChains = queryChains.filter(filter.column, filter.operator, value)
})
- sorts.forEach((sort) => {
- queryChains = queryChains.order(sort.table, sort.column, sort.ascending, sort.nullsFirst)
- })
+
+ // If sorts is empty, use the primary key as the default sort
+ if (sorts.length === 0) {
+ const primaryKey = getDefaultOrderByColumn(table)
+ if (primaryKey) {
+ queryChains = queryChains.order(table.name, primaryKey, true, true)
+ }
+ } else {
+ sorts.forEach((sort) => {
+ queryChains = queryChains.order(sort.table, sort.column, sort.ascending, sort.nullsFirst)
+ })
+ }
// Starting from page 0, fetch 500 records per call
let page = -1
@@ -138,9 +154,19 @@ export const getTableRowsSqlQuery = ({
const value = formatFilterValue(table, x)
queryChains = queryChains.filter(x.column, x.operator, value)
})
- sorts.forEach((x) => {
- queryChains = queryChains.order(x.table, x.column, x.ascending, x.nullsFirst)
- })
+
+ // If sorts is empty, use the primary key as the default sort
+ if (sorts.length === 0) {
+ const primaryKey = getDefaultOrderByColumn(table)
+
+ if (primaryKey) {
+ queryChains = queryChains.order(table.name, primaryKey, true, true)
+ }
+ } else {
+ sorts.forEach((x) => {
+ queryChains = queryChains.order(x.table, x.column, x.ascending, x.nullsFirst)
+ })
+ }
// getPagination is expecting to start from 0
const { from, to } = getPagination((page ?? 1) - 1, limit)
diff --git a/apps/studio/data/table-rows/utils.ts b/apps/studio/data/table-rows/utils.ts
index b5796abed1b..fb453c91943 100644
--- a/apps/studio/data/table-rows/utils.ts
+++ b/apps/studio/data/table-rows/utils.ts
@@ -1,5 +1,4 @@
import type { Filter, ServiceError, SupaTable } from 'components/grid'
-import { ERROR_PRIMARY_KEY_NOTFOUND } from 'components/grid/constants'
import { isNumericalColumn } from 'components/grid/utils'
import type { Table } from 'data/tables/table-query'
@@ -24,7 +23,9 @@ export function getPrimaryKeys({ table }: { table: Table }): {
} {
const pkColumns = table.primary_keys
if (!pkColumns || pkColumns.length == 0) {
- return { error: { message: ERROR_PRIMARY_KEY_NOTFOUND } }
+ return {
+ error: { message: 'Please add a primary key column to your table to update or delete rows' },
+ }
}
return { primaryKeys: pkColumns.map((x) => x.name) }
}