Files
supabase/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx
T
Charis ed6d1b4c63 feat(studio): show error details in AlertError and attribute user faults in SQL errors (#53242)
## Problem

`AlertError` gives users and support no way to correlate a failure with
Sentry or platform logs. It also treats every failure the same: a bad
table editor filter or an offline browser gets "try refreshing, contact
support".

On the reporting side, SQL errors were attributed by who wrote the whole
statement. That made errors in the user's part of mixed SQL Studio's
fault: policy expressions, function bodies, cron schedules, table editor
filters and row edits. Marking them as user SQL instead would drop them
from Sentry entirely.

Part of FE-4772.

## Solution

**`AlertError`**
- Platform and Studio faults show the request ID, the Sentry event ID
(labeled "before sampling", since the event may be sampled out) and a
"Copy details" button.
- The copied text never includes `formattedError`, metadata, the cause
or SQL.
- SQL errors copy the SQLSTATE, position and query name instead of the
message.
- User faults (`isUserError`) show their message with "Please try again.
If the issue persists, try refreshing your browser." There is no support
link, no IDs and no copy button.
- Offline shows only "You may be temporarily offline. Check your
internet connection and try again."
- Defaults come from `getErrorPresentation`, and props the caller passes
still win. The table editor passes a filter-specific description when
filters are set.

**SQL error classification**
- `executeSql` takes an optional `isUserFaultSqlState` predicate for
Studio SQL. When it matches, the error is a `StudioSqlError` with reason
`user_input` and fault `user`, and is still redacted to SQLSTATE plus
query name.
- `isUserFaultForValues` (classes 22, 23 and P0, plus 42501 and 57014)
is for typed values: table editor filters and row edits, cron name and
schedule.
- `isUserFaultForSql` (any SQLSTATE except server classes 08, 53, 57
other than 57014, 58 and XX) is for embedded user SQL: policies,
functions, the custom access token hook.
- `isUserFaultForStatsStatement` is for `pg_stat_statements` text (Query
Insights `EXPLAIN`, index advisor). It treats 42P02 (`$1` placeholders)
as Studio's fault.
- `UserSqlError` is now only SQL the user wrote in full, and it is still
never sent.
- The policy, function and cron mutation hooks no longer take
`sqlOrigin`.

**Routing and types**
- `ERROR_ROUTING` is one table keyed by tag, then by fault. Its type
requires exactly the faults each class can produce.
- User faults get `SAMPLE_USER_FAULT` (default 0.01, set with
`NEXT_PUBLIC_SENTRY_SAMPLE_RATE_USER_FAULT`) to catch misclassification.
- The error class decides privacy (`isNeverReportedError`), separately
from the rate.
- Sentry events get a `reason` tag.
- Each class declares its `reasons`, so a mistyped reason fails
typecheck.

## Review instructions

1. Open the table editor, add a filter with a wrong-typed value (text on
an integer column). The alert shows the Postgres error, the filter hint,
and no support link, IDs or copy button.
2. Make a query fail with a platform error (e.g. block a `/platform/`
request in DevTools). The alert shows the request ID, the event ID and
"Copy details". Paste the copied text and check it has no SQL or
`formattedError`.
3. Go offline in DevTools and trigger a query. Only the offline message
shows.
4. Create a policy with an invalid `USING` expression. The toast shows
the Postgres error. In Sentry it is a `StudioSqlError` with reason
`user_input`, sampled at the user-fault rate.
5. Review `lib/errors/error-routing.ts` and
`data/error-classification.ts` for the routing table and the SQLSTATE
predicates.
2026-11-12 15:19:25 -05:00

658 lines
26 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { acceptUntrustedSql, untrustedSql } from '@supabase/pg-meta/src/pg-format'
import { isEmpty, isNull, keyBy, mapValues, partition } from 'lodash'
import { PlusIcon, TrashIcon } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import {
Button,
cn,
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
Input,
RadioGroupStacked,
RadioGroupStackedItem,
ScrollArea,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Separator,
Sheet,
SheetContent,
SheetFooter,
SheetSection,
Switch,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import z from 'zod'
import { convertArgumentTypes, convertConfigParams } from '../Functions.utils'
import { CreateFunctionConfigParamsSection } from './CreateFunctionConfigParamsSection'
import { CreateFunctionHeader } from './CreateFunctionHeader'
import { FunctionEditor } from './FunctionEditor'
import { POSTGRES_DATA_TYPES } from '@/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.constants'
import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { SchemaSelector } from '@/components/ui/SchemaSelector'
import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-extensions-query'
import { useDatabaseFunctionCreateMutation } from '@/data/database-functions/database-functions-create-mutation'
import type { SavedDatabaseFunction } from '@/data/database-functions/database-functions-query'
import { useDatabaseFunctionUpdateMutation } from '@/data/database-functions/database-functions-update-mutation'
import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
import { useProtectedSchemas } from '@/hooks/useProtectedSchemas'
import { getWriteGrantToastMessage, getWriteGrantTooltip, useGrant } from '@/lib/grants'
const FORM_ID = 'create-function-sidepanel'
interface CreateFunctionProps {
func?: SavedDatabaseFunction
isDuplicating?: boolean
visible: boolean
onClose: () => void
}
const FormSchema = z.object({
name: z.string().trim().min(1),
type: z.enum(['function', 'procedure']),
schema: z.string().trim().min(1),
args: z.array(z.object({ name: z.string().trim().min(1), type: z.string().trim() })),
behavior: z.enum(['IMMUTABLE', 'STABLE', 'VOLATILE']),
definition: z.string().trim().min(1),
language: z.string().trim(),
return_type: z.string().trim(),
security_definer: z.boolean(),
config_params: z
.array(z.object({ name: z.string().trim().min(1), value: z.string().trim().min(1) }))
.optional(),
})
export const CreateFunction = ({
func,
visible,
isDuplicating = false,
onClose,
}: CreateFunctionProps) => {
const { selectedSchema } = useQuerySchemaState()
const { data: project } = useSelectedProjectQuery()
const [advancedSettingsShown, setAdvancedSettingsShown] = useState(false)
const [focusedEditor, setFocusedEditor] = useState(false)
const isEditing = !isDuplicating && !!func?.id
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
})
const [type, language] = useWatch({ control: form.control, name: ['type', 'language'] })
const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({
checkIsDirty: () => form.formState.isDirty,
onClose,
})
const writeGrant = useGrant(
'POST /platform/pg-meta/{ref}/query',
{ projectRef: project?.ref },
{ variant: 'write' }
)
const { mutate: createDatabaseFunction, isPending: isCreating } =
useDatabaseFunctionCreateMutation()
const { mutate: updateDatabaseFunction, isPending: isUpdating } =
useDatabaseFunctionUpdateMutation()
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!project) return console.error('Project is required')
if (!writeGrant.grant) {
return toast.error(
getWriteGrantToastMessage(writeGrant.status, isEditing ? 'update' : 'create', 'functions')
)
}
// Submit click is the explicit user gesture that promotes form-entered SQL fragments
// (`args` items, `return_type`, and each `config_params` value) to executable.
const payload = {
...data,
args: data.args.map((x) => acceptUntrustedSql(untrustedSql(`${x.name} ${x.type}`))),
return_type: acceptUntrustedSql(untrustedSql(data.return_type)),
config_params: mapValues(keyBy(data.config_params, 'name'), (item) =>
acceptUntrustedSql(untrustedSql(item.value))
),
}
if (isEditing) {
updateDatabaseFunction(
{
func,
grant: writeGrant.grant,
projectRef: project.ref,
connectionString: project.connectionString,
payload,
},
{
onSuccess: () => {
toast.success(`Successfully updated function ${data.name}`)
onClose()
},
}
)
} else {
createDatabaseFunction(
{
grant: writeGrant.grant,
projectRef: project.ref,
connectionString: project.connectionString,
payload,
},
{
onSuccess: () => {
toast.success(`Successfully created function ${data.name}`)
onClose()
},
}
)
}
}
useEffect(() => {
if (visible) {
setFocusedEditor(false)
const type = func?.type ?? 'function'
form.reset({
type,
name: func?.name ?? '',
schema: func?.schema ?? selectedSchema,
args: convertArgumentTypes({ type, value: func?.argument_types || '' }).value,
behavior: func?.behavior ?? 'VOLATILE',
definition: func?.definition ?? '',
language: func?.language ?? 'plpgsql',
return_type: func?.return_type ?? 'void',
security_definer: func?.security_definer ?? false,
config_params: convertConfigParams(func?.config_params).value,
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, func?.id])
const { data: protectedSchemas } = useProtectedSchemas()
return (
<Sheet open={visible} onOpenChange={handleOpenChange}>
<SheetContent
size="default"
className="p-0 flex flex-row gap-0 min-w-screen! lg:min-w-[600px]!"
>
<div className="flex flex-col grow w-full">
<CreateFunctionHeader selectedFunction={func?.name} isDuplicating={isDuplicating} />
<Separator />
<Form {...form}>
<form
id={FORM_ID}
className="grow overflow-auto"
onSubmit={form.handleSubmit(onSubmit)}
>
<fieldset disabled={!writeGrant.grant} className="contents">
<SheetSection
className={cn(focusedEditor ? 'hidden' : '', 'flex flex-col gap-y-4')}
>
<FormField
control={form.control}
name="schema"
render={({ field }) => (
<FormItemLayout
label="Schema"
description={
<>
Tables made in the table editor will be in <code>public</code>
</>
}
layout="horizontal"
>
<FormControl>
<SchemaSelector
selectedSchemaName={field.value}
excludedSchemas={protectedSchemas?.map((s) => s.name)}
size="small"
onSelectSchema={(name) => field.onChange(name)}
/>
</FormControl>
</FormItemLayout>
)}
/>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItemLayout
label="Name of function"
description="Name will also be used for the function name in postgres"
layout="horizontal"
>
<FormControl>
<Input {...field} placeholder="Name of function" />
</FormControl>
</FormItemLayout>
)}
/>
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
<SheetSection className={focusedEditor ? 'hidden' : 'flex flex-col gap-y-4'}>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItemLayout label="Type" layout="horizontal">
<Select
disabled={isEditing}
onValueChange={field.onChange}
defaultValue={field.value}
>
<SelectTrigger className="col-span-8">
{field.value === 'function' ? 'Function' : 'Stored procedure'}
</SelectTrigger>
<SelectContent align="end">
<SelectItem value="function">
<p>Function</p>
<p className="text-foreground-lighter">
For query logic, triggers, and RPC calls
</p>
</SelectItem>
<SelectItem value="procedure">
<p>Stored procedure</p>
<p className="text-foreground-lighter">
For batch or multi-step tasks that manages transactions
</p>
</SelectItem>
</SelectContent>
</Select>
</FormItemLayout>
)}
/>
{type === 'function' && (
<FormField
control={form.control}
name="return_type"
render={({ field }) => (
<FormItemLayout label="Return type" layout="horizontal">
{/* Form selects don't need form controls, otherwise the CSS gets weird */}
<Select
disabled={isEditing}
onValueChange={field.onChange}
defaultValue={field.value}
>
<SelectTrigger className="col-span-8">
<SelectValue />
</SelectTrigger>
<SelectContent>
<ScrollArea className="h-52">
{[
'void',
'record',
'trigger',
'integer',
...POSTGRES_DATA_TYPES,
].map((option) => (
<SelectItem value={option} key={option}>
{option}
</SelectItem>
))}
</ScrollArea>
</SelectContent>
</Select>
</FormItemLayout>
)}
/>
)}
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
<SheetSection className={focusedEditor ? 'hidden' : ''}>
<FormFieldArgs readonly={isEditing} />
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
<SheetSection className={`${focusedEditor ? 'h-full' : ''} px-0!`}>
<FormField
control={form.control}
name="definition"
render={({ field }) => (
<FormItem className="space-y-4 flex flex-col h-full">
<div className="px-content">
<FormLabel className="text-base text-foreground">Definition</FormLabel>
<FormDescription className="text-sm text-foreground-light">
<p>
The language below should be written in <code>{language}</code>.
</p>
{!isEditing && (
<p>Change the language in the Advanced Settings below.</p>
)}
</FormDescription>
</div>
<div
className={cn(
'border border-default flex',
focusedEditor ? 'grow ' : 'h-72'
)}
>
<FunctionEditor
field={field}
language={language}
focused={focusedEditor}
setFocused={setFocusedEditor}
isReadOnly={!writeGrant.grant}
/>
</div>
<FormMessage className="px-content" />
</FormItem>
)}
/>
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
{isEditing ? null : (
<>
<SheetSection className={focusedEditor ? 'hidden' : ''}>
<div className="space-y-8 rounded-sm bg-studio py-4 px-6 border border-overlay">
<FormItem className="flex flex-row items-center justify-between">
<div className="space-y-0.5">
<FormLabel className="text-sm">Show advanced settings</FormLabel>
<FormDescription className="text-foreground-lighter">
These are settings that might be familiar for Postgres developers
</FormDescription>
</div>
<FormControl>
<Switch
checked={advancedSettingsShown}
onCheckedChange={(checked) => setAdvancedSettingsShown(checked)}
/>
</FormControl>
</FormItem>
</div>
</SheetSection>
{advancedSettingsShown && (
<>
<SheetSection className={focusedEditor ? 'hidden' : 'space-y-2 pt-0'}>
<FormFieldLanguage />
{type === 'function' && (
<FormField
control={form.control}
name="behavior"
render={({ field }) => (
<FormItemLayout label="Behavior" layout="horizontal">
{/* Form selects don't need form controls, otherwise the CSS gets weird */}
<Select defaultValue={field.value} onValueChange={field.onChange}>
<SelectTrigger className="col-span-8">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="IMMUTABLE" key="IMMUTABLE">
immutable
</SelectItem>
<SelectItem value="STABLE" key="STABLE">
stable
</SelectItem>
<SelectItem value="VOLATILE" key="VOLATILE">
volatile
</SelectItem>
</SelectContent>
</Select>
</FormItemLayout>
)}
/>
)}
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
<SheetSection className={focusedEditor ? 'hidden' : ''}>
<CreateFunctionConfigParamsSection />
</SheetSection>
<Separator className={focusedEditor ? 'hidden' : ''} />
<SheetSection className={focusedEditor ? 'hidden' : ''}>
<h5 className="text-base text-foreground mb-4">Type of Security</h5>
<FormField
control={form.control}
name="security_definer"
render={({ field }) => (
<FormItem>
<FormControl className="col-span-8">
<RadioGroupStacked
onValueChange={(value) =>
field.onChange(value == 'SECURITY_DEFINER')
}
value={field.value ? 'SECURITY_DEFINER' : 'SECURITY_INVOKER'}
>
<RadioGroupStackedItem
value="SECURITY_INVOKER"
id="SECURITY_INVOKER"
label="SECURITY INVOKER"
description={
<>
Function is to be executed with the privileges of the user
that <span className="text-foreground">calls it</span>.
</>
}
/>
<RadioGroupStackedItem
value="SECURITY_DEFINER"
id="SECURITY_DEFINER"
label="SECURITY DEFINER"
description={
<>
Function is to be executed with the privileges of the user
that <span className="text-foreground">created it</span>.
</>
}
/>
</RadioGroupStacked>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</SheetSection>
</>
)}
</>
)}
</fieldset>
</form>
</Form>
<SheetFooter>
<Button disabled={isCreating || isUpdating} onClick={confirmOnClose}>
Cancel
</Button>
<ButtonTooltip
variant="primary"
form={FORM_ID}
type="submit"
disabled={isCreating || isUpdating || !writeGrant.grant}
loading={isCreating || isUpdating}
tooltip={{
content: {
side: 'top',
text: getWriteGrantTooltip(
writeGrant.status,
isEditing ? 'update' : 'create',
'functions'
),
},
}}
>
{isEditing ? <span>Save</span> : <span>Create</span>} <span>function</span>
</ButtonTooltip>
</SheetFooter>
</div>
<DiscardChangesConfirmationDialog {...modalProps} />
</SheetContent>
</Sheet>
)
}
interface FormFieldConfigParamsProps {
readonly?: boolean
}
const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {
const { fields, append, remove } = useFieldArray<z.infer<typeof FormSchema>>({
name: 'args',
})
return (
<div className="flex flex-col gap-y-4">
<div>
<h5 className="text-base text-foreground">Arguments</h5>
<p className="text-sm text-foreground-light">
Arguments can be referenced in the function body using either names or numbers.
</p>
</div>
<div className="space-y-2">
{readonly && isEmpty(fields) && (
<span className="text-sm text-foreground-lighter">No argument for this function</span>
)}
{fields.map((field, index) => {
return (
<div className="flex flex-row space-x-1" key={field.id}>
<FormField
name={`args.${index}.name`}
render={({ field }) => (
<FormItem className="flex-1">
<FormControl>
<Input {...field} disabled={readonly} placeholder="argument_name" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name={`args.${index}.type`}
render={({ field }) => (
<FormItem className="flex-1">
<FormControl>
{readonly ? (
<Input value={field.value} disabled readOnly className="h-auto" />
) : (
<Select
disabled={readonly}
onValueChange={field.onChange}
defaultValue={field.value}
>
<SelectTrigger className="h-[34px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<ScrollArea className="h-52">
{['integer', ...POSTGRES_DATA_TYPES].map((option) => (
<SelectItem value={option} key={option}>
{option}
</SelectItem>
))}
</ScrollArea>
</SelectContent>
</Select>
)}
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{!readonly && (
<Tooltip>
<TooltipTrigger asChild>
<Button
icon={<TrashIcon size={12} />}
onClick={() => remove(index)}
className="h-[34px] w-[34px]"
aria-label="Remove argument"
// Tooltip repeats the label; screen readers would read it twice
aria-describedby={undefined}
/>
</TooltipTrigger>
<TooltipContent side="bottom">Remove </TooltipContent>
</Tooltip>
)}
</div>
)
})}
{!readonly && (
<Button
icon={<PlusIcon size={12} />}
onClick={() => append({ name: '', type: 'integer' })}
disabled={readonly}
>
Add a new argument
</Button>
)}
</div>
</div>
)
}
const ALL_ALLOWED_LANGUAGES = ['plpgsql', 'sql', 'plcoffee', 'plv8', 'plls']
const FormFieldLanguage = () => {
const { data: project } = useSelectedProjectQuery()
const { data: enabledExtensions } = useDatabaseExtensionsQuery(
{
projectRef: project?.ref,
connectionString: project?.connectionString,
},
{
select(data) {
return partition(data, (ext) => !isNull(ext.installed_version))[0]
},
}
)
const allowedLanguages = useMemo(() => {
return ALL_ALLOWED_LANGUAGES.filter((lang) => {
if (lang.startsWith('pl')) {
return enabledExtensions?.find((ex) => ex.name === lang) !== undefined
}
return true
})
}, [enabledExtensions])
return (
<FormField
name="language"
render={({ field }) => (
<FormItemLayout label="Language" layout="horizontal">
{/* Form selects don't need form controls, otherwise the CSS gets weird */}
<Select onValueChange={field.onChange} defaultValue={field.value}>
<SelectTrigger className="col-span-8">
<SelectValue />
</SelectTrigger>
<SelectContent>
{allowedLanguages.map((option) => (
<SelectItem value={option} key={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItemLayout>
)}
/>
)
}