Skip to content

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

[Dashboard] Postgrest API settings renamed to "Data API" settings. now using react-hook-form (#26793)

Jonathan Summers-Muir81b1dc2161f6
diff --git a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
index a58832c1398..969cc833024 100644
--- a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
+++ b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
@@ -1,36 +1,50 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { indexOf } from 'lodash'
-import { useEffect } from 'react'
-import toast from 'react-hot-toast'
-
import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import {
- FormActions,
- FormPanel,
- FormSection,
- FormSectionContent,
- FormSectionLabel,
-} from 'components/ui/Forms'
+import { FormActions, FormPanel } from 'components/ui/Forms'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
import { useProjectPostgrestConfigUpdateMutation } from 'data/config/project-postgrest-config-update-mutation'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { useSchemasQuery } from 'data/database/schemas-query'
import { useCheckPermissions } from 'hooks'
-import { AlertCircle, Info } from 'lucide-react'
+import { indexOf } from 'lodash'
+import Link from 'next/link'
+import { useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+import toast from 'react-hot-toast'
import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
+ Admonition,
Button,
- Form,
- Input,
- InputNumber,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ Form_Shadcn_,
+ Input_Shadcn_,
+ Skeleton,
} from 'ui'
-import { MultiSelectV2 } from 'ui-patterns/MultiSelectDeprecated/MultiSelectV2'
-import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import {
+ MultiSelector,
+ MultiSelectorContent,
+ MultiSelectorInput,
+ MultiSelectorItem,
+ MultiSelectorList,
+ MultiSelectorTrigger,
+} from 'ui-patterns/multi-select'
+import { z } from 'zod'
-import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
-import Link from 'next/link'
+const formSchema = z.object({
+ dbSchema: z.array(z.string()),
+ dbExtraSearchPath: z.string(),
+ maxRows: z.number().max(1000000, "Can't be more than 1,000,000"),
+ dbPool: z
+ .number()
+ .min(0, 'Must be more than 0')
+ .max(1000, "Can't be more than 1000")
+ .optional()
+ .nullable(),
+})
const PostgrestConfig = () => {
const { ref: projectRef } = useParams()
@@ -60,17 +74,28 @@ const PostgrestConfig = () => {
connectionString: project?.connectionString,
})
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ mode: 'onChange',
+ defaultValues: {
+ dbSchema: config?.db_schema ? config?.db_schema.replace(/ /g, '').split(',') : [],
+ maxRows: config?.max_rows,
+ dbExtraSearchPath: config?.db_extra_search_path,
+ dbPool: config?.db_pool,
+ },
+ })
+
const formId = 'project-postgres-config'
- const initialValues = { db_schema: '', max_rows: '', db_extra_search_path: '', db_pool: '' }
- const updateConfig = async (updatedConfig: typeof initialValues) => {
- if (!projectRef) return console.error('Project ref is required')
+ const onSubmit = async (values: z.infer<typeof formSchema>) => {
+ if (!projectRef) return console.error('Project ref is required') // is this needed ?
+
updatePostgrestConfig({
projectRef,
- dbSchema: updatedConfig.db_schema,
- maxRows: updatedConfig.max_rows,
- dbExtraSearchPath: updatedConfig.db_extra_search_path,
- dbPool: updatedConfig.db_pool || null,
+ dbSchema: values.dbSchema.join(', '),
+ maxRows: values.maxRows,
+ dbExtraSearchPath: values.dbExtraSearchPath,
+ dbPool: values.dbPool ? values.dbPool : null,
})
}
@@ -90,171 +115,208 @@ const PostgrestConfig = () => {
}
}) ?? []
- const isPublicSchemaEnabled = config?.db_schema
- .split(',')
- .map((name) => name.trim())
- .includes('public')
-
const isGraphqlExtensionEnabled =
(extensions ?? []).find((ext) => ext.name === 'pg_graphql')?.installed_version !== null
- return (
- <Form id={formId} initialValues={initialValues} validate={() => {}} onSubmit={updateConfig}>
- {({ handleReset, resetForm, values, initialValues }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
- // [Alaister] although this "technically" is breaking the rules of React hooks
- // it won't error because the hooks are always rendered in the same order
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- if (config) {
- const values = {
- db_schema: config.db_schema,
- max_rows: config.max_rows,
- db_extra_search_path: config.db_extra_search_path ?? '',
- db_pool: config.db_pool || null,
- }
+ function resetForm() {
+ if (config) {
+ form.reset({
+ dbSchema: config.db_schema ? config.db_schema.replace(/ /g, '').split(',') : [],
+ maxRows: config.max_rows,
+ dbExtraSearchPath: config.db_extra_search_path,
+ dbPool: config.db_pool,
+ })
+ }
+ }
+
+ useEffect(() => {
+ if (schema && config) {
+ resetForm()
+ }
+ }, [schema && config])
- resetForm({ values, initialValues: values })
+ return (
+ <Form_Shadcn_ {...form}>
+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
+ <FormPanel
+ disabled={true}
+ header={<p>Data API Settings</p>}
+ footer={
+ <div className="flex px-8 py-4">
+ <FormActions
+ form={formId}
+ isSubmitting={isUpdating}
+ hasChanges={form.formState.isDirty}
+ handleReset={resetForm}
+ disabled={!canUpdatePostgrestConfig}
+ helper={
+ !canUpdatePostgrestConfig
+ ? "You need additional permissions to update your project's API settings"
+ : undefined
+ }
+ />
+ </div>
}
- }, [config])
+ >
+ {isError ? (
+ <Admonition type="destructive" title="Failed to retrieve API settings" />
+ ) : (
+ <>
+ <FormField_Shadcn_
+ control={form.control}
+ name="dbSchema"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="w-full">
+ <FormItemLayout
+ label="Exposed schemas"
+ description="The schemas to expose in your API. Tables, views and stored procedures in
+ these schemas will get API endpoints."
+ layout="horizontal"
+ className="px-8 py-8"
+ >
+ {isLoadingSchemas ? (
+ <div className="col-span-12 flex flex-col gap-2 lg:col-span-7">
+ <Skeleton className="w-full h-[38px]" />
+ </div>
+ ) : (
+ <MultiSelector
+ onValuesChange={field.onChange}
+ values={field.value}
+ size={'small'}
+ >
+ <MultiSelectorTrigger>
+ <MultiSelectorInput placeholder="Select schemas for Data API..." />
+ </MultiSelectorTrigger>
+ <MultiSelectorContent>
+ <MultiSelectorList>
+ {schema.map((x, i) => (
+ <MultiSelectorItem key={x.id + '-' + i} value={x.name}>
+ {x.name}
+ </MultiSelectorItem>
+ ))}
+ </MultiSelectorList>
+ </MultiSelectorContent>
+ </MultiSelector>
+ )}
- return (
- <>
- <FormPanel
- disabled={true}
- header={<p>API settings</p>}
- footer={
- <div className="flex px-8 py-4">
- <FormActions
- form={formId}
- isSubmitting={isUpdating}
- hasChanges={hasChanges}
- handleReset={handleReset}
- disabled={!canUpdatePostgrestConfig}
- helper={
- !canUpdatePostgrestConfig
- ? "You need additional permissions to update your project's API settings"
- : undefined
- }
- />
- </div>
- }
- >
- {isError ? (
- <div className="flex items-center justify-center py-8 space-x-2">
- <AlertCircle size={16} strokeWidth={1.5} />
- <p className="text-sm text-foreground-light">Failed to retrieve API settings</p>
- </div>
- ) : (
- <>
- <FormSection header={<FormSectionLabel>Exposed schemas</FormSectionLabel>}>
- {isLoadingSchemas ? (
- <div className="col-span-12 flex flex-col gap-2 lg:col-span-7">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- </div>
- ) : (
- <FormSectionContent loading={false}>
- {schema.length >= 1 && (
- <div className="grid gap-2">
- <MultiSelectV2
- options={schema}
- disabled={!canUpdatePostgrestConfig}
- value={
- values?.db_schema
- ? values.db_schema.replace(/ /g, '').split(',')
- : []
- }
- placeholder="Choose a schema to expose"
- searchPlaceholder="Search for a schema"
- onChange={(event) => {
- let updatedValues: any = values
- updatedValues.db_schema = event.join(', ')
- resetForm({ values: updatedValues, initialValues: updatedValues })
- updateConfig({ ...updatedValues })
- }}
- />
- <p className="text-foreground-lighter text-sm">
- The schemas to expose in your API. Tables, views and stored procedures
- in these schemas will get API endpoints.
+ {!field.value.includes('public') && (
+ <Admonition
+ type="default"
+ title="The public schema for this project is not exposed"
+ className="mt-2"
+ >
+ <>
+ <p>
+ You will not be able to query tables and views in the{' '}
+ <code>public</code> schema via supabase-js or HTTP clients.
</p>
-
- {!isPublicSchemaEnabled && (
- <Alert_Shadcn_ variant="default">
- <Info className="h-4 w-4" />
- <AlertTitle_Shadcn_>
- The public schema for this project is not exposed
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- <p>
- You will not be able to query tables and views in the{' '}
- <code>public</code> schema via supabase-js or HTTP clients.
- </p>
- {isGraphqlExtensionEnabled && (
- <div className="grid gap-3 mt-2">
- <div>
- Tables in the <code>public</code> schema are still exposed
- over our GraphQL endpoints.
- </div>
- <p>
- <Button asChild type="default">
- <Link
- href={`/project/${projectRef}/database/extensions`}
- className="!no-underline !hover:bg-surface-100 !text-foreground"
- >
- Disable the pg_graphql extension
- </Link>
- </Button>
- </p>
- </div>
- )}
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
+ {isGraphqlExtensionEnabled && (
+ <>
+ <p>
+ Tables in the <code className="text-xs">public</code> schema are
+ still exposed over our GraphQL endpoints.
+ </p>
+ <Button asChild type="default">
+ <Link
+ href={`/project/${projectRef}/database/extensions`}
+ // className="!no-underline !hover:bg-surface-100 !text-foreground"
+ >
+ Disable the pg_graphql extension
+ </Link>
+ </Button>
+ </>
)}
- </div>
- )}
- </FormSectionContent>
- )}
- </FormSection>
+ </>
+ </Admonition>
+ )}
+ </FormItemLayout>
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="dbExtraSearchPath"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="w-full">
+ <FormItemLayout
+ className="w-full px-8 py-8"
+ layout="horizontal"
+ label="Extra search path"
+ description="Extra schemas to add to the search path of every request. Multiple schemas must be comma-separated."
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ size="small"
+ disabled={!canUpdatePostgrestConfig}
+ {...field}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="maxRows"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="w-full">
+ <FormItemLayout
+ className="w-full px-8 py-8"
+ layout="horizontal"
+ label="Max rows"
+ description="The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests."
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ size="small"
+ disabled={!canUpdatePostgrestConfig}
+ {...field}
+ type="number"
+ {...form.register('maxRows', {
+ valueAsNumber: true, // Ensure the value is handled as a number
+ })}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ </FormItem_Shadcn_>
+ )}
+ />
- <FormSection header={<FormSectionLabel>Extra search path</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <Input
- id="db_extra_search_path"
- size="small"
- disabled={!canUpdatePostgrestConfig}
- descriptionText="Extra schemas to add to the search path of every request. Multiple schemas must be comma-separated."
- />
- </FormSectionContent>
- </FormSection>
- <FormSection header={<FormSectionLabel>Max rows</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <InputNumber
- id="max_rows"
- size="small"
- disabled={!canUpdatePostgrestConfig}
- descriptionText="The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests."
- />
- </FormSectionContent>
- </FormSection>
- <FormSection header={<FormSectionLabel>Pool size</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <InputNumber
- id="db_pool"
- size="small"
- disabled={!canUpdatePostgrestConfig}
- descriptionText="Number of maximum connections to keep open in the Data API server's database pool. Unset to let it be configured automatically based on compute size."
- placeholder="Configured automatically based on compute size"
- />
- </FormSectionContent>
- </FormSection>
- </>
- )}
- </FormPanel>
- </>
- )
- }}
- </Form>
+ <FormField_Shadcn_
+ control={form.control}
+ name="dbPool"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="w-full">
+ <FormItemLayout
+ className="w-full px-8 py-8"
+ layout="horizontal"
+ label="Pool size"
+ description="Number of maximum connections to keep open in the Data API server's database pool. Unset to let it be configured automatically based on compute size."
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ size="small"
+ disabled={!canUpdatePostgrestConfig}
+ {...field}
+ type="number"
+ placeholder="Configured automatically based on compute size"
+ onChange={(e) =>
+ field.onChange(e.target.value === '' ? null : Number(e.target.value))
+ }
+ value={field.value === null ? '' : field.value}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ </FormItem_Shadcn_>
+ )}
+ />
+ </>
+ )}
+ </FormPanel>
+ </form>
+ </Form_Shadcn_>
)
}
diff --git a/apps/studio/data/config/project-postgrest-config-update-mutation.ts b/apps/studio/data/config/project-postgrest-config-update-mutation.ts
index 82f1e3409d0..528e552019e 100644
--- a/apps/studio/data/config/project-postgrest-config-update-mutation.ts
+++ b/apps/studio/data/config/project-postgrest-config-update-mutation.ts
@@ -9,9 +9,9 @@ import { configKeys } from './keys'
export type ProjectPostgrestConfigUpdateVariables = {
projectRef: string
dbSchema: string
- maxRows: string
+ maxRows: number
dbExtraSearchPath: string
- dbPool: string | null
+ dbPool: number | null
}
export async function updateProjectPostgrestConfig({
diff --git a/apps/studio/pages/project/[ref]/settings/api.tsx b/apps/studio/pages/project/[ref]/settings/api.tsx
index 50d3b2a8106..85f89e48d2c 100644
--- a/apps/studio/pages/project/[ref]/settings/api.tsx
+++ b/apps/studio/pages/project/[ref]/settings/api.tsx
@@ -1,12 +1,6 @@
import ServiceList from 'components/interfaces/Settings/API/ServiceList'
import { SettingsLayout } from 'components/layouts'
-import {
- ScaffoldColumn,
- ScaffoldContainer,
- ScaffoldHeader,
- ScaffoldSection,
- ScaffoldTitle,
-} from 'components/layouts/Scaffold'
+import { ScaffoldContainer, ScaffoldHeader, ScaffoldTitle } from 'components/layouts/Scaffold'
import type { NextPageWithLayout } from 'types'
const ApiSettings: NextPageWithLayout = () => {
diff --git a/packages/ui-patterns/multi-select/multi-select.tsx b/packages/ui-patterns/multi-select/multi-select.tsx
index 52ae002775d..a993f9a9e37 100644
--- a/packages/ui-patterns/multi-select/multi-select.tsx
+++ b/packages/ui-patterns/multi-select/multi-select.tsx
@@ -158,7 +158,7 @@ const MultiSelector = ({
>
<CommandPrimitive
onKeyDown={handleKeyDown}
- className={cn('overflow-visible bg-transparent flex flex-col', className)}
+ className={cn('relative overflow-visible bg-transparent flex flex-col', className)}
dir={dir}
{...props}
>