Files
supabase/apps/studio/data/table-rows/get-cell-value-mutation.ts
Drew McLellan f7f27aac78 fix(studio): escape json and jsonb values in SQL copy and export (#53372)
## What

Fixes invalid or corrupted SQL from "Copy rows as SQL" and "Export table
as SQL" for json/jsonb columns (FE-4860, closes #49196).

## Why

The SQL formatter built json literals by rewriting `JSON.stringify`
output with regexes. That corrupted values containing double quotes or
backslashes, and produced invalid SQL for jsonb columns holding plain
strings or other non-object values.

## How

- `formatTableRowsToSQL` now serializes the parsed value and only
escapes single quotes.
- Grid rows carry json columns as text (the grid query casts them to
`::text`), so a new `parseGridJsonColumns` helper parses untruncated
json cells before formatting. It is used by "Copy rows as SQL" and the
selected-rows export. Truncated cells are left alone so they are still
fetched in full.
- The SQL export keeps json columns unstringified
(`preserveJsonValues`), so a jsonb string like `"hello"` stays
distinguishable from JSON text. CSV and JSON exports are unchanged.

No `::text` cast was added to the export query: the API already returns
json values parsed.

## Testing

- Unit tests for values with `"`, `\`, `'`, plain-string jsonb, arrays,
numbers, booleans and null, plus `parseGridJsonColumns`.
- Ran the formatter output against a local Postgres: both the parsed
(fetch-all) and grid-text (copy / selected rows) shapes loaded and
round-tripped identically for jsonb and json columns. The old
formatter's output failed with `invalid input syntax for type json` on
the same data.
- Not exercised end to end in the Studio UI, and the truncated-cell path
is covered by unit tests only.

## Not in scope

The JSON export still stringifies objects before `JSON.stringify`, so
json columns come out as nested strings. That is separate pre-existing
behavior.
2026-11-16 13:52:05 +00:00

90 lines
2.6 KiB
TypeScript

import { ident, safeSql } from '@supabase/pg-meta'
import { Query } from '@supabase/pg-meta/src/query'
import { useMutation } from '@tanstack/react-query'
import { toast } from 'sonner'
import { unguarded } from '@/data/fetchers'
import { executeSql } from '@/data/sql/execute-sql-mutation'
import type { StudioError } from '@/lib/errors/studio-errors'
import { RoleImpersonationState, wrapWithRoleImpersonation } from '@/lib/role-impersonation'
import { isRoleImpersonationEnabled } from '@/state/role-impersonation-state'
import type { UseCustomMutationOptions } from '@/types'
export type GetCellValueVariables = {
projectRef: string
connectionString?: string | null
table: { schema: string; name: string }
column: string
pkMatch: { [key: string]: any }
roleImpersonationState?: RoleImpersonationState
/**
* Return the value as text. For json/jsonb columns this keeps the exact JSON text, whereas the
* default returns a parsed value that can lose number precision.
*/
asText?: boolean
}
export function getCellValueSql({
table,
column,
pkMatch,
asText = false,
}: Pick<GetCellValueVariables, 'table' | 'column' | 'pkMatch' | 'asText'>) {
return new Query()
.from(table.name, table.schema ?? undefined)
.select(asText ? safeSql`${ident(column)}::text as ${ident(column)}` : ident(column))
.match(pkMatch)
.toSql()
}
export async function getCellValue({
projectRef,
connectionString,
table,
column,
pkMatch,
roleImpersonationState,
asText,
}: GetCellValueVariables) {
const sql = wrapWithRoleImpersonation(
getCellValueSql({ table, column, pkMatch, asText }),
roleImpersonationState
)
const { result } = await executeSql({
projectRef,
connectionString,
sqlOrigin: 'studio',
queryName: 'get-cell-value',
sql,
isRoleImpersonationEnabled: isRoleImpersonationEnabled(roleImpersonationState?.role),
grant: unguarded.migrating,
})
return result?.[0][column]
}
type TableRowCreateData = Awaited<ReturnType<typeof getCellValue>>
export const useGetCellValueMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseCustomMutationOptions<TableRowCreateData, StudioError, GetCellValueVariables>,
'mutationFn'
> = {}) => {
return useMutation<TableRowCreateData, StudioError, GetCellValueVariables>({
mutationFn: (vars) => getCellValue(vars),
async onSuccess(data, variables, context) {
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(data.message)
} else {
onError(data, variables, context)
}
},
...options,
})
}