Skip to content

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

Support for Dedicated Pooler in Connection Pooling (#33817)

Joshen Lima458977e2da8
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx
index 1d93f5fb677..1d211ddc1e7 100644
--- a/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx
@@ -5,10 +5,12 @@ import { UseFormReturn } from 'react-hook-form'
import { components } from 'api-types'
import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { DocsButton } from 'components/ui/DocsButton'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils'
+import { InstanceSpecs } from 'lib/constants'
import { cn, FormField_Shadcn_, RadioGroupCard, RadioGroupCardItem, Skeleton } from 'ui'
import { ComputeBadge } from 'ui-patterns'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
@@ -22,8 +24,6 @@ import {
import { BillingChangeBadge } from '../ui/BillingChangeBadge'
import FormMessage from '../ui/FormMessage'
import { NoticeBar } from '../ui/NoticeBar'
-import { InstanceSpecs } from 'lib/constants'
-import { DocsButton } from 'components/ui/DocsButton'
/**
* to do: this could be a type from api-types
@@ -196,7 +196,6 @@ export function ComputeSizeField({ form, disabled }: ComputeSizeFieldProps) {
lockedOption && 'opacity-50'
)}
disabled={disabled || lockedOption}
- // @ts-expect-error
label={
<>
{showUpgradeBadge && compute.identifier === 'ci_micro' && (
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
index 1b7d7f091c2..734dc4f28cc 100644
--- a/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
@@ -57,11 +57,6 @@ export const DISK_LIMITS = {
},
}
-export const DISK_TYPE_LABELS = {
- [DiskType.GP3]: 'General Purpose SSD (gp3)',
- [DiskType.IO2]: 'Provisioned IOPS SSD (io2)',
-}
-
interface PlanDetails {
includedDiskGB: { gp3: number; io2: number }
}
diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts
index 6b6e15d41bb..c9407d2e881 100644
--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts
@@ -1,5 +1,7 @@
// https://supabase.com/docs/guides/platform/performance#optimizing-the-number-of-connections
// https://github.com/supabase/infrastructure/blob/develop/worker/src/lib/constants.ts#L544-L596
+// https://github.com/supabase/supabase-admin-api/blob/master/optimizations/pgbouncer.go
+// [Joshen] This matches for both Supavisor and PgBouncer
export const POOLING_OPTIMIZATIONS = {
ci_nano: {
diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx
index 122ff895fbf..2645568895c 100644
--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx
@@ -1,25 +1,30 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
import { capitalize } from 'lodash'
-import { Fragment, useEffect } from 'react'
+import { Fragment, useEffect, useMemo, useRef, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
-import { toast } from 'sonner'
import z from 'zod'
-import { useParams } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AlertError from 'components/ui/AlertError'
import { DocsButton } from 'components/ui/DocsButton'
-import { StringToPositiveNumber } from 'components/ui/Forms/Form.constants'
+import { setValueAsNullableNumber } from 'components/ui/Forms/Form.constants'
import { FormActions } from 'components/ui/Forms/FormActions'
+import { InlineLink } from 'components/ui/InlineLink'
import Panel from 'components/ui/Panel'
-import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { useAuthConfigQuery } from 'data/auth/auth-config-query'
import { useMaxConnectionsQuery } from 'data/database/max-connections-query'
-import { usePoolingConfigurationQuery } from 'data/database/pooling-configuration-query'
-import { usePoolingConfigurationUpdateMutation } from 'data/database/pooling-configuration-update-mutation'
+import { usePgbouncerConfigQuery } from 'data/database/pgbouncer-config-query'
+import { usePgbouncerConfigurationUpdateMutation } from 'data/database/pgbouncer-config-update-mutation'
+import { usePgbouncerStatusQuery } from 'data/database/pgbouncer-status-query'
+import { useSupavisorConfigurationQuery } from 'data/database/pooling-configuration-query'
+import { useSupavisorConfigurationUpdateMutation } from 'data/database/pooling-configuration-update-mutation'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useFlag } from 'hooks/ui/useFlag'
+import { toast } from 'sonner'
import { useDatabaseSettingsStateSnapshot } from 'state/database-settings'
import {
AlertDescription_Shadcn_,
@@ -27,116 +32,294 @@ import {
Alert_Shadcn_,
Badge,
FormControl_Shadcn_,
- FormDescription_Shadcn_,
FormField_Shadcn_,
- FormItem_Shadcn_,
- FormLabel_Shadcn_,
- FormMessage_Shadcn_,
Form_Shadcn_,
Input_Shadcn_,
Listbox,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ Select_Shadcn_,
Separator,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ cn,
} from 'ui'
import { Admonition } from 'ui-patterns'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
import { SESSION_MODE_DESCRIPTION, TRANSACTION_MODE_DESCRIPTION } from '../Database.constants'
import { POOLING_OPTIMIZATIONS } from './ConnectionPooling.constants'
-const formId = 'connection-pooling-form'
+const formId = 'pooling-configuration-form'
-const FormSchema = z.object({
- default_pool_size: StringToPositiveNumber,
- pool_mode: z.union([z.literal('transaction'), z.literal('session')]),
- max_client_conn: StringToPositiveNumber,
+const PoolingConfigurationFormSchema = z.object({
+ type: z.union([z.literal('Supavisor'), z.literal('PgBouncer')]),
+ default_pool_size: z.number().nullable(),
+ pool_mode: z.union([z.literal('transaction'), z.literal('session'), z.literal('statement')]),
+ max_client_conn: z.number().nullable(),
})
+/**
+ * [Joshen] Some outstanding questions that need clarification for support both type of poolers
+ * I've left comments in the code itself below, but just leaving a summary here for easier reference
+ * - How to check for when Supavisor is ready to receive connections? We have pgbouncer/status for PgBouncer
+ * - Are we currently ensuring the 2 hour window on the BE? I noticed pgbouncer/status flips active to false in a second after setting pgbouncer_enabled to false
+ * - Existing projects currently have pgbouncer_enabled and supavisor_enabled as true, are we going to backfill?
+ * - We're using pgbouncer_enabled to determine the pooler type, which means that all projects are going to show on the UI that pgbouncer is being used
+ *
+ * Apart from the above, some pointers to note:
+ * - max_client_conn should be editable for pgbouncer
+ * - (Nice to have) Show a countdown of 2 hours when the pooler is swapped as a UI indication for users
+ * - [TODO] Connect UI needs to be updated to show the correct pooler connection string depending on which type is being used
+ * - [TODO] Project addons IPv4 needs an update on the CTA "You do not need...", needs to now be dependent on the Pooler type
+ *
+ * Added a feature flag just in case
+ * - Toggles visibility of Pooler Type input field
+ * - Whether to use pgbouncer_enabled to determine pooler type
+ */
+
export const ConnectionPooling = () => {
const { ref: projectRef } = useParams()
const { project } = useProjectContext()
+ const org = useSelectedOrganization()
const snap = useDatabaseSettingsStateSnapshot()
+ const allowPgBouncerSelection = useFlag('dualPoolerSupport')
- const { data: addons } = useProjectAddonsQuery({ projectRef })
- const computeInstance = addons?.selected_addons.find((addon) => addon.type === 'compute_instance')
- const poolingOptimizations =
- POOLING_OPTIMIZATIONS[
- (computeInstance?.variant.identifier as keyof typeof POOLING_OPTIMIZATIONS) ??
- (project?.infra_compute_size === 'nano' ? 'ci_nano' : 'ci_micro')
- ]
- const defaultPoolSize = poolingOptimizations.poolSize ?? 15
- const defaultMaxClientConn = poolingOptimizations.maxClientConn ?? 200
- const computeSize =
- computeInstance?.variant.name ?? capitalize(project?.infra_compute_size) ?? 'Micro'
+ const toastIdRef = useRef<string | number>()
+ const [showConfirmation, setShowConfirmation] = useState(false)
+ const [refetchPgBouncerStatus, setRefetchPgBouncerStatus] = useState<boolean>(false)
+
+ const canUpdateConnectionPoolingConfiguration = useCheckPermissions(
+ PermissionAction.UPDATE,
+ 'projects',
+ { resource: { project_id: project?.id } }
+ )
const {
- data: poolingInfo,
- error,
- isLoading,
- isError,
- isSuccess,
- } = usePoolingConfigurationQuery({ projectRef })
+ data: supavisorPoolingInfo,
+ error: supavisorConfigError,
+ isLoading: isLoadingSupavisorConfig,
+ isError: isErrorSupavisorConfig,
+ isSuccess: isSuccessSupavisorConfig,
+ } = useSupavisorConfigurationQuery({ projectRef })
- const { data: authConfig } = useAuthConfigQuery({ projectRef })
+ const {
+ data: pgbouncerConfig,
+ error: pgbouncerConfigError,
+ isLoading: isLoadingPgbouncerConfig,
+ isError: isErrorPgbouncerConfig,
+ isSuccess: isSuccessPgbouncerConfig,
+ } = usePgbouncerConfigQuery({
+ projectRef,
+ })
const { data: maxConnData } = useMaxConnectionsQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
+ const { data: addons } = useProjectAddonsQuery({ projectRef })
+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
- const poolingConfiguration = poolingInfo?.find((x) => x.database_type === 'PRIMARY')
- const connectionPoolingUnavailable = poolingConfiguration?.pool_mode === null
-
- const canUpdateConnectionPoolingConfiguration = useCheckPermissions(
- PermissionAction.UPDATE,
- 'projects',
+ usePgbouncerStatusQuery(
+ { projectRef },
{
- resource: {
- project_id: project?.id,
+ refetchInterval: (data) => {
+ // [Joshen] Need to clarify the following:
+ // - How to check for when Supavisor is ready to receive connections when swapping over to Supavisor
+ // - I notice status goes to false when i swap over to Supavisor in 2 seconds, does this mean that PgBouncer is already offline?
+ // - Cause we need to consider the 2 hour window that we're providing for users to swap over the pooler connection strings
+ if (refetchPgBouncerStatus) {
+ if (
+ (!!pgbouncerConfig?.pgbouncer_enabled && !data?.active) ||
+ (!pgbouncerConfig?.pgbouncer_enabled && !!data?.active)
+ ) {
+ return 2000
+ } else {
+ toast.success(
+ `${data?.active ? 'Dedicated Pooler' : 'Supavisor'} is now ready to receive connections!`,
+ { id: toastIdRef.current }
+ )
+ toastIdRef.current = undefined
+ setRefetchPgBouncerStatus(false)
+ return false
+ }
+ } else {
+ return false
+ }
},
}
)
- const form = useForm<z.infer<typeof FormSchema>>({
- resolver: zodResolver(FormSchema),
+ const { mutate: updateSupavisorConfig, isLoading: isUpdatingSupavisor } =
+ useSupavisorConfigurationUpdateMutation()
+ const {
+ mutate: updatePgbouncerConfig,
+ mutateAsync: updatePgBouncerConfigAsync,
+ isLoading: isUpdatingPgBouncer,
+ } = usePgbouncerConfigurationUpdateMutation()
+
+ const form = useForm<z.infer<typeof PoolingConfigurationFormSchema>>({
+ resolver: zodResolver(PoolingConfigurationFormSchema),
defaultValues: {
- pool_mode: poolingConfiguration?.pool_mode as 'transaction' | 'session',
- default_pool_size: poolingConfiguration?.default_pool_size as number | undefined,
- max_client_conn: poolingConfiguration?.max_client_conn as number | undefined,
+ type: undefined,
+ pool_mode: undefined,
+ default_pool_size: undefined,
+ max_client_conn: null,
},
})
+ const { type, default_pool_size, max_client_conn } = form.watch()
+ const error = useMemo(
+ () => (type === 'PgBouncer' ? pgbouncerConfigError : supavisorConfigError),
+ [type]
+ )
+ const isLoading = useMemo(
+ () => (type === 'PgBouncer' ? isLoadingPgbouncerConfig : isLoadingSupavisorConfig),
+ [type]
+ )
+ const isError = useMemo(
+ () => (type === 'PgBouncer' ? isErrorPgbouncerConfig : isErrorSupavisorConfig),
+ [type]
+ )
+ const isSuccess = useMemo(
+ () => (type === 'PgBouncer' ? isSuccessPgbouncerConfig : isSuccessSupavisorConfig),
+ [type]
+ )
+ const isSaving = isUpdatingSupavisor || isUpdatingPgBouncer
- const { mutate: updateConfiguration, isLoading: isUpdating } =
- usePoolingConfigurationUpdateMutation({
- onSuccess: (data) => {
- if (data) {
- form.reset({
- pool_mode: data.pool_mode,
- default_pool_size: data.default_pool_size,
- max_client_conn: poolingConfiguration?.max_client_conn,
- })
- }
- toast.success('Successfully saved settings')
- },
- })
+ const currentPooler = allowPgBouncerSelection
+ ? pgbouncerConfig?.pgbouncer_enabled
+ ? 'PgBouncer'
+ : 'Supavisor'
+ : 'Supavisor'
+ // [Joshen] These are labels just for user-facing texts
+ const formattedCurrentPooler =
+ currentPooler === 'PgBouncer' ? 'the Dedicated Pooler' : currentPooler
+ const formattedTargetPooler = type === 'PgBouncer' ? 'the Dedicated Pooler' : type
+
+ const hasIpv4Addon = !!addons?.selected_addons.find((addon) => addon.type === 'ipv4')
+ const computeInstance = addons?.selected_addons.find((addon) => addon.type === 'compute_instance')
+ const computeSize =
+ computeInstance?.variant.name ?? capitalize(project?.infra_compute_size) ?? 'Nano'
+ const poolingOptimizations =
+ POOLING_OPTIMIZATIONS[
+ (computeInstance?.variant.identifier as keyof typeof POOLING_OPTIMIZATIONS) ??
+ (project?.infra_compute_size === 'nano' ? 'ci_nano' : 'ci_micro')
+ ]
+ const defaultPoolSize = poolingOptimizations.poolSize ?? 15
+ const defaultMaxClientConn = poolingOptimizations.maxClientConn ?? 200
+
+ const isFreePlan = subscription?.plan.id === 'free'
+ const supavisorConfig = supavisorPoolingInfo?.find((x) => x.database_type === 'PRIMARY')
+ const connectionPoolingUnavailable =
+ type === 'PgBouncer' ? pgbouncerConfig?.pool_mode === null : supavisorConfig?.pool_mode === null
+ const disablePoolModeSelection =
+ type === 'Supavisor' && supavisorConfig?.pool_mode === 'transaction'
+ const disablePgBouncerSelection = computeSize === 'Nano'
+ const showPoolModeWarning = type === 'Supavisor' && supavisorConfig?.pool_mode === 'session'
+ const isChangingPoolerType =
+ (currentPooler === 'PgBouncer' && type === 'Supavisor') ||
+ (currentPooler === 'Supavisor' && type === 'PgBouncer')
+
+ const poolerSwitchWarningTitle =
+ 'Your current pooler will be active for 2 hours before fully deactivated'
+ const poolerSwitchWarningDescription = `Migrate your applications from ${formattedCurrentPooler} to ${formattedTargetPooler} during this time by switching to ${formattedTargetPooler} connection strings in your applications.`
+
+ const onSubmit: SubmitHandler<z.infer<typeof PoolingConfigurationFormSchema>> = async (data) => {
+ const { type, pool_mode, default_pool_size, max_client_conn } = data
- const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!projectRef) return console.error('Project ref is required')
- if (!poolingInfo) return console.error('Pooling info required')
+ if (isChangingPoolerType && !showConfirmation) return setShowConfirmation(true)
- updateConfiguration({
- ref: projectRef,
- default_pool_size: data.default_pool_size as number | undefined,
- pool_mode: data.pool_mode,
- })
+ if (type === 'PgBouncer') {
+ if (!pgbouncerConfig) return console.error('Pgbouncer configuration is required')
+ updatePgbouncerConfig(
+ {
+ ref: projectRef,
+ pgbouncer_enabled: true,
+ ignore_startup_parameters: pgbouncerConfig.ignore_startup_parameters ?? '',
+ pool_mode: pool_mode as 'transaction' | 'session' | 'statement',
+ max_client_conn,
+ default_pool_size: default_pool_size as number | undefined,
+ },
+ {
+ onSuccess: (data) => {
+ if (isChangingPoolerType) {
+ const toastId = toast.loading('Swapping pooler to the Dedicated Pooler')
+ toastIdRef.current = toastId
+ setRefetchPgBouncerStatus(true)
+ } else {
+ toast.success(`Successfully updated Dedicated Pooler configuration`)
+ }
+
+ setShowConfirmation(false)
+ form.reset({ type: 'PgBouncer', ...data })
+ },
+ }
+ )
+ } else if (type === 'Supavisor') {
+ if (isChangingPoolerType && pgbouncerConfig) {
+ await updatePgBouncerConfigAsync({
+ ref: projectRef,
+ pgbouncer_enabled: false,
+ ignore_startup_parameters: pgbouncerConfig.ignore_startup_parameters ?? '',
+ pool_mode: pgbouncerConfig.pool_mode as 'transaction' | 'session' | 'statement',
+ })
+ }
+ updateSupavisorConfig(
+ {
+ ref: projectRef,
+ default_pool_size,
+ pool_mode: pool_mode as 'transaction' | 'session',
+ },
+ {
+ onSuccess: (data) => {
+ if (isChangingPoolerType) {
+ const toastId = toast.loading('Swapping pooler to Supavisor')
+ toastIdRef.current = toastId
+ setRefetchPgBouncerStatus(true)
+ } else {
+ toast.success(`Successfully updated Supavisor configuration`)
+ }
+ setShowConfirmation(false)
+ form.reset({ type: 'Supavisor', ...data })
+ },
+ }
+ )
+ }
+ }
+
+ const resetForm = () => {
+ if (currentPooler === 'PgBouncer') {
+ if (pgbouncerConfig) {
+ form.reset({
+ type: 'PgBouncer',
+ pool_mode: pgbouncerConfig.pool_mode,
+ default_pool_size: pgbouncerConfig.default_pool_size,
+ max_client_conn: pgbouncerConfig.max_client_conn,
+ })
+ }
+ } else {
+ if (supavisorConfig) {
+ form.reset({
+ type: 'Supavisor',
+ pool_mode: supavisorConfig.pool_mode,
+ default_pool_size: supavisorConfig.default_pool_size,
+ max_client_conn: supavisorConfig.max_client_conn,
+ })
+ }
+ }
}
useEffect(() => {
- if (isSuccess) {
- form.reset({
- pool_mode: poolingConfiguration?.pool_mode as 'transaction' | 'session',
- default_pool_size: poolingConfiguration?.default_pool_size as number | undefined,
- max_client_conn: poolingConfiguration?.max_client_conn as number | undefined,
- })
+ // [Joshen] We're using pgbouncer_enabled from pgbouncer's config to determine the current type
+ if (isSuccessPgbouncerConfig && isSuccessSupavisorConfig) {
+ resetForm()
}
- }, [isSuccess, authConfig])
+ }, [isSuccessPgbouncerConfig, isSuccessSupavisorConfig])
return (
<section id="connection-pooler">
@@ -145,12 +328,8 @@ export const ConnectionPooling = () => {
title={
<div className="w-full flex items-center justify-between">
<div className="flex items-center gap-x-2">
- <p>
- {connectionPoolingUnavailable
- ? 'Connection Pooling is not available for this project'
- : 'Connection pooling configuration'}
- </p>
- <Badge>Supavisor</Badge>
+ <p>Connection pooling configuration</p>
+ {!allowPgBouncerSelection && <Badge>Supavisor</Badge>}
</div>
<DocsButton href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pooler" />
</div>
@@ -158,9 +337,9 @@ export const ConnectionPooling = () => {
footer={
<FormActions
form={formId}
- isSubmitting={isUpdating}
+ isSubmitting={isSaving}
hasChanges={form.formState.isDirty}
- handleReset={() => form.reset()}
+ handleReset={() => resetForm()}
helper={
!canUpdateConnectionPoolingConfiguration
? 'You need additional permissions to update connection pooling settings'
@@ -169,158 +348,310 @@ export const ConnectionPooling = () => {
/>
}
>
- {isLoading && (
- <Panel.Content className="space-y-8">
- {Array.from({ length: 4 }).map((_, i) => (
- <Fragment key={i}>
- <div className="grid gap-2 items-center md:grid md:grid-cols-12 md:gap-x-4 w-full">
- <ShimmeringLoader className="h-4 w-1/3 col-span-4" delayIndex={i} />
- <ShimmeringLoader className="h-8 w-full col-span-8" delayIndex={i} />
- </div>
- <Separator />
- </Fragment>
- ))}
-
- <ShimmeringLoader className="h-8 w-full" />
- </Panel.Content>
- )}
+ <Panel.Content>
+ {isLoading && (
+ <div className="flex flex-col gap-y-4">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Fragment key={`loader-${i}`}>
+ <div className="grid gap-2 items-center md:grid md:grid-cols-12 md:gap-x-4 w-full">
+ <ShimmeringLoader className="h-4 w-1/3 col-span-4" delayIndex={i} />
+ <ShimmeringLoader className="h-8 w-full col-span-8" delayIndex={i} />
+ </div>
+ <Separator />
+ </Fragment>
+ ))}
- {isError && (
- <div className="p-4">
- <AlertError error={error} subject="Failed to retrieve pooling configuration" />
- </div>
- )}
-
- {isSuccess && (
- <>
- {connectionPoolingUnavailable && (
- <p>Please start a new project to enable this feature.</p>
- )}
- <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"
- 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
- disabled={poolingConfiguration?.pool_mode === 'transaction'}
- value={field.value}
- className="w-full"
- onChange={(value) => field.onChange(value)}
+ <ShimmeringLoader className="h-8 w-full" />
+ </div>
+ )}
+ {isError && (
+ <AlertError
+ error={error}
+ subject="Failed to retrieve connection pooler configuration"
+ />
+ )}
+ {isSuccess && (
+ <>
+ {connectionPoolingUnavailable && (
+ <Admonition
+ type="default"
+ title="Unable to retrieve pooling configuration"
+ description="Please start a new project to enable this feature"
+ />
+ )}
+ <Form_Shadcn_ {...form}>
+ <form
+ id={formId}
+ className="flex flex-col gap-y-6 w-full"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ {allowPgBouncerSelection && (
+ <FormField_Shadcn_
+ control={form.control}
+ name="type"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="horizontal"
+ label="Pooler Type"
+ description={
+ <>
+ {isChangingPoolerType && (
+ <Admonition
+ type="warning"
+ className="mt-2"
+ title={poolerSwitchWarningTitle}
+ description={poolerSwitchWarningDescription}
+ />
+ )}
+ {type === 'PgBouncer' && !hasIpv4Addon && (
+ <Admonition
+ type="default"
+ className="mt-2"
+ title="The Dedicated Pooler does not support IPv4"
+ description={
+ <>
+ If you were using Supavisor for IPv6, we recommend purchasing
+ a dedicated IPv4 address from the{' '}
+ <InlineLink
+ href={`/project/${projectRef}/settings/addons?panel=ipv4`}
+ >
+ add-ons page
+ </InlineLink>
+ {isChangingPoolerType && ' before changing your pooler type'}.
+ </>
+ }
+ />
+ )}
+ </>
+ }
>
- <Listbox.Option key="transaction" label="Transaction" value="transaction">
- <p>Transaction mode</p>
- <p className="text-xs text-foreground-lighter">
- {TRANSACTION_MODE_DESCRIPTION}
- </p>
- </Listbox.Option>
- <Listbox.Option key="session" label="Session" value="session">
- <p>Session mode</p>
- <p className="text-xs text-foreground-lighter">
- {SESSION_MODE_DESCRIPTION}
- </p>
- </Listbox.Option>
- </Listbox>
- </FormControl_Shadcn_>
-
- {poolingConfiguration?.pool_mode === 'transaction' && (
- <FormDescription_Shadcn_ className="col-start-5 col-span-8 flex flex-col gap-y-2">
- <Alert_Shadcn_>
- <AlertTitle_Shadcn_ className="text-foreground">
- Pool mode is permanently set to Transaction on port 6543
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- You can use Session mode by connecting to the pooler on port 5432
- instead
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- </FormDescription_Shadcn_>
- )}
-
- {poolingConfiguration?.pool_mode === 'session' && (
- <>
- {field.value === 'transaction' ? (
- <FormDescription_Shadcn_ className="col-start-5 col-span-8 flex flex-col gap-y-2">
- <Admonition
- type="warning"
- title="Pool mode will be set to transaction permanently on port 6543"
- description="This will take into effect once saved. If you are using Session mode with port 6543 in your applications, please update to use port 5432 instead before saving."
- />
- </FormDescription_Shadcn_>
- ) : (
- <FormDescription_Shadcn_ className="col-start-5 col-span-8 flex flex-col gap-y-2">
- {/* [Joshen] Can probably remove this after Feb 28 */}
- <Panel.Notice
- layout="vertical"
- className="border rounded-lg"
- title="Deprecating Session Mode on Port 6543"
- description="On February 28, 2025, Supavisor is deprecating Session Mode on port 6543. Please update your application/database clients to use port 5432 for Session Mode."
- href="https://github.com/orgs/supabase/discussions/32755"
- buttonText="Read the announcement"
- />
- <Admonition
- showIcon={false}
- type="default"
- title="Set to transaction mode to use both pooling modes concurrently"
- description="Session mode can be used concurrently with transaction mode by
- using 5432 for session and 6543 for transaction. However, by
- configuring the pooler mode to session here, you will not be able
- to use transaction mode at the same time."
- />
- </FormDescription_Shadcn_>
- )}
- </>
+ <Select_Shadcn_
+ {...field}
+ disabled={refetchPgBouncerStatus}
+ onValueChange={(e) => {
+ field.onChange(e)
+ if (e === 'Supavisor' && supavisorConfig) {
+ form.setValue('type', 'Supavisor')
+ form.setValue('pool_mode', supavisorConfig.pool_mode)
+ form.setValue(
+ 'default_pool_size',
+ supavisorConfig.default_pool_size
+ )
+ form.setValue('max_client_conn', supavisorConfig.max_client_conn)
+ } else if (e === 'PgBouncer' && pgbouncerConfig) {
+ form.setValue('type', 'PgBouncer')
+ form.setValue('pool_mode', pgbouncerConfig.pool_mode as any)
+ form.setValue(
+ 'default_pool_size',
+ pgbouncerConfig.default_pool_size as any
+ )
+ form.setValue(
+ 'max_client_conn',
+ pgbouncerConfig.max_client_conn || null
+ )
+ }
+ }}
+ >
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_ className="max-w-80">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="Supavisor">
+ <div className="flex gap-x-2 items-center">
+ <p className="text-sm text-foreground">Supavisor</p>
+ <Badge>IPv4</Badge>
+ </div>
+ </SelectItem_Shadcn_>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <SelectItem_Shadcn_
+ disabled={disablePgBouncerSelection}
+ value="PgBouncer"
+ className={cn(
+ disablePgBouncerSelection && '!pointer-events-auto'
+ )}
+ >
+ <div className="flex items-center gap-x-2">
+ <p className="text-sm text-foreground">Dedicated Pooler</p>
+ <div className="flex items-center gap-x-1">
+ {hasIpv4Addon && <Badge>Dedicated IPv4</Badge>}
+ <Badge>IPv6</Badge>
+ </div>
+ </div>
+ </SelectItem_Shadcn_>
+ </TooltipTrigger>
+ {disablePgBouncerSelection && (
+ <TooltipContent side="right" className="w-72">
+ Dedicated Pooler can only be used while on a Micro Compute and
+ above.{' '}
+ {isFreePlan ? (
+ <>
+ <InlineLink
+ href={`/org/${org?.slug}/billing?panel=subscriptionPlan`}
+ >
+ Upgrade your plan
+ </InlineLink>{' '}
+ to adjust your project's compute size.
+ </>
+ ) : (
+ <>
+ Upgrade your compute size through your{' '}
+ <InlineLink
+ href={`/project/${projectRef}/settings/compute-and-disk`}
+ >
+ project's settings
+ </InlineLink>
+ .
+ </>
+ )}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormItemLayout>
)}
+ />
+ )}
- <FormDescription_Shadcn_ className="col-start-5 col-span-8 flex flex-col gap-y-2">
- <p>
- Specify when a connection can be returned to the pool.{' '}
- <span
- tabIndex={0}
- onClick={() => snap.setShowPoolingModeHelper(true)}
- className="cursor-pointer underline underline-offset-2"
+ <FormField_Shadcn_
+ control={form.control}
+ name="pool_mode"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="horizontal"
+ label="Pool Mode"
+ description={
+ <>
+ {disablePoolModeSelection && (
+ <Alert_Shadcn_ className="mt-0">
+ <AlertTitle_Shadcn_ className="text-foreground">
+ Pool mode is permanently set to Transaction on port 6543
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ You can use Session mode by connecting to the pooler on port 5432
+ instead
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )}
+ {showPoolModeWarning && (
+ <>
+ {field.value === 'transaction' ? (
+ <Admonition
+ type="warning"
+ title="Pool mode will be set to transaction permanently on port 6543"
+ description="This will take into effect once saved. If you are using Session mode with port 6543 in your applications, please update to use port 5432 instead before saving."
+ />
+ ) : (
+ <>
+ <Panel.Notice
+ layout="vertical"
+ className="border rounded-lg"
+ title="Deprecating Session Mode on Port 6543"
+ description="On February 28, 2025, Supavisor is deprecating Session Mode on port 6543. Please update your application/database clients to use port 5432 for Session Mode."
+ href="https://github.com/orgs/supabase/discussions/32755"
+ buttonText="Read the announcement"
+ />
+ <Admonition
+ className="mt-2"
+ showIcon={false}
+ type="default"
+ title="Set to transaction mode to use both pooling modes concurrently"
+ description="Session mode can be used concurrently with transaction mode by
+ using 5432 for session and 6543 for transaction. However, by
+ configuring the pooler mode to session here, you will not be able
+ to use transaction mode at the same time."
+ />
+ </>
+ )}
+ </>
+ )}
+ <p className="mt-2">
+ Specify when a connection can be returned to the pool.{' '}
+ <span
+ tabIndex={0}
+ onClick={() => snap.setShowPoolingModeHelper(true)}
+ className="transition cursor-pointer underline underline-offset-2 decoration-foreground-lighter hover:decoration-foreground text-foreground"
+ >
+ Learn more about pool modes
+ </span>
+ .
+ </p>
+ </>
+ }
+ >
+ <FormControl_Shadcn_>
+ <Listbox
+ disabled={disablePoolModeSelection}
+ value={field.value}
+ className="w-full"
+ onChange={(value) => field.onChange(value)}
>
- Learn more about pool modes
- </span>
- .
- </p>
- </FormDescription_Shadcn_>
+ <Listbox.Option
+ key="transaction"
+ label="Transaction"
+ value="transaction"
+ >
+ <p>Transaction mode</p>
+ <p className="text-xs text-foreground-lighter">
+ {TRANSACTION_MODE_DESCRIPTION}
+ </p>
+ </Listbox.Option>
+ <Listbox.Option key="session" label="Session" value="session">
+ <p>Session mode</p>
+ <p className="text-xs text-foreground-lighter">
+ {SESSION_MODE_DESCRIPTION}
+ </p>
+ </Listbox.Option>
+ </Listbox>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
- <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
- </FormItem_Shadcn_>
- )}
- />
- <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">
- Pool Size
- </FormLabel_Shadcn_>
- <FormControl_Shadcn_ className="col-span-8">
- <Input_Shadcn_
- {...field}
- type="number"
- className="w-full"
- value={field.value || undefined}
- placeholder={field.value === null ? `${defaultPoolSize}` : ''}
- />
- </FormControl_Shadcn_>
- {maxConnData !== undefined &&
- Number(form.getValues('default_pool_size') ?? 15) >
- maxConnData.maxConnections * 0.8 && (
- <div className="col-start-5 col-span-8">
- <Alert_Shadcn_ variant="warning">
+ <FormField_Shadcn_
+ control={form.control}
+ name="default_pool_size"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="horizontal"
+ label="Pool Size"
+ description={
+ <>
+ <p>
+ The maximum number of connections made to the underlying Postgres
+ cluster, per user+db combination. Pool size has a default of{' '}
+ {defaultPoolSize} based on your compute size of {computeSize}.
+ </p>
+ {type === 'Supavisor' && (
+ <p className="mt-2">
+ Please refer to our{' '}
+ <InlineLink href="https://supabase.com/docs/guides/database/connection-management#configuring-supavisors-pool-size">
+ documentation
+ </InlineLink>{' '}
+ to find out more.
+ </p>
+ )}
+ </>
+ }
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ type="number"
+ className="w-full"
+ value={field.value || undefined}
+ placeholder={!field.value ? `${defaultPoolSize}` : ''}
+ {...form.register('default_pool_size', {
+ setValueAs: setValueAsNullableNumber,
+ })}
+ />
+ </FormControl_Shadcn_>
+ {!!maxConnData &&
+ (default_pool_size ?? 15) > maxConnData.maxConnections * 0.8 && (
+ <Alert_Shadcn_ variant="warning" className="mt-2">
<AlertTitle_Shadcn_ className="text-foreground">
Pool size is greater than 80% of the max connections (
{maxConnData.maxConnections}) on your database
@@ -330,72 +661,87 @@ export const ConnectionPooling = () => {
connections.
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
- </div>
- )}
- <FormDescription_Shadcn_ className="col-start-5 col-span-8">
- The maximum number of connections made to the underlying Postgres cluster,
- per user+db combination. Pool size has a default of {defaultPoolSize} based
- on your compute size of {computeSize}.
- </FormDescription_Shadcn_>
- <FormDescription_Shadcn_ className="col-start-5 col-span-8">
- Please refer to our{' '}
- <a
- href="https://supabase.com/docs/guides/database/connection-management#configuring-supavisors-pool-size"
- target="_blank"
- rel="noreferrer"
- className="underline"
- >
- documentation
- </a>{' '}
- to find out more.
- </FormDescription_Shadcn_>
- <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
- </FormItem_Shadcn_>
- )}
- />
- <FormField_Shadcn_
- disabled
- 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"
- placeholder={field.value === null ? `${defaultMaxClientConn}` : ''}
- />
- </FormControl_Shadcn_>
- <FormDescription_Shadcn_ className="col-start-5 col-span-8">
- The maximum number of concurrent client connections allowed. This value is
- fixed at {defaultMaxClientConn} based on your compute size of {computeSize}{' '}
- and cannot be changed.
- </FormDescription_Shadcn_>
- <FormDescription_Shadcn_ className="col-start-5 col-span-8">
- Please refer to our{' '}
- <a
- href="https://supabase.com/docs/guides/database/connection-management#configuring-supavisors-pool-size"
- target="_blank"
- rel="noreferrer"
- className="underline"
- >
- documentation
- </a>{' '}
- to find out more.
- </FormDescription_Shadcn_>
- <FormMessage_Shadcn_ className="col-start-5 col-span-8" />
- </FormItem_Shadcn_>
- )}
- />
- </form>
- </Form_Shadcn_>
- </>
- )}
+ )}
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="max_client_conn"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="horizontal"
+ label="Max Client Connections"
+ description={
+ <>
+ <p>
+ The maximum number of concurrent client connections allowed.{' '}
+ {type === 'Supavisor' ? (
+ <>
+ This value is fixed at {defaultMaxClientConn} based on your
+ compute size of {computeSize} and cannot be changed.
+ </>
+ ) : (
+ <>
+ This has a default of {defaultMaxClientConn} based on your compute
+ size of {computeSize}.
+ </>
+ )}
+ </p>
+ {type === 'Supavisor' && (
+ <p className="mt-2">
+ Please refer to our{' '}
+ <InlineLink href="https://supabase.com/docs/guides/database/connection-management#configuring-supavisors-pool-size">
+ documentation
+ </InlineLink>{' '}
+ to find out more.
+ </p>
+ )}
+ </>
+ }
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ type="number"
+ className="w-full"
+ value={field.value || ''}
+ disabled={type === 'Supavisor'}
+ placeholder={!field.value ? `${defaultMaxClientConn}` : ''}
+ {...form.register('max_client_conn', {
+ setValueAs: setValueAsNullableNumber,
+ })}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </form>
+ </Form_Shadcn_>
+ </>
+ )}
+ </Panel.Content>
</Panel>
+ <ConfirmationModal
+ size="medium"
+ visible={showConfirmation}
+ loading={isSaving}
+ title={`Confirm switching pooler type to ${formattedTargetPooler}`}
+ confirmLabel="Confirm"
+ onCancel={() => setShowConfirmation(false)}
+ onConfirm={() => onSubmit(form.getValues())}
+ alert={{
+ base: { variant: 'warning' },
+ title: poolerSwitchWarningTitle,
+ description: poolerSwitchWarningDescription,
+ }}
+ >
+ <p className="text-sm text-foreground-light">
+ Are you sure you wish to switch your pooler type to {formattedTargetPooler} and apply the
+ provided configurations?
+ </p>
+ </ConfirmationModal>
</section>
)
}
diff --git a/apps/studio/components/ui/Forms/Form.constants.ts b/apps/studio/components/ui/Forms/Form.constants.ts
index ad65518ec6c..e3910fabb06 100644
--- a/apps/studio/components/ui/Forms/Form.constants.ts
+++ b/apps/studio/components/ui/Forms/Form.constants.ts
@@ -1,19 +1,5 @@
import * as z from 'zod'
-// This validator validates a string to be a positive integer or if it's an empty string, transforms it to a null
-export 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(),
-])
-
export const StringNumberOrNull = z
.string()
.transform((v) => (v === '' ? null : v))
@@ -22,3 +8,10 @@ export const StringNumberOrNull = z
message: 'Invalid number',
})
.transform((value) => (value === null ? null : Number(value)))
+
+/**
+ * [Joshen] After wrangling with RHF I think this is the easiest way to handle nullable number fields
+ * - Declare the field normally as you would in the zod form schema (e.g field: z.number().nullable())
+ * - In the InputField, add a form.register call `{...form.register('field_name', { setValueAs: setValueAsNullableNumber })}`
+ */
+export const setValueAsNullableNumber = (v: any) => (v === '' || v === null ? null : parseInt(v))
diff --git a/apps/studio/components/ui/Panel.tsx b/apps/studio/components/ui/Panel.tsx
index dbc51b7dfa0..12b2d88f0bc 100644
--- a/apps/studio/components/ui/Panel.tsx
+++ b/apps/studio/components/ui/Panel.tsx
@@ -36,11 +36,7 @@ function Panel(props: PropsWithChildren<PanelProps>) {
</div>
)}
{props.children}
- {props.footer && (
- <div className="bg-surface-100 border-t border-default">
- <div className="flex h-12 items-center px-4 md:px-6">{props.footer}</div>
- </div>
- )}
+ {props.footer && <Footer>{props.footer}</Footer>}
</div>
)
@@ -55,6 +51,14 @@ function Content({ children, className }: { children: ReactNode; className?: str
return <div className={cn('px-4 md:px-6 py-4', className)}>{children}</div>
}
+function Footer({ children }: { children: ReactNode; className?: string }) {
+ return (
+ <div className="bg-surface-100 border-t border-default">
+ <div className="flex h-12 items-center px-4 md:px-6">{children}</div>
+ </div>
+ )
+}
+
const PanelNotice = forwardRef<
HTMLDivElement,
{
@@ -139,5 +143,6 @@ const PanelNotice = forwardRef<
PanelNotice.displayName = 'PanelNotice'
Panel.Content = Content
+Panel.Footer = Footer
Panel.Notice = PanelNotice
export default Panel
diff --git a/apps/studio/data/database/pgbouncer-config-query.ts b/apps/studio/data/database/pgbouncer-config-query.ts
index d3deadb9e33..93809e5ba4c 100644
--- a/apps/studio/data/database/pgbouncer-config-query.ts
+++ b/apps/studio/data/database/pgbouncer-config-query.ts
@@ -4,12 +4,12 @@ import { get, handleError } from 'data/fetchers'
import { ResponseError } from 'types'
import { databaseKeys } from './keys'
-export type ProjectPgbouncerConfigVariables = {
+export type PgbouncerConfigVariables = {
projectRef?: string
}
-export async function getProjectPgbouncerConfig(
- { projectRef }: ProjectPgbouncerConfigVariables,
+export async function getPgbouncerConfig(
+ { projectRef }: PgbouncerConfigVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
@@ -22,19 +22,19 @@ export async function getProjectPgbouncerConfig(
return data
}
-export type ProjectPgbouncerConfigData = Awaited<ReturnType<typeof getProjectPgbouncerConfig>>
-export type ProjectPgbouncerConfigError = ResponseError
+export type PgbouncerConfigData = Awaited<ReturnType<typeof getPgbouncerConfig>>
+export type PgbouncerConfigError = ResponseError
-export const useProjectPgbouncerConfigQuery = <TData = ProjectPgbouncerConfigData>(
- { projectRef }: ProjectPgbouncerConfigVariables,
+export const usePgbouncerConfigQuery = <TData = PgbouncerConfigData>(
+ { projectRef }: PgbouncerConfigVariables,
{
enabled = true,
...options
- }: UseQueryOptions<ProjectPgbouncerConfigData, ProjectPgbouncerConfigError, TData> = {}
+ }: UseQueryOptions<PgbouncerConfigData, PgbouncerConfigError, TData> = {}
) =>
- useQuery<ProjectPgbouncerConfigData, ProjectPgbouncerConfigError, TData>(
+ useQuery<PgbouncerConfigData, PgbouncerConfigError, TData>(
databaseKeys.pgbouncerConfig(projectRef),
- ({ signal }) => getProjectPgbouncerConfig({ projectRef }, signal),
+ ({ signal }) => getPgbouncerConfig({ projectRef }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined',
...options,
diff --git a/apps/studio/data/database/pgbouncer-config-update-mutation.ts b/apps/studio/data/database/pgbouncer-config-update-mutation.ts
new file mode 100644
index 00000000000..3159da1b0b1
--- /dev/null
+++ b/apps/studio/data/database/pgbouncer-config-update-mutation.ts
@@ -0,0 +1,73 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import type { components } from 'data/api'
+import { handleError, patch } from 'data/fetchers'
+import type { ResponseError } from 'types'
+import { databaseKeys } from './keys'
+
+export type PgbouncerConfigurationUpdateVariables = {
+ ref: string
+} & components['schemas']['UpdatePgbouncerConfigBody']
+
+export async function updatePgbouncerConfiguration({
+ ref,
+ pool_mode,
+ default_pool_size,
+ pgbouncer_enabled,
+ ignore_startup_parameters,
+ max_client_conn,
+}: PgbouncerConfigurationUpdateVariables) {
+ if (!ref) return console.error('Project ref is required')
+
+ const { data, error } = await patch('/platform/projects/{ref}/config/pgbouncer', {
+ params: { path: { ref } },
+ body: {
+ default_pool_size,
+ pool_mode,
+ pgbouncer_enabled,
+ ignore_startup_parameters,
+ max_client_conn,
+ },
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type PgbouncerConfigurationUpdateData = Awaited<ReturnType<typeof updatePgbouncerConfiguration>>
+
+export const usePgbouncerConfigurationUpdateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<
+ PgbouncerConfigurationUpdateData,
+ ResponseError,
+ PgbouncerConfigurationUpdateVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<
+ PgbouncerConfigurationUpdateData,
+ ResponseError,
+ PgbouncerConfigurationUpdateVariables
+ >((vars) => updatePgbouncerConfiguration(vars), {
+ async onSuccess(data, variables, context) {
+ const { ref } = variables
+ await queryClient.invalidateQueries(databaseKeys.pgbouncerConfig(ref))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to update PgBouncer configuration: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/database/pgbouncer-status-query.ts b/apps/studio/data/database/pgbouncer-status-query.ts
index 623808b292c..fd178fd8eb2 100644
--- a/apps/studio/data/database/pgbouncer-status-query.ts
+++ b/apps/studio/data/database/pgbouncer-status-query.ts
@@ -4,12 +4,12 @@ import { get, handleError } from 'data/fetchers'
import { ResponseError } from 'types'
import { databaseKeys } from './keys'
-export type ProjectPgbouncerStatusVariables = {
+export type PgbouncerStatusVariables = {
projectRef?: string
}
-export async function getProjectPgbouncerStatus(
- { projectRef }: ProjectPgbouncerStatusVariables,
+export async function getPgbouncerStatus(
+ { projectRef }: PgbouncerStatusVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
@@ -22,19 +22,19 @@ export async function getProjectPgbouncerStatus(
return data
}
-export type ProjectPgbouncerStatusData = Awaited<ReturnType<typeof getProjectPgbouncerStatus>>
-export type ProjectPgbouncerStatusError = ResponseError
+export type PgbouncerStatusData = Awaited<ReturnType<typeof getPgbouncerStatus>>
+export type PgbouncerStatusError = ResponseError
-export const useProjectPgbouncerStatusQuery = <TData = ProjectPgbouncerStatusData>(
- { projectRef }: ProjectPgbouncerStatusVariables,
+export const usePgbouncerStatusQuery = <TData = PgbouncerStatusData>(
+ { projectRef }: PgbouncerStatusVariables,
{
enabled = true,
...options
- }: UseQueryOptions<ProjectPgbouncerStatusData, ProjectPgbouncerStatusError, TData> = {}
+ }: UseQueryOptions<PgbouncerStatusData, PgbouncerStatusError, TData> = {}
) =>
- useQuery<ProjectPgbouncerStatusData, ProjectPgbouncerStatusError, TData>(
+ useQuery<PgbouncerStatusData, PgbouncerStatusError, TData>(
databaseKeys.pgbouncerStatus(projectRef),
- ({ signal }) => getProjectPgbouncerStatus({ projectRef }, signal),
+ ({ signal }) => getPgbouncerStatus({ projectRef }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined',
...options,
diff --git a/apps/studio/data/database/pooling-configuration-query.ts b/apps/studio/data/database/pooling-configuration-query.ts
index 9f58ebad7c5..8059e26dcb0 100644
--- a/apps/studio/data/database/pooling-configuration-query.ts
+++ b/apps/studio/data/database/pooling-configuration-query.ts
@@ -31,6 +31,9 @@ export async function getPoolingConfiguration(
export type PoolingConfigurationData = Awaited<ReturnType<typeof getPoolingConfiguration>>
export type PoolingConfigurationError = ResponseError
+/**
+ * @deprecated use useSupavisorConfigurationQuery isntead
+ */
export const usePoolingConfigurationQuery = <TData = PoolingConfigurationData>(
{ projectRef }: PoolingConfigurationVariables,
{
@@ -46,3 +49,22 @@ export const usePoolingConfigurationQuery = <TData = PoolingConfigurationData>(
...options,
}
)
+
+/**
+ * Just a duplicate of usePoolingConfigurationQuery until we move everything over
+ */
+export const useSupavisorConfigurationQuery = <TData = PoolingConfigurationData>(
+ { projectRef }: PoolingConfigurationVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<PoolingConfigurationData, PoolingConfigurationError, TData> = {}
+) =>
+ useQuery<PoolingConfigurationData, PoolingConfigurationError, TData>(
+ databaseKeys.poolingConfiguration(projectRef),
+ ({ signal }) => getPoolingConfiguration({ projectRef }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database/pooling-configuration-update-mutation.ts b/apps/studio/data/database/pooling-configuration-update-mutation.ts
index f02db60d97b..8252daecf98 100644
--- a/apps/studio/data/database/pooling-configuration-update-mutation.ts
+++ b/apps/studio/data/database/pooling-configuration-update-mutation.ts
@@ -57,7 +57,42 @@ export const usePoolingConfigurationUpdateMutation = ({
},
async onError(data, variables, context) {
if (onError === undefined) {
- toast.error(`Failed to update pooling configuration: ${data.message}`)
+ toast.error(`Failed to update PgBouncer configuration: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
+
+export const useSupavisorConfigurationUpdateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<
+ PoolingConfigurationUpdateData,
+ ResponseError,
+ PoolingConfigurationUpdateVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<
+ PoolingConfigurationUpdateData,
+ ResponseError,
+ PoolingConfigurationUpdateVariables
+ >((vars) => updatePoolingConfiguration(vars), {
+ async onSuccess(data, variables, context) {
+ const { ref } = variables
+ await queryClient.invalidateQueries(databaseKeys.poolingConfiguration(ref))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to update Supavisor configuration: ${data.message}`)
} else {
onError(data, variables, context)
}
diff --git a/packages/ui/src/components/radio-group-card.tsx b/packages/ui/src/components/radio-group-card.tsx
index 234817b79cd..1f0b8c6adfb 100644
--- a/packages/ui/src/components/radio-group-card.tsx
+++ b/packages/ui/src/components/radio-group-card.tsx
@@ -16,7 +16,7 @@ RadioGroupCard.displayName = RadioGroupPrimitive.Root.displayName
interface RadioGroupCardItemProps {
image?: React.ReactNode
- label: string
+ label: string | React.ReactNode
showIndicator?: boolean
}