Files
supabase/apps/studio/data/table-rows/table-row-create-mutation.ts
T
Joshen Lim a1abc2d00f Refactor table editor logic for handling null and undefined values (#44331)
## Context

Resolves https://github.com/supabase/supabase/issues/43548

There's currently an issue with the Table Editor where if you have, for
example, a nullable `text` column with a default value, inserting a new
row and selecting "Set to NULL" doesn't do anything, and saving will
insert the row with the default value
<img width="700" height="258" alt="image"
src="https://github.com/user-attachments/assets/6a284ebb-c346-40a6-9a30-793118844084"
/>

This stems from a legacy logic in the Table Editor whereby we treat
`null` values as "no input" - which is incorrect as `null` values are
also valid values. So the PR here changes a few things to resolve this
properly:

## Changes involved
Main fix: 
- `undefined` will be the "no input" value instead, and it'll be the
default value when generating the row object for inserting a new row
- `NULL` or even empty string like `''` will be treated as they are
(valid inputs)

Secondary adjustments:
- (Queue operations) Queueing an insert with no value but default value
is NULL, will show the placeholder as `DEFAULT` instead of `NULL` for
better accuracy in representation
<img width="892" height="96" alt="image"
src="https://github.com/user-attachments/assets/02cf86bf-c17b-4e25-9a8f-17960b1d2575"
/>
- Added a `Set to Default` CTA here, but will only show up if adding a
new row or updating a queued insert row operation, which will set the
value of the input field back to `undefined` for PG to handle it as the
default value
<img width="734" height="208" alt="image"
src="https://github.com/user-attachments/assets/23887c0c-533e-4494-acbe-61309ff5d7c5"
/>


## To test
Verify within the Table Editor (along with queue operation feature
preview)
- For inserting a new row, setting value to NULL and setting value to
Default works
- For updating a row, setting value to NULL works
2026-03-30 23:33:53 +08:00

111 lines
3.2 KiB
TypeScript

import { Query } from '@supabase/pg-meta/src/query'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { executeSql } from 'data/sql/execute-sql-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { RoleImpersonationState, wrapWithRoleImpersonation } from 'lib/role-impersonation'
import { toast } from 'sonner'
import { isRoleImpersonationEnabled } from 'state/role-impersonation-state'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { tableRowKeys } from './keys'
export type TableRowCreateVariables = {
projectRef: string
connectionString?: string | null
table: { id: number; name: string; schema?: string }
payload: any
enumArrayColumns: string[]
returning?: boolean
roleImpersonationState?: RoleImpersonationState
}
export function getTableRowCreateSql({
table,
payload,
returning = false,
enumArrayColumns,
}: Pick<TableRowCreateVariables, 'table' | 'payload' | 'enumArrayColumns' | 'returning'>) {
return new Query()
.from(table.name, table.schema ?? undefined)
.insert([payload], { returning, enumArrayColumns })
.toSql()
}
export async function createTableRow({
projectRef,
connectionString,
table,
payload,
enumArrayColumns,
returning,
roleImpersonationState,
}: TableRowCreateVariables) {
const sql = wrapWithRoleImpersonation(
getTableRowCreateSql({ table, payload, enumArrayColumns, returning }),
roleImpersonationState
)
const { result } = await executeSql({
projectRef,
connectionString,
sql,
isRoleImpersonationEnabled: isRoleImpersonationEnabled(roleImpersonationState?.role),
})
return result
}
type TableRowCreateData = Awaited<ReturnType<typeof createTableRow>>
export const useTableRowCreateMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseCustomMutationOptions<TableRowCreateData, ResponseError, TableRowCreateVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
const { mutate: sendEvent } = useSendEventMutation()
const { data: org } = useSelectedOrganizationQuery()
return useMutation<TableRowCreateData, ResponseError, TableRowCreateVariables>({
mutationFn: (vars) => createTableRow(vars),
async onSuccess(data, variables, context) {
const { projectRef, table } = variables
// Track data insertion event
try {
sendEvent({
action: 'table_data_added',
properties: {
method: 'table_editor',
schema_name: table.schema,
table_name: table.name,
},
groups: {
project: projectRef,
...(org?.slug && { organization: org.slug }),
},
})
} catch (error) {
console.error('Failed to track table data insertion event:', error)
}
await queryClient.invalidateQueries({
queryKey: tableRowKeys.tableRowsAndCount(projectRef, table.id),
})
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(data.message)
} else {
onError(data, variables, context)
}
},
...options,
})
}