The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add support for managing stored procedures under database functions (#46977)
Joshen Lim097f220c5cb8
diff --git a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsxindex 8363f32de1c..24055a99f51 100644--- a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx+++ b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx@@ -412,7 +412,10 @@ revoke execute on function ${ident(schema)}.${ident(functionName)} from authentidisabled={field.disabled}filterFunction={(func) => {if (supportedReturnTypes.includes(func.return_type)) {- const { value } = convertArgumentTypes(func.argument_types)+ const { value } = convertArgumentTypes({+ type: func.type,+ value: func.argument_types,+ })if (value.length !== 1) return falsereturn value[0].type === 'json' || value[0].type === 'jsonb'}diff --git a/apps/studio/components/interfaces/Database/Functions/CreateFunction/CreateFunctionHeader.tsx b/apps/studio/components/interfaces/Database/Functions/CreateFunction/CreateFunctionHeader.tsxindex 78129118d5d..4a705baaec7 100644--- a/apps/studio/components/interfaces/Database/Functions/CreateFunction/CreateFunctionHeader.tsx+++ b/apps/studio/components/interfaces/Database/Functions/CreateFunction/CreateFunctionHeader.tsx@@ -1,5 +1,4 @@-import { X } from 'lucide-react'-import { cn, SheetClose, SheetHeader, SheetTitle } from 'ui'+import { SheetHeader, SheetTitle } from 'ui'interface CreateFunctionHeaderProps {selectedFunction?: string@@ -13,23 +12,20 @@ export const CreateFunctionHeader = ({return (<SheetHeader className="py-3 flex flex-row justify-between items-center border-b-0"><div className="flex flex-row gap-3 items-center max-w-[75%]">- <SheetClose- className={cn(- 'text-muted hover:text ring-offset-background transition-opacity hover:opacity-100',- 'focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2',- 'disabled:pointer-events-none data-[state=open]:bg-secondary',- 'transition'- )}- >- <X className="h-3 w-3" />- <span className="sr-only">Close</span>- </SheetClose><SheetTitle className="truncate">- {selectedFunction !== undefined- ? isDuplicating- ? `Duplicate function`- : `Edit '${selectedFunction}' function`- : 'Add a new function'}+ {selectedFunction !== undefined ? (+ isDuplicating ? (+ <>+ Duplicate <code className="text-code-inline text-sm">{selectedFunction}</code>+ </>+ ) : (+ <>+ Edit <code className="text-code-inline text-sm">{selectedFunction}</code>+ </>+ )+ ) : (+ 'Add a new function'+ )}</SheetTitle></div></SheetHeader>diff --git a/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx b/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsxindex 5e425d93784..789208cb6d3 100644--- a/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx+++ b/apps/studio/components/interfaces/Database/Functions/CreateFunction/index.tsx@@ -45,6 +45,7 @@ import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-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'@@ -60,6 +61,7 @@ interface CreateFunctionProps {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']),@@ -78,7 +80,9 @@ export const CreateFunction = ({isDuplicating = false,onClose,}: CreateFunctionProps) => {+ const { selectedSchema } = useQuerySchemaState()const { data: project } = useSelectedProjectQuery()+const [advancedSettingsShown, setAdvancedSettingsShown] = useState(false)const [focusedEditor, setFocusedEditor] = useState(false)@@ -87,7 +91,7 @@ export const CreateFunction = ({const form = useForm<z.infer<typeof FormSchema>>({resolver: zodResolver(FormSchema),})- const language = form.watch('language')+ const { type, language } = form.watch()const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({checkIsDirty: () => form.formState.isDirty,@@ -147,10 +151,12 @@ export const CreateFunction = ({useEffect(() => {if (visible) {setFocusedEditor(false)+ const type = func?.type ?? 'function'form.reset({+ type,name: func?.name ?? '',- schema: func?.schema ?? 'public',- args: convertArgumentTypes(func?.argument_types || '').value,+ schema: func?.schema ?? selectedSchema,+ args: convertArgumentTypes({ type, value: func?.argument_types || '' }).value,behavior: func?.behavior ?? 'VOLATILE',definition: func?.definition ?? '',language: func?.language ?? 'plpgsql',@@ -167,20 +173,46 @@ export const CreateFunction = ({return (<Sheet open={visible} onOpenChange={handleOpenChange}><SheetContent- showClose={false}- size={'default'}- className={'p-0 flex flex-row gap-0 min-w-screen! lg:min-w-[600px]!'}+ 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}><formid={FORM_ID}className="grow overflow-auto"onSubmit={form.handleSubmit(onSubmit)}>- <SheetSection className={focusedEditor ? 'hidden' : ''}>+ <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 className="text-code-inline">public</code>+ </>+ }+ layout="horizontal"+ >+ <FormControl>+ <SchemaSelector+ selectedSchemaName={field.value}+ excludedSchemas={protectedSchemas?.map((s) => s.name)}+ size="small"+ onSelectSchema={(name) => field.onChange(name)}+ />+ </FormControl>+ </FormItemLayout>+ )}+ /><FormFieldcontrol={form.control}name="name"@@ -197,36 +229,53 @@ export const CreateFunction = ({)}/></SheetSection>+<Separator className={focusedEditor ? 'hidden' : ''} />- <SheetSection className={focusedEditor ? 'hidden' : 'space-y-4'}>++ <SheetSection className={focusedEditor ? 'hidden' : 'flex flex-col gap-y-4'}><FormFieldcontrol={form.control}- name="schema"+ name="type"render={({ field }) => (- <FormItemLayout- label="Schema"- description="Tables made in the table editor will be in 'public'"- layout="horizontal"- >- <FormControl>- <SchemaSelector- selectedSchemaName={field.value}- excludedSchemas={protectedSchemas?.map((s) => s.name)}- size="small"- onSelectSchema={(name) => field.onChange(name)}- />- </FormControl>+ <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>)}/>- {!isEditing && (+ {type === 'function' && (<FormFieldcontrol={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 onValueChange={field.onChange} defaultValue={field.value}>+ <Select+ disabled={isEditing}+ onValueChange={field.onChange}+ defaultValue={field.value}+ ><SelectTrigger className="col-span-8"><SelectValue /></SelectTrigger>@@ -247,11 +296,15 @@ export const CreateFunction = ({/>)}</SheetSection>+<Separator className={focusedEditor ? 'hidden' : ''} />+<SheetSection className={focusedEditor ? 'hidden' : ''}><FormFieldArgs readonly={isEditing} /></SheetSection>+<Separator className={focusedEditor ? 'hidden' : ''} />+<SheetSection className={`${focusedEditor ? 'h-full' : ''} px-0!`}><FormFieldcontrol={form.control}@@ -262,7 +315,8 @@ export const CreateFunction = ({<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>.+ The language below should be written in{' '}+ <code className="text-code-inline">{language}</code>.</p>{!isEditing && <p>Change the language in the Advanced Settings below.</p>}</FormDescription>@@ -287,16 +341,14 @@ export const CreateFunction = ({/></SheetSection><Separator className={focusedEditor ? 'hidden' : ''} />- {isEditing ? (- <></>- ) : (+ {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-base">Show advanced settings</FormLabel>- <FormDescription>+ <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>@@ -313,31 +365,33 @@ export const CreateFunction = ({<><SheetSection className={focusedEditor ? 'hidden' : 'space-y-2 pt-0'}><FormFieldLanguage />- <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>- )}- />+ {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' : ''}>@@ -423,16 +477,16 @@ const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {})return (- <>- <div className="flex flex-col">+ <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 pt-4">+ <div className="space-y-2">{readonly && isEmpty(fields) && (- <span className="text-foreground-lighter">No argument for this function</span>+ <span className="text-sm text-foreground-lighter">No argument for this function</span>)}{fields.map((field, index) => {return (@@ -456,26 +510,24 @@ const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {{readonly ? (<Input value={field.value} disabled readOnly className="h-auto" />) : (- <>- <Select- disabled={readonly}- onValueChange={field.onChange}- defaultValue={field.value}- >- <SelectTrigger className="h-[38px]">- <SelectValue />- </SelectTrigger>- <SelectContent>- <ScrollArea className="h-52">- {['integer', ...POSTGRES_DATA_TYPES].map((option) => (- <SelectItem value={option} key={option}>- {option}- </SelectItem>- ))}- </ScrollArea>- </SelectContent>- </Select>- </>+ <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 />@@ -485,10 +537,10 @@ const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {{!readonly && (<Button- variant="danger"+ variant="default"icon={<Trash size={12} />}onClick={() => remove(index)}- className="h-[38px] w-[38px]"+ className="h-[34px] w-[34px]"/>)}</div>@@ -506,7 +558,7 @@ const FormFieldArgs = ({ readonly }: FormFieldConfigParamsProps) => {</Button>)}</div>- </>+ </div>)}diff --git a/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts b/apps/studio/components/interfaces/Database/Functions/Functions.utils.tsindex 392cf12b978..89c4dace653 100644--- a/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts+++ b/apps/studio/components/interfaces/Database/Functions/Functions.utils.ts@@ -1,11 +1,27 @@import { isEmpty } from 'lodash'+/**+ * Procedures expose their arguments with explicit `IN` mode prefixes+ * (e.g. "IN a integer, IN b integer"); strip them so they read like functions.+ * `INOUT`/`VARIADIC` are left intact since `IN\s+` requires whitespace after `IN`.+ */+export function stripInArgModePrefixes(value: string) {+ return value?.replace(/(^|,)\s*IN\s+/gi, '$1')+}+/*** convert argument_types = "a integer, b integer"* to args = {value: [{name:'a', type:'integer'}, {name:'b', type:'integer'}]}*/-export function convertArgumentTypes(value: string) {- const items = value?.split(',').map((item) => item.trim())+export function convertArgumentTypes({+ type,+ value,+}: {+ type: 'function' | 'procedure'+ value: string+}) {+ const normalizedValue = type === 'procedure' ? stripInArgModePrefixes(value) : value+ const items = normalizedValue?.split(',').map((item) => item.trim())if (isEmpty(value) || !items || items.length === 0) return { value: [] }const temp = itemsdiff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsxindex a7c27c50792..20e9822aecd 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx@@ -1,10 +1,12 @@import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'import { includes, noop, sortBy } from 'lodash'import { Copy, Edit, Edit2, FileText, MoreVertical, Trash } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import {Button,+ cn,DropdownMenu,DropdownMenuContent,DropdownMenuItem,@@ -14,29 +16,31 @@ import {TableRow,} from 'ui'+import { stripInArgModePrefixes } from '../Functions.utils'import { getDatabaseTriggersHref } from './FunctionList.utils'import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import type { DatabaseFunction } from '@/data/database-functions/database-functions-query'+import {+ useDatabaseFunctionsQuery,+ type SavedDatabaseFunction,+} from '@/data/database-functions/database-functions-query'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'+import { useQuerySchemaState } from '@/hooks/misc/useSchemaQueryState'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'interface FunctionListProps {- schema: stringfilterString: stringisLocked: booleanreturnTypeFilter: string[]securityFilter: string[]- duplicateFunction: (fn: any) => void- editFunction: (fn: any) => void- deleteFunction: (fn: any) => void- functions: DatabaseFunction[]+ duplicateFunction: (fn: SavedDatabaseFunction) => void+ editFunction: (fn: SavedDatabaseFunction) => void+ deleteFunction: (fn: SavedDatabaseFunction) => void}-const FunctionList = ({- schema,+export const FunctionList = ({filterString,isLocked,returnTypeFilter,@@ -44,13 +48,20 @@ const FunctionList = ({duplicateFunction = noop,editFunction = noop,deleteFunction = noop,- functions,}: FunctionListProps) => {const router = useRouter()- const { data: selectedProject } = useSelectedProjectQuery()+ const { ref: projectRef } = useParams()+ const { data: project } = useSelectedProjectQuery()+ const { selectedSchema: schema } = useQuerySchemaState()const aiSnap = useAiAssistantStateSnapshot()const { openSidebar } = useSidebarManagerSnapshot()+ const { data: functions = [] } = useDatabaseFunctionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ schema,+ })+const filteredFunctions = (functions ?? []).filter((x) => {const matchesName = includes(x.name.toLowerCase(), filterString.toLowerCase())const matchesReturnType =@@ -61,11 +72,12 @@ const FunctionList = ({(securityFilter.includes('invoker') && !x.security_definer)return matchesName && matchesReturnType && matchesSecurity})+const _functions = sortBy(filteredFunctions.filter((x) => x.schema == schema),(func) => func.name.toLocaleLowerCase())- const projectRef = selectedProject?.ref+const { can: canUpdateFunctions } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,'functions'@@ -100,7 +112,9 @@ const FunctionList = ({return (<>{_functions.map((x) => {- const isApiDocumentAvailable = schema == 'public' && x.return_type !== 'trigger'+ const isApiDocumentAvailable = schema === 'public' && x.return_type !== 'trigger'+ const argumentTypes =+ x.type === 'procedure' ? stripInArgModePrefixes(x.argument_types) : x.argument_typesreturn (<TableRow key={x.id}>@@ -115,12 +129,13 @@ const FunctionList = ({{x.name}</Button></TableCell>+ <TableCell className="table-cell text-foreground-light capitalize">{x.type}</TableCell><TableCell className="table-cell"><p- title={x.argument_types}- className={`truncate ${x.argument_types ? 'text-foreground-light' : 'text-foreground-muted'}`}+ title={argumentTypes}+ className={`truncate ${argumentTypes ? 'text-foreground-light' : 'text-foreground-muted'}`}>- {x.argument_types || '–'}+ {argumentTypes || '–'}</p></TableCell><TableCell className="table-cell">@@ -133,8 +148,14 @@ const FunctionList = ({{x.return_type}</Link>) : (- <p title={x.return_type} className="truncate text-foreground-light">- {x.return_type}+ <p+ title={x.return_type}+ className={cn(+ 'truncate',+ x.return_type === null ? 'text-foreground-muted' : 'text-foreground-light'+ )}+ >+ {x.return_type === null ? '–' : x.return_type}</p>)}</TableCell>@@ -158,15 +179,21 @@ const FunctionList = ({</DropdownMenuTrigger><DropdownMenuContent side="left" className="w-52">{isApiDocumentAvailable && (- <DropdownMenuItem- className="space-x-2"- onClick={() => router.push(`/project/${projectRef}/api?rpc=${x.name}`)}- >- <FileText size={14} />- <p>Client API docs</p>- </DropdownMenuItem>+ <>+ <DropdownMenuItem+ className="space-x-2"+ onClick={() =>+ router.push(+ `/project/${projectRef}/api?rpc=${encodeURIComponent(x.name)}`+ )+ }+ >+ <FileText size={14} />+ <p>Client API docs</p>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>)}- <DropdownMenuSeparator /><DropdownMenuItem className="space-x-2" onClick={() => editFunction(x)}><Edit2 size={14} /><p>Edit function</p>@@ -241,5 +268,3 @@ const FunctionList = ({</>)}--export default FunctionListdiff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsxindex 785b085c018..7e75986a65c 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx@@ -1,6 +1,6 @@import { safeSql } from '@supabase/pg-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'-import { Search } from 'lucide-react'+import { Database, Plus, Search } from 'lucide-react'import { parseAsBoolean, parseAsJson, parseAsString, useQueryState } from 'nuqs'import { useEffect, useRef, useState } from 'react'import { toast } from 'sonner'@@ -14,11 +14,12 @@ import {TableHeader,TableRow,} from 'ui'+import { EmptyStatePresentational } from 'ui-patterns'import { Input } from 'ui-patterns/DataInputs/Input'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import { ProtectedSchemaWarning } from '../../ProtectedSchemaWarning'-import FunctionList from './FunctionList'+import { FunctionList } from './FunctionList'import { useIsInlineEditorEnabled } from '@/components/interfaces/Account/Preferences/useDashboardSettings'import { CreateFunction } from '@/components/interfaces/Database/Functions/CreateFunction'import {@@ -26,7 +27,6 @@ import {selectFilterSchema,} from '@/components/interfaces/Reports/v2/ReportsSelectFilter'import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'-import ProductEmptyState from '@/components/to-be-cleaned/ProductEmptyState'import AlertError from '@/components/ui/AlertError'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import SchemaSelector from '@/components/ui/SchemaSelector'@@ -131,8 +131,6 @@ export const FunctionsList = () => {const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedSchema })- const canAddFunctions = canCreateFunctions && !isSchemaLocked-useShortcut(SHORTCUT_IDS.LIST_PAGE_FOCUS_SEARCH,() => {@@ -163,11 +161,14 @@ export const FunctionsList = () => {} = useDatabaseFunctionsQuery({projectRef: project?.ref,connectionString: project?.connectionString,+ schema: selectedSchema,})// Get unique return types from functions in the selected schemaconst schemaFunctions = functions.filter((fn) => fn.schema === selectedSchema)- const uniqueReturnTypes = Array.from(new Set(schemaFunctions.map((fn) => fn.return_type))).sort()+ const uniqueReturnTypes = Array.from(new Set(schemaFunctions.map((fn) => fn.return_type)))+ .filter(Boolean)+ .sort()// Get security options based on what exists in the selected schemaconst hasDefiner = schemaFunctions.some((fn) => fn.security_definer)@@ -248,135 +249,105 @@ export const FunctionsList = () => {return (<>- {(functions ?? []).length === 0 ? (- <div className="flex h-full w-full items-center justify-center">- <ProductEmptyState- title="Functions"- ctaButtonLabel="Create a new function"- onClickCta={() => createFunction()}- disabled={!canCreateFunctions}- disabledMessage="You need additional permissions to create functions"- >- <p className="text-sm text-foreground-light">- PostgreSQL functions are a set of SQL and procedural commands such as declarations,- assignments, loops, flow-of-control, etc.- </p>- <p className="text-sm text-foreground-light">- It's stored on the database server and can be invoked using the SQL interface.- </p>- </ProductEmptyState>- </div>- ) : (- <div className="w-full space-y-4">- <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-2 flex-wrap">- <div className="flex flex-col lg:flex-row lg:items-center gap-2">- <Shortcut- id={SHORTCUT_IDS.LIST_PAGE_FOCUS_SCHEMA}- onTrigger={() => setSchemaSelectorOpen(true)}- side="bottom"- tooltipOpen={schemaSelectorOpen ? false : undefined}- >- <SchemaSelector- className="w-full lg:w-[180px]"- size="tiny"- showError={false}- selectedSchemaName={selectedSchema}- onSelectSchema={(schema) => {- setFilterString('')- setSelectedSchema(schema)- }}- open={schemaSelectorOpen}- onOpenChange={setSchemaSelectorOpen}- />- </Shortcut>- <Input- ref={searchInputRef}- placeholder="Search for a function"+ <div className="w-full space-y-4">+ <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-2 flex-wrap">+ <div className="flex flex-col lg:flex-row lg:items-center gap-2">+ <Shortcut+ id={SHORTCUT_IDS.LIST_PAGE_FOCUS_SCHEMA}+ onTrigger={() => setSchemaSelectorOpen(true)}+ side="bottom"+ tooltipOpen={schemaSelectorOpen ? false : undefined}+ >+ <SchemaSelector+ className="w-full lg:w-[180px]"size="tiny"- icon={<Search />}- value={filterString}- className="w-full lg:w-52"- onChange={(e) => setFilterString(e.target.value)}- onKeyDown={onSearchInputEscape(filterString, setFilterString)}- />- <ReportsSelectFilter- label="Return Type"- options={uniqueReturnTypes.map((type) => ({- label: type,- value: type,- }))}- value={returnTypeFilter ?? []}- onChange={setReturnTypeFilter}- showSearch- />- <ReportsSelectFilter- label="Security"- options={securityOptions}- value={securityFilter ?? []}- onChange={setSecurityFilter}+ showError={false}+ selectedSchemaName={selectedSchema}+ onSelectSchema={(schema) => {+ setFilterString('')+ setSelectedSchema(schema)+ }}+ open={schemaSelectorOpen}+ onOpenChange={setSchemaSelectorOpen}/>- </div>-- <div className="flex items-center gap-x-2">- {!isSchemaLocked && (- <>- {canAddFunctions ? (- <Shortcut- id={SHORTCUT_IDS.LIST_PAGE_NEW_ITEM}- label="Create new function"- onTrigger={() => createFunction()}- side="bottom"- >- <Button className="grow" onClick={() => createFunction()}>- Create a new function- </Button>- </Shortcut>- ) : (- <ButtonTooltip- disabled- className="grow"- tooltip={{- content: {- side: 'bottom',- text: 'You need additional permissions to create functions',- },- }}- >- Create a new function- </ButtonTooltip>- )}- <ButtonTooltip- variant="default"- disabled={!canCreateFunctions}- className="px-1 pointer-events-auto"- icon={<AiIconAnimation size={16} />}- onClick={() => {- openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)- aiSnap.newChat({- name: 'Create new function',- initialInput: `Create a new function for the schema ${selectedSchema} that does ...`,- })- }}- tooltip={{- content: {- side: 'bottom',- text: !canCreateFunctions- ? 'You need additional permissions to create functions'- : 'Create with Supabase Assistant',- },- }}- />- </>- )}- </div>+ </Shortcut>+ <Input+ ref={searchInputRef}+ placeholder="Search for a function"+ size="tiny"+ icon={<Search />}+ value={filterString}+ className="w-full lg:w-52"+ onChange={(e) => setFilterString(e.target.value)}+ onKeyDown={onSearchInputEscape(filterString, setFilterString)}+ />+ <ReportsSelectFilter+ label="Return Type"+ options={uniqueReturnTypes.map((type) => ({+ label: type,+ value: type,+ }))}+ value={returnTypeFilter ?? []}+ onChange={setReturnTypeFilter}+ showSearch+ />+ <ReportsSelectFilter+ label="Security"+ options={securityOptions}+ value={securityFilter ?? []}+ onChange={setSecurityFilter}+ /></div>- {isSchemaLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="functions" />}+ <div className="flex items-center gap-x-2">+ {!isSchemaLocked && (+ <>+ <CreateFunctionButton createFunction={createFunction} />+ <ButtonTooltip+ variant="default"+ disabled={!canCreateFunctions}+ className="px-1 pointer-events-auto"+ icon={<AiIconAnimation size={16} />}+ onClick={() => {+ openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)+ aiSnap.newChat({+ name: 'Create new function',+ initialInput: `Create a new function for the schema ${selectedSchema} that does ...`,+ })+ }}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canCreateFunctions+ ? 'You need additional permissions to create functions'+ : 'Create with Supabase Assistant',+ },+ }}+ />+ </>+ )}+ </div>+ </div>++ {isSchemaLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="functions" />}++ {functions.length === 0 ? (+ <>+ <EmptyStatePresentational+ icon={Database}+ title="Add your first function"+ description="PostgreSQL functions are a set of SQL and procedural commands such as declarations, assignments, loops, or flow-of-control."+ >+ <CreateFunctionButton hideIcon variant="default" createFunction={createFunction} />+ </EmptyStatePresentational>+ </>+ ) : (<Card><Table className="table-fixed overflow-x-auto"><TableHeader><TableRow><TableHead key="name">Name</TableHead>+ <TableHead key="type">Type</TableHead><TableHead key="arguments" className="table-cell">Arguments</TableHead>@@ -391,7 +362,6 @@ export const FunctionsList = () => {</TableHeader><TableBody><FunctionList- schema={selectedSchema}filterString={filterString}isLocked={isSchemaLocked}returnTypeFilter={returnTypeFilter ?? []}@@ -399,13 +369,12 @@ export const FunctionsList = () => {duplicateFunction={duplicateFunction}editFunction={editFunction}deleteFunction={(fn) => setSelectedFunctionToDelete(fn.id.toString())}- functions={functions ?? []}/></TableBody></Table></Card>- </div>- )}+ )}+ </div><CreateFunctionfunc={functionToEdit || functionToDuplicate}@@ -419,7 +388,7 @@ export const FunctionsList = () => {/><TextConfirmModal- variant={'warning'}+ variant="destructive"visible={!!functionToDelete}onCancel={() => setSelectedFunctionToDelete(null)}onConfirm={onDeleteFunction}@@ -441,3 +410,58 @@ export const FunctionsList = () => {</>)}++const CreateFunctionButton = ({+ variant = 'primary',+ hideIcon = false,+ createFunction,+}: {+ variant?: 'default' | 'primary'+ hideIcon?: boolean+ createFunction: () => void+}) => {+ const { selectedSchema } = useQuerySchemaState()+ const { can: canCreateFunctions } = useAsyncCheckPermissions(+ PermissionAction.TENANT_SQL_ADMIN_WRITE,+ 'functions'+ )+ const { isSchemaLocked } = useIsProtectedSchema({ schema: selectedSchema })+ const canAddFunctions = canCreateFunctions && !isSchemaLocked++ if (canAddFunctions) {+ return (+ <Shortcut+ id={SHORTCUT_IDS.LIST_PAGE_NEW_ITEM}+ label="Create new function"+ onTrigger={() => createFunction()}+ side="bottom"+ >+ <Button+ variant={variant}+ className="grow"+ onClick={() => createFunction()}+ icon={hideIcon ? null : <Plus />}+ >+ New function+ </Button>+ </Shortcut>+ )+ } else {+ return (+ <ButtonTooltip+ disabled+ variant={variant}+ className="grow"+ icon={hideIcon ? null : <Plus />}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create functions',+ },+ }}+ >+ New function+ </ButtonTooltip>+ )+ }+}diff --git a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsxindex 33fa3698d31..85053d5f71a 100644--- a/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx+++ b/apps/studio/components/interfaces/Database/Schemas/SchemaGraph.tsx@@ -513,7 +513,7 @@ export const SchemaGraph = () => {}>{canAddTables && (- <Button asChild className="mt-2" variant="default" icon={<Plus />}>+ <Button asChild className="mt-2 w-min" variant="default" icon={<Plus />}><Link href={`/project/${ref}/editor?create=table`}>New table</Link></Button>)}diff --git a/apps/studio/data/database-functions/database-functions-delete-mutation.ts b/apps/studio/data/database-functions/database-functions-delete-mutation.tsindex e4b6d55c254..d8c857d9da3 100644--- a/apps/studio/data/database-functions/database-functions-delete-mutation.ts+++ b/apps/studio/data/database-functions/database-functions-delete-mutation.ts@@ -19,7 +19,7 @@ export async function deleteDatabaseFunction({connectionString,func,}: DatabaseFunctionDeleteVariables) {- const { sql, zod } = pgMeta.functions.remove(func)+ const { sql, zod } = pgMeta.functions.remove(func, { type: func.type })const { result } = await executeSql({projectRef,diff --git a/apps/studio/data/database-functions/database-functions-query.ts b/apps/studio/data/database-functions/database-functions-query.tsindex 184454d9d33..688a3abf385 100644--- a/apps/studio/data/database-functions/database-functions-query.ts+++ b/apps/studio/data/database-functions/database-functions-query.ts@@ -9,6 +9,7 @@ import type { ResponseError, UseCustomQueryOptions } from '@/types'export type DatabaseFunctionsVariables = {projectRef?: stringconnectionString?: string | null+ schema?: string}export type DatabaseFunction = z.infer<typeof pgMeta.functions.pgFunctionZod>@@ -25,17 +26,19 @@ export type SavedDatabaseFunction = Omit<identity_argument_types: SafeSqlFragmentreturn_type: SafeSqlFragmentconfig_params: Record<string, SafeSqlFragment> | null+ type: 'function' | 'procedure'}-const pgMetaFunctionsList = pgMeta.functions.list()-export async function getDatabaseFunctions(- { projectRef, connectionString }: DatabaseFunctionsVariables,+ { projectRef, connectionString, schema }: DatabaseFunctionsVariables,signal?: AbortSignal,headersInit?: HeadersInit) {let headers = new Headers(headersInit)+ const pgMetaFunctionsList = pgMeta.functions.list({+ includedSchemas: schema ? [schema] : undefined,+ })const { result } = await executeSql({projectRef,@@ -54,15 +57,17 @@ export type DatabaseFunctionsData = Awaited<ReturnType<typeof getDatabaseFunctioexport type DatabaseFunctionsError = ResponseErrorexport const useDatabaseFunctionsQuery = <TData = DatabaseFunctionsData>(- { projectRef, connectionString }: DatabaseFunctionsVariables,+ vars: DatabaseFunctionsVariables,{enabled = true,...options}: UseCustomQueryOptions<DatabaseFunctionsData, DatabaseFunctionsError, TData> = {}-) =>- useQuery<DatabaseFunctionsData, DatabaseFunctionsError, TData>({- queryKey: databaseKeys.databaseFunctions(projectRef),- queryFn: ({ signal }) => getDatabaseFunctions({ projectRef, connectionString }, signal),+) => {+ const { projectRef, schema } = vars+ return useQuery<DatabaseFunctionsData, DatabaseFunctionsError, TData>({+ queryKey: databaseKeys.databaseFunctions(projectRef, schema),+ queryFn: ({ signal }) => getDatabaseFunctions(vars, signal),enabled: enabled && typeof projectRef !== 'undefined',...options,})+}diff --git a/apps/studio/data/database-functions/database-functions-update-mutation.ts b/apps/studio/data/database-functions/database-functions-update-mutation.tsindex da01a462a4e..28c4e28ca27 100644--- a/apps/studio/data/database-functions/database-functions-update-mutation.ts+++ b/apps/studio/data/database-functions/database-functions-update-mutation.ts@@ -1,5 +1,5 @@import pgMeta from '@supabase/pg-meta'-import type { PGFunctionCreate } from '@supabase/pg-meta/src/pg-meta-functions'+import type { PGFunctionUpdate } from '@supabase/pg-meta/src/pg-meta-functions'import { useMutation, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'import { z } from 'zod'@@ -13,7 +13,7 @@ export type DatabaseFunctionUpdateVariables = {projectRef: stringconnectionString?: string | nullfunc: SavedDatabaseFunction- payload: PGFunctionCreate+ payload: PGFunctionUpdate}export async function updateDatabaseFunction({diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.tsindex aa6033e2977..9a2b67d9aa6 100644--- a/apps/studio/data/database/keys.ts+++ b/apps/studio/data/database/keys.ts@@ -9,8 +9,8 @@ export const databaseKeys = {schema: string | undefined,table: string | undefined) => ['projects', projectRef, 'table-columns', schema, table] as const,- databaseFunctions: (projectRef: string | undefined) =>- ['projects', projectRef, 'database-functions'] as const,+ databaseFunctions: (projectRef: string | undefined, schema?: string) =>+ ['projects', projectRef, 'database-functions', schema].filter(Boolean),entityDefinition: (projectRef: string | undefined, id?: number) =>['projects', projectRef, 'entity-definition', id] as const,entityDefinitions: (projectRef: string | undefined, schemas: string[]) =>diff --git a/e2e/studio/features/database.spec.ts b/e2e/studio/features/database.spec.tsindex 9ce50e800f2..2a0e1822e8b 100644--- a/e2e/studio/features/database.spec.ts+++ b/e2e/studio/features/database.spec.ts@@ -1274,7 +1274,8 @@ test.describe('Database Functions', () => {await page.waitForLoadState('networkidle')// create a new function button exists in public schema- await expect(page.getByRole('button', { name: 'Create a new function' })).toBeVisible()+ const newFunctionButton = page.getByRole('button', { name: 'New function' }).first()+ await expect(newFunctionButton).toBeVisible()// change schema -> authawait page.getByTestId('schema-selector').click()@@ -1283,7 +1284,7 @@ test.describe('Database Functions', () => {await expect(page.getByText('email')).toBeVisible()await expect(page.getByText('jwt')).toBeVisible()// create a new function button does not exist in other schemas- await expect(page.getByRole('button', { name: 'Create a new function' })).not.toBeVisible()+ await expect(page.getByRole('button', { name: 'New function' })).not.toBeVisible()// filter by queryingawait page.getByRole('textbox', { name: 'Search for a function' }).fill('email')@@ -1311,7 +1312,7 @@ test.describe('Database Functions', () => {await page.waitForLoadState('networkidle')// create new function- await page.getByRole('button', { name: 'Create a new function' }).click()+ await page.getByRole('button', { name: 'New function' }).first().click()await page.getByRole('textbox', { name: 'Name of function' }).fill(databaseFunctionName)const editor = page.getByRole('presentation')await editor.click()diff --git a/packages/pg-meta/src/pg-meta-functions.ts b/packages/pg-meta/src/pg-meta-functions.tsindex 720991d349d..45054a18dc8 100644--- a/packages/pg-meta/src/pg-meta-functions.ts+++ b/packages/pg-meta/src/pg-meta-functions.ts@@ -12,6 +12,9 @@ import {} from './pg-format'import { FUNCTIONS_SQL } from './sql/functions'+export const pgRoutineKindZod = z.enum(['function', 'procedure'])+export type PGRoutineKind = z.infer<typeof pgRoutineKindZod>+export const pgFunctionZod = z.object({id: z.number(),schema: z.string(),@@ -33,6 +36,7 @@ export const pgFunctionZod = z.object({has_default: z.boolean(),})),+ type: pgRoutineKindZod,argument_types: z.string(),identity_argument_types: z.string(),return_type_id: z.number(),@@ -174,6 +178,8 @@ export function retrieve({export const pgFunctionCreateZod = z.object({name: z.string(),definition: z.string(),+ // 'procedure' omits RETURNS, behavior, and strictness — see _generateCreateFunctionSql+ type: pgRoutineKindZod.optional(),args: z.array(z.string()).optional(),behavior: z.enum(['IMMUTABLE', 'STABLE', 'VOLATILE']).optional(),config_params: z.record(z.string(), z.string()).optional(),@@ -242,9 +248,11 @@ function _generateCreateFunctionSql(behavior,security_definer,config_params,+ type = 'function',}: PGFunctionCreate,{ replace = false } = {}): SafeSqlFragment {+ const isProcedure = type === 'procedure'const argsFragment = args && args.length > 0 ? joinSqlFragments(args, ', ') : safeSql``const configParamsFragment =config_params && Object.keys(config_params).length > 0@@ -258,13 +266,14 @@ function _generateCreateFunctionSql(): safeSql``+ // Procedures don't accept a RETURNS clause, a volatility category, or a+ // strictness clause (CALLED ON NULL INPUT) — only functions do.return safeSql`- CREATE ${replace ? safeSql`OR REPLACE` : safeSql``} FUNCTION ${ident(schema!)}.${ident(name!)}(${argsFragment})- RETURNS ${return_type!}+ CREATE ${replace ? safeSql`OR REPLACE` : safeSql``} ${isProcedure ? safeSql`PROCEDURE` : safeSql`FUNCTION`} ${ident(schema!)}.${ident(name!)}(${argsFragment})+ ${isProcedure ? safeSql`` : safeSql`RETURNS ${return_type!}`}AS ${literal(definition)}LANGUAGE ${keyword(language!)}- ${keyword(behavior!)}- CALLED ON NULL INPUT+ ${isProcedure ? safeSql`` : safeSql`${keyword(behavior!)} CALLED ON NULL INPUT`}${security_definer ? safeSql`SECURITY DEFINER` : safeSql`SECURITY INVOKER`}${configParamsFragment};`@@ -280,6 +289,7 @@ export function create({behavior = 'VOLATILE',security_definer = false,config_params = {},+ type = 'function',}: PGFunctionCreate) {const sql = _generateCreateFunctionSql({name,@@ -291,6 +301,7 @@ export function create({behavior,security_definer,config_params,+ type,})return {@@ -317,6 +328,7 @@ export function update(): { sql: SafeSqlFragment; zod: z.ZodType<void> } {const args = splitArgumentTypes(currentFunc.argument_types)const identityArgs = currentFunc.identity_argument_types+ const routineKeyword = currentFunc.type === 'procedure' ? safeSql`PROCEDURE` : safeSql`FUNCTION`const updateDefinitionSql =typeof definition === 'string'@@ -326,6 +338,7 @@ export function update(definition,args,config_params: currentFunc.config_params ?? {},+ type: currentFunc.type,},{ replace: true })@@ -333,12 +346,12 @@ export function update(const updateNameSql =name && name !== currentFunc.name- ? safeSql`ALTER FUNCTION ${ident(currentFunc.schema)}.${ident(currentFunc.name)}(${identityArgs}) RENAME TO ${ident(name)};`+ ? safeSql`ALTER ${routineKeyword} ${ident(currentFunc.schema)}.${ident(currentFunc.name)}(${identityArgs}) RENAME TO ${ident(name)};`: safeSql``const updateSchemaSql =schema && schema !== currentFunc.schema- ? safeSql`ALTER FUNCTION ${ident(currentFunc.schema)}.${ident(name || currentFunc.name)}(${identityArgs}) SET SCHEMA ${ident(schema)};`+ ? safeSql`ALTER ${routineKeyword} ${ident(currentFunc.schema)}.${ident(name || currentFunc.name)}(${identityArgs}) SET SCHEMA ${ident(schema)};`: safeSql``const sql = safeSql`@@ -373,6 +386,7 @@ export function update(export const pgFunctionDeleteZod = z.object({cascade: z.boolean().default(false).optional(),+ type: pgRoutineKindZod.optional(),})export type PGFunctionDelete = z.infer<typeof pgFunctionDeleteZod>@@ -381,7 +395,8 @@ export function remove(func: PGSavedFunction,{ cascade = false }: PGFunctionDelete = {}): { sql: SafeSqlFragment; zod: z.ZodType<void> } {- const sql = safeSql`DROP FUNCTION ${ident(func.schema)}.${ident(func.name)}(${func.identity_argument_types}) ${cascade ? safeSql`CASCADE` : safeSql`RESTRICT`};`+ const routineKeyword = func.type === 'procedure' ? safeSql`PROCEDURE` : safeSql`FUNCTION`+ const sql = safeSql`DROP ${routineKeyword} ${ident(func.schema)}.${ident(func.name)}(${func.identity_argument_types}) ${cascade ? safeSql`CASCADE` : safeSql`RESTRICT`};`return {sql,diff --git a/packages/pg-meta/src/sql/functions.ts b/packages/pg-meta/src/sql/functions.tsindex 257cb7bc5bf..7b3b6dd5f03 100644--- a/packages/pg-meta/src/sql/functions.ts+++ b/packages/pg-meta/src/sql/functions.ts@@ -25,13 +25,20 @@ with functions as (frompg_proc as pwhere- p.prokind = 'f'+ p.prokind in ('f', 'p'))selectf.oid as id,n.nspname as schema,f.proname as name,l.lanname as language,+ case f.prokind+ when 'f' then 'function'+ when 'p' then 'procedure'+ when 'a' then 'aggregate'+ when 'w' then 'window'+ else 'unknown'+ end as type,casewhen l.lanname = 'internal' then ''else f.prosrcdiff --git a/packages/pg-meta/test/functions.test.ts b/packages/pg-meta/test/functions.test.tsindex 530699fe1af..bc7c38d892f 100644--- a/packages/pg-meta/test/functions.test.ts+++ b/packages/pg-meta/test/functions.test.ts@@ -71,6 +71,7 @@ withTestDatabase('list functions', async ({ executeQuery }) => {"return_type_relation_id": null,"schema": "public","security_definer": false,+ "type": "function",}`)@@ -183,6 +184,7 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>"return_type_relation_id": null,"schema": "public","security_definer": true,+ "type": "function",},"error": null,}@@ -245,6 +247,7 @@ withTestDatabase('retrieve, create, update, delete', async ({ executeQuery }) =>"return_type_relation_id": null,"schema": "test_schema","security_definer": true,+ "type": "function",},"error": null,}@@ -302,6 +305,7 @@ withTestDatabase('retrieve set-returning function', async ({ executeQuery }) =>"return_type_relation_id": Any<Number>,"schema": "public","security_definer": false,+ "type": "function",}`)