Skip to content

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

Chore/gracefully handle large text or json in table editor (#26792)

Joshen Lim0a0f2260f9a4
diff --git a/apps/studio/components/grid/SupabaseGrid.tsx b/apps/studio/components/grid/SupabaseGrid.tsx
index 62bdca74830..0d15e15667b 100644
--- a/apps/studio/components/grid/SupabaseGrid.tsx
+++ b/apps/studio/components/grid/SupabaseGrid.tsx
@@ -1,10 +1,10 @@
-import { useParams } from 'common'
import { useEffect, useRef, useState } from 'react'
import { DataGridHandle } from 'react-data-grid'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { createPortal } from 'react-dom'
+import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useTableRowsQuery } from 'data/table-rows/table-rows-query'
import { useUrlState } from 'hooks'
@@ -22,10 +22,10 @@ import Footer from './components/footer/Footer'
import { Grid } from './components/grid'
import Header from './components/header/Header'
import { RowContextMenu } from './components/menu'
+import { STORAGE_KEY_PREFIX } from './constants'
import { StoreProvider, useDispatch, useTrackedState } from './store'
-import type { SupabaseGridProps } from './types'
import { InitialStateType } from './store/reducers'
-import { STORAGE_KEY_PREFIX } from './constants'
+import type { SupabaseGridProps } from './types'
import { getGridColumns } from './utils/gridColumns'
function onLoadStorage(storageRef: string, tableName: string, schema?: string | null) {
diff --git a/apps/studio/components/grid/components/editor/JsonEditor.tsx b/apps/studio/components/grid/components/editor/JsonEditor.tsx
index 694bf7e4916..8b7523ed9cc 100644
--- a/apps/studio/components/grid/components/editor/JsonEditor.tsx
+++ b/apps/studio/components/grid/components/editor/JsonEditor.tsx
@@ -1,12 +1,29 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
-import type { RenderEditCellProps } from 'react-data-grid'
+import { PostgresTable } from '@supabase/postgres-meta'
+import { isNil } from 'lodash'
+import { Maximize } from 'lucide-react'
import { useCallback, useState } from 'react'
-import { IconMaximize, Popover } from 'ui'
+import type { RenderEditCellProps } from 'react-data-grid'
+import toast from 'react-hot-toast'
+import { useParams } from 'common'
import { BlockKeys, MonacoEditor, NullValue } from 'components/grid/components/common'
import { useTrackedState } from 'components/grid/store'
-import { prettifyJSON, tryParseJson, removeJSONTrailingComma } from 'lib/helpers'
-import { isNil } from 'lodash'
+import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
+import { useSelectedProject } from 'hooks'
+import useTable from 'hooks/misc/useTable'
+import { prettifyJSON, removeJSONTrailingComma, tryParseJson } from 'lib/helpers'
+import { Popover, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_ } from 'ui'
+import { TruncatedWarningOverlay } from '.'
+
+const verifyJSON = (value: string) => {
+ try {
+ JSON.parse(value)
+ return true
+ } catch (err) {
+ return false
+ }
+}
interface JsonEditorProps<TRow, TSummaryRow = unknown>
extends RenderEditCellProps<TRow, TSummaryRow> {
@@ -14,6 +31,19 @@ interface JsonEditorProps<TRow, TSummaryRow = unknown>
onExpandEditor: (column: string, row: TRow) => void
}
+const tryFormatInitialValue = (value: string) => {
+ try {
+ const jsonValue = JSON.parse(value)
+ return JSON.stringify(jsonValue)
+ } catch (err) {
+ if (typeof value === 'string') {
+ return value.replaceAll(`\"`, `"`)
+ } else {
+ return JSON.stringify(value)
+ }
+ }
+}
+
export const JsonEditor = <TRow, TSummaryRow = unknown>({
row,
column,
@@ -22,27 +52,69 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
onExpandEditor,
}: JsonEditorProps<TRow, TSummaryRow>) => {
const state = useTrackedState()
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
+ const { data: selectedTable } = useTable(id)
+ const project = useSelectedProject()
const gridColumn = state.gridColumns.find((x) => x.name == column.key)
- const initialValue = row[column.key as keyof TRow] as unknown
- const jsonString = prettifyJSON(!isNil(initialValue) ? JSON.stringify(initialValue) : '')
+ const initialValue = row[column.key as keyof TRow] as string
+ const jsonString = prettifyJSON(!isNil(initialValue) ? tryFormatInitialValue(initialValue) : '')
+ const isTruncated =
+ typeof initialValue === 'string' &&
+ initialValue.endsWith('...') &&
+ initialValue.length > MAX_CHARACTERS
const [isPopoverOpen, setIsPopoverOpen] = useState(true)
const [value, setValue] = useState<string | null>(jsonString)
+ const { mutate: getCellValue, isLoading, isSuccess } = useGetCellValueMutation()
+
+ const loadFullValue = () => {
+ if (selectedTable === undefined || project === undefined) return
+ if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ return toast('Unable to load value as table has no primary keys')
+ }
+
+ const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ return { ...a, [b.name]: (row as any)[b.name] }
+ }, {})
+
+ getCellValue(
+ {
+ table: { schema: selectedTable.schema, name: selectedTable.name },
+ column: column.name as string,
+ pkMatch,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ {
+ onSuccess: (data) => {
+ setValue(JSON.stringify(data))
+ },
+ }
+ )
+ }
+
const cancelChanges = useCallback(() => {
if (isEditable) onRowChange(row, true)
setIsPopoverOpen(false)
}, [])
- const saveChanges = useCallback((newValue: string | null) => {
- const updatedValue = newValue !== null ? removeJSONTrailingComma(newValue) : newValue
- if (updatedValue !== value) commitChange(newValue)
- }, [])
+ const saveChanges = useCallback(
+ (newValue: string | null) => {
+ const updatedValue = newValue !== null ? removeJSONTrailingComma(newValue) : newValue
+ if (updatedValue !== value) {
+ commitChange(newValue)
+ } else {
+ setIsPopoverOpen(false)
+ }
+ },
+ [isSuccess]
+ )
const onChange = (_value: string | undefined) => {
if (!isEditable) return
-
if (!_value || _value == '') setValue(null)
else setValue(_value)
}
@@ -79,61 +151,65 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
sideOffset={-35}
className="rounded-none"
overlay={
- <BlockKeys value={value} onEscape={cancelChanges} onEnter={saveChanges}>
- <MonacoEditor
- width={`${gridColumn?.width || column.width}px`}
- value={value ?? ''}
- language="json"
- readOnly={!isEditable}
- onChange={onChange}
- />
- <div className="flex items-start justify-between p-2 bg-surface-200 space-x-2">
- {isEditable ? (
- <div className="space-y-1">
- <div className="flex items-center space-x-2">
- <div className="px-1.5 py-[2.5px] rounded bg-selection border border-strong flex items-center justify-center">
- <span className="text-[10px]">⏎</span>
+ isTruncated && !isSuccess ? (
+ <div
+ style={{ width: `${gridColumn?.width || column.width}px` }}
+ className="flex items-center justify-center flex-col relative"
+ >
+ <MonacoEditor
+ readOnly
+ onChange={() => {}}
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ language="markdown"
+ />
+ <TruncatedWarningOverlay isLoading={isLoading} loadFullValue={loadFullValue} />
+ </div>
+ ) : (
+ <BlockKeys value={value} onEscape={cancelChanges} onEnter={saveChanges}>
+ <MonacoEditor
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ language="json"
+ readOnly={!isEditable}
+ onChange={onChange}
+ />
+ <div className="flex items-start justify-between p-2 bg-surface-200 gap-x-2">
+ {isEditable && (
+ <div className="space-y-1">
+ <div className="flex items-center space-x-2">
+ <div className="px-1.5 py-[2.5px] rounded bg-selection border border-strong flex items-center justify-center">
+ <span className="text-[10px]">⏎</span>
+ </div>
+ <p className="text-xs text-foreground-light">Save changes</p>
</div>
- <p className="text-xs text-foreground-light">Save changes</p>
- </div>
- <div className="flex items-center space-x-2">
- <div className="px-1 py-[2.5px] rounded bg-selection border border-strong flex items-center justify-center">
- <span className="text-[10px]">Esc</span>
+ <div className="flex items-center space-x-2">
+ <div className="px-1 py-[2.5px] rounded bg-selection border border-strong flex items-center justify-center">
+ <span className="text-[10px]">Esc</span>
+ </div>
+ <p className="text-xs text-foreground-light">Cancel changes</p>
</div>
- <p className="text-xs text-foreground-light">Cancel changes</p>
</div>
- </div>
- ) : (
- <div />
- )}
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger>
- <div
- className={[
- 'border border-strong rounded p-1 flex items-center justify-center',
- 'transition cursor-pointer bg-selection hover:bg-border-strong',
- ].join(' ')}
- onClick={() => onSelectExpand()}
- >
- <IconMaximize size={12} strokeWidth={2} />
- </div>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
+ )}
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
<div
className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
+ 'border border-strong rounded p-1 flex items-center justify-center',
+ 'transition cursor-pointer bg-selection hover:bg-border-strong',
].join(' ')}
+ onClick={() => onSelectExpand()}
>
- <span className="text-xs text-foreground">Expand editor</span>
+ <Maximize size={12} strokeWidth={2} />
</div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- </div>
- </BlockKeys>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom" align="center">
+ <span>Expand editor</span>
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ </div>
+ </BlockKeys>
+ )
}
>
<div
@@ -147,12 +223,3 @@ export const JsonEditor = <TRow, TSummaryRow = unknown>({
</Popover>
)
}
-
-const verifyJSON = (value: string) => {
- try {
- JSON.parse(value)
- return true
- } catch (err) {
- return false
- }
-}
diff --git a/apps/studio/components/grid/components/editor/TextEditor.tsx b/apps/studio/components/grid/components/editor/TextEditor.tsx
index 590cd3fd5b0..3579233e76b 100644
--- a/apps/studio/components/grid/components/editor/TextEditor.tsx
+++ b/apps/studio/components/grid/components/editor/TextEditor.tsx
@@ -1,7 +1,22 @@
-import * as Tooltip from '@radix-ui/react-tooltip'
-import { useCallback, useState } from 'react'
+import { PostgresTable } from '@supabase/postgres-meta'
import type { RenderEditCellProps } from 'react-data-grid'
-import { Button, IconMaximize, Popover } from 'ui'
+import toast from 'react-hot-toast'
+
+import { useParams } from 'common'
+import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
+import { useSelectedProject } from 'hooks'
+import useTable from 'hooks/misc/useTable'
+import { Maximize } from 'lucide-react'
+import { useCallback, useState } from 'react'
+import {
+ Button,
+ Popover,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+ Tooltip_Shadcn_,
+} from 'ui'
+import { TruncatedWarningOverlay } from '.'
import { useTrackedState } from '../../store'
import { BlockKeys, EmptyValue, MonacoEditor, NullValue } from '../common'
@@ -18,20 +33,59 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
onExpandEditor: (column: string, row: TRow) => void
}) => {
const state = useTrackedState()
- const [isPopoverOpen, setIsPopoverOpen] = useState(true)
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
+ const { data: selectedTable } = useTable(id)
+ const project = useSelectedProject()
+
const gridColumn = state.gridColumns.find((x) => x.name == column.key)
const initialValue = row[column.key as keyof TRow] as unknown as string
+ const [isPopoverOpen, setIsPopoverOpen] = useState(true)
const [value, setValue] = useState<string | null>(initialValue)
+ const { mutate: getCellValue, isLoading, isSuccess } = useGetCellValueMutation()
+
+ const isTruncated =
+ typeof initialValue === 'string' &&
+ initialValue.endsWith('...') &&
+ initialValue.length > MAX_CHARACTERS
+
+ const loadFullValue = () => {
+ if (selectedTable === undefined || project === undefined) return
+ if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ return toast('Unable to load value as table has no primary keys')
+ }
+
+ const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ return { ...a, [b.name]: (row as any)[b.name] }
+ }, {})
+
+ getCellValue(
+ {
+ table: { schema: selectedTable.schema, name: selectedTable.name },
+ column: column.name as string,
+ pkMatch,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ { onSuccess: (data) => setValue(data) }
+ )
+ }
+
const cancelChanges = useCallback(() => {
if (isEditable) onRowChange(row, true)
setIsPopoverOpen(false)
}, [])
- const saveChanges = useCallback((newValue: string | null) => {
- if (isEditable) onRowChange({ ...row, [column.key]: newValue }, true)
- setIsPopoverOpen(false)
- }, [])
+ const saveChanges = useCallback(
+ (newValue: string | null) => {
+ if (isEditable && newValue !== value) {
+ onRowChange({ ...row, [column.key]: newValue }, true)
+ }
+ setIsPopoverOpen(false)
+ },
+ [isSuccess]
+ )
const onSelectExpand = () => {
cancelChanges()
@@ -41,9 +95,8 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
})
}
- function onChange(_value: string | undefined) {
+ const onChange = (_value: string | undefined) => {
if (!isEditable) return
-
if (!_value) setValue('')
else setValue(_value)
}
@@ -56,70 +109,72 @@ export const TextEditor = <TRow, TSummaryRow = unknown>({
sideOffset={-35}
className="rounded-none"
overlay={
- <BlockKeys value={value} onEscape={cancelChanges} onEnter={saveChanges}>
- <MonacoEditor
- width={`${gridColumn?.width || column.width}px`}
- value={value ?? ''}
- readOnly={!isEditable}
- onChange={onChange}
- />
- {isEditable && (
- <div className="flex items-start justify-between p-2 bg-surface-200 space-x-2">
- <div className="space-y-1">
- <div className="flex items-center space-x-2">
- <div className="px-1.5 py-[2.5px] rounded bg-surface-300 border border-strong flex items-center justify-center">
- <span className="text-[10px]">⏎</span>
+ isTruncated && !isSuccess ? (
+ <div
+ style={{ width: `${gridColumn?.width || column.width}px` }}
+ className="flex items-center justify-center flex-col relative"
+ >
+ <MonacoEditor
+ readOnly
+ onChange={() => {}}
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ language="markdown"
+ />
+ <TruncatedWarningOverlay isLoading={isLoading} loadFullValue={loadFullValue} />
+ </div>
+ ) : (
+ <BlockKeys value={value} onEscape={cancelChanges} onEnter={saveChanges}>
+ <MonacoEditor
+ width={`${gridColumn?.width || column.width}px`}
+ value={value ?? ''}
+ readOnly={!isEditable}
+ onChange={onChange}
+ />
+ {isEditable && (
+ <div className="flex items-start justify-between p-2 bg-surface-200 space-x-2">
+ <div className="space-y-1">
+ <div className="flex items-center space-x-2">
+ <div className="px-1.5 py-[2.5px] rounded bg-surface-300 border border-strong flex items-center justify-center">
+ <span className="text-[10px]">⏎</span>
+ </div>
+ <p className="text-xs text-foreground-light">Save changes</p>
</div>
- <p className="text-xs text-foreground-light">Save changes</p>
- </div>
- <div className="flex items-center space-x-2">
- <div className="px-1 py-[2.5px] rounded bg-surface-300 border border-strong flex items-center justify-center">
- <span className="text-[10px]">Esc</span>
+ <div className="flex items-center space-x-2">
+ <div className="px-1 py-[2.5px] rounded bg-surface-300 border border-strong flex items-center justify-center">
+ <span className="text-[10px]">Esc</span>
+ </div>
+ <p className="text-xs text-foreground-light">Cancel changes</p>
</div>
- <p className="text-xs text-foreground-light">Cancel changes</p>
</div>
- </div>
- <div className="flex flex-col items-end gap-y-1">
- <div>
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
+ <div className="flex flex-col items-end gap-y-1">
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
<Button
type="default"
className="px-1"
onClick={() => onSelectExpand()}
- icon={<IconMaximize size={12} strokeWidth={2} />}
+ icon={<Maximize size={12} strokeWidth={2} />}
/>
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Expand editor</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom">Expand editor</TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ {isNullable && (
+ <Button
+ asChild
+ htmlType="button"
+ type="default"
+ size="tiny"
+ onClick={() => saveChanges(null)}
+ >
+ <div>Set to NULL</div>
+ </Button>
+ )}
</div>
- {isNullable && (
- <Button
- asChild
- htmlType="button"
- type="default"
- size="tiny"
- onClick={() => saveChanges(null)}
- >
- <div>Set to NULL</div>
- </Button>
- )}
</div>
- </div>
- )}
- </BlockKeys>
+ )}
+ </BlockKeys>
+ )
}
>
<div
diff --git a/apps/studio/components/grid/components/editor/index.ts b/apps/studio/components/grid/components/editor/index.ts
deleted file mode 100644
index 4869badf6da..00000000000
--- a/apps/studio/components/grid/components/editor/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export * from './BooleanEditor'
-export * from './DateEditor'
-export * from './DateTimeEditor'
-export * from './JsonEditor'
-export * from './NumberEditor'
-export * from './SelectEditor'
-export * from './TextEditor'
-export * from './TimeEditor'
diff --git a/apps/studio/components/grid/components/editor/index.tsx b/apps/studio/components/grid/components/editor/index.tsx
new file mode 100644
index 00000000000..c4881491269
--- /dev/null
+++ b/apps/studio/components/grid/components/editor/index.tsx
@@ -0,0 +1,39 @@
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
+import { Button, cn } from 'ui'
+
+export * from './BooleanEditor'
+export * from './DateEditor'
+export * from './DateTimeEditor'
+export * from './JsonEditor'
+export * from './NumberEditor'
+export * from './SelectEditor'
+export * from './TextEditor'
+export * from './TimeEditor'
+
+export const TruncatedWarningOverlay = ({
+ isLoading,
+ loadFullValue,
+}: {
+ isLoading: boolean
+ loadFullValue: () => void
+}) => {
+ return (
+ <div
+ className={cn(
+ 'absolute top-0 left-0 flex items-center justify-center flex-col gap-y-3',
+ 'text-xs w-full h-full px-3 text-center',
+ 'bg-default/80 backdrop-blur-[1.5px]'
+ )}
+ >
+ <div className="flex flex-col gap-y-1">
+ <p>Value is larger than {MAX_CHARACTERS.toLocaleString()} characters</p>
+ <p className="text-foreground-light">
+ You may try to render the entire value, but your browser may run into performance issues
+ </p>
+ </div>
+ <Button type="default" loading={isLoading} onClick={loadFullValue}>
+ Load full value
+ </Button>
+ </div>
+ )
+}
diff --git a/apps/studio/components/grid/components/formatter/JsonFormatter.tsx b/apps/studio/components/grid/components/formatter/JsonFormatter.tsx
index 21d5df8828d..3e12bfe7db4 100644
--- a/apps/studio/components/grid/components/formatter/JsonFormatter.tsx
+++ b/apps/studio/components/grid/components/formatter/JsonFormatter.tsx
@@ -1,16 +1,25 @@
-import * as React from 'react'
+import { PropsWithChildren } from 'react'
import type { RenderCellProps } from 'react-data-grid'
+
import type { SupaRow } from '../../types'
import { EmptyValue, NullValue } from '../common'
-export const JsonFormatter = (p: React.PropsWithChildren<RenderCellProps<SupaRow, unknown>>) => {
+export const JsonFormatter = (p: PropsWithChildren<RenderCellProps<SupaRow, unknown>>) => {
let value = p.row[p.column.key]
if (value === null) return <NullValue />
if (value === '') return <EmptyValue />
- try {
- value = JSON.stringify(value)
- } catch (err) {}
- return <>{value}</>
+ // [Joshen] With reference to table-rows-query, we're only pulling max n characters on text/jsonb columns
+ // If column value is longer, value will be concatenated with ..., and we just want to make sure the JSON
+ // still renders seemingly like JSON in the grid
+ const isTruncated = typeof value === 'string' && value.endsWith('...')
+ if (isTruncated) return <>{value}</>
+
+ try {
+ const jsonValue = JSON.parse(value)
+ return <>{JSON.stringify(jsonValue)}</>
+ } catch (err) {
+ return <>{JSON.stringify(value)}</>
+ }
}
diff --git a/apps/studio/components/grid/utils/gridColumns.tsx b/apps/studio/components/grid/utils/gridColumns.tsx
index d04773f0ef1..8bc3534bb4f 100644
--- a/apps/studio/components/grid/utils/gridColumns.tsx
+++ b/apps/studio/components/grid/utils/gridColumns.tsx
@@ -1,18 +1,5 @@
import { CalculatedColumn } from 'react-data-grid'
-import type { ColumnType, SupaColumn, SupaRow, SupaTable } from '../types'
-import {
- isArrayColumn,
- isBoolColumn,
- isCiTextColumn,
- isDateColumn,
- isDateTimeColumn,
- isEnumColumn,
- isForeignKeyColumn,
- isJsonColumn,
- isNumericalColumn,
- isTextColumn,
- isTimeColumn,
-} from './types'
+
import {
BooleanEditor,
DateEditor,
@@ -25,14 +12,28 @@ import {
TimeEditor,
TimeWithTimezoneEditor,
} from 'components/grid/components/editor'
-import { AddColumn, ColumnHeader, SelectColumn } from 'components/grid/components/grid'
-import { COLUMN_MIN_WIDTH } from 'components/grid/constants'
import {
BooleanFormatter,
DefaultFormatter,
ForeignKeyFormatter,
JsonFormatter,
} from 'components/grid/components/formatter'
+import { AddColumn, ColumnHeader, SelectColumn } from 'components/grid/components/grid'
+import { COLUMN_MIN_WIDTH } from 'components/grid/constants'
+import type { ColumnType, SupaColumn, SupaRow, SupaTable } from '../types'
+import {
+ isArrayColumn,
+ isBoolColumn,
+ isCiTextColumn,
+ isDateColumn,
+ isDateTimeColumn,
+ isEnumColumn,
+ isForeignKeyColumn,
+ isJsonColumn,
+ isNumericalColumn,
+ isTextColumn,
+ isTimeColumn,
+} from './types'
export const ESTIMATED_CHARACTER_PIXEL_WIDTH = 9
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
index f09076ef328..dc36f696942 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/InputField.tsx
@@ -1,9 +1,20 @@
import { includes, noop } from 'lodash'
-import { Button, IconEdit2, IconLink, Input, Listbox, Select } from 'ui'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Input,
+ Listbox,
+ Select,
+} from 'ui'
+import { Edit, Edit2, Link } from 'lucide-react'
import { DATETIME_TYPES, JSON_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'
import { DateTimeInput } from './DateTimeInput'
import type { RowField } from './RowEditor.types'
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
export interface InputFieldProps {
field: RowField
@@ -11,6 +22,7 @@ export interface InputFieldProps {
isEditable?: boolean
onUpdateField?: (changes: object) => void
onEditJson?: (data: any) => void
+ onEditText?: (data: any) => void
onSelectForeignKey?: () => void
}
@@ -20,6 +32,7 @@ const InputField = ({
isEditable = true,
onUpdateField = noop,
onEditJson = noop,
+ onEditText = noop,
onSelectForeignKey = noop,
}: InputFieldProps) => {
if (field.enums.length > 0) {
@@ -103,7 +116,7 @@ const InputField = ({
className="mr-1"
htmlType="button"
onClick={onSelectForeignKey}
- icon={<IconLink />}
+ icon={<Link />}
>
Select record
</Button>
@@ -113,15 +126,27 @@ const InputField = ({
}
if (includes(TEXT_TYPES, field.format)) {
+ const isTruncated = field.value?.endsWith('...') && (field.value ?? '').length > MAX_CHARACTERS
+
return (
<div className="text-area-text-sm">
<Input.TextArea
layout="horizontal"
label={field.name}
className="text-sm"
- descriptionText={field.comment}
+ descriptionText={
+ <>
+ {field.comment && <p>{field.comment}</p>}
+ {isTruncated && (
+ <p>
+ Note: Value is too large to be rendered in the dashboard. Please expand the editor
+ to edit the value
+ </p>
+ )}
+ </>
+ }
labelOptional={field.format}
- disabled={!isEditable}
+ disabled={!isEditable || isTruncated}
error={errors[field.name]}
rows={5}
value={field.value ?? ''}
@@ -135,17 +160,21 @@ const InputField = ({
: `NULL (Default: ${field.defaultValue})`
}
actions={
- <div className="mr-1 mt-0.5">
- {(field.isNullable || (!field.isNullable && field.defaultValue)) && (
- <Button
- type="default"
- size="tiny"
- onClick={() => onUpdateField({ [field.name]: null })}
- >
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="default" icon={<Edit />} className="px-1.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem onClick={() => onUpdateField({ [field.name]: null })}>
Set to NULL
- </Button>
- )}
- </div>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => onEditText({ column: field.name, value: field.value })}
+ >
+ Expand editor
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
}
onChange={(event: any) => onUpdateField({ [field.name]: event.target.value })}
/>
@@ -154,14 +183,26 @@ const InputField = ({
}
if (includes(JSON_TYPES, field.format)) {
+ const isTruncated = field.value?.endsWith('...') && (field.value ?? '').length > MAX_CHARACTERS
+
return (
<Input
layout="horizontal"
value={field.value ?? ''}
label={field.name}
- descriptionText={field.comment}
+ descriptionText={
+ <>
+ {field.comment && <p>{field.comment}</p>}
+ {isTruncated && (
+ <p>
+ Note: Value is too large to be rendered in the dashboard. Please expand the editor
+ to edit the value
+ </p>
+ )}
+ </>
+ }
labelOptional={field.format}
- disabled={!isEditable}
+ disabled={!isEditable || isTruncated}
placeholder={field?.defaultValue ?? 'NULL'}
error={errors[field.name]}
onChange={(event: any) => onUpdateField({ [field.name]: event.target.value })}
@@ -169,8 +210,8 @@ const InputField = ({
<Button
type="default"
htmlType="button"
- onClick={() => onEditJson({ column: field.name, jsonString: field.value })}
- icon={<IconEdit2 />}
+ onClick={() => onEditJson({ column: field.name, value: field.value })}
+ icon={<Edit2 />}
>
Edit JSON
</Button>
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
index a2cd8067b73..9f2b0d0553b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/JsonEditor/JsonEditor.tsx
@@ -1,15 +1,23 @@
import * as Tooltip from '@radix-ui/react-tooltip'
+import { PostgresTable } from '@supabase/postgres-meta'
+import { AlignLeft } from 'lucide-react'
import { useEffect, useState } from 'react'
-import { Button, IconAlignLeft, SidePanel } from 'ui'
+import toast from 'react-hot-toast'
+import { Button, SidePanel, cn } from 'ui'
+import { useParams } from 'common'
import TwoOptionToggle from 'components/ui/TwoOptionToggle'
-import { minifyJSON, prettifyJSON, tryParseJson, removeJSONTrailingComma } from 'lib/helpers'
-import toast from 'react-hot-toast'
+import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
+import { useSelectedProject } from 'hooks'
+import useTable from 'hooks/misc/useTable'
+import { minifyJSON, prettifyJSON, removeJSONTrailingComma, tryParseJson } from 'lib/helpers'
import ActionBar from '../../ActionBar'
import { DrilldownViewer } from './DrilldownViewer'
import JsonCodeEditor from './JsonCodeEditor'
interface JsonEditProps {
+ row?: { [key: string]: any }
column: string
jsonString: string
visible: boolean
@@ -21,6 +29,7 @@ interface JsonEditProps {
}
const JsonEdit = ({
+ row,
column,
jsonString,
visible,
@@ -30,15 +39,16 @@ const JsonEdit = ({
closePanel,
onSaveJSON,
}: JsonEditProps) => {
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
+ const { data: selectedTable } = useTable(id)
+ const project = useSelectedProject()
+
const [view, setView] = useState<'edit' | 'view'>('edit')
const [jsonStr, setJsonStr] = useState('')
+ const isTruncated = jsonString.endsWith('...') && jsonString.length > MAX_CHARACTERS
- useEffect(() => {
- if (visible) {
- const temp = prettifyJSON(jsonString)
- setJsonStr(temp)
- }
- }, [visible])
+ const { mutate: getCellValue, isLoading, isSuccess } = useGetCellValueMutation()
const validateJSON = async (resolve: () => void) => {
try {
@@ -51,11 +61,44 @@ const JsonEdit = ({
}
}
- function prettify() {
+ const prettify = () => {
const res = prettifyJSON(jsonStr)
setJsonStr(res)
}
+ const loadFullValue = () => {
+ if (selectedTable === undefined || project === undefined || row === undefined) return
+ if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ return toast('Unable to load value as table has no primary keys')
+ }
+
+ const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ return { ...a, [b.name]: (row as any)[b.name] }
+ }, {})
+
+ getCellValue(
+ {
+ table: { schema: selectedTable.schema, name: selectedTable.name },
+ column: column,
+ pkMatch,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ {
+ onSuccess: (data) => {
+ setJsonStr(JSON.stringify(data))
+ },
+ }
+ )
+ }
+
+ useEffect(() => {
+ if (visible) {
+ const temp = prettifyJSON(jsonString)
+ setJsonStr(temp)
+ }
+ }, [visible])
+
return (
<SidePanel
size="large"
@@ -70,39 +113,41 @@ const JsonEdit = ({
Viewing JSON Field: <code>{column}</code>
</p>
)}
- <div className="flex items-center gap-x-2">
- {view === 'edit' && (
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger asChild>
- <Button
- type="default"
- icon={<IconAlignLeft />}
- className="px-1"
- onClick={() => prettify()}
- />
- </Tooltip.Trigger>
- <Tooltip.Portal>
- <Tooltip.Content side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background',
- ].join(' ')}
- >
- <span className="text-xs text-foreground">Prettify JSON</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- </Tooltip.Root>
- )}
- <TwoOptionToggle
- options={['view', 'edit']}
- activeOption={view}
- borderOverride="border-muted"
- onClickOption={setView}
- />
- </div>
+ {(!isTruncated || (isTruncated && isSuccess)) && (
+ <div className="flex items-center gap-x-2">
+ {view === 'edit' && (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <Button
+ type="default"
+ icon={<AlignLeft />}
+ className="px-1"
+ onClick={() => prettify()}
+ />
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">Prettify JSON</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ )}
+ <TwoOptionToggle
+ options={['view', 'edit']}
+ activeOption={view}
+ borderOverride="border-muted"
+ onClickOption={setView}
+ />
+ </div>
+ )}
</div>
}
visible={visible}
@@ -117,7 +162,7 @@ const JsonEdit = ({
/>
}
>
- <div className="flex flex-auto h-full flex-col space-y-4">
+ <div className="flex flex-auto h-full flex-col gap-y-4 relative">
{view === 'edit' ? (
<div className="w-full h-full flex-grow">
<JsonCodeEditor
@@ -130,6 +175,26 @@ const JsonEdit = ({
) : (
<DrilldownViewer jsonData={tryParseJson(jsonStr)} />
)}
+ {isTruncated && !isSuccess && (
+ <div
+ className={cn(
+ 'absolute top-0 left-0 flex items-center justify-center flex-col gap-y-3',
+ 'text-sm w-full h-full px-2 text-center',
+ 'bg-default/80 backdrop-blur-[1.5px]'
+ )}
+ >
+ <div className="flex flex-col gap-y-1 w-80">
+ <p>JSON value is larger than {MAX_CHARACTERS.toLocaleString()} characters</p>
+ <p className="text-foreground-light">
+ You may try to render the entire JSON value, but your browser may run into
+ performance issues
+ </p>
+ </div>
+ <Button type="default" loading={isLoading} onClick={loadFullValue}>
+ Load full JSON data
+ </Button>
+ </div>
+ )}
</div>
</SidePanel>
)
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
index 8995af9a952..ac46996af56 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.tsx
@@ -1,7 +1,7 @@
import type { PostgresTable } from '@supabase/postgres-meta'
-import type { Dictionary } from 'types'
-import { isEmpty, isUndefined, noop, partition } from 'lodash'
+import { isEmpty, noop, partition } from 'lodash'
import { useEffect, useMemo, useState } from 'react'
+import type { Dictionary } from 'types'
import { SidePanel } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
@@ -11,13 +11,14 @@ import ForeignRowSelector from './ForeignRowSelector/ForeignRowSelector'
import HeaderTitle from './HeaderTitle'
import InputField from './InputField'
import { JsonEditor } from './JsonEditor'
-import type { JsonEditValue, RowField } from './RowEditor.types'
+import type { EditValue, RowField } from './RowEditor.types'
import {
generateRowFields,
generateRowObjectFromFields,
generateUpdateRowPayload,
validateFields,
} from './RowEditor.utils'
+import { TextEditor } from './TextEditor'
export interface RowEditorProps {
row?: Dictionary<any>
@@ -38,13 +39,16 @@ const RowEditor = ({
}: RowEditorProps) => {
const [errors, setErrors] = useState<Dictionary<any>>({})
const [rowFields, setRowFields] = useState<any[]>([])
- const [selectedValueForJsonEdit, setSelectedValueForJsonEdit] = useState<JsonEditValue>()
+
+ const [selectedValueForTextEdit, setSelectedValueForTextEdit] = useState<EditValue>()
+ const [selectedValueForJsonEdit, setSelectedValueForJsonEdit] = useState<EditValue>()
const [isSelectingForeignKey, setIsSelectingForeignKey] = useState<boolean>(false)
const [referenceRow, setReferenceRow] = useState<RowField>()
- const isNewRecord = isUndefined(row)
- const isEditingJson = !isUndefined(selectedValueForJsonEdit)
+ const isNewRecord = row === undefined
+ const isEditingText = selectedValueForTextEdit !== undefined
+ const isEditingJson = selectedValueForJsonEdit !== undefined
const [loading, setLoading] = useState(false)
@@ -140,7 +144,7 @@ const RowEditor = ({
visible={visible}
header={<HeaderTitle isNewRecord={isNewRecord} tableName={selectedTable.name} />}
className={`transition-all duration-100 ease-in ${
- isEditingJson || isSelectingForeignKey ? ' mr-32' : ''
+ isEditingText || isEditingJson || isSelectingForeignKey ? ' mr-32' : ''
}`}
onCancel={closePanel}
>
@@ -181,6 +185,7 @@ const RowEditor = ({
field={field}
errors={errors}
onUpdateField={onUpdateField}
+ onEditText={setSelectedValueForTextEdit}
onEditJson={setSelectedValueForJsonEdit}
onSelectForeignKey={() => onOpenForeignRowSelector(field)}
/>
@@ -190,10 +195,22 @@ const RowEditor = ({
</SidePanel.Content>
</>
)}
+
+ <TextEditor
+ visible={isEditingText}
+ row={row}
+ column={selectedValueForTextEdit?.column ?? ''}
+ closePanel={() => setSelectedValueForTextEdit(undefined)}
+ onSaveField={(value) => {
+ onUpdateField({ [selectedValueForTextEdit?.column ?? '']: value })
+ setSelectedValueForTextEdit(undefined)
+ }}
+ />
<JsonEditor
visible={isEditingJson}
+ row={row}
column={selectedValueForJsonEdit?.column ?? ''}
- jsonString={selectedValueForJsonEdit?.jsonString ?? ''}
+ jsonString={selectedValueForJsonEdit?.value ?? ''}
closePanel={() => setSelectedValueForJsonEdit(undefined)}
onSaveJSON={(value) => {
onUpdateField({ [selectedValueForJsonEdit?.column ?? '']: value })
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types.ts
index b9093798754..ba9e8800f47 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types.ts
@@ -1,9 +1,9 @@
import type { PostgresRelationship } from '@supabase/postgres-meta'
-export interface JsonEditValue {
+export interface EditValue {
row?: any
column: string
- jsonString: string
+ value: string
}
export interface RowField {
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
index 5e0c20ea30b..920bf00ea59 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/TextEditor.tsx
@@ -1,16 +1,25 @@
-import remarkGfm from 'remark-gfm'
import { Editor } from '@monaco-editor/react'
+import { PostgresTable } from '@supabase/postgres-meta'
+import { Loader } from 'lucide-react'
import { useEffect, useState } from 'react'
-import { IconLoader, SidePanel } from 'ui'
+import toast from 'react-hot-toast'
+import remarkGfm from 'remark-gfm'
-import { useTableEditorStateSnapshot } from 'state/table-editor'
-import ActionBar from '../ActionBar'
-import TwoOptionToggle from 'components/ui/TwoOptionToggle'
+import { useParams } from 'common'
import { Markdown } from 'components/interfaces/Markdown'
+import TwoOptionToggle from 'components/ui/TwoOptionToggle'
+import { useGetCellValueMutation } from 'data/table-rows/get-cell-value-mutation'
+import { MAX_CHARACTERS } from 'data/table-rows/table-rows-query'
+import { useSelectedProject } from 'hooks'
+import useTable from 'hooks/misc/useTable'
+import { Button, SidePanel, cn } from 'ui'
+import ActionBar from '../ActionBar'
interface TextEditorProps {
visible: boolean
readOnly?: boolean
+ row?: { [key: string]: any }
+ column: string
closePanel: () => void
onSaveField: (value: string, resolve: () => void) => void
}
@@ -18,16 +27,48 @@ interface TextEditorProps {
export const TextEditor = ({
visible,
readOnly = false,
+ row,
+ column,
closePanel,
onSaveField,
}: TextEditorProps) => {
+ const { id: _id } = useParams()
+ const id = _id ? Number(_id) : undefined
+ const { data: selectedTable } = useTable(id)
+ const project = useSelectedProject()
+
const [strValue, setStrValue] = useState('')
const [view, setView] = useState<'edit' | 'view'>('edit')
+ const value = row?.[column as keyof typeof row] as unknown as string
+ const isTruncated = value?.endsWith('...') && value.length > MAX_CHARACTERS
+
+ const { mutate: getCellValue, isLoading, isSuccess } = useGetCellValueMutation()
+
+ const loadFullValue = () => {
+ if (selectedTable === undefined || project === undefined || row === undefined) return
+ if ((selectedTable as PostgresTable).primary_keys.length === 0) {
+ return toast('Unable to load value as table has no primary keys')
+ }
+
+ const pkMatch = (selectedTable as PostgresTable).primary_keys.reduce((a, b) => {
+ return { ...a, [b.name]: (row as any)[b.name] }
+ }, {})
- const snap = useTableEditorStateSnapshot()
- const column = (snap.sidePanel?.type === 'cell' && snap.sidePanel.value?.column) ?? ''
- const row = (snap.sidePanel?.type === 'cell' && snap.sidePanel.value?.row) ?? {}
- const value = row[column as keyof typeof row] as unknown as string
+ getCellValue(
+ {
+ table: { schema: selectedTable.schema, name: selectedTable.name },
+ column: column,
+ pkMatch,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ { onSuccess: (data) => setStrValue(data) }
+ )
+ }
+
+ const saveValue = (resolve: () => void) => {
+ if (onSaveField) onSaveField(strValue, resolve)
+ }
useEffect(() => {
if (visible) {
@@ -36,10 +77,6 @@ export const TextEditor = ({
}
}, [visible])
- const saveValue = (resolve: () => void) => {
- if (onSaveField) onSaveField(strValue, resolve)
- }
-
return (
<SidePanel
size="large"
@@ -50,12 +87,14 @@ export const TextEditor = ({
<p>
{readOnly ? 'Viewing' : 'Editing'} value of: <code>{column}</code>
</p>
- <TwoOptionToggle
- options={['view', 'edit']}
- activeOption={view}
- borderOverride="border-muted"
- onClickOption={setView}
- />
+ {(!isTruncated || (isTruncated && isSuccess)) && (
+ <TwoOptionToggle
+ options={['view', 'edit']}
+ activeOption={view}
+ borderOverride="border-muted"
+ onClickOption={setView}
+ />
+ )}
</div>
}
customFooter={
@@ -68,7 +107,7 @@ export const TextEditor = ({
/>
}
>
- <div className="flex flex-auto h-full flex-col space-y-4">
+ <div className="relative flex flex-auto h-full flex-col gap-y-4">
{view === 'edit' ? (
<div className="w-full h-full flex-grow">
<Editor
@@ -77,7 +116,7 @@ export const TextEditor = ({
className="monaco-editor"
defaultLanguage="markdown"
value={strValue}
- loading={<IconLoader className="animate-spin" strokeWidth={2} size={20} />}
+ loading={<Loader className="animate-spin" strokeWidth={2} size={20} />}
options={{
readOnly,
tabSize: 2,
@@ -111,6 +150,26 @@ export const TextEditor = ({
/>
</SidePanel.Content>
)}
+ {isTruncated && !isSuccess && (
+ <div
+ className={cn(
+ 'absolute top-0 left-0 flex items-center justify-center flex-col gap-y-3',
+ 'text-sm w-full h-full px-2 text-center',
+ 'bg-default/80 backdrop-blur-[1.5px]'
+ )}
+ >
+ <div className="flex flex-col gap-y-1 w-80">
+ <p>Text value is larger than {MAX_CHARACTERS.toLocaleString()} characters</p>
+ <p className="text-foreground-light">
+ You may try to render the entire text value, but your browser may run into
+ performance issues
+ </p>
+ </div>
+ <Button type="default" loading={isLoading} onClick={loadFullValue}>
+ Load full text data
+ </Button>
+ </div>
+ )}
</div>
</SidePanel>
)
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 98509e4df5e..cd3d2c01455 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -3,7 +3,6 @@ import { useQueryClient } from '@tanstack/react-query'
import { isEmpty, isUndefined, noop } from 'lodash'
import { useState } from 'react'
import { toast } from 'react-hot-toast'
-import { Modal } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ToastLoader } from 'components/ui/ToastLoader'
@@ -246,11 +245,8 @@ const SidePanelEditor = ({
}
await Promise.all([
- queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints'])),
queryClient.invalidateQueries(tableKeys.table(project?.ref, selectedTable!.id)),
- queryClient.invalidateQueries(
- sqlKeys.query(project?.ref, [selectedTable!.schema, selectedTable!.name])
- ),
+ queryClient.invalidateQueries(sqlKeys.query(project?.ref, ['foreign-key-constraints'])),
queryClient.invalidateQueries(
sqlKeys.query(project?.ref, [
'table-definition',
@@ -260,6 +256,11 @@ const SidePanelEditor = ({
),
queryClient.invalidateQueries(entityTypeKeys.list(project?.ref)),
])
+
+ await queryClient.invalidateQueries(
+ sqlKeys.query(project?.ref, [selectedTable!.schema, selectedTable!.name])
+ )
+
setIsEdited(false)
snap.closeSidePanel()
}
@@ -609,7 +610,7 @@ const SidePanelEditor = ({
<JsonEditor
visible={snap.sidePanel?.type === 'json'}
column={(snap.sidePanel?.type === 'json' && snap.sidePanel.jsonValue.column) || ''}
- jsonString={(snap.sidePanel?.type === 'json' && snap.sidePanel.jsonValue.jsonString) || ''}
+ jsonString={(snap.sidePanel?.type === 'json' && snap.sidePanel.jsonValue.value) || ''}
backButtonLabel="Cancel"
applyButtonLabel="Save changes"
readOnly={!editable}
@@ -618,6 +619,8 @@ const SidePanelEditor = ({
/>
<TextEditor
visible={snap.sidePanel?.type === 'cell'}
+ column={(snap.sidePanel?.type === 'cell' && snap.sidePanel.value?.column) || ''}
+ row={(snap.sidePanel?.type === 'cell' && snap.sidePanel.value?.row) || {}}
closePanel={onClosePanel}
onSaveField={onSaveColumnValue}
/>
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 17b7910dcd4..7f51502a6e7 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -274,7 +274,7 @@ const TableGridEditor = ({
onImportData={snap.onImportData}
onError={onError}
onExpandJSONEditor={(column, row) => {
- snap.onExpandJSONEditor({ column, row, jsonString: JSON.stringify(row[column]) || '' })
+ snap.onExpandJSONEditor({ column, row, value: JSON.stringify(row[column]) || '' })
}}
onExpandTextEditor={(column, row) => {
snap.onExpandTextEditor(column, row)
diff --git a/apps/studio/data/table-rows/get-cell-value-mutation.ts b/apps/studio/data/table-rows/get-cell-value-mutation.ts
new file mode 100644
index 00000000000..0059b791e71
--- /dev/null
+++ b/apps/studio/data/table-rows/get-cell-value-mutation.ts
@@ -0,0 +1,68 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { Query } from 'components/grid'
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+
+export type GetCellValueVariables = {
+ projectRef: string
+ connectionString?: string
+ table: { schema: string; name: string }
+ column: string
+ pkMatch: { [key: string]: any }
+}
+
+export function getCellValueSql({
+ table,
+ column,
+ pkMatch,
+}: Pick<GetCellValueVariables, 'table' | 'column' | 'pkMatch'>) {
+ return new Query()
+ .from(table.name, table.schema ?? undefined)
+ .select(column)
+ .match(pkMatch)
+ .toSql()
+}
+
+export async function getCellValue({
+ projectRef,
+ connectionString,
+ table,
+ column,
+ pkMatch,
+}: GetCellValueVariables) {
+ const sql = getCellValueSql({ table, column, pkMatch })
+ const { result } = await executeSql({ projectRef, connectionString, sql })
+ return result?.[0][column]
+}
+
+type TableRowCreateData = Awaited<ReturnType<typeof getCellValue>>
+
+export const useGetCellValueMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<TableRowCreateData, ResponseError, GetCellValueVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<TableRowCreateData, ResponseError, GetCellValueVariables>(
+ (vars) => getCellValue(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, table } = variables
+ // await queryClient.invalidateQueries(sqlKeys.query(projectRef, [table.schema, table.name]))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(data.message)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/table-rows/table-rows-query.ts b/apps/studio/data/table-rows/table-rows-query.ts
index 879d4c8d37e..654f2b426f4 100644
--- a/apps/studio/data/table-rows/table-rows-query.ts
+++ b/apps/studio/data/table-rows/table-rows-query.ts
@@ -2,6 +2,11 @@ import type { QueryKey, UseQueryOptions } from '@tanstack/react-query'
import { IS_PLATFORM } from 'common'
import { Filter, Query, Sort, SupaRow, SupaTable } from 'components/grid'
+import {
+ JSON_TYPES,
+ TEXT_TYPES,
+} from 'components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants'
+import { KB } from 'lib/constants'
import {
ImpersonationRole,
ROLE_IMPERSONATION_NO_RESULTS,
@@ -21,6 +26,9 @@ type GetTableRowsArgs = {
impersonatedRole?: ImpersonationRole
}
+// [Joshen] We can probably make this reasonably high, but for now max aim to load 10kb
+export const MAX_CHARACTERS = 10 * KB
+
export const fetchAllTableRows = async ({
projectRef,
connectionString,
@@ -94,22 +102,30 @@ export const getTableRowsSqlQuery = ({
}: GetTableRowsArgs) => {
const query = new Query()
- if (!table) {
- return ``
- }
+ if (!table) return ``
- const enumArrayColumns = table.columns
+ // [Joshen] Only truncate text/json based columns as their length could go really big
+ // Note: Risk of payload being too large if the user has many many text/json based columns
+ // although possibly negligible risk.
+ const truncatedColumns = table.columns
.filter((column) => {
- return (column?.enum ?? []).length > 0 && column.dataType.toLowerCase() === 'array'
+ return (
+ ((column?.enum ?? []).length > 0 && column.dataType.toLowerCase() === 'array') ||
+ TEXT_TYPES.includes(column.format) ||
+ JSON_TYPES.includes(column.format)
+ )
+ })
+ .map((column) => {
+ if ((column?.enum ?? []).length > 0 && column.dataType.toLowerCase() === 'array') {
+ return `"${column.name}"::text[]`
+ } else {
+ return `case when length("${column.name}"::text) > ${MAX_CHARACTERS} then concat(left("${column.name}"::text, ${MAX_CHARACTERS}), '...') else "${column.name}"::text end "${column.name}"`
+ }
})
- .map((column) => column.name)
- let queryChains =
- enumArrayColumns.length > 0
- ? query
- .from(table.name, table.schema ?? undefined)
- .select(`*,${enumArrayColumns.map((x) => `"${x}"::text[]`).join(',')}`)
- : query.from(table.name, table.schema ?? undefined).select()
+ let queryChains = query
+ .from(table.name, table.schema ?? undefined)
+ .select(truncatedColumns.length > 0 ? `*,${truncatedColumns.join(',')}` : '*')
filters
.filter((x) => x.value && x.value != '')
@@ -158,7 +174,11 @@ export const useTableRowsQuery = <TData extends TableRowsData = TableRowsData>(
queryKey: [
...(queryKey ?? []),
{
- table: { name: table?.name, schema: table?.schema },
+ table: {
+ name: table?.name,
+ schema: table?.schema,
+ columns: table?.columns.map((c) => c.name),
+ },
impersonatedRole,
...args,
},
diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.ts
index 9a9686681c2..b22e7e9b354 100644
--- a/apps/studio/lib/constants/index.ts
+++ b/apps/studio/lib/constants/index.ts
@@ -64,3 +64,5 @@ export const OPT_IN_TAGS = {
}
export const GB = 1024 * 1024 * 1024
+export const MB = 1024 * 1024
+export const KB = 1024
diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsx
index cc1f72ea2b3..eae0b829e0b 100644
--- a/apps/studio/state/table-editor.tsx
+++ b/apps/studio/state/table-editor.tsx
@@ -1,9 +1,9 @@
import type { PostgresColumn } from '@supabase/postgres-meta'
import type { SupaRow } from 'components/grid'
-import type { Dictionary } from 'types'
import { ForeignRowSelectorProps } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector'
-import type { JsonEditValue } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'
+import { EditValue } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'
import { PropsWithChildren, createContext, useContext, useRef } from 'react'
+import type { Dictionary } from 'types'
import { proxy, useSnapshot } from 'valtio'
type ForeignKey = {
@@ -18,7 +18,7 @@ export type SidePanel =
| { type: 'column'; column?: PostgresColumn }
| { type: 'table'; mode: 'new' | 'edit' | 'duplicate' }
| { type: 'schema'; mode: 'new' | 'edit' }
- | { type: 'json'; jsonValue: JsonEditValue }
+ | { type: 'json'; jsonValue: EditValue }
| {
type: 'foreign-row-selector'
foreignKey: ForeignKey
@@ -165,7 +165,7 @@ export const createTableEditorState = () => {
},
/* Misc */
- onExpandJSONEditor: (jsonValue: JsonEditValue) => {
+ onExpandJSONEditor: (jsonValue: EditValue) => {
state.ui = {
open: 'side-panel',
sidePanel: { type: 'json', jsonValue },