Skip to content

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

chore: Migrate Connection Pooling form to use `react-hook-form` (#19743)

Ivan Vasilov82d21d7ed6d4
diff --git a/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx b/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx
index 903507db8bc..a1628b16058 100644
--- a/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx
+++ b/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx
@@ -85,9 +85,9 @@ export const ProfileInformation = ({ profile }: { profile: Profile }) => {
First name
</FormLabel_Shadcn_>
<FormControl_Shadcn_ className="col-span-8">
- <Input_Shadcn_ {...field} className="w-full !mt-0" />
+ <Input_Shadcn_ {...field} className="w-full" />
</FormControl_Shadcn_>
- <FormMessage_Shadcn_ />
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
</FormItem_Shadcn_>
)}
/>
@@ -100,8 +100,9 @@ export const ProfileInformation = ({ profile }: { profile: Profile }) => {
Last name
</FormLabel_Shadcn_>
<FormControl_Shadcn_ className="col-span-8">
- <Input_Shadcn_ {...field} className="w-full mt-0" />
+ <Input_Shadcn_ {...field} className="w-full" />
</FormControl_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
</FormItem_Shadcn_>
)}
/>
diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
index 1444db199ca..bd8a6526352 100644
--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
@@ -1,43 +1,46 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { Fragment, useState } from 'react'
-import { Input } from 'ui'
-import { AutoField } from 'uniforms-bootstrap4'
+import { useParams } from 'common'
+import { Fragment } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import {
+ FormControl_Shadcn_,
+ FormDescription_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Form_Shadcn_,
+ Input,
+ Input_Shadcn_,
+ Listbox,
+} from 'ui'
+import z from 'zod'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
import AlertError from 'components/ui/AlertError'
import Divider from 'components/ui/Divider'
+import { FormActions } from 'components/ui/Forms'
import Panel from 'components/ui/Panel'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { usePoolingConfigurationQuery } from 'data/database/pooling-configuration-query'
+import {
+ PoolingConfigurationData,
+ usePoolingConfigurationQuery,
+} from 'data/database/pooling-configuration-query'
import { usePoolingConfigurationUpdateMutation } from 'data/database/pooling-configuration-update-mutation'
import { useCheckPermissions, useStore } from 'hooks'
-import { pluckObjectFields } from 'lib/helpers'
+
+const formId = 'connection-pooling-form'
const ConnectionPooling = () => {
- const { project } = useProjectContext()
- const projectRef = project?.ref ?? 'default'
+ const { ref: projectRef } = useParams()
const {
data: poolingConfiguration,
error,
isLoading,
isError,
isSuccess,
- } = usePoolingConfigurationQuery({ projectRef })
-
- const formModel = poolingConfiguration
- const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']
- const connectionInfo = isSuccess ? pluckObjectFields(formModel, DB_FIELDS) : {}
- const BOUNCER_FIELDS = [
- 'default_pool_size',
- 'ignore_startup_parameters',
- 'pool_mode',
- 'pgbouncer_enabled',
- 'supavisor_enabled',
- 'max_client_conn',
- 'connectionString',
- ]
- const bouncerInfo = isSuccess ? pluckObjectFields(formModel, BOUNCER_FIELDS) : {}
+ } = usePoolingConfigurationQuery({ projectRef: projectRef! })
return (
<>
@@ -86,11 +89,7 @@ const ConnectionPooling = () => {
</Panel.Content>
</Panel>
) : (
- <PgbouncerConfig
- projectRef={projectRef}
- bouncerInfo={bouncerInfo}
- connectionInfo={connectionInfo}
- />
+ <MainConfig projectRef={projectRef!} poolingInfo={poolingConfiguration} />
)}
</>
)}
@@ -100,44 +99,35 @@ const ConnectionPooling = () => {
export default ConnectionPooling
-interface ConfigProps {
+// This validator validates a string to be a positive integer or if it's an empty string, transforms it to a null
+const StringToPositiveNumber = z.union([
+ // parse the value if it's a number
+ z.number().positive().int(),
+ // parse the value if it's a non-empty string
+ z.string().min(1).pipe(z.coerce.number().positive().int()),
+ // transform a non-empty string into a null value
+ z
+ .string()
+ .max(0, 'The field accepts only a number')
+ .transform((v) => null),
+ z.null(),
+])
+
+const FormSchema = z.object({
+ default_pool_size: StringToPositiveNumber,
+ ignore_startup_parameters: z.string(),
+ pool_mode: z.union([z.literal('transaction'), z.literal('session'), z.literal('statement')]),
+ max_client_conn: StringToPositiveNumber,
+})
+
+interface MainConfigProps {
projectRef: string
- bouncerInfo: {
- default_pool_size: number
- ignore_startup_parameters: 'string'
- pool_mode: string
- pgbouncer_enabled: boolean
- max_client_conn: number
- connectionString: string
- supavisor_enabled: boolean
- }
- connectionInfo: {
- db_host: string
- db_name: string
- db_port: number
- db_user: string
- inserted_at: string
- }
+ poolingInfo: PoolingConfigurationData
}
-export const PgbouncerConfig = ({ projectRef, bouncerInfo, connectionInfo }: ConfigProps) => {
+export const MainConfig = ({ projectRef, poolingInfo }: MainConfigProps) => {
const { ui } = useStore()
const { project } = useProjectContext()
- const [updates, setUpdates] = useState({
- pool_mode: bouncerInfo.pool_mode || 'transaction',
- default_pool_size: bouncerInfo.default_pool_size || undefined,
- ignore_startup_parameters: bouncerInfo.ignore_startup_parameters || '',
- pgbouncer_enabled: bouncerInfo.pgbouncer_enabled,
- max_client_conn: bouncerInfo.max_client_conn || undefined,
- })
-
- const { mutateAsync: updateConfiguration, isLoading: isUpdating } =
- usePoolingConfigurationUpdateMutation({
- onSuccess: (res) => {
- setUpdates({ ...(res as any) })
- ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
- },
- })
const canUpdateConnectionPoolingConfiguration = useCheckPermissions(
PermissionAction.UPDATE,
@@ -149,128 +139,220 @@ export const PgbouncerConfig = ({ projectRef, bouncerInfo, connectionInfo }: Con
}
)
- const updateConfig = async (updatedConfig: any) => {
+ const form = useForm<z.infer<typeof FormSchema>>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: {
+ ignore_startup_parameters: poolingInfo.ignore_startup_parameters,
+ pool_mode: poolingInfo.pool_mode as 'transaction' | 'session' | 'statement',
+ default_pool_size: poolingInfo.default_pool_size as number | undefined,
+ max_client_conn: poolingInfo.max_client_conn as number | undefined,
+ },
+ })
+
+ const { mutateAsync: updateConfiguration, isLoading: isUpdating } =
+ usePoolingConfigurationUpdateMutation({
+ onSuccess: (data) => {
+ if (data) {
+ form.reset({
+ ignore_startup_parameters: data.ignore_startup_parameters,
+ pool_mode: data.pool_mode,
+ default_pool_size: data.default_pool_size,
+ max_client_conn: data.max_client_conn,
+ })
+ }
+
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
+ },
+ })
+
+ const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
try {
await updateConfiguration({
ref: projectRef,
- pgbouncer_enabled: updatedConfig.pgbouncer_enabled,
- default_pool_size: updatedConfig.default_pool_size,
- ignore_startup_parameters: updatedConfig.ignore_startup_parameters,
- pool_mode: updatedConfig.pool_mode,
- max_client_conn: updatedConfig.max_client_conn,
+ // pgbouncer can't be disabled in the UI, so just pass it along
+ pgbouncer_enabled: poolingInfo.pgbouncer_enabled,
+ default_pool_size: data.default_pool_size as number | undefined,
+ ignore_startup_parameters: data.ignore_startup_parameters,
+ pool_mode: data.pool_mode,
+ max_client_conn: data.max_client_conn,
})
} finally {
}
}
- const formSchema = {
- properties: {
- pool_mode: {
- title: 'Pool Mode',
- type: 'string',
- options: [
- {
- label: 'Transaction',
- value: 'transaction',
- },
- {
- label: 'Session',
- value: 'session',
- },
- ],
- },
- ignore_startup_parameters: {
- title: 'Ignore Startup Parameters',
- type: 'string',
- help: 'Defaults are either blank or "extra_float_digits"',
- },
- max_client_conn: {
- title: 'Max Client Connections',
- oneOf: [{ type: 'integer' }, { type: 'null' }],
- help: 'The maximum number of concurrent client connections allowed. Overrides default optimizations; refer to https://supabase.com/docs/guides/platform/custom-postgres-config#pooler-config',
- },
- default_pool_size: {
- title: 'Default Pool Size',
- oneOf: [{ type: 'integer' }, { type: 'null' }],
- help: 'The maximum number of connections made to the underlying Postgres cluster, per user+db combination. Overrides default optimizations; refer to https://supabase.com/docs/guides/platform/custom-postgres-config#pooler-config',
- },
- },
- required: ['pool_mode'],
- type: 'object',
- }
-
return (
- <div id="connection-pooling">
- <SchemaFormPanel
- title="Connection Pooling Custom Configuration"
- schema={formSchema}
- model={updates}
- submitLabel="Save"
- cancelLabel="Cancel"
- loading={isUpdating}
- onChangeModel={(model: any) => setUpdates(model)}
- onSubmit={(model: any) => updateConfig(model)}
- onReset={() => setUpdates(bouncerInfo)}
- disabled={!canUpdateConnectionPoolingConfiguration}
- disabledMessage="You need additional permissions to update connection pooling settings"
- >
- <div className="space-y-6 py-4">
- {bouncerInfo.pgbouncer_enabled && (
- <>
- <AutoField
+ <Panel
+ className="mb-8"
+ title={<h5>Connection Pooling</h5>}
+ footer={
+ poolingInfo.pgbouncer_enabled && (
+ <FormActions
+ form={formId}
+ isSubmitting={isUpdating}
+ hasChanges={form.formState.isDirty}
+ handleReset={() => form.reset()}
+ helper={
+ !canUpdateConnectionPoolingConfiguration
+ ? 'You need additional permissions to update connection pooling settings'
+ : undefined
+ }
+ />
+ )
+ }
+ >
+ {poolingInfo.pgbouncer_enabled && (
+ <>
+ <Form_Shadcn_ {...form}>
+ <form
+ id={formId}
+ className="space-y-6 w-full px-8 py-8"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <FormField_Shadcn_
+ control={form.control}
name="pool_mode"
- showInlineError
- errorMessage="You must select one of the two options"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="grid gap-2 md:grid md:grid-cols-12 space-y-0">
+ <FormLabel_Shadcn_ className="flex flex-col space-y-2 col-span-4 text-sm justify-center text-foreground-light">
+ Pool Mode
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Listbox
+ value={field.value}
+ className="w-full"
+ onChange={(value) => field.onChange(value)}
+ >
+ <Listbox.Option key="transaction" label="Transaction" value="transaction">
+ Transaction
+ </Listbox.Option>
+ <Listbox.Option key="session" label="Session" value="session">
+ Session
+ </Listbox.Option>
+ </Listbox>
+ </FormControl_Shadcn_>
+ <FormDescription_Shadcn_ className="col-start-5 col-span-8">
+ Specify when a connection can be returned to the pool. Please refer to our{' '}
+ <a
+ href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pool"
+ target="_blank"
+ className="underline"
+ >
+ documentation
+ </a>{' '}
+ to find out the most suitable mode for your use case.
+ </FormDescription_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
+ </FormItem_Shadcn_>
+ )}
/>
- <div className="!mt-1 flex" style={{ marginLeft: 'calc(33% + 0.5rem)' }}>
- <p className="text-sm text-foreground-lighter">
- Specify when a connection can be returned to the pool. To find out the most
- suitable mode for your use case,{' '}
- <a
- className="text-green-900"
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pool"
- >
- click here
- </a>
- .
- </p>
- </div>
- {!bouncerInfo.supavisor_enabled && (
+ <FormField_Shadcn_
+ control={form.control}
+ name="default_pool_size"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="grid gap-2 md:grid md:grid-cols-12 space-y-0">
+ <FormLabel_Shadcn_ className="flex flex-col space-y-2 col-span-4 text-sm justify-center text-foreground-light">
+ Default Pool Size
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Input_Shadcn_
+ className="w-full"
+ {...field}
+ value={field.value || undefined}
+ />
+ </FormControl_Shadcn_>
+ <FormDescription_Shadcn_ className="col-start-5 col-span-8">
+ The maximum number of connections made to the underlying Postgres cluster, per
+ user+db combination. Overrides default optimizations; Please refer to our{' '}
+ <a
+ href="https://supabase.com/docs/guides/platform/custom-postgres-config#pooler-config"
+ target="_blank"
+ className="underline"
+ >
+ documentation
+ </a>{' '}
+ to find out more.
+ </FormDescription_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
+ </FormItem_Shadcn_>
+ )}
+ />
+ {!poolingInfo.supavisor_enabled && (
<>
- <Divider light />
- <AutoField name="ignore_startup_parameters" />
- <Divider light />
- <AutoField name="max_client_conn" />
+ <FormField_Shadcn_
+ control={form.control}
+ name="ignore_startup_parameters"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="grid gap-2 md:grid md:grid-cols-12 space-y-0">
+ <FormLabel_Shadcn_ className="flex flex-col space-y-2 col-span-4 text-sm justify-center text-foreground-light">
+ Ignore Startup Parameters
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Input_Shadcn_ {...field} className="w-full" />
+ </FormControl_Shadcn_>
+ <FormDescription_Shadcn_ className="col-start-5 col-span-8">
+ Defaults are either blank or "extra_float_digits"
+ </FormDescription_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
+ </FormItem_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ control={form.control}
+ name="max_client_conn"
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="grid gap-2 md:grid md:grid-cols-12 space-y-0">
+ <FormLabel_Shadcn_ className="flex flex-col space-y-2 col-span-4 text-sm justify-center text-foreground-light">
+ Max Client Connections
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Input_Shadcn_
+ {...field}
+ value={field.value || undefined}
+ className="w-full"
+ />
+ </FormControl_Shadcn_>
+ <FormDescription_Shadcn_ className="col-start-5 col-span-8">
+ The maximum number of concurrent client connections allowed. Overrides
+ default optimizations; Please refer to our{' '}
+ <a
+ href="https://supabase.com/docs/guides/platform/custom-postgres-config#pooler-config"
+ target="_blank"
+ className="underline"
+ >
+ documentation
+ </a>{' '}
+ to found out more.
+ </FormDescription_Shadcn_>
+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
+ </FormItem_Shadcn_>
+ )}
+ />
</>
)}
- <Divider light />
- <AutoField name="default_pool_size" />
- </>
- )}
- <Divider light />
- <Input
- className="input-mono"
- layout="horizontal"
- readOnly
- copy
- disabled
- value={connectionInfo.db_port}
- label="Port"
- />
- <Divider light />
- <Input
- className="input-mono"
- layout="vertical"
- readOnly
- copy
- disabled
- label="Connection string"
- value={bouncerInfo.connectionString}
- />
- </div>
- </SchemaFormPanel>
- </div>
+ </form>
+ </Form_Shadcn_>
+ <div className="border-muted border-t"></div>
+ </>
+ )}
+ <Input
+ className="input-mono w-full px-8 py-8 flex items-center"
+ layout="horizontal"
+ readOnly
+ copy
+ disabled
+ value={poolingInfo.db_port}
+ label="Port"
+ />
+ <div className="border-muted border-t"></div>
+ <Input
+ className="input-mono w-full px-8 py-8"
+ layout="vertical"
+ readOnly
+ copy
+ disabled
+ label="Connection string"
+ value={poolingInfo.connectionString}
+ />
+ </Panel>
)
}
diff --git a/apps/studio/data/database/pooling-configuration-query.ts b/apps/studio/data/database/pooling-configuration-query.ts
index eecf45b5bae..b4d47e0bb4d 100644
--- a/apps/studio/data/database/pooling-configuration-query.ts
+++ b/apps/studio/data/database/pooling-configuration-query.ts
@@ -1,6 +1,5 @@
import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
+import { get } from 'data/fetchers'
import { useCallback } from 'react'
import { ResponseError } from 'types'
import { databaseKeys } from './keys'
@@ -9,31 +8,16 @@ export type PoolingConfigurationVariables = {
projectRef: string
}
-export type PoolingConfiguration = {
- db_dns_name: string
- db_host: string
- db_name: string
- db_port: number
- db_ssl: boolean
- db_user: string
- default_pool_size: number | null
- ignore_startup_parameters: string
- inserted_at: string
- max_client_conn: number | null
- pgbouncer_enabled: boolean
- supavisor_enabled: boolean
- pgbouncer_status: string
- pool_mode: string
- connectionString: string
-}
-
export async function getPoolingConfiguration(
{ projectRef }: PoolingConfigurationVariables,
signal?: AbortSignal
) {
- const response = await get(`${API_URL}/projects/${projectRef}/config/pgbouncer`, { signal })
- if (response.error) throw response.error
- return response as PoolingConfiguration
+ const { data, error } = await get(`/platform/projects/{ref}/config/pgbouncer`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+ if (error) throw error
+ return data
}
export type PoolingConfigurationData = Awaited<ReturnType<typeof getPoolingConfiguration>>
diff --git a/apps/studio/data/database/pooling-configuration-update-mutation.ts b/apps/studio/data/database/pooling-configuration-update-mutation.ts
index a4e7b9845d8..c994e25fa05 100644
--- a/apps/studio/data/database/pooling-configuration-update-mutation.ts
+++ b/apps/studio/data/database/pooling-configuration-update-mutation.ts
@@ -1,18 +1,14 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-hot-toast'
+import { components } from 'data/api'
import { patch } from 'data/fetchers'
import { ResponseError } from 'types'
import { databaseKeys } from './keys'
export type PoolingConfigurationUpdateVariables = {
ref: string
- pgbouncer_enabled: boolean
- ignore_startup_parameters: string
- pool_mode: 'transaction' | 'session' | 'statement'
- default_pool_size?: number
- max_client_conn?: number | null
-}
+} & components['schemas']['UpdatePgbouncerConfigBody']
export async function updatePoolingConfiguration({
ref,