The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: adjust connect sheet for cli and self-hosted (#46217)
Andrey A.c1b473e4720d
diff --git a/apps/studio/components/interfaces/ConnectSheet/Connect.types.ts b/apps/studio/components/interfaces/ConnectSheet/Connect.types.tsindex 89fce6b86d8..63beba7ac22 100644--- a/apps/studio/components/interfaces/ConnectSheet/Connect.types.ts+++ b/apps/studio/components/interfaces/ConnectSheet/Connect.types.ts@@ -1,3 +1,9 @@+import type { DeploymentMode } from '@/hooks/misc/useDeploymentMode'++// Re-exported so ConnectSheet consumers can keep importing from Connect.types+// without reaching across to the hooks tree.+export type { DeploymentMode }+// ============================================================================// Project Keys (existing)// ============================================================================@@ -154,4 +160,5 @@ export interface StepContentProps {state: ConnectStateprojectKeys: ProjectKeysconnectionStringPooler: ConnectionStringPooler+ deploymentMode: DeploymentMode}diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsxindex 5e2995765c1..7c0265a7a7e 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx@@ -9,13 +9,14 @@ import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import type {ConnectionStringPooler,ConnectState,+ DeploymentMode,ProjectKeys,ResolvedStep,StepContentProps,} from './Connect.types'import { ConnectSheetStep } from './ConnectSheetStep'import { CopyPromptAdmonition } from './CopyPromptAdmonition'-import { getConnectionStrings } from './DatabaseSettings.utils'+import { buildConnectionStringPooler, getConnectionStrings } from './DatabaseSettings.utils'import { getAddons } from '@/components/interfaces/Billing/Subscription/Subscription.utils'import { DocsButton } from '@/components/ui/DocsButton'import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'@@ -23,6 +24,7 @@ import { usePgbouncerConfigQuery } from '@/data/database/pgbouncer-config-query'import { useSupavisorConfigurationQuery } from '@/data/database/supavisor-configuration-query'import { useProjectAddonsQuery } from '@/data/subscriptions/project-addons-query'import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'+import { useDeploymentMode } from '@/hooks/misc/useDeploymentMode'import { DOCS_URL } from '@/lib/constants'import { pluckObjectFields } from '@/lib/helpers'@@ -55,7 +57,7 @@ function resolveContentPath(template: string, state: ConnectState): string {/*** Hook to fetch and prepare connection strings for step content.*/-function useConnectionStringPooler(): ConnectionStringPooler {+function useConnectionStringPooler(deploymentMode: DeploymentMode): ConnectionStringPooler {const { ref: projectRef } = useParams()const { hasAccess: allowPgBouncerSelection } = useCheckEntitlements('dedicated_pooler')@@ -65,49 +67,64 @@ function useConnectionStringPooler(): ConnectionStringPooler {const { data: addons } = useProjectAddonsQuery({ projectRef })const { ipv4: ipv4Addon } = getAddons(addons?.selected_addons ?? [])- const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']- const emptyState = { db_user: '', db_host: '', db_port: '', db_name: '' }- const connectionInfo = pluckObjectFields(settings || emptyState, DB_FIELDS)+ // Each intermediate derived value is memoized so its reference stays stable+ // across renders while the upstream query data is unchanged. Without this,+ // pluckObjectFields / getConnectionStrings would mint fresh objects every+ // render and invalidate the final useMemo on each tick (and ripple through+ // every consumer that lists ConnectionStringPooler in their own deps).+ const connectionInfo = useMemo(() => {+ const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']+ const emptyState = { db_user: '', db_host: '', db_port: '', db_name: '' }+ return pluckObjectFields(settings || emptyState, DB_FIELDS)+ }, [settings])+const poolingConfigurationShared = supavisorConfig?.find((x) => x.database_type === 'PRIMARY')const poolingConfigurationDedicated = allowPgBouncerSelection ? pgbouncerConfig : undefined- const connectionStringsShared = getConnectionStrings({- connectionInfo,- poolingInfo: {- connectionString: poolingConfigurationShared?.connection_string ?? '',- db_host: poolingConfigurationShared?.db_host ?? '',- db_name: poolingConfigurationShared?.db_name ?? '',- db_port: poolingConfigurationShared?.db_port ?? 0,- db_user: poolingConfigurationShared?.db_user ?? '',- },- metadata: { projectRef },- })-- const connectionStringsDedicated =- poolingConfigurationDedicated !== undefined- ? getConnectionStrings({- connectionInfo,- poolingInfo: {- connectionString: poolingConfigurationDedicated.connection_string,- db_host: poolingConfigurationDedicated.db_host,- db_name: poolingConfigurationDedicated.db_name,- db_port: poolingConfigurationDedicated.db_port,- db_user: poolingConfigurationDedicated.db_user,- },- metadata: { projectRef },- })- : undefined+ const connectionStringsShared = useMemo(+ () =>+ getConnectionStrings({+ connectionInfo,+ poolingInfo: {+ connectionString: poolingConfigurationShared?.connection_string ?? '',+ db_host: poolingConfigurationShared?.db_host ?? '',+ db_name: poolingConfigurationShared?.db_name ?? '',+ db_port: poolingConfigurationShared?.db_port ?? 0,+ db_user: poolingConfigurationShared?.db_user ?? '',+ },+ metadata: { projectRef },+ }),+ [connectionInfo, poolingConfigurationShared, projectRef]+ )++ const connectionStringsDedicated = useMemo(+ () =>+ poolingConfigurationDedicated !== undefined+ ? getConnectionStrings({+ connectionInfo,+ poolingInfo: {+ connectionString: poolingConfigurationDedicated.connection_string,+ db_host: poolingConfigurationDedicated.db_host,+ db_name: poolingConfigurationDedicated.db_name,+ db_port: poolingConfigurationDedicated.db_port,+ db_user: poolingConfigurationDedicated.db_user,+ },+ metadata: { projectRef },+ })+ : undefined,+ [connectionInfo, poolingConfigurationDedicated, projectRef]+ )return useMemo(- () => ({- transactionShared: connectionStringsShared.pooler.uri,- sessionShared: connectionStringsShared.pooler.uri.replace('6543', '5432'),- transactionDedicated: connectionStringsDedicated?.pooler.uri,- sessionDedicated: connectionStringsDedicated?.pooler.uri.replace('6543', '5432'),- ipv4SupportedForDedicatedPooler: !!ipv4Addon,- direct: connectionStringsShared.direct.uri,- }),- [connectionStringsShared, connectionStringsDedicated, ipv4Addon]+ () =>+ buildConnectionStringPooler({+ deploymentMode,+ connectionInfo,+ connectionStringsShared,+ connectionStringsDedicated,+ ipv4Addon: !!ipv4Addon,+ }),+ [deploymentMode, connectionInfo, connectionStringsShared, connectionStringsDedicated, ipv4Addon])}@@ -120,11 +137,13 @@ function StepContent({state,projectKeys,connectionStringPooler,+ deploymentMode,}: {contentId: stringstate: ConnectStateprojectKeys: ProjectKeysconnectionStringPooler: ConnectionStringPooler+ deploymentMode: DeploymentMode}) {// Resolve any template placeholders in the content pathconst filePath = useMemo(() => resolveContentPath(contentId, state), [contentId, state])@@ -145,6 +164,7 @@ function StepContent({state={state}projectKeys={projectKeys}connectionStringPooler={connectionStringPooler}+ deploymentMode={deploymentMode}/>)}@@ -152,7 +172,8 @@ function StepContent({export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsSectionProps) {const { ref } = useParams()const stepsContainerRef = useRef<HTMLDivElement | null>(null)- const connectionStringPooler = useConnectionStringPooler()+ const deploymentMode = useDeploymentMode()+ const connectionStringPooler = useConnectionStringPooler(deploymentMode)const { data: ipv4Addon } = useProjectAddonsQuery({ projectRef: ref },@@ -164,11 +185,14 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS})const showIpv4AddonNotice =+ deploymentMode.isPlatform &&state.mode === 'direct' &&!ipv4Addon &&(state.connectionMethod === 'direct' ||(state.connectionMethod === 'transaction' && !state.useSharedPooler))+ const showSelfHostedMcpNotice = deploymentMode.isSelfHosted && state.mode === 'mcp'+if (steps.length === 0) return nullreturn (@@ -192,6 +216,20 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS/>)}+ {showSelfHostedMcpNotice && (+ <Admonition+ type="default"+ title="MCP for self-hosted Supabase requires extra setup"+ description="The configuration below points at the hosted Supabase MCP server. To use MCP against your self-hosted instance, follow the self-hosted MCP guide."+ actions={[+ <DocsButton+ key="docs"+ href="https://supabase.com/docs/guides/self-hosting/enable-mcp"+ />,+ ]}+ />+ )}+<div className="mt-6" ref={stepsContainerRef}>{steps.map((step, index) => (<ConnectSheetStep@@ -205,6 +243,7 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsSstate={state}projectKeys={projectKeys}connectionStringPooler={connectionStringPooler}+ deploymentMode={deploymentMode}/></ConnectSheetStep>))}diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.tsnew file mode 100644index 00000000000..b05ba6802cb--- /dev/null+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts@@ -0,0 +1,160 @@+import { describe, expect, test } from 'vitest'++import {+ buildConnectionParameters,+ buildSafeConnectionString,+ DEFAULT_PORT,+ parseConnectionParams,+ PASSWORD_PLACEHOLDER,+ resolveConnectionString,+} from './ConnectionString.utils'++describe('parseConnectionParams', () => {+ test('returns hidden defaults for an empty string', () => {+ expect(parseConnectionParams('')).toEqual({+ host: 'hidden',+ port: DEFAULT_PORT,+ user: 'hidden',+ database: 'hidden',+ })+ })++ test('returns hidden defaults for an unparseable URL', () => {+ expect(parseConnectionParams('not a url')).toEqual({+ host: 'hidden',+ port: DEFAULT_PORT,+ user: 'hidden',+ database: 'hidden',+ })+ })++ test('parses a platform-shaped connection string', () => {+ const uri =+ 'postgresql://postgres.projref:[YOUR-PASSWORD]@aws-0-eu-west-1.pooler.supabase.com:6543/postgres'+ expect(parseConnectionParams(uri)).toEqual({+ host: 'aws-0-eu-west-1.pooler.supabase.com',+ port: '6543',+ user: 'postgres.projref',+ database: 'postgres',+ })+ })++ test('decodes percent-encoded bracket placeholders in the user info', () => {+ // The URL parser percent-encodes the `[`/`]` in self-hosted's POOLER_TENANT_ID placeholder.+ // parseConnectionParams must decode so the displayed user matches what we wrote.+ const uri =+ 'postgresql://postgres.[POOLER_TENANT_ID]:[YOUR-PASSWORD]@supabase.example.com:6543/postgres'+ expect(parseConnectionParams(uri).user).toBe('postgres.[POOLER_TENANT_ID]')+ })+})++describe('buildSafeConnectionString', () => {+ test('returns empty string when input is empty', () => {+ expect(buildSafeConnectionString('', parseConnectionParams(''))).toBe('')+ })++ test('rebuilds the URL with PASSWORD_PLACEHOLDER and the parsed params (round-trips brackets)', () => {+ const uri =+ 'postgresql://postgres.[POOLER_TENANT_ID]:[YOUR-PASSWORD]@supabase.example.com:6543/postgres'+ const params = parseConnectionParams(uri)+ const safe = buildSafeConnectionString(uri, params)+ expect(safe).toBe(+ `postgresql://postgres.[POOLER_TENANT_ID]:${PASSWORD_PLACEHOLDER}@supabase.example.com:6543/postgres`+ )+ })++ test('preserves search params from the original URL', () => {+ const uri = 'postgresql://postgres.proj:[YOUR-PASSWORD]@host:5432/postgres?sslmode=require'+ const params = parseConnectionParams(uri)+ expect(buildSafeConnectionString(uri, params)).toContain('?sslmode=require')+ })+})++describe('resolveConnectionString', () => {+ const pooler = {+ transactionShared: 'tx-shared',+ sessionShared: 'session-shared',+ transactionDedicated: 'tx-dedicated',+ sessionDedicated: 'session-dedicated',+ ipv4SupportedForDedicatedPooler: true,+ direct: 'direct-uri',+ }++ test('returns empty string when pooler bag is undefined', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'direct',+ useSharedPooler: false,+ connectionStringPooler: undefined,+ })+ ).toBe('')+ })++ test('direct method returns the direct URI', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'direct',+ useSharedPooler: false,+ connectionStringPooler: pooler,+ })+ ).toBe('direct-uri')+ })++ test('session method returns sessionShared', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'session',+ useSharedPooler: false,+ connectionStringPooler: pooler,+ })+ ).toBe('session-shared')+ })++ test('transaction prefers dedicated when available and useSharedPooler is false', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'transaction',+ useSharedPooler: false,+ connectionStringPooler: pooler,+ })+ ).toBe('tx-dedicated')+ })++ test('transaction falls back to shared when useSharedPooler is true', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'transaction',+ useSharedPooler: true,+ connectionStringPooler: pooler,+ })+ ).toBe('tx-shared')+ })++ test('transaction falls back to shared when no dedicated pooler exists', () => {+ expect(+ resolveConnectionString({+ connectionMethod: 'transaction',+ useSharedPooler: false,+ connectionStringPooler: { ...pooler, transactionDedicated: undefined },+ })+ ).toBe('tx-shared')+ })+})++describe('buildConnectionParameters', () => {+ test('produces host/port/database/user rows in display order', () => {+ expect(+ buildConnectionParameters({+ host: 'h',+ port: '5432',+ user: 'u',+ database: 'd',+ })+ ).toEqual([+ { key: 'host', value: 'h' },+ { key: 'port', value: '5432' },+ { key: 'database', value: 'd' },+ { key: 'user', value: 'u' },+ ])+ })+})diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.tsindex 07d0771825c..96c07fa8851 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts@@ -49,10 +49,20 @@ export const parseConnectionParams = (connectionString: string): ConnectionParamtry {const parsed = new URL(connectionString)+ // The URL parser percent-encodes characters that aren't valid in user-info+ // (e.g. brackets in the self-hosted `postgres.[POOLER_TENANT_ID]` placeholder).+ // Decode so the displayed string matches the literal we wrote.+ const decode = (value: string) => {+ try {+ return decodeURIComponent(value)+ } catch {+ return value+ }+ }return {host: parsed.hostname || 'hidden',port: parsed.port || DEFAULT_PORT,- user: parsed.username || 'hidden',+ user: parsed.username ? decode(parsed.username) : 'hidden',database: parsed.pathname?.replace(/^\//, '') || 'hidden',}} catch (error) {diff --git a/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.tsnew file mode 100644index 00000000000..3df757d5617--- /dev/null+++ b/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.test.ts@@ -0,0 +1,174 @@+import { describe, expect, test } from 'vitest'++import {+ buildConnectionStringPooler,+ getSelfHostedDirectStrings,+ getSelfHostedPoolerStrings,+} from './DatabaseSettings.utils'+import type { DeploymentMode } from '@/hooks/misc/useDeploymentMode'++const platform: DeploymentMode = { isPlatform: true, isCli: false, isSelfHosted: false }+const cli: DeploymentMode = { isPlatform: false, isCli: true, isSelfHosted: false }+const selfHosted: DeploymentMode = { isPlatform: false, isCli: false, isSelfHosted: true }++// Minimal ConnectionStrings stub — only `uri` matters for buildConnectionStringPooler.+const makeStrings = (poolerUri: string, directUri: string) =>+ ({+ direct: {+ uri: directUri,+ psql: '',+ golang: '',+ jdbc: '',+ dotnet: '',+ nodejs: '',+ php: '',+ python: '',+ sqlalchemy: '',+ },+ pooler: {+ uri: poolerUri,+ psql: '',+ golang: '',+ jdbc: '',+ dotnet: '',+ nodejs: '',+ php: '',+ python: '',+ sqlalchemy: '',+ },+ }) as any++describe('getSelfHostedPoolerStrings', () => {+ test('uses POOLER_TENANT_ID and YOUR-PASSWORD placeholders', () => {+ const strings = getSelfHostedPoolerStrings('db.example.com', 6543)+ expect(strings.uri).toBe(+ 'postgresql://postgres.[POOLER_TENANT_ID]:[YOUR-PASSWORD]@db.example.com:6543/postgres'+ )+ })++ test('threads host, port, and database name through every format', () => {+ const strings = getSelfHostedPoolerStrings('db.example.com', 5432, 'mydb')+ expect(strings.uri).toContain('db.example.com:5432/mydb')+ expect(strings.psql).toContain('db.example.com:5432/mydb')+ expect(strings.jdbc).toContain('db.example.com:5432/mydb')+ expect(strings.golang).toContain('host=db.example.com')+ expect(strings.golang).toContain('port=5432')+ expect(strings.golang).toContain('dbname=mydb')+ expect(strings.dotnet).toContain('Server=db.example.com')+ expect(strings.dotnet).toContain('Port=5432')+ expect(strings.dotnet).toContain('Database=mydb')+ expect(strings.nodejs).toBe(`DATABASE_URL=${strings.uri}`)+ })++ test('defaults database name to postgres', () => {+ const strings = getSelfHostedPoolerStrings('db.example.com', 6543)+ expect(strings.uri.endsWith('/postgres')).toBe(true)+ })+})++describe('getSelfHostedDirectStrings', () => {+ test('uses plain postgres user (no tenant id)', () => {+ const strings = getSelfHostedDirectStrings('db.example.com', 5432)+ expect(strings.uri).toBe('postgresql://postgres:[YOUR-PASSWORD]@db.example.com:5432/postgres')+ })++ test('threads host, port, and database name through every format', () => {+ const strings = getSelfHostedDirectStrings('db.example.com', 5432, 'mydb')+ expect(strings.uri).toContain('postgres:[YOUR-PASSWORD]@db.example.com:5432/mydb')+ expect(strings.jdbc).toContain('db.example.com:5432/mydb')+ expect(strings.golang).toContain('user=postgres\n')+ expect(strings.dotnet).toContain('User Id=postgres;')+ })+})++describe('buildConnectionStringPooler', () => {+ const sharedPlatform = makeStrings(+ 'postgresql://postgres.proj:[YOUR-PASSWORD]@aws-0-eu-west-1.pooler.supabase.com:6543/postgres',+ 'postgresql://postgres:[YOUR-PASSWORD]@db.proj.supabase.co:5432/postgres'+ )+ const dedicatedPlatform = makeStrings(+ 'postgresql://dedicated.proj:[YOUR-PASSWORD]@aws-0-eu-west-1.pooler.supabase.com:6543/postgres',+ ''+ )+ const connectionInfo = { db_host: 'db.example.com', db_port: 5432 }++ test('platform: returns shared + dedicated pooler bag and direct URI', () => {+ const result = buildConnectionStringPooler({+ deploymentMode: platform,+ connectionInfo,+ connectionStringsShared: sharedPlatform,+ connectionStringsDedicated: dedicatedPlatform,+ ipv4Addon: true,+ })++ expect(result.transactionShared).toBe(sharedPlatform.pooler.uri)+ expect(result.sessionShared).toBe(sharedPlatform.pooler.uri.replace('6543', '5432'))+ expect(result.transactionDedicated).toBe(dedicatedPlatform.pooler.uri)+ expect(result.sessionDedicated).toBe(dedicatedPlatform.pooler.uri.replace('6543', '5432'))+ expect(result.ipv4SupportedForDedicatedPooler).toBe(true)+ expect(result.direct).toBe(sharedPlatform.direct.uri)+ })++ test('platform without IPv4 addon flips ipv4SupportedForDedicatedPooler', () => {+ const result = buildConnectionStringPooler({+ deploymentMode: platform,+ connectionInfo,+ connectionStringsShared: sharedPlatform,+ ipv4Addon: false,+ })+ expect(result.ipv4SupportedForDedicatedPooler).toBe(false)+ expect(result.transactionDedicated).toBeUndefined()+ expect(result.sessionDedicated).toBeUndefined()+ })++ test('CLI: collapses pooler URIs to the direct URI (no pooler in CLI)', () => {+ const directUri = sharedPlatform.direct.uri+ const result = buildConnectionStringPooler({+ deploymentMode: cli,+ connectionInfo,+ connectionStringsShared: sharedPlatform,+ ipv4Addon: false,+ })++ expect(result.direct).toBe(directUri)+ expect(result.transactionShared).toBe(directUri)+ expect(result.sessionShared).toBe(directUri)+ expect(result.transactionDedicated).toBeUndefined()+ expect(result.sessionDedicated).toBeUndefined()+ expect(result.ipv4SupportedForDedicatedPooler).toBe(false)+ })++ test('self-hosted: uses Supavisor placeholders on 6543/dbPort, direct on dbPort', () => {+ const result = buildConnectionStringPooler({+ deploymentMode: selfHosted,+ connectionInfo: { db_host: 'supabase.example.com', db_port: 5432 },+ connectionStringsShared: sharedPlatform,+ ipv4Addon: true,+ })++ expect(result.transactionShared).toBe(+ 'postgresql://postgres.[POOLER_TENANT_ID]:[YOUR-PASSWORD]@supabase.example.com:6543/postgres'+ )+ expect(result.sessionShared).toBe(+ 'postgresql://postgres.[POOLER_TENANT_ID]:[YOUR-PASSWORD]@supabase.example.com:5432/postgres'+ )+ expect(result.direct).toBe(+ 'postgresql://postgres:[YOUR-PASSWORD]@supabase.example.com:5432/postgres'+ )+ expect(result.transactionDedicated).toBeUndefined()+ expect(result.sessionDedicated).toBeUndefined()+ // ipv4Addon=true must NOT leak into self-hosted: there's no dedicated pooler here+ expect(result.ipv4SupportedForDedicatedPooler).toBe(false)+ })++ test('self-hosted: falls back to port 5432 when db_port is unset', () => {+ const result = buildConnectionStringPooler({+ deploymentMode: selfHosted,+ connectionInfo: { db_host: 'supabase.example.com', db_port: 0 },+ connectionStringsShared: sharedPlatform,+ ipv4Addon: false,+ })+ expect(result.sessionShared).toContain(':5432/postgres')+ expect(result.direct).toContain(':5432/postgres')+ })+})diff --git a/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.ts b/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.tsindex 60d5c88df04..e0e75995c5a 100644--- a/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.ts+++ b/apps/studio/components/interfaces/ConnectSheet/DatabaseSettings.utils.ts@@ -1,3 +1,5 @@+import type { ConnectionStringPooler, DeploymentMode } from './Connect.types'+type ConnectionStrings = {psql: stringuri: string@@ -10,6 +12,86 @@ type ConnectionStrings = {sqlalchemy: string}+/**+ * Self-hosted Supavisor pooler strings. User/password are placeholders that+ * the operator fills in — `POOLER_TENANT_ID` and the postgres password are+ * defined in the docker-compose env.+ */+export const getSelfHostedPoolerStrings = (+ dbHost: string,+ port: number | string,+ dbName: string = 'postgres'+): ConnectionStrings => {+ const user = 'postgres.[POOLER_TENANT_ID]'+ const password = '[YOUR-PASSWORD]'++ const uri = `postgresql://${user}:${password}@${dbHost}:${port}/${dbName}`+ const psql = `psql 'postgresql://${user}:${password}@${dbHost}:${port}/${dbName}'`+ const golang = `user=${user}\npassword=${password}\nhost=${dbHost}\nport=${port}\ndbname=${dbName}`+ const jdbc = `jdbc:postgresql://${dbHost}:${port}/${dbName}?user=${user}&password=${password}`+ const dotnet = `{+ "ConnectionStrings": {+ "DefaultConnection": "User Id=${user};Password=${password};Server=${dbHost};Port=${port};Database=${dbName}"+ }+}`+ const nodejs = `DATABASE_URL=${uri}`++ return {+ psql,+ uri,+ golang,+ jdbc,+ dotnet,+ nodejs,+ php: golang,+ python: golang,+ sqlalchemy: golang,+ }+}++/**+ * Self-hosted direct postgres connection strings. Requires the operator to+ * have exposed postgres on the host — by default docker-compose does not.+ */+export const getSelfHostedDirectStrings = (+ dbHost: string,+ port: number | string,+ dbName: string = 'postgres'+): ConnectionStrings => {+ const user = 'postgres'+ const password = '[YOUR-PASSWORD]'++ const uri = `postgresql://${user}:${password}@${dbHost}:${port}/${dbName}`+ const psql = `psql 'postgresql://${user}:${password}@${dbHost}:${port}/${dbName}'`+ const golang = `user=${user}\npassword=${password}\nhost=${dbHost}\nport=${port}\ndbname=${dbName}`+ const jdbc = `jdbc:postgresql://${dbHost}:${port}/${dbName}?user=${user}&password=${password}`+ const dotnet = `{+ "ConnectionStrings": {+ "DefaultConnection": "User Id=${user};Password=${password};Server=${dbHost};Port=${port};Database=${dbName}"+ }+}`+ const nodejs = `DATABASE_URL=${uri}`++ return {+ psql,+ uri,+ golang,+ jdbc,+ dotnet,+ nodejs,+ php: golang,+ python: golang,+ sqlalchemy: golang,+ }+}++/**+ * Returns `{ direct, pooler }`. `.direct` depends only on `connectionInfo`, so+ * when callers invoke this twice (once per pooler flavor) as+ * `connectionStringsShared` / `connectionStringsDedicated`, both `.direct`+ * fields are identical — the `Shared`/`Dedicated` suffix only describes which+ * pooler URI you get from `.pooler`.+ */export const getConnectionStrings = ({connectionInfo,poolingInfo,@@ -133,3 +215,65 @@ dbname=${poolerName}`},}}++/**+ * Shapes the ConnectionStringPooler "bag" consumed by every connection-string+ * step. On platform we keep the existing shared/dedicated pooler layout; on+ * self-hosted we substitute Supavisor placeholder strings on the standard+ * ports; on CLI we collapse to direct since no pooler is exposed.+ */+export const buildConnectionStringPooler = ({+ deploymentMode,+ connectionInfo,+ connectionStringsShared,+ connectionStringsDedicated,+ ipv4Addon,+}: {+ deploymentMode: DeploymentMode+ connectionInfo: { db_host: string; db_port: number | string }+ connectionStringsShared: { direct: ConnectionStrings; pooler: ConnectionStrings }+ connectionStringsDedicated?: { direct: ConnectionStrings; pooler: ConnectionStrings }+ ipv4Addon: boolean+}): ConnectionStringPooler => {+ if (deploymentMode.isSelfHosted) {+ const dbHost = connectionInfo.db_host+ const dbPort = connectionInfo.db_port || 5432+ const sessionPool = getSelfHostedPoolerStrings(dbHost, dbPort)+ const transactionPool = getSelfHostedPoolerStrings(dbHost, 6543)+ const directConn = getSelfHostedDirectStrings(dbHost, dbPort)+ return {+ transactionShared: transactionPool.uri,+ sessionShared: sessionPool.uri,+ transactionDedicated: undefined,+ sessionDedicated: undefined,+ ipv4SupportedForDedicatedPooler: false,+ direct: directConn.uri,+ }+ }++ if (deploymentMode.isCli) {+ // CLI exposes postgres directly; no pooler is available, so any code path+ // that reaches for a pooler URI falls back to the direct connection.+ const directUri = connectionStringsShared.direct.uri+ return {+ transactionShared: directUri,+ sessionShared: directUri,+ transactionDedicated: undefined,+ sessionDedicated: undefined,+ ipv4SupportedForDedicatedPooler: false,+ direct: directUri,+ }+ }++ // Port-swap 6543→5432 derives session from transaction. For shared this is a+ // real Supavisor session connection; for dedicated it lands on direct Postgres+ // (PgBouncer has no session mode).+ return {+ transactionShared: connectionStringsShared.pooler.uri,+ sessionShared: connectionStringsShared.pooler.uri.replace('6543', '5432'),+ transactionDedicated: connectionStringsDedicated?.pooler.uri,+ sessionDedicated: connectionStringsDedicated?.pooler.uri.replace('6543', '5432'),+ ipv4SupportedForDedicatedPooler: ipv4Addon,+ direct: connectionStringsShared.direct.uri,+ }+}diff --git a/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts b/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.tsindex 447cf524855..b40723f1e5e 100644--- a/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/connect.schema.test.ts@@ -94,7 +94,9 @@ describe('connect.schema:fields', () => {const field = connectSchema.fields.connectionMethodexpect(field.type).toBe('radio-list')expect(field.options).toEqual({ source: 'connectionMethods' })- expect(field.defaultValue).toBe('direct')+ // defaultValue is intentionally unset — useConnectState.setMode picks the+ // per-deployment-mode default (platform/CLI: 'direct'; self-hosted: 'session')+ expect(field.defaultValue).toBeUndefined()})test('useSharedPooler field should depend on transaction connection method', () => {diff --git a/apps/studio/components/interfaces/ConnectSheet/connect.schema.ts b/apps/studio/components/interfaces/ConnectSheet/connect.schema.tsindex 6ee7fe32cf1..5db2b1addfc 100644--- a/apps/studio/components/interfaces/ConnectSheet/connect.schema.ts+++ b/apps/studio/components/interfaces/ConnectSheet/connect.schema.ts@@ -258,7 +258,8 @@ export const connectSchema: ConnectSchema = {type: 'radio-list',label: 'Connection Method',options: { source: 'connectionMethods' },- defaultValue: 'direct',+ // Default is set per deployment mode by useConnectState.setMode('direct'):+ // platform/CLI → 'direct', self-hosted → 'session'.},useSharedPooler: {id: 'useSharedPooler',diff --git a/apps/studio/components/interfaces/ConnectSheet/content/drizzle/content.tsx b/apps/studio/components/interfaces/ConnectSheet/content/drizzle/content.tsxindex 9be84484d59..10a6a6106d1 100644--- a/apps/studio/components/interfaces/ConnectSheet/content/drizzle/content.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/content/drizzle/content.tsx@@ -2,29 +2,42 @@ import { MultipleCodeBlock } from 'ui-patterns/MultipleCodeBlock'import type { StepContentProps } from '@/components/interfaces/ConnectSheet/Connect.types'-const ContentFile = ({ connectionStringPooler }: StepContentProps) => {- const files = [- {- name: '.env',- language: 'bash',- code:- connectionStringPooler.ipv4SupportedForDedicatedPooler &&- connectionStringPooler.transactionDedicated- ? `+const ContentFile = ({ connectionStringPooler, deploymentMode }: StepContentProps) => {+ const envCode = deploymentMode.isCli+ ? `+# Connect to Postgres via the direct connection+DATABASE_URL="${connectionStringPooler.direct}"+`+ : deploymentMode.isSelfHosted+ ? `+# Connect to Postgres via the self-hosted transaction-mode pooler+DATABASE_URL="${connectionStringPooler.transactionShared}"+`+ : connectionStringPooler.transactionDedicated &&+ connectionStringPooler.ipv4SupportedForDedicatedPooler+ ? `+# Connect to Postgres via the dedicated transaction-mode pooler (IPv4-only)DATABASE_URL="${connectionStringPooler.transactionDedicated}"`- : connectionStringPooler.transactionDedicated &&- !connectionStringPooler.ipv4SupportedForDedicatedPooler- ? `-# Use Shared connection pooler (supports both IPv4/IPv6)+ : connectionStringPooler.transactionDedicated &&+ !connectionStringPooler.ipv4SupportedForDedicatedPooler+ ? `+# Connect to Postgres via the shared transaction-mode pooler (IPv4-only)DATABASE_URL="${connectionStringPooler.transactionShared}"-# If your network supports IPv6 or you purchased IPv4 addon, use dedicated pooler+# For paid projects, if your network supports IPv6, or you purchased the IPv4 add-on, use the dedicated transaction-mode pooler as an alternative# DATABASE_URL="${connectionStringPooler.transactionDedicated}"`- : `+ : `+# Connect to Postgres via the shared transaction-mode pooler (IPv4-only)DATABASE_URL="${connectionStringPooler.transactionShared}"-`,+`++ const files = [+ {+ name: '.env',+ language: 'bash',+ code: envCode,},{name: 'drizzle/schema.ts',diff --git a/apps/studio/components/interfaces/ConnectSheet/content/prisma/content.tsx b/apps/studio/components/interfaces/ConnectSheet/content/prisma/content.tsxindex 5dfe5b7f60a..d331286607c 100644--- a/apps/studio/components/interfaces/ConnectSheet/content/prisma/content.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/content/prisma/content.tsx@@ -1,43 +1,59 @@import { MultipleCodeBlock } from 'ui-patterns/MultipleCodeBlock'import type { StepContentProps } from '@/components/interfaces/ConnectSheet/Connect.types'-import { IS_PLATFORM } from '@/lib/constants'-const ContentFile = ({ connectionStringPooler }: StepContentProps) => {- const files = [- {- name: '.env.local',- language: 'bash',- code:- connectionStringPooler.ipv4SupportedForDedicatedPooler &&- connectionStringPooler.transactionDedicated- ? `-# Connect to Supabase via connection pooling.+const ContentFile = ({ connectionStringPooler, deploymentMode }: StepContentProps) => {+ const envCode = deploymentMode.isCli+ ? `+# Connect to Postgres via the direct connection+DATABASE_URL="${connectionStringPooler.direct}"++# Used for migrations+DIRECT_URL="${connectionStringPooler.direct}"+`+ : deploymentMode.isSelfHosted+ ? `+# Connect to Postgres via the self-hosted transaction-mode pooler+DATABASE_URL="${connectionStringPooler.transactionShared}?pgbouncer=true"++# Connect to Postgres via the self-hosted session-mode pooler (used for migrations)+DIRECT_URL="${connectionStringPooler.sessionShared}"+`+ : connectionStringPooler.transactionDedicated &&+ connectionStringPooler.ipv4SupportedForDedicatedPooler+ ? `+# Connect to Postgres via the dedicated transaction-mode pooler (IPv4-only)DATABASE_URL="${connectionStringPooler.transactionDedicated}?pgbouncer=true"-# Direct connection to the database. Used for migrations.+# Connect to Postgres directly (used for migrations)DIRECT_URL="${connectionStringPooler.sessionDedicated}"`- : connectionStringPooler.transactionDedicated &&- !connectionStringPooler.ipv4SupportedForDedicatedPooler- ? `-# Connect to Supabase via Shared Connection Pooler+ : connectionStringPooler.transactionDedicated &&+ !connectionStringPooler.ipv4SupportedForDedicatedPooler+ ? `+# Connect to Postgres via the shared transaction-mode pooler (IPv4-only)DATABASE_URL="${connectionStringPooler.transactionShared}?pgbouncer=true"-# Direct connection to the database through Shared Pooler (supports IPv4/IPv6). Used for migrations.+# Connect to Postgres via the shared session-mode pooler (used for migrations)DIRECT_URL="${connectionStringPooler.sessionShared}"-# If your network supports IPv6 or you purchased IPv4 addon, use dedicated pooler+# For paid projects, if your network supports IPv6, or you purchased the IPv4 add-on, use the dedicated transaction-mode pooler with a direct connection to Postgres for migrations as an alternative# DATABASE_URL="${connectionStringPooler.transactionDedicated}?pgbouncer=true"# DIRECT_URL="${connectionStringPooler.sessionDedicated}"`- : `-# Connect to Supabase ${IS_PLATFORM ? 'via connection pooling' : ''}-DATABASE_URL="${IS_PLATFORM ? `${connectionStringPooler.transactionShared}?pgbouncer=true` : connectionStringPooler.direct}"+ : `+# Connect to Postgres via the shared transaction-mode pooler (IPv4-only)+DATABASE_URL="${connectionStringPooler.transactionShared}?pgbouncer=true"++# Connect to Postgres via the shared session-mode pooler (used for migrations)+DIRECT_URL="${connectionStringPooler.sessionShared}"+`-# Direct connection to the database. Used for migrations-DIRECT_URL="${IS_PLATFORM ? connectionStringPooler.sessionShared : connectionStringPooler.direct}"-`,+ const files = [+ {+ name: '.env.local',+ language: 'bash',+ code: envCode,},{name: 'prisma/schema.prisma',diff --git a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsxindex 2ef2dc80622..7cfe723a089 100644--- a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx@@ -4,7 +4,7 @@ import { Badge } from 'ui'import { CodeBlock } from 'ui-patterns/CodeBlock'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'-import { getConnectionStrings } from '../../../DatabaseSettings.utils'+import { buildConnectionStringPooler, getConnectionStrings } from '../../../DatabaseSettings.utils'import { IPv4StatusPanel, type IPv4Status } from './IPv4StatusPanel'import { getAddons } from '@/components/interfaces/Billing/Subscription/Subscription.utils'import {@@ -16,6 +16,7 @@ import {} from '@/components/interfaces/ConnectSheet/Connect.constants'import type {ConnectionStringPooler,+ DeploymentMode,StepContentProps,} from '@/components/interfaces/ConnectSheet/Connect.types'import { ConnectionParameters } from '@/components/interfaces/ConnectSheet/ConnectionParameters'@@ -48,7 +49,7 @@ const buildJdbcString = (params: { host: string; port: string; database: string;* We can however, consider to shift this logic into ConnectStepsSection, such that we can consider read replicas for* the other tabs like "Framework" and "ORM" too. However, leaving them out for now and only updating "Direct"*/-const useConnectionStringDatabases = () => {+const useConnectionStringDatabases = (deploymentMode: DeploymentMode) => {const { ref: projectRef } = useParams()const { hasAccess: allowPgBouncerSelection } = useCheckEntitlements('dedicated_pooler')@@ -58,60 +59,73 @@ const useConnectionStringDatabases = () => {const { data: addons } = useProjectAddonsQuery({ projectRef })const { ipv4: ipv4Addon } = getAddons(addons?.selected_addons ?? [])- const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']- const emptyState = { db_user: '', db_host: '', db_port: '', db_name: '' }+ // Memoized so the per-database pooler bag (consumed by resolveConnectionString+ // downstream) keeps a stable identity across renders. Without this the inner+ // pluckObjectFields/getConnectionStrings calls would mint fresh objects every+ // render and ripple through the resolveConnectionString useMemo below.+ return useMemo(() => {+ const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']+ const emptyState = { db_user: '', db_host: '', db_port: '', db_name: '' }- return Object.fromEntries(- databases.map((db) => {- const connectionInfo = pluckObjectFields(db || emptyState, DB_FIELDS)- const poolingConfigurationShared = supavisorConfig?.find(- (x) => x.identifier === db.identifier- )- const poolingConfigurationDedicated = allowPgBouncerSelection ? pgbouncerConfig : undefined+ return Object.fromEntries(+ databases.map((db) => {+ const connectionInfo = pluckObjectFields(db || emptyState, DB_FIELDS)+ const poolingConfigurationShared = supavisorConfig?.find(+ (x) => x.identifier === db.identifier+ )+ const poolingConfigurationDedicated = allowPgBouncerSelection ? pgbouncerConfig : undefined- const connectionStringsShared = getConnectionStrings({- connectionInfo,- poolingInfo: {- connectionString: poolingConfigurationShared?.connection_string ?? '',- db_host: poolingConfigurationShared?.db_host ?? '',- db_name: poolingConfigurationShared?.db_name ?? '',- db_port: poolingConfigurationShared?.db_port ?? 0,- db_user: poolingConfigurationShared?.db_user ?? '',- },- metadata: { projectRef: db.identifier },- })+ const connectionStringsShared = getConnectionStrings({+ connectionInfo,+ poolingInfo: {+ connectionString: poolingConfigurationShared?.connection_string ?? '',+ db_host: poolingConfigurationShared?.db_host ?? '',+ db_name: poolingConfigurationShared?.db_name ?? '',+ db_port: poolingConfigurationShared?.db_port ?? 0,+ db_user: poolingConfigurationShared?.db_user ?? '',+ },+ metadata: { projectRef: db.identifier },+ })- const connectionStringsDedicated =- poolingConfigurationDedicated !== undefined- ? getConnectionStrings({- connectionInfo,- poolingInfo: {- connectionString: poolingConfigurationDedicated.connection_string.replace(- projectRef ?? '_',- db.identifier- ),- db_host: poolingConfigurationDedicated.db_host,- db_name: poolingConfigurationDedicated.db_name,- db_port: poolingConfigurationDedicated.db_port,- db_user: poolingConfigurationDedicated.db_user,- },- metadata: { projectRef: db.identifier },- })- : undefined+ const connectionStringsDedicated =+ poolingConfigurationDedicated !== undefined+ ? getConnectionStrings({+ connectionInfo,+ poolingInfo: {+ connectionString: poolingConfigurationDedicated.connection_string.replace(+ projectRef ?? '_',+ db.identifier+ ),+ db_host: poolingConfigurationDedicated.db_host,+ db_name: poolingConfigurationDedicated.db_name,+ db_port: poolingConfigurationDedicated.db_port,+ db_user: poolingConfigurationDedicated.db_user,+ },+ metadata: { projectRef: db.identifier },+ })+ : undefined- return [- db.identifier,- {- transactionShared: connectionStringsShared.pooler.uri,- sessionShared: connectionStringsShared.pooler.uri.replace('6543', '5432'),- transactionDedicated: connectionStringsDedicated?.pooler.uri,- sessionDedicated: connectionStringsDedicated?.pooler.uri.replace('6543', '5432'),- ipv4SupportedForDedicatedPooler: !!ipv4Addon,- direct: connectionStringsShared.direct.uri,- },- ]- })- )+ return [+ db.identifier,+ buildConnectionStringPooler({+ deploymentMode,+ connectionInfo,+ connectionStringsShared,+ connectionStringsDedicated,+ ipv4Addon: !!ipv4Addon,+ }),+ ]+ })+ )+ }, [+ databases,+ pgbouncerConfig,+ supavisorConfig,+ allowPgBouncerSelection,+ ipv4Addon,+ projectRef,+ deploymentMode,+ ])}const CONNECTION_METHOD_TO_TELEMETRY: Record<@@ -127,7 +141,7 @@ const CONNECTION_METHOD_TO_TELEMETRY: Record<* Step component for direct database connections.* Uses state to determine which connection string to show.*/-function DirectConnectionContent({ state }: StepContentProps) {+function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {const track = useTrack()const { ref: projectRef } = useParams()const { hasAccess: hasDedicatedPooler } = useCheckEntitlements('dedicated_pooler')@@ -138,7 +152,7 @@ function DirectConnectionContent({ state }: StepContentProps) {const connectionMethod = (state.connectionMethod as ConnectionStringMethod) ?? 'direct'const useSharedPooler = Boolean(state.useSharedPooler)- const connectionStrings = useConnectionStringDatabases()+ const connectionStrings = useConnectionStringDatabases(deploymentMode)const connectionStringPooler: ConnectionStringPooler | undefined =connectionStrings[connectionSource as keyof typeof connectionStrings]const hasIPv4Addon = connectionStringPooler?.ipv4SupportedForDedicatedPooler ?? false@@ -257,9 +271,11 @@ function DirectConnectionContent({ state }: StepContentProps) {? 'Shared Pooler': null+ const showSelfHostedDirectNotice = deploymentMode.isSelfHosted && connectionMethod === 'direct'+return (<div className="flex flex-col gap-2">- {poolerBadge && !isHighAvailability && (+ {deploymentMode.isPlatform && poolerBadge && !isHighAvailability && (<div className="flex items-center gap-x-2"><Badge>{poolerBadge}</Badge></div>@@ -274,7 +290,21 @@ function DirectConnectionContent({ state }: StepContentProps) {>{connectionString}</CodeBlock>- {projectRef && !isHighAvailability && (+ {showSelfHostedDirectNotice && (+ <p className="text-sm text-foreground-light">+ Manually{' '}+ <a+ href="https://supabase.com/docs/guides/self-hosting/docker#exposing-your-postgres-database"+ target="_blank"+ rel="noopener noreferrer"+ className="underline hover:text-foreground"+ >+ configurable+ </a>{' '}+ for self-hosted Supabase.+ </p>+ )}+ {deploymentMode.isPlatform && projectRef && !isHighAvailability && (<div className="mt-2"><IPv4StatusPanelmethod={connectionMethod}diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts b/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.tsindex 6638dedddc7..476f665ff21 100644--- a/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/useConnectState.test.ts@@ -1,5 +1,5 @@import { act, renderHook } from '@testing-library/react'-import { describe, expect, test, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'import { useConnectState } from './useConnectState'@@ -19,6 +19,11 @@ vi.mock('@/hooks/misc/useSelectedProject', () => ({useIsHighAvailability: vi.fn().mockImplementation(() => false),}))+const deploymentModeMock = { isPlatform: true, isCli: false, isSelfHosted: false }+vi.mock('@/hooks/misc/useDeploymentMode', () => ({+ useDeploymentMode: () => deploymentModeMock,+}))+describe('useConnectState', () => {// ============================================================================// Initial State Tests@@ -564,4 +569,130 @@ describe('useConnectState', () => {expect(modeIds).toContain('mcp')})})++ // ============================================================================+ // Deployment-Mode-Aware Tests+ // ============================================================================++ describe('deployment mode', () => {+ beforeEach(() => {+ Object.assign(deploymentModeMock, {+ isPlatform: true,+ isCli: false,+ isSelfHosted: false,+ })+ })++ afterEach(() => {+ Object.assign(deploymentModeMock, {+ isPlatform: true,+ isCli: false,+ isSelfHosted: false,+ })+ })++ describe('connectionMethod options filtering', () => {+ test('platform exposes direct, transaction and session', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: true,+ isCli: false,+ isSelfHosted: false,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)+ expect(values).toEqual(['direct', 'transaction', 'session'])+ })++ test('CLI exposes only direct', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: true,+ isSelfHosted: false,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)+ expect(values).toEqual(['direct'])+ })++ test('self-hosted exposes session, transaction, direct (session first)', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: false,+ isSelfHosted: true,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const values = result.current.getFieldOptions('connectionMethod').map((o) => o.value)+ expect(values).toEqual(['session', 'transaction', 'direct'])+ })++ test('self-hosted overrides direct method description', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: false,+ isSelfHosted: true,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const directOption = result.current+ .getFieldOptions('connectionMethod')+ .find((o) => o.value === 'direct')+ expect(directOption?.description).toBe('Manually configurable for self-hosted Supabase.')+ })++ test('self-hosted overrides session method description', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: false,+ isSelfHosted: true,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'direct' }))+ const sessionOption = result.current+ .getFieldOptions('connectionMethod')+ .find((o) => o.value === 'session')+ expect(sessionOption?.description).toBe(+ 'Supavisor (default pooler for self-hosted Supabase).'+ )+ })+ })++ describe('setMode default for connectionMethod', () => {+ test('platform defaults to direct', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: true,+ isCli: false,+ isSelfHosted: false,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'framework' }))+ act(() => {+ result.current.setMode('direct')+ })+ expect(result.current.state.connectionMethod).toBe('direct')+ })++ test('CLI defaults to direct', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: true,+ isSelfHosted: false,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'framework' }))+ act(() => {+ result.current.setMode('direct')+ })+ expect(result.current.state.connectionMethod).toBe('direct')+ })++ test('self-hosted defaults to session', () => {+ Object.assign(deploymentModeMock, {+ isPlatform: false,+ isCli: false,+ isSelfHosted: true,+ })+ const { result } = renderHook(() => useConnectState({ mode: 'framework' }))+ act(() => {+ result.current.setMode('direct')+ })+ expect(result.current.state.connectionMethod).toBe('session')+ })+ })+ })})diff --git a/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts b/apps/studio/components/interfaces/ConnectSheet/useConnectState.tsindex 415eeb2542b..9d9c1952460 100644--- a/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts+++ b/apps/studio/components/interfaces/ConnectSheet/useConnectState.ts@@ -20,6 +20,7 @@ import type {ConnectMode,ConnectSchema,ConnectState,+ DeploymentMode,FieldOption,ResolvedField,ResolvedStep,@@ -28,6 +29,7 @@ import { resolveFrameworkLibraryKey } from './Connect.utils'import { Database, useReadReplicasQuery } from '@/data/read-replicas/replicas-query'import { formatDatabaseID, formatDatabaseRegion } from '@/data/read-replicas/replicas.utils'import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'+import { useDeploymentMode } from '@/hooks/misc/useDeploymentMode'import { useIsHighAvailability } from '@/hooks/misc/useSelectedProject'// ============================================================================@@ -42,10 +44,12 @@ function getFieldOptionsFromSource({source,state,databases,+ deploymentMode,}: {source: stringstate: ConnectStatedatabases: Database[]+ deploymentMode: DeploymentMode}): FieldOption[] {switch (source) {case 'frameworks':@@ -104,12 +108,27 @@ function getFieldOptionsFromSource({return []}- case 'connectionMethods':- return Object.values(connectionStringMethodOptions).map((m) => ({+ case 'connectionMethods': {+ const all = Object.values(connectionStringMethodOptions)+ const allowed: string[] = deploymentMode.isCli+ ? ['direct']+ : deploymentMode.isSelfHosted+ ? ['session', 'transaction', 'direct']+ : ['direct', 'transaction', 'session']+ const filtered = allowed+ .map((value) => all.find((m) => m.value === value))+ .filter((m): m is (typeof all)[number] => !!m)+ return filtered.map((m) => ({value: m.value,label: m.label,- description: m.description,+ description:+ deploymentMode.isSelfHosted && m.value === 'direct'+ ? 'Manually configurable for self-hosted Supabase.'+ : deploymentMode.isSelfHosted && m.value === 'session'+ ? 'Supavisor (default pooler for self-hosted Supabase).'+ : m.description,}))+ }case 'connectionSources':return databases.map((db) => {@@ -160,10 +179,12 @@ function resolveFieldOptionsWithSource({field,state,databases,+ deploymentMode,}: {field: ResolvedFieldstate: ConnectStatedatabases: Database[]+ deploymentMode: DeploymentMode}): FieldOption[] {// If already resolved (from conditional resolution)if (field.resolvedOptions.length > 0) {@@ -173,7 +194,12 @@ function resolveFieldOptionsWithSource({// Check if it's a source referenceconst options = connectSchema.fields[field.id]?.optionsif (options && typeof options === 'object' && 'source' in options) {- return getFieldOptionsFromSource({ source: options.source as string, state, databases })+ return getFieldOptionsFromSource({+ source: options.source as string,+ state,+ databases,+ deploymentMode,+ })}return []@@ -198,6 +224,7 @@ export function useConnectState(initialState?: Partial<ConnectState>): UseConnecconst { data: databases = [] } = useReadReplicasQuery({ projectRef })const { hasAccess: hasDedicatedPooler } = useCheckEntitlements('dedicated_pooler')const isHighAvailability = useIsHighAvailability()+ const deploymentMode = useDeploymentMode()const [state, setState] = useState<ConnectState>(() => {const defaults = getDefaultState({ schema: connectSchema })@@ -300,7 +327,8 @@ export function useConnectState(initialState?: Partial<ConnectState>): UseConnec}if (mode === 'direct') {- next.connectionMethod = next.connectionMethod ?? 'direct'+ const defaultMethod = deploymentMode.isSelfHosted ? 'session' : 'direct'+ next.connectionMethod = next.connectionMethod ?? defaultMethodnext.connectionType = next.connectionType ?? 'uri'next.connectionSource = projectRef ?? '_'}@@ -316,12 +344,14 @@ export function useConnectState(initialState?: Partial<ConnectState>): UseConnecreturn next})},- [projectRef]+ [projectRef, deploymentMode.isSelfHosted])const activeFields = useMemo(() => {let fields = getActiveFields(connectSchema, state)- if (!hasDedicatedPooler) {+ if (!hasDedicatedPooler || !deploymentMode.isPlatform) {+ // useSharedPooler is a platform-only toggle (CLI has no pooler; self-hosted+ // already uses Supavisor shared)fields = fields.filter((f) => f.id !== 'useSharedPooler')}if (isHighAvailability) {@@ -330,7 +360,7 @@ export function useConnectState(initialState?: Partial<ConnectState>): UseConnec.map((f) => (f.id === 'connectionType' ? { ...f, label: 'Connection Type' } : f))}return fields- }, [state, hasDedicatedPooler, isHighAvailability])+ }, [state, hasDedicatedPooler, isHighAvailability, deploymentMode.isPlatform])const resolvedSteps = useMemo(() => resolveSteps(connectSchema, state), [state])@@ -338,9 +368,9 @@ export function useConnectState(initialState?: Partial<ConnectState>): UseConnec(fieldId: string): FieldOption[] => {const field = activeFields.find((f) => f.id === fieldId)if (!field) return []- return resolveFieldOptionsWithSource({ field, state, databases })+ return resolveFieldOptionsWithSource({ field, state, databases, deploymentMode })},- [activeFields, state, databases]+ [activeFields, state, databases, deploymentMode])return {diff --git a/apps/studio/data/config/deployment-mode-query.ts b/apps/studio/data/config/deployment-mode-query.tsnew file mode 100644index 00000000000..1ecd1e34c89--- /dev/null+++ b/apps/studio/data/config/deployment-mode-query.ts@@ -0,0 +1,40 @@+import { useQuery } from '@tanstack/react-query'++import { configKeys } from './keys'+import { handleError } from '@/data/fetchers'+import { API_URL, IS_PLATFORM } from '@/lib/constants'+import type { ResponseError, UseCustomQueryOptions } from '@/types'++export type DeploymentModeResponse = {+ is_cli_mode: boolean+}++export async function getDeploymentMode(signal?: AbortSignal): Promise<DeploymentModeResponse> {+ const response = await fetch(`${API_URL}/platform/deployment-mode`, { signal })+ const body = await response.json()++ if (!response.ok) {+ handleError(body)+ }++ return body+}++export type DeploymentModeData = Awaited<ReturnType<typeof getDeploymentMode>>+export type DeploymentModeError = ResponseError++export const useDeploymentModeQuery = <TData = DeploymentModeData>(+ options: UseCustomQueryOptions<DeploymentModeData, DeploymentModeError, TData> = {}+) => {+ const { enabled = true, ...rest } = options++ return useQuery<DeploymentModeData, DeploymentModeError, TData>({+ queryKey: configKeys.deploymentMode(),+ queryFn: ({ signal }) => getDeploymentMode(signal),+ // Only fetch in non-platform mode (CLI or self-hosted)+ enabled: enabled && !IS_PLATFORM,+ // Deployment mode is fixed for a session+ staleTime: Infinity,+ ...rest,+ })+}diff --git a/apps/studio/data/config/keys.ts b/apps/studio/data/config/keys.tsindex b9e286c8ec0..1a01c675641 100644--- a/apps/studio/data/config/keys.ts+++ b/apps/studio/data/config/keys.ts@@ -26,4 +26,5 @@ export const configKeys = {['projects', projectRef, 'available-unpause-versions'] as const,diskAutoscaleConfig: (projectRef: string | undefined) =>['projects', projectRef, 'disk-autoscale-config'] as const,+ deploymentMode: () => ['deployment-mode'] as const,}diff --git a/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.ts b/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.tsnew file mode 100644index 00000000000..4f540cb8330--- /dev/null+++ b/apps/studio/hooks/misc/__tests__/useDeploymentMode.test.ts@@ -0,0 +1,96 @@+import { renderHook } from '@testing-library/react'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import { useDeploymentMode } from '../useDeploymentMode'++const { mockIsPlatform, mockUseDeploymentModeQuery } = vi.hoisted(() => ({+ mockIsPlatform: { value: false },+ mockUseDeploymentModeQuery: vi.fn(),+}))++vi.mock('@/lib/constants', async () => {+ const actual = await vi.importActual<Record<string, unknown>>('@/lib/constants')+ return {+ ...actual,+ get IS_PLATFORM() {+ return mockIsPlatform.value+ },+ }+})++vi.mock('@/data/config/deployment-mode-query', () => ({+ useDeploymentModeQuery: mockUseDeploymentModeQuery,+}))++describe('useDeploymentMode', () => {+ beforeEach(() => {+ mockIsPlatform.value = false+ mockUseDeploymentModeQuery.mockReset()+ })++ test('platform build: returns isPlatform regardless of query state', () => {+ mockIsPlatform.value = true+ mockUseDeploymentModeQuery.mockReturnValue({ data: undefined })++ const { result } = renderHook(() => useDeploymentMode())++ expect(result.current).toEqual({+ isPlatform: true,+ isCli: false,+ isSelfHosted: false,+ })+ })++ test('non-platform, loading window (data undefined): defaults to CLI', () => {+ // `?? true` flip — see useDeploymentMode for the asymmetry rationale.+ // `'direct'` is the only universally-valid method, so CLI-during-loading+ // is the safe guess that avoids pinning an invalid `connectionMethod`.+ mockUseDeploymentModeQuery.mockReturnValue({ data: undefined })++ const { result } = renderHook(() => useDeploymentMode())++ expect(result.current).toEqual({+ isPlatform: false,+ isCli: true,+ isSelfHosted: false,+ })+ })++ test('non-platform, resolved is_cli_mode=true: CLI', () => {+ mockUseDeploymentModeQuery.mockReturnValue({ data: { is_cli_mode: true } })++ const { result } = renderHook(() => useDeploymentMode())++ expect(result.current).toEqual({+ isPlatform: false,+ isCli: true,+ isSelfHosted: false,+ })+ })++ test('non-platform, resolved is_cli_mode=false: self-hosted', () => {+ mockUseDeploymentModeQuery.mockReturnValue({ data: { is_cli_mode: false } })++ const { result } = renderHook(() => useDeploymentMode())++ expect(result.current).toEqual({+ isPlatform: false,+ isCli: false,+ isSelfHosted: true,+ })+ })++ test('returns a stable reference across renders when primitive flags do not change', () => {+ // Distinct `data` object refs with equal contents — pins memoization on the+ // primitive flags (`[isCli, isSelfHosted]`), not on the `data` reference.+ mockUseDeploymentModeQuery+ .mockReturnValueOnce({ data: { is_cli_mode: false } })+ .mockReturnValueOnce({ data: { is_cli_mode: false } })++ const { result, rerender } = renderHook(() => useDeploymentMode())+ const first = result.current+ rerender()++ expect(result.current).toBe(first)+ })+})diff --git a/apps/studio/hooks/misc/useDeploymentMode.ts b/apps/studio/hooks/misc/useDeploymentMode.tsnew file mode 100644index 00000000000..dafbd9a66ec--- /dev/null+++ b/apps/studio/hooks/misc/useDeploymentMode.ts@@ -0,0 +1,38 @@+import { useMemo } from 'react'++import { useDeploymentModeQuery } from '@/data/config/deployment-mode-query'+import { IS_PLATFORM } from '@/lib/constants'++export type DeploymentMode = {+ isPlatform: boolean+ isCli: boolean+ isSelfHosted: boolean+}++/**+ * Resolves the current Studio deployment mode (platform / CLI / self-hosted).+ *+ * `isPlatform` is the build-time `IS_PLATFORM` constant — prefer that constant+ * directly when you only need the platform-vs-not split (build-time, server-+ * side, or module-scope). Reach for this hook when you need to distinguish+ * CLI from self-hosted at runtime, which is something `IS_PLATFORM` can't+ * express on its own.+ *+ * CLI vs self-hosted is resolved server-side by /platform/deployment-mode+ * (reading `CURRENT_CLI_VERSION`). The underlying query is disabled on+ * platform builds, so the hook is a no-op there.+ *+ * The return is memoized on the primitive flags so consumers can safely list+ * the whole `DeploymentMode` object in their `useMemo`/`useCallback` deps.+ */+export function useDeploymentMode(): DeploymentMode {+ const { data } = useDeploymentModeQuery()+ // Default to CLI (`?? true`) during the loading window. `'direct'` is the only+ // method valid in every environment, so a self-hosted user briefly seeing CLI+ // defaults lands on a valid (if not preferred) choice — whereas a CLI user+ // briefly seeing self-hosted defaults gets `connectionMethod` pinned to+ // `'session'`, which isn't a valid CLI method.+ const isCli = !IS_PLATFORM && (data?.is_cli_mode ?? true)+ const isSelfHosted = !IS_PLATFORM && !isCli+ return useMemo(() => ({ isPlatform: IS_PLATFORM, isCli, isSelfHosted }), [isCli, isSelfHosted])+}diff --git a/apps/studio/lib/api/self-hosted/settings.test.ts b/apps/studio/lib/api/self-hosted/settings.test.tsindex c584e6b4ae8..d4458dc34c8 100644--- a/apps/studio/lib/api/self-hosted/settings.test.ts+++ b/apps/studio/lib/api/self-hosted/settings.test.ts@@ -9,6 +9,7 @@ vi.mock('./util', () => ({vi.mock('@/lib/constants/api', () => ({PROJECT_ENDPOINT: 'localhost:8000',PROJECT_ENDPOINT_PROTOCOL: 'http',+ PROJECT_DB_HOST: 'localhost',}))describe('api/self-hosted/settings', () => {diff --git a/apps/studio/lib/api/self-hosted/settings.ts b/apps/studio/lib/api/self-hosted/settings.tsindex 071ea6e1c43..f7b8a40ae06 100644--- a/apps/studio/lib/api/self-hosted/settings.ts+++ b/apps/studio/lib/api/self-hosted/settings.ts@@ -1,7 +1,8 @@import { components } from 'api-types'+import { POSTGRES_PORT } from './constants'import { assertSelfHosted } from './util'-import { PROJECT_ENDPOINT, PROJECT_ENDPOINT_PROTOCOL } from '@/lib/constants/api'+import { PROJECT_DB_HOST, PROJECT_ENDPOINT, PROJECT_ENDPOINT_PROTOCOL } from '@/lib/constants/api'type ProjectAppConfig = components['schemas']['ProjectSettingsResponse']['app_config'] & {protocol?: string@@ -29,10 +30,10 @@ export function getProjectSettings() {},cloud_provider: 'AWS',db_dns_name: '-',- db_host: 'localhost',+ db_host: PROJECT_DB_HOST,db_ip_addr_config: 'legacy' as const,db_name: 'postgres',- db_port: 5432,+ db_port: POSTGRES_PORT,db_user: 'postgres',inserted_at: '2021-08-02T06:40:40.646Z',jwt_secret:diff --git a/apps/studio/lib/constants/api.ts b/apps/studio/lib/constants/api.tsindex 2c586edbe54..98753c292a3 100644--- a/apps/studio/lib/constants/api.ts+++ b/apps/studio/lib/constants/api.ts@@ -8,6 +8,7 @@ export const PROJECT_ANALYTICS_URL = process.env.LOGFLARE_URLexport const PROJECT_REST_URL = `${PUBLIC_URL.origin}/rest/v1/`export const PROJECT_ENDPOINT = PUBLIC_URL.hostexport const PROJECT_ENDPOINT_PROTOCOL = PUBLIC_URL.protocol.replace(':', '')+export const PROJECT_DB_HOST = PUBLIC_URL.hostnameexport const DEFAULT_PROJECT = {id: 1,diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.tsindex 4db71799866..0ed4e00616c 100644--- a/apps/studio/lib/constants/index.ts+++ b/apps/studio/lib/constants/index.ts@@ -4,6 +4,13 @@ export * from './infrastructure'export const IS_PLATFORM = process.env.NEXT_PUBLIC_IS_PLATFORM === 'true'+/**+ * Server-side flag for Supabase CLI (local development) runs. Detected via+ * CURRENT_CLI_VERSION, which the CLI sets when launching Studio. The browser+ * cannot read this directly — use the /platform/deployment-mode endpoint.+ */+export const IS_CLI = !IS_PLATFORM && !!process.env.CURRENT_CLI_VERSION+/*** Indicates that the app is running in a test environment (E2E tests).* Set via NEXT_PUBLIC_NODE_ENV=test in the generateLocalEnv.js script.diff --git a/apps/studio/pages/api/platform/deployment-mode.ts b/apps/studio/pages/api/platform/deployment-mode.tsnew file mode 100644index 00000000000..fbc17165639--- /dev/null+++ b/apps/studio/pages/api/platform/deployment-mode.ts@@ -0,0 +1,27 @@+import { NextApiRequest, NextApiResponse } from 'next'++import type { DeploymentModeResponse } from '@/data/config/deployment-mode-query'+import apiWrapper from '@/lib/api/apiWrapper'+import { IS_CLI } from '@/lib/constants'++export default function deploymentMode(req: NextApiRequest, res: NextApiResponse) {+ return apiWrapper(req, res, handler)+}++async function handler(req: NextApiRequest, res: NextApiResponse) {+ const { method } = req++ switch (method) {+ case 'GET':+ return handleGet(req, res)+ default:+ res.setHeader('Allow', ['GET'])+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })+ }+}++const handleGet = async (_req: NextApiRequest, res: NextApiResponse<DeploymentModeResponse>) => {+ return res.status(200).json({+ is_cli_mode: IS_CLI,+ })+}diff --git a/apps/studio/pages/api/platform/projects/[ref]/databases.ts b/apps/studio/pages/api/platform/projects/[ref]/databases.tsindex c8ef80907af..4a932fe9f30 100644--- a/apps/studio/pages/api/platform/projects/[ref]/databases.ts+++ b/apps/studio/pages/api/platform/projects/[ref]/databases.ts@@ -2,7 +2,8 @@ import { paths } from 'api-types'import { NextApiRequest, NextApiResponse } from 'next'import apiWrapper from '@/lib/api/apiWrapper'-import { PROJECT_REST_URL } from '@/lib/constants/api'+import { POSTGRES_PORT } from '@/lib/api/self-hosted/constants'+import { PROJECT_DB_HOST, PROJECT_REST_URL } from '@/lib/constants/api'export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)@@ -27,9 +28,9 @@ const handleGet = async (_req: NextApiRequest, res: NextApiResponse<ResponseDatacloud_provider: 'localhost' as any,connectionString: '',connection_string_read_only: '',- db_host: '127.0.0.1',+ db_host: PROJECT_DB_HOST,db_name: 'postgres',- db_port: 5432,+ db_port: POSTGRES_PORT,db_user: 'postgres',identifier: 'default',inserted_at: '',diff --git a/apps/studio/pages/api/platform/props/project/[ref]/api.ts b/apps/studio/pages/api/platform/props/project/[ref]/api.tsindex e821639993f..eed87d7ddc6 100644--- a/apps/studio/pages/api/platform/props/project/[ref]/api.ts+++ b/apps/studio/pages/api/platform/props/project/[ref]/api.ts@@ -1,8 +1,10 @@import { NextApiRequest, NextApiResponse } from 'next'import apiWrapper from '@/lib/api/apiWrapper'+import { POSTGRES_PORT } from '@/lib/api/self-hosted/constants'import {DEFAULT_PROJECT,+ PROJECT_DB_HOST,PROJECT_ENDPOINT,PROJECT_ENDPOINT_PROTOCOL,PROJECT_REST_URL,@@ -28,9 +30,9 @@ const handleGetAll = async (_req: NextApiRequest, res: NextApiResponse) => {project: {...DEFAULT_PROJECT,api_key_supabase_encrypted: '',- db_host: 'localhost',+ db_host: PROJECT_DB_HOST,db_name: 'postgres',- db_port: 5432,+ db_port: POSTGRES_PORT,db_ssl: false,db_user: 'postgres',services: [