Skip to content

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

Chore/update database connection string settings (#20429)

Joshen Lim09a77a85e539
diff --git a/apps/studio/components/interfaces/Database/index.ts b/apps/studio/components/interfaces/Database/index.ts
index 2946567545b..46eb0254b69 100644
--- a/apps/studio/components/interfaces/Database/index.ts
+++ b/apps/studio/components/interfaces/Database/index.ts
@@ -14,8 +14,6 @@ import PublicationsTables from './Publications/PublicationsTables'
import BackupsList from './Backups/BackupsList'
-import ConnectionPooling from '../Settings/Database/ConnectionPooling'
-
import CreateTrigger from './Triggers/CreateTrigger'
import DeleteTrigger from './Triggers/DeleteTrigger'
@@ -27,7 +25,6 @@ import EnumeratedTypes from './EnumeratedTypes/EnumeratedTypes'
export {
BackupsList,
ColumnList,
- ConnectionPooling,
CreateFunction,
CreateTrigger,
CreateWrapper,
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index 360fd9912f1..eac13c0f384 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -2,7 +2,9 @@ import * as Tooltip from '@radix-ui/react-tooltip'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import clsx from 'clsx'
import Link from 'next/link'
+import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
+import { plans as subscriptionsPlans } from 'shared-data/plans'
import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
@@ -10,15 +12,13 @@ import InformationBox from 'components/ui/InformationBox'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
import { useOrganizationBillingSubscriptionPreview } from 'data/organizations/organization-billing-subscription-preview'
-import { OrgPlan } from 'data/subscriptions/types'
+import { useOrgPlansQuery } from 'data/subscriptions/org-plans-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
-import { SubscriptionTier } from 'data/subscriptions/types'
+import { OrgPlan, SubscriptionTier } from 'data/subscriptions/types'
import { useCheckPermissions, useSelectedOrganization, useStore } from 'hooks'
import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import Telemetry from 'lib/telemetry'
-import { useRouter } from 'next/router'
-import { plans as subscriptionsPlans } from 'shared-data/plans'
import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
import {
Button,
@@ -34,7 +34,6 @@ import EnterpriseCard from './EnterpriseCard'
import ExitSurveyModal from './ExitSurveyModal'
import MembersExceedLimitModal from './MembersExceedLimitModal'
import PaymentMethodSelection from './PaymentMethodSelection'
-import { useOrgPlansQuery } from 'data/subscriptions/org-plans-query'
const PlanUpdateSidePanel = () => {
const { ui } = useStore()
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
index 5c3f95cd61a..b2f6ecfe848 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
@@ -1,7 +1,7 @@
+import { useParams } from 'common'
import dayjs from 'dayjs'
import Link from 'next/link'
-import { useParams } from 'common'
import {
ScaffoldSection,
ScaffoldSectionContent,
@@ -10,7 +10,9 @@ import {
import AlertError from 'components/ui/AlertError'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import SparkBar from 'components/ui/SparkBar'
+import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useOrgUsageQuery } from 'data/usage/org-usage-query'
import { useFlag } from 'hooks'
import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
import {
@@ -24,8 +26,6 @@ import {
} from 'ui'
import ProjectUpdateDisabledTooltip from '../ProjectUpdateDisabledTooltip'
import PlanUpdateSidePanel from './PlanUpdateSidePanel'
-import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'
-import { useOrgUsageQuery } from 'data/usage/org-usage-query'
const Subscription = () => {
const { slug } = useParams()
diff --git a/apps/studio/components/interfaces/Settings/Addons/Addons.tsx b/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
index 9e29adb3aa5..2b7f0401fbb 100644
--- a/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
+++ b/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
@@ -1,9 +1,20 @@
+import { useParams } from 'common'
import dayjs from 'dayjs'
+import { useTheme } from 'next-themes'
+import Image from 'next/image'
import Link from 'next/link'
import { useMemo } from 'react'
+import {
+ Alert,
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ IconAlertCircle,
+ IconChevronRight,
+ IconExternalLink,
+} from 'ui'
-import { useParams } from 'common'
-import { useTheme } from 'next-themes'
import {
getAddons,
subscriptionHasHipaaAddon,
@@ -23,28 +34,17 @@ import {
import AlertError from 'components/ui/AlertError'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useInfraMonitoringQuery } from 'data/analytics/infra-monitoring-query'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
+import { ProjectAddonVariantMeta } from 'data/subscriptions/types'
import { useFlag, useProjectByRef, useSelectedOrganization } from 'hooks'
import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils'
import { BASE_PATH } from 'lib/constants'
import { getDatabaseMajorVersion, getSemanticVersion } from 'lib/helpers'
import { SUBSCRIPTION_PANEL_KEYS, useSubscriptionPageStateSnapshot } from 'state/subscription-page'
-import {
- Alert,
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Button,
- IconAlertCircle,
- IconChevronRight,
- IconExternalLink,
-} from 'ui'
-import Image from 'next/image'
import ComputeInstanceSidePanel from './ComputeInstanceSidePanel'
-import PITRSidePanel from './PITRSidePanel'
import CustomDomainSidePanel from './CustomDomainSidePanel'
-import { ProjectAddonVariantMeta } from 'data/subscriptions/types'
-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import PITRSidePanel from './PITRSidePanel'
const Addons = () => {
const { resolvedTheme } = useTheme()
diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
deleted file mode 100644
index 740ad9b0815..00000000000
--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling.tsx
+++ /dev/null
@@ -1,358 +0,0 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-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 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 {
- PoolingConfigurationData,
- usePoolingConfigurationQuery,
-} from 'data/database/pooling-configuration-query'
-import { usePoolingConfigurationUpdateMutation } from 'data/database/pooling-configuration-update-mutation'
-import { useCheckPermissions, useStore } from 'hooks'
-
-const formId = 'connection-pooling-form'
-
-const ConnectionPooling = () => {
- const { ref: projectRef } = useParams()
- const {
- data: poolingConfiguration,
- error,
- isLoading,
- isError,
- isSuccess,
- } = usePoolingConfigurationQuery({ projectRef: projectRef! })
-
- return (
- <>
- {isLoading && (
- <Panel
- title={
- <h5 key="panel-title" className="mb-0">
- Connection Pooling
- </h5>
- }
- >
- <Panel.Content className="space-y-8">
- {Array.from({ length: 5 }).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>
- <Divider light />
- </Fragment>
- ))}
-
- <ShimmeringLoader className="h-8 w-full" />
- </Panel.Content>
- </Panel>
- )}
- {isError && (
- <div className="p-4">
- <AlertError error={error} subject="Failed to retrieve pooling configuration" />
- </div>
- )}
- {isSuccess && (
- <>
- {!poolingConfiguration?.pgbouncer_enabled && poolingConfiguration?.pool_mode === null ? (
- <Panel
- title={
- <h5 key="panel-title" className="mb-0">
- Connection Pooling is not available for this project
- </h5>
- }
- >
- <Panel.Content>
- <p className="text-foreground-light">
- Please start a new project to enable this feature.
- </p>
- </Panel.Content>
- </Panel>
- ) : (
- <MainConfig projectRef={projectRef!} poolingInfo={poolingConfiguration} />
- )}
- </>
- )}
- </>
- )
-}
-
-export default ConnectionPooling
-
-// 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
- poolingInfo: PoolingConfigurationData
-}
-
-const MainConfig = ({ projectRef, poolingInfo }: MainConfigProps) => {
- const { ui } = useStore()
- const { project } = useProjectContext()
-
- const canUpdateConnectionPoolingConfiguration = useCheckPermissions(
- PermissionAction.UPDATE,
- 'projects',
- {
- resource: {
- project_id: project?.id,
- },
- }
- )
-
- 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 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 {
- }
- }
-
- return (
- <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"
- 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_>
- )}
- />
- <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 && (
- <>
- <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_>
- )}
- />
- </>
- )}
- </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/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts
new file mode 100644
index 00000000000..b593853bdd0
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.constants.ts
@@ -0,0 +1,41 @@
+// 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
+
+export const POOLING_OPTIMIZATIONS = {
+ ci_small: {
+ maxClientConn: 1000,
+ poolSize: 15,
+ },
+ ci_medium: {
+ maxClientConn: 1000,
+ poolSize: 15,
+ },
+ ci_large: {
+ maxClientConn: 1000,
+ poolSize: 15,
+ },
+ ci_xlarge: {
+ maxClientConn: 1000,
+ poolSize: 20,
+ },
+ ci_2xlarge: {
+ maxClientConn: 1500,
+ poolSize: 25,
+ },
+ ci_4xlarge: {
+ maxClientConn: 3000,
+ poolSize: 32,
+ },
+ ci_8xlarge: {
+ maxClientConn: 6000,
+ poolSize: 64,
+ },
+ ci_12xlarge: {
+ maxClientConn: 9000,
+ poolSize: 96,
+ },
+ ci_16xlarge: {
+ maxClientConn: 12000,
+ poolSize: 128,
+ },
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx
new file mode 100644
index 00000000000..afcd5f6aa23
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx
@@ -0,0 +1,565 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
+import { Fragment, useEffect } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import {
+ Badge,
+ Button,
+ FormControl_Shadcn_,
+ FormDescription_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Form_Shadcn_,
+ IconExternalLink,
+ Input,
+ Input_Shadcn_,
+ Listbox,
+} from 'ui'
+import z from 'zod'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+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 { usePoolingConfigurationUpdateMutation } from 'data/database/pooling-configuration-update-mutation'
+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
+import { useCheckPermissions, useStore } from 'hooks'
+import { POOLING_OPTIMIZATIONS } from './ConnectionPooling.constants'
+
+const formId = 'connection-pooling-form'
+
+// 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,
+})
+
+export const ConnectionPooling = () => {
+ const { ui } = useStore()
+ const { ref: projectRef } = useParams()
+ const { project } = useProjectContext()
+
+ const { data: addons } = useProjectAddonsQuery({ projectRef })
+ const computeInstance = addons?.selected_addons.find((addon) => addon.type === 'compute_instance')
+
+ const {
+ data: poolingInfo,
+ error,
+ isLoading,
+ isError,
+ isSuccess,
+ } = usePoolingConfigurationQuery({ projectRef: projectRef })
+
+ const connectionPoolingUnavailable =
+ !poolingInfo?.pgbouncer_enabled && poolingInfo?.pool_mode === null
+
+ // [Joshen] TODO this needs to be obtained from BE as 26th Jan is when we'll start - projects will be affected at different rates
+ const resolvesToIpV6 = !poolingInfo?.supavisor_enabled && false // Number(new Date()) > Number(dayjs.utc('01-26-2024', 'MM-DD-YYYY').toDate())
+
+ const canUpdateConnectionPoolingConfiguration = useCheckPermissions(
+ PermissionAction.UPDATE,
+ 'projects',
+ {
+ resource: {
+ project_id: project?.id,
+ },
+ }
+ )
+
+ 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) => {
+ if (!projectRef) return console.error('Project ref is required')
+ if (!poolingInfo) return console.error('Pooling info required')
+
+ try {
+ await updateConfiguration({
+ ref: projectRef,
+ // 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 {
+ }
+ }
+
+ useEffect(() => {
+ if (isSuccess) {
+ form.reset({
+ 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,
+ })
+ }
+ }, [isSuccess])
+
+ return (
+ <section id="connection-pooler">
+ <Panel
+ className="!mb-0"
+ 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'
+ : 'Connect to your database via connection pooling'}
+ </p>
+ {isSuccess && (
+ <div className="flex items-center gap-x-1">
+ <Badge color={poolingInfo?.supavisor_enabled ? 'green' : 'scale'}>
+ With {poolingInfo?.supavisor_enabled ? 'Supavisor' : 'PGBouncer'}
+ </Badge>
+ <Badge color={resolvesToIpV6 ? 'amber' : 'scale'}>
+ {resolvesToIpV6 ? 'Resolves to IPv6' : 'Resolves to IPv4'}
+ </Badge>
+ </div>
+ )}
+ </div>
+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ <a href="https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pooler">
+ Documentation
+ </a>
+ </Button>
+ </div>
+ }
+ footer={
+ (poolingInfo?.pgbouncer_enabled ?? false) && (
+ <FormActions
+ form={formId}
+ isSubmitting={isUpdating}
+ hasChanges={form.formState.isDirty}
+ handleReset={() => form.reset()}
+ helper={
+ !canUpdateConnectionPoolingConfiguration
+ ? 'You need additional permissions to update connection pooling settings'
+ : undefined
+ }
+ />
+ )
+ }
+ >
+ {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>
+ <Divider light />
+ </Fragment>
+ ))}
+
+ <ShimmeringLoader className="h-8 w-full" />
+ </Panel.Content>
+ )}
+
+ {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>
+ )}
+ {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"
+ 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 flex flex-col gap-y-2">
+ <p>
+ 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#how-connection-pooling-works"
+ target="_blank"
+ className="underline"
+ >
+ documentation
+ </a>{' '}
+ to find out the most suitable mode for your use case.
+ </p>
+ <p>
+ If you're using{' '}
+ <span className="text-foreground">prepared statements</span> in your
+ database, you will need to either use the{' '}
+ <span className="text-foreground">Session</span> pool mode or use port{' '}
+ <span className="text-foreground">5432</span> in the connection
+ string.
+ </p>
+ </FormDescription_Shadcn_>
+ <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">
+ Default Pool Size
+ </FormLabel_Shadcn_>
+ <FormControl_Shadcn_ className="col-span-8">
+ <Input_Shadcn_
+ className="w-full"
+ {...field}
+ value={field.value || undefined}
+ placeholder={
+ poolingInfo.supavisor_enabled && field.value === null
+ ? `Default: ${
+ POOLING_OPTIMIZATIONS?.[
+ computeInstance?.variant
+ .identifier as keyof typeof POOLING_OPTIMIZATIONS
+ ]?.poolSize ?? 15
+ }`
+ : ''
+ }
+ />
+ </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 && (
+ <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}
+ disabled={poolingInfo.supavisor_enabled}
+ 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={
+ poolingInfo.supavisor_enabled
+ ? poolingInfo.supavisor_enabled && field.value === null
+ ? `${
+ POOLING_OPTIMIZATIONS?.[
+ computeInstance?.variant
+ .identifier as keyof typeof POOLING_OPTIMIZATIONS
+ ]?.maxClientConn ?? 200
+ }`
+ : ''
+ : ''
+ }
+ />
+ </FormControl_Shadcn_>
+ <FormDescription_Shadcn_ className="col-start-5 col-span-8">
+ The maximum number of concurrent client connections allowed.{' '}
+ {poolingInfo.supavisor_enabled
+ ? 'This value is fixed and cannot be changed. '
+ : '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_>
+ )}
+ />
+ </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 Number"
+ />
+
+ <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}
+ descriptionText={
+ poolingInfo.supavisor_enabled && (
+ <div className="flex flex-col gap-y-1">
+ <p className="text-sm">
+ You may also connect to another database or with another user via Supavisor
+ with the following URI format:
+ </p>
+ <p className="text-sm font-mono tracking-tighter">
+ postgres://
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">[db-user]</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Database user (e.g postgres)
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ .
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">{project?.ref}</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Project's reference ID
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ :
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">[db-password]</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">Database password</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ @aws-0-
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">{project?.region}</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">Project's region</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ .pooler.supabase.com:
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">{poolingInfo.db_port}</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background w-[200px] text-center',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Database port number (Use 5432 if using prepared statements)
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ /
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <span className="text-foreground">[db-name]</span>
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ Database name (e.g postgres)
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ </p>
+ </div>
+ )
+ }
+ />
+ </>
+ )}
+ </Panel>
+ </section>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString.tsx
index ca710732df1..a4f406f1e56 100644
--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString.tsx
@@ -1,28 +1,43 @@
import { useParams, useTelemetryProps } from 'common'
import { useRouter } from 'next/router'
-import { useEffect, useRef } from 'react'
-import { Input, Tabs } from 'ui'
+import { useEffect, useRef, useState } from 'react'
+import { Input, Separator, Tabs } from 'ui'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AlertError from 'components/ui/AlertError'
import DatabaseSelector from 'components/ui/DatabaseSelector'
-import Panel from 'components/ui/Panel'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useProjectSettingsQuery } from 'data/config/project-settings-query'
import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
-
import { useFlag } from 'hooks'
import { pluckObjectFields } from 'lib/helpers'
import Telemetry from 'lib/telemetry'
import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
-
-const DatabaseConnectionString = () => {
+import { getConnectionStrings } from './DatabaseSettings.utils'
+
+const CONNECTION_TYPES = [
+ { id: 'psql', label: 'PSQL' },
+ { id: 'uri', label: 'URI' },
+ { id: 'golang', label: 'Golang' },
+ { id: 'jdbc', label: 'JDBC' },
+ { id: 'dotnet', label: '.NET' },
+ { id: 'nodejs', label: 'Nodejs' },
+ { id: 'php', label: 'PHP' },
+ { id: 'python', label: 'Python' },
+]
+
+export const DatabaseConnectionString = () => {
const router = useRouter()
+ const { project: projectDetails } = useProjectContext()
const { ref: projectRef, connectionString } = useParams()
const telemetryProps = useTelemetryProps()
const state = useDatabaseSelectorStateSnapshot()
- const readReplicasEnabled = useFlag('readReplicas')
+ const readReplicasEnabled = useFlag('readReplicas') && projectDetails?.is_read_replicas_enabled
const connectionStringsRef = useRef<HTMLDivElement>(null)
+ const [selectedTab, setSelectedTab] = useState<
+ 'psql' | 'uri' | 'golang' | 'jdbc' | 'dotnet' | 'nodejs' | 'php' | 'python'
+ >('psql')
const {
data,
@@ -39,6 +54,7 @@ const DatabaseConnectionString = () => {
isError: isErrorReadReplicas,
isSuccess: isSuccessReadReplicas,
} = useReadReplicasQuery({ projectRef })
+
const error = readReplicasEnabled ? readReplicasError : projectSettingsError
const isLoading = readReplicasEnabled ? isLoadingReadReplicas : isLoadingProjectSettings
const isError = readReplicasEnabled ? isErrorReadReplicas : isErrorProjectSettings
@@ -55,7 +71,8 @@ const DatabaseConnectionString = () => {
? pluckObjectFields(selectedDatabase || emptyState, DB_FIELDS)
: pluckObjectFields(project || emptyState, DB_FIELDS)
- const handleCopy = (labelValue?: string) =>
+ const handleCopy = (id: string) => {
+ const labelValue = CONNECTION_TYPES.find((type) => type.id === id)?.label
Telemetry.sendEvent(
{
category: 'settings',
@@ -65,162 +82,57 @@ const DatabaseConnectionString = () => {
telemetryProps,
router
)
- const uriConnString =
- `postgresql://${connectionInfo.db_user}:[YOUR-PASSWORD]@` +
- `${connectionInfo.db_host}:${connectionInfo.db_port.toString()}` +
- `/${connectionInfo.db_name}`
- const golangConnString =
- `user=${connectionInfo.db_user} password=[YOUR-PASSWORD] ` +
- `host=${connectionInfo.db_host} port=${connectionInfo.db_port.toString()}` +
- ` dbname=${connectionInfo.db_name}`
- const psqlConnString =
- `psql -h ${connectionInfo.db_host} -p ` +
- `${connectionInfo.db_port.toString()} -d ${connectionInfo.db_name} ` +
- `-U ${connectionInfo.db_user}`
+ }
+
+ const connectionStrings = getConnectionStrings(connectionInfo)
useEffect(() => {
- if (connectionString !== undefined && connectionStringsRef.current !== undefined) {
+ if (
+ readReplicasEnabled &&
+ connectionString !== undefined &&
+ connectionStringsRef.current !== undefined
+ ) {
state.setSelectedDatabaseId(connectionString)
connectionStringsRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' })
}
}, [connectionString])
return (
- <div className="space-y-10">
- <section className="space-y-6">
- <Panel
- title={
- <div ref={connectionStringsRef} className="w-full flex items-center justify-between">
- <h5 key="panel-title" className="mb-0">
- Connection string
- </h5>
- {readReplicasEnabled && <DatabaseSelector />}
- </div>
- }
- className="!m-0"
+ <div id="connection-string">
+ <div ref={connectionStringsRef} className="flex flex-col py-4">
+ <div className="px-6 mb-2">
+ <h5 key="panel-title" className="mb-0">
+ Connection string
+ </h5>
+ {readReplicasEnabled && <DatabaseSelector />}
+ </div>
+ <Tabs
+ type="underlined"
+ size="tiny"
+ activeId={selectedTab}
+ baseClassNames="!space-y-0 -mb-[1px] px-6"
+ onChange={setSelectedTab}
>
- <Panel.Content>
- {isLoading && <ShimmeringLoader className="h-8 w-full" />}
- {isError && <AlertError error={error} subject="Failed to retrieve database settings" />}
- {isSuccess && (
- <Tabs type="underlined" size="small">
- <Tabs.Panel id="psql" label="PSQL">
- <Input
- copy
- readOnly
- disabled
- value={psqlConnString}
- onCopy={() => {
- handleCopy('PSQL')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="uri" label="URI">
- <Input
- copy
- readOnly
- disabled
- value={uriConnString}
- onCopy={() => {
- handleCopy('URI')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="golang" label="Golang">
- <Input
- copy
- readOnly
- disabled
- value={golangConnString}
- onCopy={() => {
- handleCopy('Golang')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="jdbc" label="JDBC">
- <Input
- copy
- readOnly
- disabled
- value={
- `jdbc:postgresql://${
- connectionInfo.db_host
- }:${connectionInfo.db_port.toString()}` +
- `/${connectionInfo.db_name}?user=${connectionInfo.db_user}&password=[YOUR-PASSWORD]`
- }
- onCopy={() => {
- handleCopy('JDBC')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="dotnet" label=".NET">
- <Input
- copy
- readOnly
- disabled
- value={
- `User Id=${connectionInfo.db_user};Password=[YOUR-PASSWORD];` +
- `Server=${
- connectionInfo.db_host
- };Port=${connectionInfo.db_port.toString()};` +
- `Database=${connectionInfo.db_name}`
- }
- onCopy={() => {
- handleCopy('.NET')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="nodejs" label="Nodejs">
- <Input
- copy
- readOnly
- disabled
- value={uriConnString}
- onCopy={() => {
- handleCopy('Nodejs')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="php" label="PHP">
- <Input
- copy
- readOnly
- disabled
- value={golangConnString}
- onCopy={() => {
- handleCopy('PHP')
- }}
- />
- </Tabs.Panel>
-
- <Tabs.Panel id="python" label="Python">
- <Input
- copy
- readOnly
- disabled
- value={
- `user=${connectionInfo.db_user} password=[YOUR-PASSWORD]` +
- ` host=${connectionInfo.db_host} port=${connectionInfo.db_port.toString()}` +
- ` database=${connectionInfo.db_name}`
- }
- onCopy={() => {
- handleCopy('Python')
- }}
- />
- </Tabs.Panel>
- </Tabs>
- )}
- </Panel.Content>
- </Panel>
- </section>
+ {CONNECTION_TYPES.map((type) => (
+ <Tabs.Panel key={type.id} id={type.id} label={type.label} />
+ ))}
+ </Tabs>
+ <Separator />
+ </div>
+
+ <div className="px-6 pb-4">
+ {isLoading && <ShimmeringLoader className="h-8 w-full" />}
+ {isError && <AlertError error={error} subject="Failed to retrieve database settings" />}
+ {isSuccess && (
+ <Input
+ copy
+ readOnly
+ disabled
+ value={connectionStrings[selectedTab]}
+ onCopy={() => handleCopy(selectedTab)}
+ />
+ )}
+ </div>
</div>
)
}
-
-export default DatabaseConnectionString
diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
index 582c831c943..0f37ea9d5b6 100644
--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
@@ -19,14 +19,16 @@ import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
Alert_Shadcn_,
+ Badge,
Button,
IconAlertTriangle,
IconExternalLink,
Input,
+ Separator,
} from 'ui'
import ConfirmDisableReadOnlyModeModal from './ConfirmDisableReadOnlyModal'
-import DatabaseConnectionString from './DatabaseConnectionString'
import ResetDbPassword from './ResetDbPassword'
+import { DatabaseConnectionString } from './DatabaseConnectionString'
const DatabaseSettings = () => {
const router = useRouter()
@@ -41,6 +43,9 @@ const DatabaseSettings = () => {
const connectionStringsRef = useRef<HTMLDivElement>(null)
const [showConfirmationModal, setShowConfirmationModal] = useState(false)
+ // [Joshen] TODO this needs to be obtained from BE as 26th Jan is when we'll start - projects will be affected at different rates
+ const resolvesToIpV6 = false // Number(new Date()) > Number(dayjs.utc('01-26-2024', 'MM-DD-YYYY').toDate())
+
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
const {
data,
@@ -97,150 +102,193 @@ const DatabaseSettings = () => {
return (
<>
- <div className="space-y-10">
- <section className="space-y-6">
- <h3 className="text-foreground mb-2 text-xl">Database Settings</h3>
-
- {isReadOnlyMode && (
- <Alert_Shadcn_ variant="destructive">
- <IconAlertTriangle />
- <AlertTitle_Shadcn_>
- Project is in read-only mode and database is no longer accepting write requests
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- You have reached 95% of your project's disk space, and read-only mode has been
- enabled to preserve your database's stability and prevent your project from
- exceeding its current billing plan. To resolve this, you may:
- <ul className="list-disc pl-6 mt-1">
+ <section id="direct-connection">
+ {isReadOnlyMode && (
+ <Alert_Shadcn_ variant="destructive">
+ <IconAlertTriangle />
+ <AlertTitle_Shadcn_>
+ Project is in read-only mode and database is no longer accepting write requests
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ You have reached 95% of your project's disk space, and read-only mode has been enabled
+ to preserve your database's stability and prevent your project from exceeding its
+ current billing plan. To resolve this, you may:
+ <ul className="list-disc pl-6 mt-1">
+ <li>
+ Temporarily disable read-only mode to free up space and reduce your database size
+ </li>
+ {subscription?.plan.id === 'free' ? (
<li>
- Temporarily disable read-only mode to free up space and reduce your database
- size
+ <Link href={`/org/${organization?.slug}/billing?panel=subscriptionPlan`}>
+ <a className="text underline">Upgrade to the Pro plan</a>
+ </Link>{' '}
+ to increase your database size limit to 8GB.
</li>
- {subscription?.plan.id === 'free' ? (
- <li>
- <Link href={`/org/${organization?.slug}/billing?panel=subscriptionPlan`}>
- <a className="text underline">Upgrade to the Pro plan</a>
- </Link>{' '}
- to increase your database size limit to 8GB.
- </li>
- ) : subscription?.plan.id === 'pro' && subscription?.usage_billing_enabled ? (
- <li>
- <Link href={`/org/${organization?.slug}/billing?panel=subscriptionPlan`}>
- <a className="text-foreground underline">Disable your Spend Cap</a>
- </Link>{' '}
- to allow your project to auto-scale and expand beyond the 8GB database size
- limit
- </li>
- ) : null}
- </ul>
- </AlertDescription_Shadcn_>
- <div className="mt-4 flex items-center space-x-2">
- <Button type="default" onClick={() => setShowConfirmationModal(true)}>
- Disable read-only mode
- </Button>
- <Button asChild type="default" icon={<IconExternalLink />}>
- <Link
- href="https://supabase.com/docs/guides/platform/database-size#disabling-read-only-mode"
- target="_blank"
- rel="noreferrer"
- >
- Learn more
- </Link>
- </Button>
- </div>
- </Alert_Shadcn_>
- )}
-
- <Panel
- title={
- <div className="w-full flex items-center justify-between">
- <h5 key="panel-title" className="mb-0">
- Connection info
- </h5>
- {showReadReplicasUI && <DatabaseSelector />}
+ ) : subscription?.plan.id === 'pro' && subscription?.usage_billing_enabled ? (
+ <li>
+ <Link href={`/org/${organization?.slug}/billing?panel=subscriptionPlan`}>
+ <a className="text-foreground underline">Disable your Spend Cap</a>
+ </Link>{' '}
+ to allow your project to auto-scale and expand beyond the 8GB database size
+ limit
+ </li>
+ ) : null}
+ </ul>
+ </AlertDescription_Shadcn_>
+ <div className="mt-4 flex items-center space-x-2">
+ <Button type="default" onClick={() => setShowConfirmationModal(true)}>
+ Disable read-only mode
+ </Button>
+ <Button asChild type="default" icon={<IconExternalLink />}>
+ <Link
+ href="https://supabase.com/docs/guides/platform/database-size#disabling-read-only-mode"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Learn more
+ </Link>
+ </Button>
+ </div>
+ </Alert_Shadcn_>
+ )}
+
+ <Panel
+ title={
+ <div className="w-full flex items-center justify-between">
+ <div className="flex items-center gap-x-2">
+ <h5 className="mb-0">Connect to your database directly</h5>
+ <Badge color={resolvesToIpV6 ? 'amber' : 'scale'}>
+ {resolvesToIpV6 ? 'Resolves to IPv6' : 'Resolves to IPv4'}
+ </Badge>
</div>
- }
- className="!m-0"
- >
- <Panel.Content className="space-y-6">
- {isLoading &&
- Array.from({ length: 5 }).map((_, i) => (
- <div
- key={i}
- 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>
- ))}
- {isError && <AlertError error={error} subject="Failed to retrieve databases" />}
- {isSuccess && (
- <>
- <Input
- className="input-mono"
- layout="horizontal"
- readOnly
- copy
- disabled
- value={connectionInfo.db_host}
- label="Host"
- onCopy={() => {
- handleCopy('Host')
- }}
- />
-
- <Input
- className="input-mono"
- layout="horizontal"
- readOnly
- copy
- disabled
- value={connectionInfo.db_name}
- label="Database name"
- />
-
- <Input
- className="input-mono"
- layout="horizontal"
- readOnly
- copy
- disabled
- value={connectionInfo.db_port.toString()}
- label="Port"
- />
-
- <Input
- layout="horizontal"
- className="input-mono table-input-cell text-base"
- readOnly
- copy
- disabled
- value={connectionInfo.db_user}
- label="User"
- />
-
- <Input
- className="input-mono"
- layout="horizontal"
- disabled
- readOnly
- value={
- state.selectedDatabaseId !== projectRef
- ? '[The password for your primary database]'
- : '[The password you provided when you created this project]'
- }
- label="Password"
- />
- </>
- )}
- </Panel.Content>
- </Panel>
- </section>
-
- <DatabaseConnectionString />
-
- <ResetDbPassword disabled={isLoading || isError} />
- </div>
+ {showReadReplicasUI && <DatabaseSelector />}
+ </div>
+ }
+ className="!m-0"
+ >
+ <Panel.Content className="space-y-6">
+ {isLoading &&
+ Array.from({ length: 5 }).map((_, i) => (
+ <div
+ key={i}
+ 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>
+ ))}
+ {isError && <AlertError error={error} subject="Failed to retrieve databases" />}
+ {isSuccess && (
+ <>
+ <Alert_Shadcn_ variant="warning">
+ <IconAlertTriangle strokeWidth={2} />
+ <AlertTitle_Shadcn_>
+ Direct database access via IPv4 and pgBouncer will be removed from January 26th
+ 2024
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_ className="space-y-3">
+ <p>
+ We strongly recommend using{' '}
+ <span
+ tabIndex={0}
+ className="cursor-pointer text-foreground underline underline-offset-[4px] decoration-brand-500 hover:decoration-foreground"
+ onClick={() => {
+ const connectionPooler = document.getElementById('connection-pooler')
+ connectionPooler?.scrollIntoView({ block: 'center', behavior: 'smooth' })
+ }}
+ >
+ connection pooling
+ </span>{' '}
+ to connect to your database. You'll only need to change the connection string
+ that you're using in your application to the pooler's connection string which
+ can be found in the{' '}
+ <span
+ tabIndex={0}
+ className="cursor-pointer text-foreground underline underline-offset-[4px] decoration-brand-500 hover:decoration-foreground"
+ onClick={() => {
+ const connectionPooler = document.getElementById('connection-pooler')
+ connectionPooler?.scrollIntoView({ block: 'center', behavior: 'smooth' })
+ }}
+ >
+ connection pooling settings
+ </span>
+ .
+ </p>
+ <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ <a
+ href="https://github.com/orgs/supabase/discussions/17817"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Learn more
+ </a>
+ </Button>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ <Input
+ className="input-mono"
+ layout="horizontal"
+ readOnly
+ copy
+ disabled
+ value={connectionInfo.db_host}
+ label="Host"
+ onCopy={() => {
+ handleCopy('Host')
+ }}
+ />
+
+ <Input
+ className="input-mono"
+ layout="horizontal"
+ readOnly
+ copy
+ disabled
+ value={connectionInfo.db_name}
+ label="Database name"
+ />
+
+ <Input
+ className="input-mono"
+ layout="horizontal"
+ readOnly
+ copy
+ disabled
+ value={connectionInfo.db_port.toString()}
+ label="Port"
+ />
+
+ <Input
+ layout="horizontal"
+ className="input-mono table-input-cell text-base"
+ readOnly
+ copy
+ disabled
+ value={connectionInfo.db_user}
+ label="User"
+ />
+
+ <Input
+ className="input-mono"
+ layout="horizontal"
+ disabled
+ readOnly
+ value={
+ state.selectedDatabaseId !== projectRef
+ ? '[The password for your primary database]'
+ : '[The password you provided when you created this project]'
+ }
+ label="Password"
+ />
+ </>
+ )}
+ </Panel.Content>
+ <Separator />
+ <DatabaseConnectionString />
+ </Panel>
+ </section>
+
+ <ResetDbPassword disabled={isLoading || isError} />
<ConfirmDisableReadOnlyModeModal
visible={showConfirmationModal}
diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.utils.ts b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.utils.ts
new file mode 100644
index 00000000000..50223293c67
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.utils.ts
@@ -0,0 +1,41 @@
+export const getConnectionStrings = (connectionInfo: {
+ db_user: string
+ db_port: number
+ db_host: string
+ db_name: string
+}) => {
+ const uriConnString =
+ `postgresql://${connectionInfo.db_user}:[YOUR-PASSWORD]@` +
+ `${connectionInfo.db_host}:${connectionInfo.db_port.toString()}` +
+ `/${connectionInfo.db_name}`
+ const golangConnString =
+ `user=${connectionInfo.db_user} password=[YOUR-PASSWORD] ` +
+ `host=${connectionInfo.db_host} port=${connectionInfo.db_port.toString()}` +
+ ` dbname=${connectionInfo.db_name}`
+ const psqlConnString =
+ `psql -h ${connectionInfo.db_host} -p ` +
+ `${connectionInfo.db_port.toString()} -d ${connectionInfo.db_name} ` +
+ `-U ${connectionInfo.db_user}`
+ const jdbcConnString =
+ `jdbc:postgresql://${connectionInfo.db_host}:${connectionInfo.db_port.toString()}` +
+ `/${connectionInfo.db_name}?user=${connectionInfo.db_user}&password=[YOUR-PASSWORD]`
+ const dotNetConnString =
+ `User Id=${connectionInfo.db_user};Password=[YOUR-PASSWORD];` +
+ `Server=${connectionInfo.db_host};Port=${connectionInfo.db_port.toString()};` +
+ `Database=${connectionInfo.db_name}`
+ const pythonConnString =
+ `user=${connectionInfo.db_user} password=[YOUR-PASSWORD]` +
+ ` host=${connectionInfo.db_host} port=${connectionInfo.db_port.toString()}` +
+ ` database=${connectionInfo.db_name}`
+
+ return {
+ psql: psqlConnString,
+ uri: uriConnString,
+ golang: golangConnString,
+ jdbc: jdbcConnString,
+ dotnet: dotNetConnString,
+ nodejs: uriConnString,
+ php: golangConnString,
+ python: pythonConnString,
+ }
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/index.ts b/apps/studio/components/interfaces/Settings/Database/index.ts
index 376e2f198e5..4e13e0f7952 100644
--- a/apps/studio/components/interfaces/Settings/Database/index.ts
+++ b/apps/studio/components/interfaces/Settings/Database/index.ts
@@ -1,4 +1,4 @@
-import ConnectionPooling from './ConnectionPooling'
+import { ConnectionPooling } from './ConnectionPooling/ConnectionPooling'
import NetworkRestrictions from './NetworkRestrictions/NetworkRestrictions'
import DatabaseSettings from './DatabaseSettings/DatabaseSettings'
diff --git a/apps/studio/data/database/pooling-configuration-query.ts b/apps/studio/data/database/pooling-configuration-query.ts
index 9a02f1b5e21..4959c1ecd2c 100644
--- a/apps/studio/data/database/pooling-configuration-query.ts
+++ b/apps/studio/data/database/pooling-configuration-query.ts
@@ -4,13 +4,15 @@ import { ResponseError } from 'types'
import { databaseKeys } from './keys'
export type PoolingConfigurationVariables = {
- projectRef: string
+ projectRef?: string
}
export async function getPoolingConfiguration(
{ projectRef }: PoolingConfigurationVariables,
signal?: AbortSignal
) {
+ if (!projectRef) throw new Error('Project ref is required')
+
const { data, error } = await get(`/platform/projects/{ref}/config/pgbouncer`, {
params: { path: { ref: projectRef } },
signal,
diff --git a/apps/studio/pages/project/[ref]/settings/database.tsx b/apps/studio/pages/project/[ref]/settings/database.tsx
index 80aabb114d5..3401c8184b4 100644
--- a/apps/studio/pages/project/[ref]/settings/database.tsx
+++ b/apps/studio/pages/project/[ref]/settings/database.tsx
@@ -15,8 +15,11 @@ const ProjectSettings: NextPageWithLayout = () => {
return (
<div className="1xl:px-28 mx-auto flex flex-col px-5 pt-6 pb-14 lg:px-16 xl:px-24 2xl:px-32">
<div className="content h-full w-full overflow-y-auto space-y-10">
- <DatabaseSettings />
- <ConnectionPooling />
+ <h3 className="text-foreground text-xl">Database Settings</h3>
+ <div className="flex flex-col gap-y-4 !mt-6">
+ <ConnectionPooling />
+ <DatabaseSettings />
+ </div>
<SSLConfiguration />
<DiskSizeConfiguration />
<NetworkRestrictions />