Skip to content

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

Refactor queue operations to not mutate the query client to simplify implementation (#43964)

Joshen Lim4b5038ef9e47
diff --git a/apps/studio/components/grid/SupabaseGrid.tsx b/apps/studio/components/grid/SupabaseGrid.tsx
index 04990fd8d49..eae690d9f60 100644
--- a/apps/studio/components/grid/SupabaseGrid.tsx
+++ b/apps/studio/components/grid/SupabaseGrid.tsx
@@ -1,4 +1,4 @@
-import { keepPreviousData, useQueryClient } from '@tanstack/react-query'
+import { keepPreviousData } from '@tanstack/react-query'
import { useParams } from 'common'
import { isMsSqlForeignTable } from 'data/table-editor/table-editor-types'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
@@ -15,10 +15,7 @@ import { useTableEditorStateSnapshot } from 'state/table-editor'
import { QueuedOperation } from 'state/table-editor-operation-queue.types'
import { useTableEditorTableStateSnapshot } from 'state/table-editor-table'
-import {
- useIsQueueOperationsEnabled,
- useIsTableFilterBarEnabled,
-} from '../interfaces/App/FeaturePreview/FeaturePreviewContext'
+import { useIsTableFilterBarEnabled } from '../interfaces/App/FeaturePreview/FeaturePreviewContext'
import { Shortcuts } from './components/common/Shortcuts'
import { Footer } from './components/footer/Footer'
import { Grid } from './components/grid/Grid'
@@ -29,7 +26,7 @@ import { useTableFilter } from './hooks/useTableFilter'
import { useTableSort } from './hooks/useTableSort'
import { validateMsSqlSorting } from './MsSqlValidation'
import { GridProps } from './types'
-import { reapplyOptimisticUpdates } from './utils/queueOperationUtils'
+import { formatGridDataWithOperationValues } from './utils/queueOperationUtils'
export const SupabaseGrid = ({
customHeader,
@@ -43,9 +40,6 @@ export const SupabaseGrid = ({
const { id: _id } = useParams()
const tableId = _id ? Number(_id) : undefined
- const isQueueOperationsEnabled = useIsQueueOperationsEnabled()
-
- const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()
const tableEditorSnap = useTableEditorStateSnapshot()
const snap = useTableEditorTableStateSnapshot()
@@ -73,7 +67,6 @@ export const SupabaseGrid = ({
isError,
isPending: isLoading,
isRefetching,
- dataUpdatedAt,
} = useTableRowsQuery(
{
projectRef: project?.ref,
@@ -100,39 +93,9 @@ export const SupabaseGrid = ({
if (!mounted) setMounted(true)
}, [])
- // Re-apply optimistic updates when table data is loaded/refetched
- // This ensures pending changes remain visible when switching tabs or after data refresh
- // Skip re-applying during save to avoid race condition where refetch completes before queue clears
- const isSaving = tableEditorSnap.operationQueue.status === 'saving'
- useEffect(() => {
- if (
- isSuccess &&
- project?.ref &&
- tableId &&
- isQueueOperationsEnabled &&
- tableEditorSnap.hasPendingOperations &&
- !isSaving
- ) {
- reapplyOptimisticUpdates({
- queryClient,
- projectRef: project.ref,
- tableId,
- operations: tableEditorSnap.operationQueue.operations as readonly QueuedOperation[],
- })
- }
- }, [
- isSuccess,
- dataUpdatedAt,
- project?.ref,
- tableId,
- isQueueOperationsEnabled,
- tableEditorSnap.hasPendingOperations,
- tableEditorSnap.operationQueue.operations,
- queryClient,
- isSaving,
- ])
-
- const rows = data?.rows ?? EMPTY_ARR
+ const operations = tableEditorSnap.operationQueue.operations as QueuedOperation[]
+ const baseRows = data?.rows ?? EMPTY_ARR
+ const rows = formatGridDataWithOperationValues({ operations, rows: baseRows })
const HeaderComponent = newFilterBarEnabled ? HeaderNew : Header
diff --git a/apps/studio/components/grid/SupabaseGrid.utils.ts b/apps/studio/components/grid/SupabaseGrid.utils.ts
index 65765ff8072..37d5fe74082 100644
--- a/apps/studio/components/grid/SupabaseGrid.utils.ts
+++ b/apps/studio/components/grid/SupabaseGrid.utils.ts
@@ -1,18 +1,19 @@
import AwesomeDebouncePromise from 'awesome-debounce-promise'
-import { compact } from 'lodash'
-import { useEffect, useMemo } from 'react'
-import { CalculatedColumn, CellKeyboardEvent } from 'react-data-grid'
-
-import type { Filter, SavedState } from 'components/grid/types'
+import type { Filter, SavedState, SupaRow } from 'components/grid/types'
import { Entity, isTableLike } from 'data/table-editor/table-editor-types'
import { BASE_PATH } from 'lib/constants'
+import { compact } from 'lodash'
import { useSearchParams } from 'next/navigation'
import { parseAsNativeArrayOf, parseAsString, useQueryStates } from 'nuqs'
+import { useEffect, useMemo } from 'react'
+import { CalculatedColumn, CellKeyboardEvent } from 'react-data-grid'
import { copyToClipboard } from 'ui'
+
import { FilterOperatorOptions } from './components/header/filter/Filter.constants'
import { STORAGE_KEY_PREFIX } from './constants'
import type { Sort, SupaColumn, SupaTable } from './types'
import { formatClipboardValue } from './utils/common'
+import { QueuedOperation, QueuedOperationType } from '@/state/table-editor-operation-queue.types'
export function formatSortURLParams(tableName: string, sort?: string[]): Sort[] {
if (Array.isArray(sort)) {
diff --git a/apps/studio/components/grid/components/grid/Grid.utils.tsx b/apps/studio/components/grid/components/grid/Grid.utils.tsx
index 5d7affc816e..161bf2bd297 100644
--- a/apps/studio/components/grid/components/grid/Grid.utils.tsx
+++ b/apps/studio/components/grid/components/grid/Grid.utils.tsx
@@ -131,9 +131,7 @@ export function useOnRowsChange(rows: SupaRow[]) {
if (isQueueOperationsEnabled) {
queueCellEditWithOptimisticUpdate({
- queryClient,
queueOperation: tableEditorSnap.queueOperation,
- projectRef: project.ref,
tableId: snap.table.id,
table: snap.originalTable,
row: previousRow,
@@ -167,7 +165,6 @@ export function useOnRowsChange(rows: SupaRow[]) {
snap.originalTable,
snap.table.id,
tableEditorSnap,
- queryClient,
]
)
}
diff --git a/apps/studio/components/grid/components/header/Header.tsx b/apps/studio/components/grid/components/header/Header.tsx
index 95dce9dd577..055ac85976c 100644
--- a/apps/studio/components/grid/components/header/Header.tsx
+++ b/apps/studio/components/grid/components/header/Header.tsx
@@ -283,7 +283,6 @@ const RowHeader = ({ tableQueriesEnabled = true }: RowHeaderProps) => {
queueRowDeletesWithOptimisticUpdate({
rows,
table: snap.originalTable,
- queryClient,
queueOperation: tableEditorSnap.queueOperation,
projectRef: project?.ref,
})
diff --git a/apps/studio/components/grid/components/header/HeaderNew.tsx b/apps/studio/components/grid/components/header/HeaderNew.tsx
index c675bef87f5..fb12e9fe143 100644
--- a/apps/studio/components/grid/components/header/HeaderNew.tsx
+++ b/apps/studio/components/grid/components/header/HeaderNew.tsx
@@ -275,7 +275,6 @@ const RowHeader = ({ tableQueriesEnabled = true }: RowHeaderProps) => {
queueRowDeletesWithOptimisticUpdate({
rows,
table: snap.originalTable,
- queryClient,
queueOperation: tableEditorSnap.queueOperation,
projectRef: project?.ref,
})
diff --git a/apps/studio/components/grid/components/menu/RowContextMenu.tsx b/apps/studio/components/grid/components/menu/RowContextMenu.tsx
index e136f227410..1873509ca03 100644
--- a/apps/studio/components/grid/components/menu/RowContextMenu.tsx
+++ b/apps/studio/components/grid/components/menu/RowContextMenu.tsx
@@ -25,7 +25,6 @@ type RowContextMenuProps = {
type RowContextMenuItemProps = ItemParams<{ rowIdx: number }, string>
export const RowContextMenu = ({ rows }: RowContextMenuProps) => {
- const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()
const tableEditorSnap = useTableEditorStateSnapshot()
const snap = useTableEditorTableStateSnapshot()
@@ -46,7 +45,6 @@ export const RowContextMenu = ({ rows }: RowContextMenuProps) => {
queueRowDeletesWithOptimisticUpdate({
rows: [row],
table: snap.originalTable,
- queryClient,
queueOperation: tableEditorSnap.queueOperation,
projectRef: project?.ref,
})
diff --git a/apps/studio/components/grid/utils/queueOperationUtils.test.ts b/apps/studio/components/grid/utils/queueOperationUtils.test.ts
index 3905ca2d764..46ec20de044 100644
--- a/apps/studio/components/grid/utils/queueOperationUtils.test.ts
+++ b/apps/studio/components/grid/utils/queueOperationUtils.test.ts
@@ -1,10 +1,17 @@
-import { describe, test, expect } from 'vitest'
-import { generateTableChangeKey, rowMatchesIdentifiers, applyCellEdit } from './queueOperationUtils'
+import { describe, expect, test } from 'vitest'
+
+import type { SupaRow } from '../types'
import {
- type NewEditCellContentOperation,
+ formatGridDataWithOperationValues,
+ generateTableChangeKey,
+ rowMatchesIdentifiers,
+} from './queueOperationUtils'
+import {
+ QueuedOperationType,
type NewAddRowOperation,
type NewDeleteRowOperation,
- QueuedOperationType,
+ type NewEditCellContentOperation,
+ type QueuedOperation,
} from '@/state/table-editor-operation-queue.types'
describe('generateTableChangeKey', () => {
@@ -145,101 +152,257 @@ describe('rowMatchesIdentifiers', () => {
})
})
-describe('applyCellEdit', () => {
- test('should apply cell edit to matching row', () => {
- const rows = [
- { idx: 0, id: 1, name: 'old' },
- { idx: 1, id: 2, name: 'test' },
- ]
- const result = applyCellEdit(rows, 'name', { id: 1 }, 'new')
- expect(result).toEqual([
- { idx: 0, id: 1, name: 'new' },
- { idx: 1, id: 2, name: 'test' },
- ])
+describe('formatGridDataWithOperationValues', () => {
+ const makeRow = (idx: number, data: Record<string, unknown> = {}): SupaRow => ({
+ idx,
+ ...data,
})
- test('should not affect non-matching rows', () => {
- const rows = [
- { idx: 0, id: 1, name: 'old' },
- { idx: 1, id: 2, name: 'test' },
- ]
- const result = applyCellEdit(rows, 'name', { id: 3 }, 'new')
- expect(result).toEqual([
- { idx: 0, id: 1, name: 'old' },
- { idx: 1, id: 2, name: 'test' },
- ])
+ const makeEditOp = (
+ overrides: Partial<QueuedOperation & { payload: any }> = {}
+ ): QueuedOperation => ({
+ id: 'op-1',
+ tableId: 1,
+ timestamp: Date.now(),
+ type: QueuedOperationType.EDIT_CELL_CONTENT,
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'old',
+ newValue: 'new',
+ table: {} as any,
+ },
+ ...overrides,
})
- test('should create new row instances for matching row', () => {
- const rows = [{ idx: 0, id: 1, name: 'old' }]
- const result = applyCellEdit(rows, 'name', { id: 1 }, 'new')
- expect(result[0]).not.toBe(rows[0])
- expect(result[0]).toEqual({ idx: 0, id: 1, name: 'new' })
+ const makeDeleteOp = (
+ rowIdentifiers: Record<string, unknown>,
+ originalRow: SupaRow
+ ): QueuedOperation => ({
+ id: 'op-del',
+ tableId: 1,
+ timestamp: Date.now(),
+ type: QueuedOperationType.DELETE_ROW,
+ payload: { rowIdentifiers, originalRow, table: {} as any },
})
- test('should not modify original array', () => {
- const rows = [{ idx: 0, id: 1, name: 'old' }]
- const originalRows = [...rows]
- applyCellEdit(rows, 'name', { id: 1 }, 'new')
- expect(rows).toEqual(originalRows)
+ const makeAddOp = (tempId: string, rowData: Record<string, unknown> = {}): QueuedOperation => ({
+ id: 'op-add',
+ tableId: 1,
+ timestamp: Date.now(),
+ type: QueuedOperationType.ADD_ROW,
+ payload: {
+ tempId,
+ rowData: { idx: Number(tempId), __tempId: tempId, ...rowData },
+ table: {} as any,
+ },
})
- test('should handle multiple matching rows with composite keys', () => {
- const rows = [
- { idx: 0, id: 1, org_id: 10, name: 'old1' },
- { idx: 1, id: 1, org_id: 20, name: 'old2' },
- { idx: 2, id: 2, org_id: 10, name: 'old3' },
- ]
- const result = applyCellEdit(rows, 'name', { id: 1, org_id: 10 }, 'new')
- expect(result).toEqual([
- { idx: 0, id: 1, org_id: 10, name: 'new' },
- { idx: 1, id: 1, org_id: 20, name: 'old2' },
- { idx: 2, id: 2, org_id: 10, name: 'old3' },
- ])
+ test('should return rows unchanged when there are no operations', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' }), makeRow(1, { id: 2, name: 'Bob' })]
+ const result = formatGridDataWithOperationValues({ operations: [], rows })
+ expect(result).toEqual(rows)
})
- test('should handle setting value to null', () => {
- const rows = [{ idx: 0, id: 1, name: 'test' }]
- const result = applyCellEdit(rows, 'name', { id: 1 }, null)
- expect(result).toEqual([{ idx: 0, id: 1, name: null }])
+ test('should apply EDIT_CELL_CONTENT to matching row', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' }), makeRow(1, { id: 2, name: 'Bob' })]
+ const op = makeEditOp({
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result[0]).toEqual({ idx: 0, id: 1, name: 'Updated' })
+ expect(result[1]).toEqual(rows[1])
})
- test('should handle setting value to undefined', () => {
- const rows = [{ idx: 0, id: 1, name: 'test' }]
- const result = applyCellEdit(rows, 'name', { id: 1 }, undefined)
- expect(result).toEqual([{ idx: 0, id: 1, name: undefined }])
+ test('should not modify rows when EDIT_CELL_CONTENT does not match any row', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' })]
+ const op = makeEditOp({
+ payload: {
+ rowIdentifiers: { id: 999 },
+ columnName: 'name',
+ oldValue: 'old',
+ newValue: 'new',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result).toEqual(rows)
+ })
+
+ test('should apply multiple EDIT_CELL_CONTENT operations to different rows', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' }), makeRow(1, { id: 2, name: 'Bob' })]
+ const op1 = makeEditOp({
+ id: 'op-1',
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated Alice',
+ table: {} as any,
+ },
+ })
+ const op2 = makeEditOp({
+ id: 'op-2',
+ payload: {
+ rowIdentifiers: { id: 2 },
+ columnName: 'name',
+ oldValue: 'Bob',
+ newValue: 'Updated Bob',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op1, op2], rows })
+ expect(result[0].name).toBe('Updated Alice')
+ expect(result[1].name).toBe('Updated Bob')
+ })
+
+ test('last edit wins when multiple operations target the same row', () => {
+ // Each operation spreads from the original row, so only the last op's column change is preserved
+ const rows = [makeRow(0, { id: 1, name: 'Alice', email: '[email protected]' })]
+ const op1 = makeEditOp({
+ id: 'op-1',
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated',
+ table: {} as any,
+ },
+ })
+ const op2 = makeEditOp({
+ id: 'op-2',
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'email',
+ oldValue: '[email protected]',
+ newValue: '[email protected]',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op1, op2], rows })
+ // The second op overwrites the first since both spread from the original row
+ expect(result[0].name).toBe('Alice')
+ expect(result[0].email).toBe('[email protected]')
})
- test('should handle numeric values', () => {
- const rows = [{ idx: 0, id: 1, count: 0 }]
- const result = applyCellEdit(rows, 'count', { id: 1 }, 42)
- expect(result).toEqual([{ idx: 0, id: 1, count: 42 }])
+ test('should mark matching row as deleted for DELETE_ROW operation', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' }), makeRow(1, { id: 2, name: 'Bob' })]
+ const op = makeDeleteOp({ id: 1 }, rows[0])
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result[0].__isDeleted).toBe(true)
+ expect(result[1].__isDeleted).toBeUndefined()
})
- test('should handle object values', () => {
- const rows = [{ idx: 0, id: 1, data: null }]
- const newValue = { nested: { value: 123 } }
- const result = applyCellEdit(rows, 'data', { id: 1 }, newValue)
- expect(result).toEqual([{ idx: 0, id: 1, data: newValue }])
+ test('should not modify rows when DELETE_ROW does not match any row', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' })]
+ const op = makeDeleteOp({ id: 999 }, makeRow(0, { id: 999 }))
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result[0].__isDeleted).toBeUndefined()
})
- test('should handle empty rows array', () => {
- const rows: any[] = []
- const result = applyCellEdit(rows, 'name', { id: 1 }, 'new')
- expect(result).toEqual([])
+ test('should not mutate the original rows array', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' })]
+ const op = makeEditOp({
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(rows[0].name).toBe('Alice')
+ expect(result[0].name).toBe('Updated')
})
- test('should update all matching rows with same identifier', () => {
+ test('should handle mixed operation types', () => {
const rows = [
- { idx: 0, id: 1, name: 'row1' },
- { idx: 1, id: 1, name: 'row2' },
- { idx: 2, id: 2, name: 'row3' },
+ makeRow(0, { id: 1, name: 'Alice' }),
+ makeRow(1, { id: 2, name: 'Bob' }),
+ makeRow(2, { id: 3, name: 'Charlie' }),
]
- const result = applyCellEdit(rows, 'name', { id: 1 }, 'updated')
- expect(result).toEqual([
- { idx: 0, id: 1, name: 'updated' },
- { idx: 1, id: 1, name: 'updated' },
- { idx: 2, id: 2, name: 'row3' },
- ])
+
+ const editOp = makeEditOp({
+ payload: {
+ rowIdentifiers: { id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated Alice',
+ table: {} as any,
+ },
+ })
+ const deleteOp = makeDeleteOp({ id: 2 }, rows[1])
+
+ const result = formatGridDataWithOperationValues({
+ operations: [editOp, deleteOp],
+ rows,
+ })
+
+ expect(result[0].name).toBe('Updated Alice')
+ expect(result[1].__isDeleted).toBe(true)
+ expect(result[2]).toEqual(rows[2])
+ })
+
+ test('should prepend new row for ADD_ROW operation', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' })]
+ const op = makeAddOp('-100', { name: 'New Row' })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result).toHaveLength(2)
+ expect(result[0]).toMatchObject({ __tempId: '-100', name: 'New Row' })
+ expect(result[1]).toEqual(rows[0])
+ })
+
+ test('should update existing pending row for ADD_ROW with same tempId', () => {
+ const rows: SupaRow[] = [
+ { idx: -100, __tempId: '-100', name: 'Original' } as any,
+ makeRow(1, { id: 1, name: 'Alice' }),
+ ]
+ const op = makeAddOp('-100', { name: 'Updated' })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result).toHaveLength(2)
+ expect(result[0]).toMatchObject({ __tempId: '-100', name: 'Updated' })
+ })
+
+ test('should handle multiple ADD_ROW operations', () => {
+ const rows = [makeRow(0, { id: 1, name: 'Alice' })]
+ const op1 = makeAddOp('-100', { name: 'Row 1' })
+ const op2 = makeAddOp('-200', { name: 'Row 2' })
+
+ const result = formatGridDataWithOperationValues({ operations: [op1, op2], rows })
+ expect(result).toHaveLength(3)
+ expect(result[0]).toMatchObject({ __tempId: '-200', name: 'Row 2' })
+ expect(result[1]).toMatchObject({ __tempId: '-100', name: 'Row 1' })
+ })
+
+ test('should handle EDIT_CELL_CONTENT with composite primary keys', () => {
+ const rows = [makeRow(0, { tenant_id: 'a', user_id: 1, name: 'Alice' })]
+ const op = makeEditOp({
+ payload: {
+ rowIdentifiers: { tenant_id: 'a', user_id: 1 },
+ columnName: 'name',
+ oldValue: 'Alice',
+ newValue: 'Updated',
+ table: {} as any,
+ },
+ })
+
+ const result = formatGridDataWithOperationValues({ operations: [op], rows })
+ expect(result[0].name).toBe('Updated')
})
})
diff --git a/apps/studio/components/grid/utils/queueOperationUtils.ts b/apps/studio/components/grid/utils/queueOperationUtils.ts
index d9a0ffe401d..86b047369c1 100644
--- a/apps/studio/components/grid/utils/queueOperationUtils.ts
+++ b/apps/studio/components/grid/utils/queueOperationUtils.ts
@@ -1,10 +1,7 @@
-import type { QueryClient } from '@tanstack/react-query'
import { isTableLike, type Entity } from 'data/table-editor/table-editor-types'
-import { tableRowKeys } from 'data/table-rows/keys'
-import type { TableRowsData } from 'data/table-rows/table-rows-query'
import type { Dictionary } from 'types'
-import { isPendingAddRow, PendingAddRow, PendingDeleteRow, SupaRow } from '../types'
+import { isPendingAddRow, PendingAddRow, SupaRow } from '../types'
import {
EditCellContentOperation,
NewQueuedOperation,
@@ -63,68 +60,12 @@ export function rowMatchesIdentifiers(
return identifierEntries.every(([key, value]) => row[key] === value)
}
-export function applyCellEdit(
- rows: SupaRow[],
- columnName: string,
- rowIdentifiers: Dictionary<unknown>,
- newValue: unknown
-): SupaRow[] {
- return rows.map((row) => {
- const rowMatches = rowMatchesIdentifiers(row, rowIdentifiers)
- if (rowMatches) {
- return { ...row, [columnName]: newValue }
- }
- return row
- })
-}
-
-export function applyRowAdd(
- rows: SupaRow[],
- tempId: string,
- idx: number,
- rowData: Dictionary<unknown>
-): (PendingAddRow | SupaRow)[] {
- // Check if row with this tempId already exists
- const existingIndex = rows.findIndex((row) => isPendingAddRow(row) && row.__tempId === tempId)
- if (existingIndex >= 0) {
- // Update existing row in place
- return rows.map((row, index) => {
- if (index === existingIndex) {
- return { ...row, ...rowData, __tempId: tempId }
- }
- return row
- })
- }
-
- const newRow: PendingAddRow = {
- idx,
- ...rowData,
- __tempId: tempId,
- }
- return [newRow, ...rows]
-}
-
-export function markRowAsDeleted(
- rows: SupaRow[],
- rowIdentifiers: Dictionary<unknown>
-): (PendingDeleteRow | SupaRow)[] {
- return rows.map((row): PendingDeleteRow | SupaRow => {
- const rowMatches = rowMatchesIdentifiers(row, rowIdentifiers)
- if (rowMatches) {
- return { ...row, __isDeleted: true }
- }
- return row
- })
-}
-
export function removeRow(rows: SupaRow[], rowIdentifiers: Dictionary<unknown>): SupaRow[] {
return rows.filter((row) => !rowMatchesIdentifiers(row, rowIdentifiers))
}
interface QueueCellEditParams {
- queryClient: QueryClient
queueOperation: (operation: NewQueuedOperation) => void
- projectRef: string
tableId: number
table: Entity
row: SupaRow
@@ -136,9 +77,7 @@ interface QueueCellEditParams {
}
export function queueCellEditWithOptimisticUpdate({
- queryClient,
queueOperation,
- projectRef,
tableId,
table,
row,
@@ -167,22 +106,10 @@ export function queueCellEditWithOptimisticUpdate({
enumArrayColumns,
},
})
-
- // Apply optimistic update to the UI
- const queryKey = tableRowKeys.tableRows(projectRef, { table: { id: tableId } })
- queryClient.setQueriesData<TableRowsData>({ queryKey }, (old) => {
- if (!old) return old
- return {
- ...old,
- rows: applyCellEdit(old.rows, columnName, rowIdentifiers, newValue),
- }
- })
}
interface QueueRowAddParams {
- queryClient: QueryClient
queueOperation: (operation: NewQueuedOperation) => void
- projectRef: string
tableId: number
table: Entity
rowData: PendingAddRow
@@ -190,9 +117,7 @@ interface QueueRowAddParams {
}
export function queueRowAddWithOptimisticUpdate({
- queryClient,
queueOperation,
- projectRef,
tableId,
table,
rowData,
@@ -213,73 +138,58 @@ export function queueRowAddWithOptimisticUpdate({
enumArrayColumns,
},
})
-
- // Apply optimistic update to the UI
- const queryKey = tableRowKeys.tableRows(projectRef, { table: { id: tableId } })
- queryClient.setQueriesData<TableRowsData>({ queryKey }, (old) => {
- if (!old) return old
- return {
- ...old,
- rows: applyRowAdd(old.rows, tempId, idx, rowData),
- }
- })
-}
-
-interface ReapplyOptimisticUpdatesParams {
- queryClient: QueryClient
- projectRef: string
- tableId: number
- operations: readonly QueuedOperation[]
}
-export function reapplyOptimisticUpdates({
- queryClient,
- projectRef,
- tableId,
+export const formatGridDataWithOperationValues = ({
operations,
-}: ReapplyOptimisticUpdatesParams) {
- const tableOperations = operations.filter((op) => op.tableId === tableId)
- if (tableOperations.length === 0) return
-
- const queryKey = tableRowKeys.tableRows(projectRef, { table: { id: tableId } })
- queryClient.setQueriesData<TableRowsData>({ queryKey }, (old) => {
- if (!old) return old
-
- let rows = [...old.rows]
- for (const operation of tableOperations) {
- switch (operation.type) {
- case QueuedOperationType.EDIT_CELL_CONTENT: {
- const { rowIdentifiers, columnName, newValue } = operation.payload
- rows = applyCellEdit(rows, columnName, rowIdentifiers, newValue)
- break
- }
- case QueuedOperationType.ADD_ROW: {
- const { tempId, rowData } = operation.payload
- // Derive idx from tempId (tempId is stringified negative timestamp)
- const idx = Number(tempId)
- rows = applyRowAdd(rows, tempId, idx, rowData)
- break
- }
- case QueuedOperationType.DELETE_ROW: {
- const { rowIdentifiers } = operation.payload
- rows = markRowAsDeleted(rows, rowIdentifiers)
- break
- }
- default: {
- // Need to explicitly handle other operations
- throw new Error(`Unknown operation type: ${(operation as never)['type']}`)
+ rows,
+}: {
+ operations: QueuedOperation[]
+ rows: SupaRow[]
+}) => {
+ const formattedRows = rows.slice()
+
+ operations.forEach((op) => {
+ if (op.type === QueuedOperationType.EDIT_CELL_CONTENT) {
+ const { rowIdentifiers, columnName, newValue } = op.payload
+ const rowMatches = rows.find((row) => rowMatchesIdentifiers(row, rowIdentifiers))
+ if (rowMatches) {
+ formattedRows[rowMatches.idx] = { ...rowMatches, [columnName]: newValue }
+ }
+ } else if (op.type === QueuedOperationType.ADD_ROW) {
+ const { tempId, rowData } = op.payload
+ const idx = Number(tempId)
+
+ // Check if row with this tempId already exists
+ const existingIndex = formattedRows.findIndex(
+ (row) => isPendingAddRow(row) && row.__tempId === tempId
+ )
+ if (existingIndex >= 0) {
+ // Update existing row in place
+ formattedRows[existingIndex] = {
+ ...formattedRows[existingIndex],
+ ...rowData,
+ __tempId: tempId,
}
+ } else {
+ const newRow: PendingAddRow = { ...rowData, idx, __tempId: tempId }
+ formattedRows.unshift(newRow)
+ }
+ } else if (op.type === QueuedOperationType.DELETE_ROW) {
+ const { rowIdentifiers } = op.payload
+ const rowMatches = rows.find((row) => rowMatchesIdentifiers(row, rowIdentifiers))
+ if (rowMatches) {
+ formattedRows[rowMatches.idx] = { ...rowMatches, __isDeleted: true }
}
}
-
- return { ...old, rows }
})
+
+ return formattedRows
}
interface QueueRowDeletesParams {
rows: SupaRow[]
table: Entity
- queryClient: QueryClient
queueOperation: (operation: NewQueuedOperation) => void
projectRef: string | undefined
}
@@ -291,7 +201,6 @@ interface QueueRowDeletesParams {
export function queueRowDeletesWithOptimisticUpdate({
rows,
table,
- queryClient,
queueOperation,
projectRef,
}: QueueRowDeletesParams): void {
@@ -327,24 +236,5 @@ export function queueRowDeletesWithOptimisticUpdate({
table,
},
})
-
- const queryKey = tableRowKeys.tableRows(projectRef, { table: { id: table.id } })
- queryClient.setQueriesData<TableRowsData>({ queryKey }, (old) => {
- if (!old) return old
-
- // For pending add rows, remove completely
- if (isPendingAddRow(row)) {
- return {
- ...old,
- rows: removeRow(old.rows, rowIdentifiers),
- }
- }
-
- // For existing rows, mark as deleted
- return {
- ...old,
- rows: markRowAsDeleted(old.rows, rowIdentifiers),
- }
- })
}
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 088655e23a6..30db82f074c 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -1,5 +1,5 @@
-import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
import * as Sentry from '@sentry/nextjs'
+import type { PostgresColumn, PostgresTable } from '@supabase/postgres-meta'
import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import {
@@ -276,9 +276,7 @@ export const SidePanelEditor = ({
// Queue the ADD_ROW operation if queue operations feature is enabled
if (isQueueOperationsEnabled && selectedTable.primary_keys.length > 0) {
queueRowAddWithOptimisticUpdate({
- queryClient,
queueOperation: snap.queueOperation,
- projectRef: project.ref,
tableId: selectedTable.id,
table: selectedTable as unknown as Entity,
rowData: payload,
@@ -330,9 +328,7 @@ export const SidePanelEditor = ({
const oldValue = row[changedColumn]
queueCellEditWithOptimisticUpdate({
- queryClient,
queueOperation: snap.queueOperation,
- projectRef: project.ref,
tableId: selectedTable.id,
// Cast to Entity - the queue save mutation only uses id, name, schema
table: selectedTable as unknown as Entity,