The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Joshenlim/fe 4480 fdw create wrapper to only init fdw once users to name the (#51074)
Joshen Lim521881a899b6
diff --git a/apps/studio/components/interfaces/Integrations/Integration/RequiredExtensionsSection.tsx b/apps/studio/components/interfaces/Integrations/Integration/RequiredExtensionsSection.tsxindex 070985b792c..332ca63df9e 100644--- a/apps/studio/components/interfaces/Integrations/Integration/RequiredExtensionsSection.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/RequiredExtensionsSection.tsx@@ -35,9 +35,9 @@ export const RequiredExtensionsSection = ({return (<>{!hideSeparator && <Separator />}- <div className={cn('flex flex-col gap-y-4', className)}>- <h4>Required extensions</h4>- <Card>+ <div className={cn('md:grid md:grid-cols-12 gap-2', className)}>+ <h4 className="col-span-4">Required extensions</h4>+ <Card className="col-span-8"><CardContent className="p-0"><ul className="text-foreground-light text-sm">{requiredExtensions.map((requiredExtension, idx) => {diff --git a/apps/studio/components/interfaces/Integrations/Marketplace/MarketplaceDetail.tsx b/apps/studio/components/interfaces/Integrations/Marketplace/MarketplaceDetail.tsxindex 9e03a5d9f5c..5d24eb0c9d4 100644--- a/apps/studio/components/interfaces/Integrations/Marketplace/MarketplaceDetail.tsx+++ b/apps/studio/components/interfaces/Integrations/Marketplace/MarketplaceDetail.tsx@@ -1,5 +1,4 @@import { ArrowUpRight, BookOpen, Gauge, Settings } from 'lucide-react'-import { useRouter } from 'next/router'import { Button, cn } from 'ui'import { Admonition } from 'ui-patterns/Admonition'import { GenericSkeletonLoader, ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'@@ -17,7 +16,6 @@ import { UnknownInterface } from '@/components/ui/UnknownInterface'export const centeredContentClass = 'mx-auto w-full max-w-6xl px-6 xl:px-10'export const MarketplaceDetail = () => {- const router = useRouter()const {ref,activeRoute,@@ -32,7 +30,6 @@ export const MarketplaceDetail = () => {integrationStatus,isInstalled,installActionType,- wrappersTabHref,isAvailableLoading,isInstalledLoading,isIntegrationStatusLoading,@@ -84,14 +81,7 @@ export const MarketplaceDetail = () => {/>)case 'add-wrapper':- return (- <AddWrapperButton- variant="primary"- onClick={() => {- if (wrappersTabHref) router.push(`${wrappersTabHref}?new=true`)- }}- />- )+ return <AddWrapperButton variant="primary" />case 'installed':return (<Button variant="outline" disabled>diff --git a/apps/studio/components/interfaces/Integrations/Vault/Secrets/SecretsManagement.tsx b/apps/studio/components/interfaces/Integrations/Vault/Secrets/SecretsManagement.tsxindex 5933b54f035..ce11212d82d 100644--- a/apps/studio/components/interfaces/Integrations/Vault/Secrets/SecretsManagement.tsx+++ b/apps/studio/components/interfaces/Integrations/Vault/Secrets/SecretsManagement.tsx@@ -68,7 +68,8 @@ export const SecretsManagement = () => {? allSecrets.filter((secret) =>(secret?.name ?? '').toLowerCase().includes(searchValue.trim().toLowerCase()) ||- (secret?.id ?? '').toLowerCase().includes(searchValue.trim().toLowerCase())+ (secret?.id ?? '').toLowerCase().includes(searchValue.trim().toLowerCase()) ||+ (secret?.key_id ?? '').toLowerCase().includes(searchValue.trim().toLowerCase())): allSecretsdiff --git a/apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx b/apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsxindex b76f2bd6eef..df9c2376bee 100644--- a/apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Vault/Secrets/__tests__/EditSecretModal.test.tsx@@ -13,6 +13,7 @@ import type { VaultSecret } from '@/types'const secret: VaultSecret = {id: '47ca58b4-01c5-4a71-8814-c73856b02e0e',+ key_id: null,name: 'test',description: 'new text',secret: 'NASR0SoksURJ0OorMJ9FzraTzcqSWk5u1PQa2r4c3w9rUVc=',diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/AddWrapperButton.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/AddWrapperButton.tsxindex 1861253d8be..ae3bc1428dc 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/AddWrapperButton.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/AddWrapperButton.tsx@@ -1,4 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'+import Link from 'next/link'import { useMemo } from 'react'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'@@ -10,10 +12,11 @@ const WRAPPER_REQUIRED_EXTENSION_NAMES = ['wrappers', 'supabase_vault']interface AddWrapperButtonProps {variant?: 'default' | 'primary' | 'outline'- onClick: () => void}-export const AddWrapperButton = ({ variant = 'default', onClick }: AddWrapperButtonProps) => {+export const AddWrapperButton = ({ variant = 'default' }: AddWrapperButtonProps) => {+ const { ref, id } = useParams()+const { can: canCreateWrapper } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,'wrappers'@@ -33,20 +36,27 @@ export const AddWrapperButton = ({ variant = 'default', onClick }: AddWrapperBut[extensions])+ const label = needsExtensions ? 'Install wrapper' : 'Add new wrapper'+return (<ButtonTooltip+ asChild={canCreateWrapper}variant={variant}- onClick={onClick}disabled={!canCreateWrapper}tooltip={{content: {+ side: 'bottom',text: !canCreateWrapper? 'You need additional permissions to create a foreign data wrapper': undefined,},}}>- {needsExtensions ? 'Install wrapper' : 'Add new wrapper'}+ {canCreateWrapper ? (+ <Link href={`/project/${ref}/integrations/${id}/wrappers?new=true`}>{label}</Link>+ ) : (+ label+ )}</ButtonTooltip>)}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsxindex a34ebc56724..0cb3c092324 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx@@ -10,6 +10,7 @@ import {Input,RadioGroupStacked,RadioGroupStackedItem,+ Separator,SheetFooter,SheetHeader,SheetSection,@@ -19,7 +20,7 @@ import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import * as z from 'zod'import { CreateWrapperSheetProps } from './CreateWrapperSheet'-import InputField from './InputField'+import { InputField } from './InputField'import {FormSection,FormSectionContent,@@ -36,7 +37,7 @@ const FORM_ID = 'create-wrapper-form'const S3TableSchema = z.object({target: z.literal('S3Tables'),source_schema: z.string().min(1, 'Please provide a namespace name'),- wrapper_name: z.string().min(1, 'Please provide a name for your wrapper'),+ server_name: z.string().min(1, 'Please provide a name for your server'),target_schema: z.string().min(1, 'Please provide an unique target schema'),vault_aws_access_key_id: z.string().min(1, 'Required'),vault_aws_secret_access_key: z.string().min(1, 'Required'),@@ -46,7 +47,7 @@ const S3TableSchema = z.object({const R2CatalogSchema = z.object({target: z.literal('R2Catalog'),source_schema: z.string().min(1, 'Please provide a namespace name'),- wrapper_name: z.string().min(1, 'Please provide a name for your wrapper'),+ server_name: z.string().min(1, 'Please provide a name for your server'),target_schema: z.string().min(1, 'Please provide an unique target schema'),vault_aws_access_key_id: z.string().min(1, 'Required'),vault_aws_secret_access_key: z.string().min(1, 'Required'),@@ -58,7 +59,7 @@ const R2CatalogSchema = z.object({const IcebergRestCatalogSchema = z.object({target: z.literal('IcebergRestCatalog'),source_schema: z.string().min(1, 'Please provide a namespace name'),- wrapper_name: z.string().min(1, 'Please provide a name for your wrapper'),+ server_name: z.string().min(1, 'Please provide a name for your server'),target_schema: z.string().min(1, 'Please provide an unique target schema'),vault_aws_access_key_id: z.string().optional(),vault_aws_secret_access_key: z.string().optional(),@@ -107,7 +108,7 @@ const targetFields: Record<Target, { name: string; required: boolean }[]> = {type Target = 'S3Tables' | 'R2Catalog' | 'IcebergRestCatalog'const INITIAL_VALUES = {- wrapper_name: '',+ server_name: '',source_schema: '',target_schema: '',target: 'S3Tables',@@ -203,7 +204,7 @@ export const CreateIcebergWrapperSheet = ({wrapperMeta,formState: {...formValues,- server_name: `${values.wrapper_name}_server`,+ wrapper_name: wrapperMeta.name,supabase_target_schema: values.target_schema,},mode: 'schema',@@ -220,7 +221,6 @@ export const CreateIcebergWrapperSheet = ({}const isLoading = isCreatingWrapper || isSubmitting- const wrapperName = useWatch({ name: 'wrapper_name', control: form.control })const target = useWatch({ name: 'target', control: form.control })const targetOptions = wrapperMeta.server.options@@ -243,27 +243,18 @@ export const CreateIcebergWrapperSheet = ({<SheetHeader><SheetTitle>Create a {wrapperMeta.label} wrapper</SheetTitle></SheetHeader>- <SheetSection className="grow overflow-y-auto">- <FormSection header={<FormSectionLabel>Wrapper Configuration</FormSectionLabel>}>++ <SheetSection className="grow overflow-y-auto p-0">+ <FormSection+ className="p-5!"+ header={<FormSectionLabel>Server Configuration</FormSectionLabel>}+ ><FormSectionContent className="flex flex-col space-y-2" loading={false}><FormFieldcontrol={form.control}- name="wrapper_name"+ name="server_name"render={({ field }) => (- <FormItemLayout- layout="horizontal"- label="Wrapper Name"- description={- wrapperName.length > 0 ? (- <>- Your wrapper's server name will be{' '}- <code className="text-code-inline">{wrapperName}_server</code>- </>- ) : (- ''- )- }- >+ <FormItemLayout layout="horizontal" label="Server Name"><FormControl><Input {...field} /></FormControl>@@ -272,13 +263,19 @@ export const CreateIcebergWrapperSheet = ({/></FormSectionContent></FormSection>- <FormSection header={<FormSectionLabel>Data target</FormSectionLabel>}>++ <Separator />++ <FormSection+ className="p-5!"+ header={<FormSectionLabel>Data target</FormSectionLabel>}+ ><FormSectionContent className="flex flex-col space-y-2" loading={false}><FormFieldcontrol={form.control}name="target"render={({ field }) => (- <FormItemLayout layout="vertical">+ <FormItemLayout layout="horizontal" label="Import as"><div><RadioGroupStacked value={field.value} onValueChange={field.onChange}><RadioGroupStackedItem@@ -331,7 +328,10 @@ export const CreateIcebergWrapperSheet = ({</FormSectionContent></FormSection>+ <Separator />+<FormSection+ className="p-5!"header={<FormSectionLabel>{wrapperMeta.label} Configuration</FormSectionLabel>}><FormSectionContent className="flex flex-col space-y-2" loading={false}>@@ -353,11 +353,15 @@ export const CreateIcebergWrapperSheet = ({)}</FormSectionContent></FormSection>++ <Separator />+<FormSection+ className="p-5!"header={- <FormSectionLabel>- <p>Foreign Schema</p>- <p className="text-foreground-light mt-2 w-[90%]">+ <FormSectionLabel className="lg:col-span-12 flex flex-col gap-y-1">+ <p>Foreign schema</p>+ <p className="text-foreground-light">You can query your data from the foreign tables in the specified schema afterthe wrapper is created.</p>diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsxindex fd16e97dd6d..e2427d2ec6c 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx@@ -6,6 +6,7 @@ import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-formimport { toast } from 'sonner'import {Button,+ cn,Form,FormControl,FormField,@@ -16,16 +17,13 @@ import {SheetFooter,SheetHeader,SheetTitle,- Tooltip,- TooltipContent,- TooltipTrigger,WarningIcon,} from 'ui'import { Admonition } from 'ui-patterns/Admonition'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import * as z from 'zod'-import InputField from './InputField'+import { InputField } from './InputField'import { WrapperMeta } from './Wrappers.types'import {FormattedWrapperTable,@@ -39,6 +37,7 @@ import { useIsMarketplaceEnabled } from '@/components/interfaces/App/FeaturePrevimport { getExtensionDefaultSchema } from '@/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/IntegrationOverviewTabV2.utils'import { RequiredExtensionsSection } from '@/components/interfaces/Integrations/Integration/RequiredExtensionsSection'import { useIntegrationDetail } from '@/components/interfaces/Integrations/Landing/useIntegrationDetail'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import {FormSection,FormSectionContent,@@ -97,7 +96,7 @@ export const CreateWrapperSheet = ({})const initialValues = {- wrapper_name: '',+ wrapper_name: wrapperMeta.name,server_name: '',mode: wrapperMeta.tables.length > 0 ? 'tables' : 'schema',source_schema: wrapperMeta.sourceSchemaOption?.defaultValue ?? '',@@ -118,10 +117,6 @@ export const CreateWrapperSheet = ({const { getValues, setError } = formconst { errors, isDirty, isSubmitting } = form.formState- useEffect(() => {- onDirty(isDirty)- }, [onDirty, isDirty])-const {fields: tablesField,append: appendTable,@@ -135,6 +130,9 @@ export const CreateWrapperSheet = ({const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(undefined)+ const [selectedTableFieldIndex, setSelectedTableFieldIndex] = useState<number | undefined>(+ undefined+ )const { mutateAsync: enableExtension } = useDatabaseExtensionEnableMutation({ onError: () => {} })const { mutateAsync: createSchema } = useSchemaCreateMutation({ onError: () => {} })@@ -162,13 +160,14 @@ export const CreateWrapperSheet = ({}const onUpdateTable = (values: FormattedWrapperTable) => {- if (values.index !== undefined) {- removeTable(values.index)- insertTable(values.index, values)+ if (selectedTableFieldIndex !== undefined) {+ removeTable(selectedTableFieldIndex)+ insertTable(selectedTableFieldIndex, values)} else {appendTable(values)}setSelectedTableToEdit(undefined)+ setSelectedTableFieldIndex(undefined)}const onSubmit: SubmitHandler<FormSchema> = async (values) => {@@ -221,7 +220,7 @@ export const CreateWrapperSheet = ({wrapperMeta,formState: {...wrapperValues,- server_name: `${wrapperValues.wrapper_name}_server`,+ wrapper_name: wrapperMeta.name,supabase_target_schema: mode === 'schema' ? wrapperValues.target_schema : undefined,},mode: mode === 'schema' ? (wrapperMeta.sourceSchemaOption ? 'schema' : 'skip') : 'tables',@@ -248,9 +247,12 @@ export const CreateWrapperSheet = ({}}- const wrapper_name = useWatch({ name: 'wrapper_name', control: form.control })const mode = useWatch({ name: 'mode', control: form.control })+ useEffect(() => {+ onDirty(isDirty)+ }, [onDirty, isDirty])+return (<><div className="h-full" tabIndex={-1}>@@ -261,8 +263,9 @@ export const CreateWrapperSheet = ({className="flex flex-col h-full"><SheetHeader>- <SheetTitle>Create a {wrapperMeta.label} wrapper</SheetTitle>+ <SheetTitle>Create a {wrapperMeta.label} wrapper connection</SheetTitle></SheetHeader>+<div className="grow overflow-y-auto">{isMarketplaceEnabled && (<div className="px-5 py-5 flex flex-col gap-y-4 border-b">@@ -276,26 +279,17 @@ export const CreateWrapperSheet = ({<RequiredExtensionsSection hideSeparator /></div>)}- <FormSection header={<FormSectionLabel>Wrapper Configuration</FormSectionLabel>}>++ <FormSection+ className="p-5!"+ header={<FormSectionLabel>Server configuration</FormSectionLabel>}+ ><FormSectionContent className="flex flex-col space-y-2" loading={false}><FormFieldcontrol={form.control}- name="wrapper_name"+ name="server_name"render={({ field }) => (- <FormItemLayout- layout="vertical"- label="Wrapper Name"- description={- wrapper_name.length > 0 ? (- <>- Your wrapper's server name will be{' '}- <code className="text-code-inline">{wrapper_name}_server</code>- </>- ) : (- ''- )- }- >+ <FormItemLayout layout="horizontal" label="Server Name"><FormControl><Input {...field} /></FormControl>@@ -304,11 +298,14 @@ export const CreateWrapperSheet = ({/></FormSectionContent></FormSection>+<Separator />+<FormSection- header={<FormSectionLabel>{wrapperMeta.label} Configuration</FormSectionLabel>}+ className="p-5!"+ header={<FormSectionLabel>{wrapperMeta.label} configuration</FormSectionLabel>}>- <FormSectionContent className="flex flex-col space-y-2" loading={false}>+ <FormSectionContent className="flex flex-col space-y-2 gap-y-4" loading={false}>{wrapperMeta.server.options.filter((option) => !option.hidden).map((option) => (@@ -321,14 +318,19 @@ export const CreateWrapperSheet = ({))}</FormSectionContent></FormSection>+<Separator />- <FormSection header={<FormSectionLabel>Data target</FormSectionLabel>}>++ <FormSection+ className="p-5!"+ header={<FormSectionLabel>Data target</FormSectionLabel>}+ ><FormSectionContent className="flex flex-col space-y-2" loading={false}><FormFieldcontrol={form.control}name="mode"render={({ field }) => (- <FormItemLayout layout="vertical">+ <FormItemLayout label="Import as" layout="horizontal"><FormControl><RadioGroupStackedvalue={field.value as string}@@ -401,130 +403,134 @@ export const CreateWrapperSheet = ({/></FormSectionContent></FormSection>+<Separator />+{mode === 'tables' && (- <FormSection- header={- <FormSectionLabel>- <p>Foreign Tables</p>- <p className="text-foreground-light mt-2 w-[90%]">- You can query your data from these foreign tables after the wrapper is- created- </p>- </FormSectionLabel>- }- >- <FormSectionContent className="flex flex-col space-y-2" loading={false}>- <div className="flex flex-col space-y-2">- {tablesField.map((t, tableIndex) => {- // FIXME: make inference work- const table = t as unknown as FormattedWrapperTable- return (- <div- key={t.id}- className="flex items-center justify-between px-4 py-2 border rounded-md border-control"- >- <div>- <p className="text-sm">- {table.schema_name}.{table.table_name}- </p>- <p className="text-sm text-foreground-light">- Columns:{' '}- {(table.columns ?? []).map((column: any) => column.name).join(', ')}- </p>- </div>- <div className="flex items-center space-x-2">- <Tooltip>- <TooltipTrigger asChild>- <Button- className="px-1"- icon={<Edit />}- onClick={() => {- setSelectedTableToEdit(table)- }}- aria-label={`Edit ${table.table_name} foreign table`}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}- />- </TooltipTrigger>- <TooltipContent side="bottom">{`Edit ${table.table_name} foreign table`}</TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <Button- className="px-1"- icon={<Trash />}- onClick={() => {- removeTable(tableIndex)- }}- aria-label={`Remove ${table.table_name} foreign table`}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}- />- </TooltipTrigger>- <TooltipContent side="bottom">{`Remove ${table.table_name} foreign table`}</TooltipContent>- </Tooltip>+ <FormSection className="p-5!">+ <FormSectionContent loading={false}>+ <FormItemLayout+ isReactForm={false}+ layout="horizontal"+ label="Foreign tables"+ labelOptional="You can query your data from these foreign tables after the wrapper is+ created"+ className={cn(+ '[&>div>span]:text-balance',+ tablesField.length === 0 &&+ '[&>div:last-child]:flex [&>div:last-child]:items-center [&>div:last-child]:justify-end'+ )}+ >+ <div className="flex flex-col space-y-2">+ {tablesField.map((t, tableIndex) => {+ // FIXME: make inference work+ const table = t as unknown as FormattedWrapperTable+ return (+ <div+ key={t.id}+ className="flex items-center justify-between px-4 py-2 border rounded-md border-control"+ >+ <div>+ <p className="text-sm">+ {table.schema_name}.{table.table_name}+ </p>+ <p className="text-sm text-foreground-light">+ Columns:{' '}+ {(table.columns ?? []).map((column) => column.name).join(', ')}+ </p>+ </div>+ <div className="flex items-center space-x-2">+ <ButtonTooltip+ icon={<Edit />}+ onClick={() => {+ setSelectedTableFieldIndex(tableIndex)+ setSelectedTableToEdit(table)+ }}+ tooltip={{+ content: {+ side: 'bottom',+ text: `Edit ${table.table_name} foreign table`,+ },+ }}+ />+ <ButtonTooltip+ icon={<Trash />}+ onClick={() => removeTable(tableIndex)}+ tooltip={{+ content: {+ side: 'bottom',+ text: `Remove ${table.table_name} foreign table`,+ },+ }}+ />+ </div></div>- </div>- )- })}-- <div className="flex justify-end">- <Button onClick={() => setSelectedTableToEdit(NewTable)}>- Add foreign table- </Button>+ )+ })}++ <div className="flex justify-end">+ <Button+ onClick={() => {+ setSelectedTableFieldIndex(undefined)+ setSelectedTableToEdit(NewTable)+ }}+ >+ Add foreign table+ </Button>+ </div>++ {tablesField.length === 0 && errors.tables && (+ <p className="text-sm text-right text-red-900">+ {errors.tables.message?.toString()}+ </p>+ )}</div>- {tablesField.length === 0 && errors.tables && (- <p className="text-sm text-right text-red-900">- {errors.tables.message?.toString()}- </p>- )}- </div>+ </FormItemLayout></FormSectionContent></FormSection>)}- <Separator />+{mode === 'schema' && (- <FormSection- header={- <FormSectionLabel>- <p>Foreign Schema</p>- <p className="text-foreground-light mt-2 w-[90%]">- You can query your data from the foreign tables in the specified schema- after the wrapper is created.- </p>- </FormSectionLabel>- }- >+ <FormSection className="p-5!"><FormSectionContent className="flex flex-col space-y-2" loading={false}>- {wrapperMeta.sourceSchemaOption &&- !wrapperMeta.sourceSchemaOption?.readOnly && (- // Hide the field if the source schema is read-only+ <FormItemLayout+ isReactForm={false}+ layout="horizontal"+ label="Foreign schema"+ labelOptional="You can query your data from the foreign tables in the specified schema after the wrapper is created."+ className={cn('[&>div>span]:text-balance')}+ >+ {wrapperMeta.sourceSchemaOption &&+ !wrapperMeta.sourceSchemaOption?.readOnly && (+ // Hide the field if the source schema is read-only+ <InputField+ key="source_schema"+ option={wrapperMeta.sourceSchemaOption}+ control={form.control}+ />+ )}+ <div className="flex flex-col gap-2"><InputField- key="source_schema"- option={wrapperMeta.sourceSchemaOption}+ key="target_schema"+ layout="vertical"+ option={{+ name: 'target_schema',+ label: 'Specify a new schema to create all wrapper tables in',+ description:+ 'A new schema will be created. For security purposes, the wrapper tables from the foreign schema cannot be created within an existing schema.',+ required: true,+ encrypted: false,+ secureEntry: false,+ }}control={form.control}/>- )}- <div className="flex flex-col gap-2">- <InputField- key="target_schema"- option={{- name: 'target_schema',- label: 'Specify a new schema to create all wrapper tables in',- description:- 'A new schema will be created. For security purposes, the wrapper tables from the foreign schema cannot be created within an existing schema.',- required: true,- encrypted: false,- secureEntry: false,- }}- control={form.control}- />- </div>+ </div>+ </FormItemLayout></FormSectionContent></FormSection>)}</div>+<SheetFooter><Buttonsize="tiny"@@ -554,6 +560,7 @@ export const CreateWrapperSheet = ({tables={wrapperMeta.tables}onCancel={() => {setSelectedTableToEdit(undefined)+ setSelectedTableFieldIndex(undefined)}}onSave={onUpdateTable}initialData={selectedTableToEdit}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/DeleteWrapperModal.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/DeleteWrapperModal.tsxindex d6c35b2906d..d686c24cfe3 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/DeleteWrapperModal.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/DeleteWrapperModal.tsx@@ -82,7 +82,7 @@ export const DeleteWrapperModal = () => {open={selectedWrapper !== undefined}onOpenChange={() => setSelectedWrapperToDelete(null)}>- <AlertDialogContent size="medium">+ <AlertDialogContent size="small"><AlertDialogHeader><AlertDialogTitle>{`Delete connection ${selectedWrapper?.server_name}?`}</AlertDialogTitle><AlertDialogDescription>diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsxindex fafb290e561..a3848216e45 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx@@ -3,10 +3,11 @@ import { useQueryClient } from '@tanstack/react-query'import { compact } from 'lodash'import { Edit, Trash } from 'lucide-react'import { useEffect, useMemo, useState } from 'react'-import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form'+import { SubmitHandler, useFieldArray, useForm } from 'react-hook-form'import { toast } from 'sonner'import {Button,+ cn,Form,FormControl,FormField,@@ -15,15 +16,12 @@ import {SheetFooter,SheetHeader,SheetTitle,- Tooltip,- TooltipContent,- TooltipTrigger,} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import * as z from 'zod'-import InputField from './InputField'+import { InputField } from './InputField'import { WrapperMeta } from './Wrappers.types'import {convertKVStringArrayToJson,@@ -68,6 +66,16 @@ export const EditWrapperSheet = ({const queryClient = useQueryClient()const { data: project } = useSelectedProjectQuery()+ const [isLoadingSecrets, setIsLoadingSecrets] = useState(false)+ const [secretsReady, setSecretsReady] = useState(false)+ const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(+ undefined+ )+ const [selectedTableFieldIndex, setSelectedTableFieldIndex] = useState<number | undefined>(+ undefined+ )+ const [isUpdateConfirmationOpen, setIsUpdateConfirmationOpen] = useState(false)+const { mutate: updateFDW, isPending: isSaving } = useFDWUpdateMutation({onSuccess: () => {toast.success(`Successfully updated ${wrapperMeta?.label} foreign data wrapper`)@@ -81,7 +89,6 @@ export const EditWrapperSheet = ({const initialValues: Record<string, any> = useMemo(() => ({- wrapper_name: wrapper?.name,server_name: wrapper?.server_name,...convertKVStringArrayToJson(wrapper?.server_options ?? []),tables: formatWrapperTables(wrapper, wrapperMeta),@@ -109,18 +116,14 @@ export const EditWrapperSheet = ({name: 'tables',})- const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(- undefined- )- const [isUpdateConfirmationOpen, setIsUpdateConfirmationOpen] = useState(false)-const onUpdateTable = (values: FormattedWrapperTable) => {- if (values.index !== undefined) {- updateTable(values.index, values)+ if (selectedTableFieldIndex !== undefined) {+ updateTable(selectedTableFieldIndex, values)} else {appendTable(values)}setSelectedTableToEdit(undefined)+ setSelectedTableFieldIndex(undefined)}const onSubmit: SubmitHandler<FormSchema> = async (values) => {@@ -150,11 +153,6 @@ export const EditWrapperSheet = ({setIsClosing(false)}, [isDirty, confirmOnClose, isClosing, onClose, setIsClosing])- const wrapper_name = useWatch({ name: 'wrapper_name', control: form.control })-- const [isLoadingSecrets, setIsLoadingSecrets] = useState(false)- const [secretsReady, setSecretsReady] = useState(false)-useEffect(() => {let isCurrent = true@@ -168,8 +166,8 @@ export const EditWrapperSheet = ({).filter((x) => UUID_REGEX.test(x))if (encryptedIdsToFetch.length === 0) {- setSecretsReady(true)setIsLoadingSecrets(false)+ setSecretsReady(true)return}@@ -218,33 +216,20 @@ export const EditWrapperSheet = ({><SheetHeader><SheetTitle>- Edit {wrapperMeta.label} wrapper: {wrapper.name}+ Edit {wrapperMeta.label} wrapper connection: {wrapper.server_name}</SheetTitle></SheetHeader><div className="grow overflow-y-auto">- <FormSection header={<FormSectionLabel>Wrapper Configuration</FormSectionLabel>}>+ <FormSection+ className="p-5!"+ header={<FormSectionLabel>Server configuration</FormSectionLabel>}+ ><FormSectionContent className="flex flex-col space-y-2" loading={false}><FormFieldcontrol={form.control}- name="wrapper_name"+ name="server_name"render={({ field }) => (- <FormItemLayout- layout="vertical"- label="Wrapper Name"- description={- wrapper_name !== initialValues.wrapper_name ? (- <>- Your wrapper's server name will be updated to{' '}- <code className="text-code-inline">{wrapper_name}_server</code>- </>- ) : (- <>- Your wrapper's server name is{' '}- <code className="text-code-inline">{wrapper_name}_server</code>- </>- )- }- >+ <FormItemLayout layout="horizontal" label="Server name"><FormControl><Input {...field} /></FormControl>@@ -272,81 +257,85 @@ export const EditWrapperSheet = ({))}</FormSectionContent></FormSection>+<Separator />- <FormSection- header={- <FormSectionLabel>- <p>Foreign Tables</p>- <p className="text-foreground-light mt-2 w-[90%]">- You can query your data from these foreign tables after the wrapper is created- </p>- </FormSectionLabel>- }- >++ <FormSection><FormSectionContent className="flex flex-col space-y-2" loading={false}>- {tablesField.map((t, tableIndex) => {- // FIXME: make inference work- const table = t as unknown as FormattedWrapperTable- return (- <div- key={t.id}- className="flex items-center justify-between px-4 py-2 border rounded-md border-control"- >- <div>- <p className="text-sm">- {table.schema_name}.{table.table_name}- </p>- <p className="text-sm text-foreground-light">- Columns:{' '}- {(table.columns ?? []).map((column: any) => column.name).join(', ')}- </p>- </div>- <div className="flex items-center space-x-2">- <Tooltip>- <TooltipTrigger asChild>- <Button- className="px-1"+ <FormItemLayout+ layout="horizontal"+ label="Foreign tables"+ labelOptional="You can query your data from these foreign tables after the wrapper is created"+ isReactForm={false}+ className={cn(+ '[&>div>span]:text-balance',+ tablesField.length === 0 &&+ '[&>div:last-child]:flex [&>div:last-child]:items-center [&>div:last-child]:justify-end'+ )}+ >+ <div className="flex flex-col gap-y-2">+ {tablesField.map((t, tableIndex) => {+ // FIXME: make inference work+ const table = t as unknown as FormattedWrapperTable+ return (+ <div+ key={t.id}+ className="flex items-center justify-between px-4 py-2 border rounded-md border-control"+ >+ <div>+ <p className="text-sm">+ {table.schema_name}.{table.table_name}+ </p>+ <p className="text-sm text-foreground-light">+ Columns:{' '}+ {(table.columns ?? []).map((column) => column.name).join(', ')}+ </p>+ </div>+ <div className="flex items-center space-x-2">+ <ButtonTooltipicon={<Edit />}onClick={() => {+ setSelectedTableFieldIndex(tableIndex)setSelectedTableToEdit(table)}}- aria-label={`Edit ${table.table_name} foreign table`}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}+ tooltip={{+ content: {+ side: 'bottom',+ text: `Edit ${table.table_name} foreign table`,+ },+ }}/>- </TooltipTrigger>- <TooltipContent side="bottom">{`Edit ${table.table_name} foreign table`}</TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <Button- className="px-1"+ <ButtonTooltipicon={<Trash />}- onClick={() => {- removeTable(tableIndex)+ onClick={() => removeTable(tableIndex)}+ tooltip={{+ content: {+ side: 'bottom',+ text: `Remove ${table.table_name} foreign table`,+ },}}- aria-label={`Remove ${table.table_name} foreign table`}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}/>- </TooltipTrigger>- <TooltipContent side="bottom">{`Remove ${table.table_name} foreign table`}</TooltipContent>- </Tooltip>- </div>+ </div>+ </div>+ )+ })}+ <div className="flex justify-end">+ <Button+ onClick={() => {+ setSelectedTableFieldIndex(undefined)+ setSelectedTableToEdit(NewTable)+ }}+ >+ Add foreign table+ </Button></div>- )- })}-- <div className="flex justify-end">- <Button onClick={() => setSelectedTableToEdit(NewTable)}>- Add foreign table- </Button>- </div>- {tablesField.length === 0 && errors.tables && (- <p className="text-sm text-right text-red-900">- {errors.tables.message?.toString()}- </p>- )}+ {tablesField.length === 0 && errors.tables && (+ <p className="text-sm text-right text-red-900">+ {errors.tables.message?.toString()}+ </p>+ )}+ </div>+ </FormItemLayout></FormSectionContent></FormSection></div>@@ -413,6 +402,7 @@ export const EditWrapperSheet = ({tables={wrapperMeta.tables}onCancel={() => {setSelectedTableToEdit(undefined)+ setSelectedTableFieldIndex(undefined)}}onSave={onUpdateTable}initialData={selectedTableToEdit}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/InputField.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/InputField.tsxindex d5ed4a6e7b7..d0f63787288 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/InputField.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/InputField.tsx@@ -12,15 +12,17 @@ interface InputFieldProps<TFieldValues extends FieldValues = FieldValues> {control: Control<TFieldValues>loading?: booleanplaceholder?: string+ layout?: 'vertical' | 'horizontal'}-const InputField = <+export const InputField = <TFieldValues extends FieldValues = FieldValues,TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,>({control,option,loading = false,+ layout = 'horizontal',placeholder,}: InputFieldProps<TFieldValues>) => {return (@@ -30,7 +32,7 @@ const InputField = <defaultValue={(option.defaultValue ?? '') as any}render={({ field }) => (<FormItemLayout- layout="vertical"+ layout={layout}label={<div className="flex items-center space-x-2"><p>{option.label}</p>@@ -67,5 +69,3 @@ const InputField = </>)}--export default InputFielddiff --git a/apps/studio/components/interfaces/Integrations/Wrappers/OverviewTab.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/OverviewTab.tsxindex 7982d6f4b2a..ba5e278cd91 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/OverviewTab.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/OverviewTab.tsx@@ -1,93 +1,35 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import Link from 'next/link'-import { parseAsBoolean, useQueryState } from 'nuqs'-import { useState } from 'react'-import { Button, Sheet, SheetContent } from 'ui'+import { Button } from 'ui'import { Admonition } from 'ui-patterns/Admonition'import { IntegrationOverviewTab } from '../Integration/IntegrationOverviewTab'import { RequiredExtensionsSection } from '../Integration/RequiredExtensionsSection'import { useAvailableIntegrations } from '../Landing/useAvailableIntegrations'-import { CreateIcebergWrapperSheet } from './CreateIcebergWrapperSheet'-import { CreateWrapperSheet } from './CreateWrapperSheet'+import { AddWrapperButton } from './AddWrapperButton'import { WRAPPERS } from './Wrappers.constants'import { WrapperTable } from './WrapperTable'import { useIsMarketplaceEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { getServiceVersionsPath } from '@/components/interfaces/Settings/General/ServiceVersions/ServiceVersions.utils'import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'-import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'-import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-extensions-query'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'-import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'const WrapperOverviewContent = () => {- const { id } = useParams()- const wrapperMeta = WRAPPERS.find((w) => w.name === id)-- const [isDirty, setIsDirty] = useState(false)- const [createWrapperShown, setCreateWrapperShown] = useQueryState(- 'new',- parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })- )-- const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({- checkIsDirty: () => isDirty,- onClose: () => {- setCreateWrapperShown(false)- setIsDirty(false)- },- })-- // [Joshen] Opting to declare custom wrapper sheets here instead of within Wrappers.constants.ts- // as we'll easily run into circular dependencies doing so unfortunately- const CreateWrapperSheetComponent = !wrapperMeta- ? null- : wrapperMeta.customComponent- ? wrapperMeta.name === 'iceberg_wrapper'- ? CreateIcebergWrapperSheet- : null- : CreateWrapperSheet-return (- <>- <div className="flex flex-col gap-y-5">+ <div className="flex flex-col gap-y-5 max-w-5xl">+ <div className="flex items-center justify-between"><p>Recent wrappers</p>- <WrapperTable />+ <AddWrapperButton variant="primary" /></div>-- {!!CreateWrapperSheetComponent && !!wrapperMeta && (- <Sheet open={!!createWrapperShown} onOpenChange={handleOpenChange}>- <SheetContent size="lg">- <CreateWrapperSheetComponent- wrapperMeta={wrapperMeta}- onDirty={setIsDirty}- onClose={() => setCreateWrapperShown(false)}- onCloseWithConfirmation={confirmOnClose}- />- </SheetContent>- </Sheet>- )}-- <DiscardChangesConfirmationDialog {...modalProps} />- </>+ <WrapperTable />+ </div>)}const AddNewWrapperCTA = () => {const { id } = useParams()const { data: project } = useSelectedProjectQuery()- const [, setCreateWrapperShown] = useQueryState(- 'new',- parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })- )-- const { can: canCreateWrapper } = useAsyncCheckPermissions(- PermissionAction.TENANT_SQL_ADMIN_WRITE,- 'wrappers'- )const { data } = useDatabaseExtensionsQuery({projectRef: project?.ref,@@ -136,23 +78,7 @@ const AddNewWrapperCTA = () => {)}- return (- <div className="py-3 px-5 border rounded-md">- <ButtonTooltip- onClick={() => setCreateWrapperShown(true)}- disabled={!canCreateWrapper}- tooltip={{- content: {- text: !canCreateWrapper- ? 'You need additional permissions to create a foreign data wrapper'- : undefined,- },- }}- >- Add new wrapper- </ButtonTooltip>- </div>- )+ return null}export const WrapperContent = () => {diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsxindex cf967b065d2..5a30aad2341 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx@@ -14,10 +14,9 @@ import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'interface WrapperRowProps {wrapper: FDW- isShared: boolean}-export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {+export const WrapperRow = ({ wrapper }: WrapperRowProps) => {const { ref, id } = useParams()const { can: canManageWrappers } = useAsyncCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,@@ -40,47 +39,15 @@ export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {)const _tables = formatWrapperTables(wrapper, integration?.meta)- const canEdit = canManageWrappers && !isShared- let editTooltip = 'Edit wrapper'- if (!canManageWrappers) editTooltip = 'You need additional permissions to edit wrappers'- else if (isShared) editTooltip = 'Shared wrappers cannot be edited in the dashboard'+ const editTooltip = canManageWrappers+ ? 'Edit wrapper'+ : 'You need additional permissions to edit wrappers'return (<TableRow><TableCell className="gap-2 align-top py-3! min-w-80">- {wrapper.name}- <p className="text-sm text-foreground-light">- Connection: <code className="text-code-inline">{wrapper.server_name}</code>- </p>- {isShared && (- <p className="text-sm text-foreground-light">- This wrapper is shared. To edit this connection, use <code>ALTER SERVER</code> on{' '}- <code className="text-code-inline">{wrapper.server_name}</code> or{' '}- <code>ALTER FOREIGN TABLE</code> in the{' '}- <Link- href={`/project/${ref}/sql/new?skip=true`}- className="underline underline-offset-2"- >- SQL Editor- </Link>- .- {encryptedMetadata.length > 0 && (- <>- {' '}- Edit this server's credentials in{' '}- <Link- href={`/project/${ref}/integrations/vault/secrets`}- className="underline underline-offset-2"- >- Vault- </Link>- . Changes to a secret used by other connections affect them too.- </>- )}- </p>- )}-+ <p className="text-sm">{wrapper.server_name}</p>{visibleMetadata.map((metadata) => (<divkey={metadata.name}@@ -100,7 +67,7 @@ export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {return (<div key={table.id} className="flex items-center">- <Badge className="bg-surface-300 gap-2 font-mono text-[0.75rem] h-6 text-foreground rounded-r-none">+ <Badge className="bg-surface-300 gap-2 font-mono text-xs tracking-tight h-6 text-foreground rounded-r-none"><div className="relative w-3 h-3 flex items-center justify-center">{integration.icon({ className: 'p-0' })}</div>@@ -117,7 +84,7 @@ export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {</Badge><Link href={`/project/${ref}/editor/${table.id}`}>- <Badge className="transition hover:bg-surface-300 px-2 rounded-l-none gap-1.5 h-6 font-mono text-[0.75rem] border-l-0">+ <Badge className="transition hover:bg-surface-300 px-2 rounded-l-none gap-1.5 h-6 font-mono text-xs tracking-tight border-l-0"><Table2 size={12} strokeWidth={1.5} className="text-foreground-lighter/50" /><Tooltip><TooltipTrigger className="truncate max-w-28">@@ -140,17 +107,13 @@ export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {{encryptedMetadata.map((metadata) => (<div key={metadata.name} className="flex items-center space-x-2 text-sm"><Link- href={`/project/${ref}/integrations/vault/secrets?search=${encodeURIComponent(- `${wrapper.name}_${metadata.name}`+ href={`/project/${ref}/settings/vault/secrets?search=${encodeURIComponent(+ serverOptions[metadata.name] ?? '')}`}- className="transition text-foreground-light hover:text-foreground flex items-center space-x-2 max-w-28"+ className="transition text-foreground-light hover:text-foreground flex items-center gap-x-2">- <span className="truncate" title={metadata.label}>- {metadata.label}- </span>- <div>- <ExternalLink size={12} strokeWidth={1.5} className="text-foreground-lighter" />- </div>+ <span title={`View ${metadata.label} in Vault`}>{metadata.label}</span>+ <ExternalLink size={14} strokeWidth={1.5} /></Link></div>))}@@ -158,7 +121,7 @@ export const WrapperRow = ({ wrapper, isShared }: WrapperRowProps) => {<TableCell className="flex-nowrap"><div className="flex items-center gap-x-2"><ButtonTooltip- disabled={!canEdit}+ disabled={!canManageWrappers}icon={<Edit strokeWidth={1.5} />}className="px-1.5"onClick={() => setSelectedWrapperToEdit(wrapper.id.toString())}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTable.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTable.tsxindex 83e840e1f32..cce8235c697 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTable.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTable.tsx@@ -49,11 +49,7 @@ export const WrapperTable = ({ isLatest = false }: WrapperTableProps) => {)const [selectedWrapperIdToEdit, setSelectedWrapperToEdit] = useQueryState('edit', parseAsString)- const isSharedWrapper = (wrapper: (typeof wrappers)[number]) =>- data?.some((other) => other.id !== wrapper.id && other.name === wrapper.name) ?? false- const selectedWrapper = wrappers.find((w) => w.id.toString() === selectedWrapperIdToEdit)- const isSelectedWrapperShared = selectedWrapper !== undefined && isSharedWrapper(selectedWrapper)- const selectedWrapperToEdit = isSelectedWrapperShared ? undefined : selectedWrapper+ const selectedWrapperToEdit = wrappers.find((w) => w.id.toString() === selectedWrapperIdToEdit)const openedWrapperId = useRef<string | null>(null)useEffect(() => {@@ -63,22 +59,11 @@ export const WrapperTable = ({ isLatest = false }: WrapperTableProps) => {openedWrapperId.current = selectedWrapperIdToEdit} else if (isSuccess || isError) {if (openedWrapperId.current !== selectedWrapperIdToEdit) {- toast(- isSelectedWrapperShared- ? 'Shared wrappers cannot be edited in the dashboard. Use the SQL Editor to edit this connection.'- : 'Wrapper not found'- )+ toast('Wrapper not found')}setSelectedWrapperToEdit(null)}- }, [- isError,- isSelectedWrapperShared,- isSuccess,- selectedWrapperIdToEdit,- selectedWrapperToEdit,- setSelectedWrapperToEdit,- ])+ }, [isError, isSuccess, selectedWrapperIdToEdit, selectedWrapperToEdit, setSelectedWrapperToEdit])if (!integration || integration.type !== 'wrapper') {return (@@ -96,7 +81,7 @@ export const WrapperTable = ({ isLatest = false }: WrapperTableProps) => {<TableRow><TableHead className="w-[220px]">Name</TableHead><TableHead>Tables</TableHead>- <TableHead>Encrypted key</TableHead>+ <TableHead>Encrypted keys</TableHead><TableHead className="w-24"><span className="sr-only">Actions</span></TableHead>@@ -104,7 +89,7 @@ export const WrapperTable = ({ isLatest = false }: WrapperTableProps) => {</TableHeader><TableBody>{(isLatest ? wrappers.slice(0, 3) : wrappers).map((x) => (- <WrapperRow key={x.id} wrapper={x} isShared={isSharedWrapper(x)} />+ <WrapperRow key={x.id} wrapper={x} />))}</TableBody><TableFooterdiff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.constants.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.constants.tsindex 6857b4f9082..13beabd974f 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.constants.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.constants.ts@@ -1528,13 +1528,6 @@ export const WRAPPERS: WrapperMeta[] = [categories: ['data-platform'],server: {options: [- {- name: 'sa_key_id',- label: 'Service Account Key',- required: true,- encrypted: true,- secureEntry: true,- },{name: 'project_id',label: 'Project ID',@@ -1549,6 +1542,13 @@ export const WRAPPERS: WrapperMeta[] = [encrypted: false,secureEntry: false,},+ {+ name: 'sa_key_id',+ label: 'Service Account Key',+ required: true,+ encrypted: true,+ secureEntry: true,+ },],},tables: [diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.tsindex e962a44b3a4..c8b0fe58795 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.test.ts@@ -51,7 +51,7 @@ describe('getWrapperCreationFormSchema', () => {expect(result.success).toEqual(false)// Common required fieldexpect(- result.error?.issues.find((issue) => issue.path.some((p) => p === 'wrapper_name'))+ result.error?.issues.find((issue) => issue.path.some((p) => p === 'server_name'))).toBeDefined()// Table mode specific fieldexpect(@@ -66,7 +66,7 @@ describe('getWrapperCreationFormSchema', () => {expect(result.success).toEqual(false)// Common required fieldexpect(- result.error?.issues.find((issue) => issue.path.some((p) => p === 'wrapper_name'))+ result.error?.issues.find((issue) => issue.path.some((p) => p === 'server_name'))).toBeDefined()// Schema mode specific fieldexpect(@@ -99,7 +99,7 @@ describe('getEditionFormSchema', () => {expect(result.success).toEqual(false)// Common required fieldexpect(- result.error?.issues.find((issue) => issue.path.some((p) => p === 'wrapper_name'))+ result.error?.issues.find((issue) => issue.path.some((p) => p === 'server_name'))).toBeDefined()expect(result.error?.issues.find((issue) => issue.path.some((p) => p === 'tables'))diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.tsindex 2ff003648c5..550ff8fc640 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts@@ -19,7 +19,7 @@ const tableSchema = zexport const getWrapperCreationFormSchema = (wrapperMeta: WrapperMeta) => {let wrapperSchema = {// Common validation for all wrappers- wrapper_name: z.string().min(1, 'Please provide a name for your wrapper'),+ server_name: z.string().min(1, 'Please provide a name for your server'),} as Record<string, any>// Add wrapper specific options@@ -53,7 +53,7 @@ export const getWrapperCreationFormSchema = (wrapperMeta: WrapperMeta) => {export const getEditionFormSchema = (wrapperMeta: WrapperMeta) => {let wrapperSchema = {// Common validation for all wrappers- wrapper_name: z.string().min(1, 'Please provide a name for your wrapper'),+ server_name: z.string().min(1, 'Please provide a name for your server'),tables: z.array(tableSchema, { required_error: 'Please provide at least one table' }).min(1, 'Please provide at least one table'),diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrappersTab.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrappersTab.tsxindex 52243d3a910..80d3a945ab6 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrappersTab.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrappersTab.tsx@@ -5,10 +5,12 @@ import { useCallback, useState } from 'react'import { Sheet, SheetContent } from 'ui'import { AddWrapperButton } from './AddWrapperButton'+import { CreateIcebergWrapperSheet } from './CreateIcebergWrapperSheet'import { CreateWrapperSheet } from './CreateWrapperSheet'import { WRAPPERS } from './Wrappers.constants'import { wrapperMetaComparator } from './Wrappers.utils'import { WrapperTable } from './WrapperTable'+import { useIsMarketplaceEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { DocsButton } from '@/components/ui/DocsButton'import { useFDWsQuery } from '@/data/fdw/fdws-query'@@ -21,6 +23,7 @@ import { useShortcut } from '@/state/shortcuts/useShortcut'export const WrappersTab = () => {const { id } = useParams()const { data: project } = useSelectedProjectQuery()+ const isMarketplaceEnabled = useIsMarketplaceEnabled()const [isCreating, setIsCreating] = useQueryState('new',@@ -44,7 +47,6 @@ export const WrappersTab = () => {const wrappers = data ?? []const wrapperMeta = WRAPPERS.find((w) => w.name === id)-const createdWrappers = wrapperMeta? wrappers.filter((w) => wrapperMetaComparator(wrapperMeta, w)): []@@ -58,6 +60,14 @@ export const WrappersTab = () => {}, [setIsCreating]),})+ const CreateWrapperSheetComponent = !wrapperMeta+ ? null+ : wrapperMeta.customComponent+ ? wrapperMeta.name === 'iceberg_wrapper'+ ? CreateIcebergWrapperSheet+ : null+ : CreateWrapperSheet+if (!wrapperMeta) {return <div>Missing integration.</div>}@@ -70,23 +80,25 @@ export const WrappersTab = () => {<p className="text-sm text-foreground-light">No {wrapperMeta.label} wrappers have been installed</p>- <AddWrapperButton onClick={() => setIsCreating(true)} />+ <AddWrapperButton /></div></div>) : (<>- <div className="max-w-5xl flex items-center gap-x-2 justify-end mb-4">- <DocsButton href={wrapperMeta.docsUrl} />- <AddWrapperButton variant="primary" onClick={() => setIsCreating(true)} />- </div>+ {!isMarketplaceEnabled && (+ <div className="max-w-5xl flex items-center gap-x-2 justify-end mb-4">+ <DocsButton href={wrapperMeta.docsUrl} />+ <AddWrapperButton variant="primary" />+ </div>+ )}<WrapperTable /></>)}- <Sheet open={!!isCreating} onOpenChange={handleOpenChange}>+ <Sheet open={!!isCreating && canCreateWrapper} onOpenChange={handleOpenChange}><SheetContent size="lg">- {wrapperMeta && (- <CreateWrapperSheet+ {wrapperMeta && CreateWrapperSheetComponent && (+ <CreateWrapperSheetComponentwrapperMeta={wrapperMeta}onDirty={setIsDirty}onClose={() => {diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils.ts b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils.tsindex 871195c02d8..81c3ca26f06 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils.ts+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils.ts@@ -8,10 +8,6 @@ export const getAnalyticsBucketS3KeyName = (bucketId: string) => {return `${snakeCase(bucketId)}_keys`}-export const getAnalyticsBucketFDWName = (bucketId: string) => {- return `${snakeCase(bucketId)}_fdw`-}-export const getAnalyticsBucketFDWServerName = (bucketId: string) => {return `${snakeCase(bucketId)}_fdw_server`}diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsxindex c5d4dfeadcc..123d28a4cd4 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx@@ -1,6 +1,6 @@import { useMemo } from 'react'-import { getAnalyticsBucketFDWName } from './AnalyticsBucketDetails.utils'+import { getAnalyticsBucketFDWServerName } from './AnalyticsBucketDetails.utils'import { WRAPPER_HANDLERS } from '@/components/interfaces/Integrations/Wrappers/Wrappers.constants'import {getWrapperMetaForWrapper,@@ -32,7 +32,7 @@ export const useAnalyticsBucketWrapperInstance = (wrapper))- .find((w) => w.name === getAnalyticsBucketFDWName(bucketId ?? ''))+ .find((w) => w.server_name === getAnalyticsBucketFDWServerName(bucketId ?? ''))}, [data, bucketId])const icebergWrapperMeta = getWrapperMetaForWrapper(icebergWrapper)diff --git a/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx b/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsxindex c87ba11625e..a12f8288f18 100644--- a/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx+++ b/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx@@ -1,6 +1,6 @@import { useMemo } from 'react'-import { getVectorBucketFDWName } from './VectorBuckets.utils'+import { getVectorBucketFDWServerName } from './VectorBuckets.utils'import {WRAPPER_HANDLERS,WRAPPERS,@@ -30,7 +30,7 @@ export const useS3VectorsWrapperInstance = ({ bucketId }: { bucketId?: string })wrapper))- .find((w) => w.name === getVectorBucketFDWName(bucketId ?? ''))+ .find((w) => w.server_name === getVectorBucketFDWServerName(bucketId ?? ''))}, [data, bucketId])const s3VectorsWrapperMeta = WRAPPERS.find((w) => w.handlerName === WRAPPER_HANDLERS.S3_VECTORS)diff --git a/apps/studio/data/fdw/fdw-create-mutation.ts b/apps/studio/data/fdw/fdw-create-mutation.tsindex d299245a0fc..ab4d55f9b10 100644--- a/apps/studio/data/fdw/fdw-create-mutation.ts+++ b/apps/studio/data/fdw/fdw-create-mutation.ts@@ -1,4 +1,9 @@-import { getCreateFDWSql, type SafeSqlFragment } from '@supabase/pg-meta'+import {+ getCreateFDWSql,+ getCreateForeignDataWrapperSql,+ joinSqlFragments,+ type SafeSqlFragment,+} from '@supabase/pg-meta'import { wrapWithTransaction } from '@supabase/pg-meta/src/query'import { useMutation, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'@@ -27,8 +32,17 @@ export type FDWCreateVariables = {}export async function createFDW({ projectRef, connectionString, ...rest }: FDWCreateVariables) {- const sql = wrapWithTransaction(getCreateFDWSql(rest))- const { result } = await executeSql({ projectRef, connectionString, sql })+ const createForeignDataWrapperSql = getCreateForeignDataWrapperSql(rest.wrapperMeta)+ const createServerSql = getCreateFDWSql(rest)+ const sql = wrapWithTransaction(+ joinSqlFragments([createForeignDataWrapperSql, createServerSql], '\n\n')+ )+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['create-fdw'],+ })return result}diff --git a/apps/studio/data/fdw/fdw-delete-mutation.ts b/apps/studio/data/fdw/fdw-delete-mutation.tsindex 8ea295fd496..f7103931b1f 100644--- a/apps/studio/data/fdw/fdw-delete-mutation.ts+++ b/apps/studio/data/fdw/fdw-delete-mutation.ts@@ -14,7 +14,7 @@ import type { ResponseError, UseCustomMutationOptions } from '@/types'export type FDWDeleteVariables = {projectRef?: stringconnectionString?: string | null- wrapper: { id: number; name: string; server_name: string }+ wrapper: { id: number; name: string; server_name: string; server_options?: string[] | null }wrapperMeta: WrapperMeta}diff --git a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts b/apps/studio/data/storage/iceberg-wrapper-create-mutation.tsindex c98ad6d0217..22c8db52e16 100644--- a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts+++ b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts@@ -3,7 +3,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useS3AccessKeyCreateMutation } from './s3-access-key-create-mutation'import { WRAPPERS } from '@/components/interfaces/Integrations/Wrappers/Wrappers.constants'import {- getAnalyticsBucketFDWName,+ getAnalyticsBucketFDWServerName,getAnalyticsBucketS3KeyName,} from '@/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/AnalyticsBucketDetails.utils'import {@@ -49,15 +49,13 @@ export const useIcebergWrapperCreateMutation = () => {description: getAnalyticsBucketS3KeyName(bucketName),})- const wrapperName = getAnalyticsBucketFDWName(bucketName)-const params: FDWCreateVariables = {projectRef: project?.ref,connectionString: project?.connectionString,wrapperMeta: wrapperMeta!,formState: {- wrapper_name: wrapperName,- server_name: `${wrapperName}_server`,+ wrapper_name: wrapperMeta!.name,+ server_name: getAnalyticsBucketFDWServerName(bucketName),vault_aws_access_key_id: createS3KeyData?.access_key,vault_aws_secret_access_key: createS3KeyData?.secret_key,vault_token: apiKey,diff --git a/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts b/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.tsindex c77b8c329a6..5261fa57141 100644--- a/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts+++ b/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts@@ -6,7 +6,6 @@ import { useS3AccessKeyCreateMutation } from './s3-access-key-create-mutation'import { WRAPPERS } from '@/components/interfaces/Integrations/Wrappers/Wrappers.constants'import { getVectorURI } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.utils'import {- getVectorBucketFDWName,getVectorBucketFDWServerName,getVectorBucketS3KeyName,} from '@/components/interfaces/Storage/VectorBuckets/VectorBuckets.utils'@@ -74,7 +73,6 @@ export const useS3VectorsWrapperCreateMutation = () => {)}- const wrapperName = getVectorBucketFDWName(bucketName)const serverName = getVectorBucketFDWServerName(bucketName)const params: FDWCreateVariables = {@@ -82,7 +80,7 @@ export const useS3VectorsWrapperCreateMutation = () => {connectionString: project?.connectionString,wrapperMeta: wrapperMeta!,formState: {- wrapper_name: wrapperName,+ wrapper_name: wrapperMeta!.name,server_name: serverName,vault_access_key_id: accessKey,vault_secret_access_key: secretKey,diff --git a/apps/studio/data/vault/vault-secrets-query.ts b/apps/studio/data/vault/vault-secrets-query.tsindex 66601ab0287..d189fe155a9 100644--- a/apps/studio/data/vault/vault-secrets-query.ts+++ b/apps/studio/data/vault/vault-secrets-query.ts@@ -9,7 +9,7 @@ import type { ResponseError, UseCustomQueryOptions, VaultSecret } from '@/types'export const getVaultSecretsSql = () => {const sql = new Query().from('secrets', 'vault')- .select(safeSql`id,name,description,secret,created_at,updated_at`)+ .select(safeSql`id,key_id,name,description,secret,created_at,updated_at`).toSql()return sqldiff --git a/apps/studio/types/ui.ts b/apps/studio/types/ui.tsindex e32a8831f10..924fbd19a9d 100644--- a/apps/studio/types/ui.ts+++ b/apps/studio/types/ui.ts@@ -27,6 +27,7 @@ export interface ChartIntervals {export interface VaultSecret {id: string+ key_id: string | nullname: stringdescription: stringsecret: stringdiff --git a/e2e/studio/features/wrappers.spec.ts b/e2e/studio/features/wrappers.spec.tsindex 49d098fb9a8..38b21e7a0a4 100644--- a/e2e/studio/features/wrappers.spec.ts+++ b/e2e/studio/features/wrappers.spec.ts@@ -28,7 +28,7 @@ testRunner('Stripe', () => {failOnStatusCode: true,data: {query: `- drop foreign data wrapper if exists ${wrapperName} cascade;+ drop server if exists ${wrapperName} cascade;delete from vault.secrets where name = '${wrapperName}_api_key_id';drop schema ${schemaName} cascade;`,},@@ -36,9 +36,9 @@ testRunner('Stripe', () => {})await page.goto(toUrl(`/project/${ref}/integrations/stripe_wrapper/overview`))- await page.getByRole('button', { name: 'Add new wrapper' }).click()+ await page.getByRole('link', { name: 'Add new wrapper' }).click()- await page.getByRole('textbox', { name: 'Wrapper Name' }).fill(wrapperName)+ await page.getByRole('textbox', { name: 'Server Name' }).fill(wrapperName)await page.getByRole('textbox', { name: 'Stripe Secret Key' }).fill('my secret')await page.getByRole('radio', { name: 'Schema' }).click()await page@@ -69,7 +69,7 @@ testRunner('Stripe', () => {failOnStatusCode: true,data: {query: `- drop foreign data wrapper if exists ${wrapperName} cascade;+ drop server if exists ${wrapperName} cascade;delete from vault.secrets where name = '${wrapperName}_api_key_id';drop table if exists public.${tableName};`,},@@ -77,9 +77,9 @@ testRunner('Stripe', () => {})await page.goto(toUrl(`/project/${ref}/integrations/stripe_wrapper/overview`))- await page.getByRole('button', { name: 'Add new wrapper' }).click()+ await page.getByRole('link', { name: 'Add new wrapper' }).click()- await page.getByRole('textbox', { name: 'Wrapper Name' }).fill(wrapperName)+ await page.getByRole('textbox', { name: 'Server Name' }).fill(wrapperName)await page.getByRole('textbox', { name: 'Stripe Secret Key' }).fill('my secret')await page.getByRole('button', { name: 'Add foreign table' }).click()await page.getByRole('combobox').click()@@ -112,7 +112,7 @@ testRunner('S3 Wrapper', () => {failOnStatusCode: true,data: {query: `- drop foreign data wrapper if exists ${wrapperName} cascade;+ drop server if exists ${wrapperName} cascade;delete from vault.secrets where name = '${wrapperName}_vault_access_key_id';delete from vault.secrets where name = '${wrapperName}_vault_secret_access_key';drop table if exists public.${tableName};`,@@ -121,9 +121,9 @@ testRunner('S3 Wrapper', () => {})await page.goto(toUrl(`/project/${ref}/integrations/s3_wrapper/overview`))- await page.getByRole('button', { name: 'Add new wrapper' }).click()+ await page.getByRole('link', { name: 'Add new wrapper' }).click()- await page.getByRole('textbox', { name: 'Wrapper Name' }).fill(wrapperName)+ await page.getByRole('textbox', { name: 'Server Name' }).fill(wrapperName)await page.getByRole('textbox', { name: 'Access Key ID' }).fill('s3 access id')await page.getByRole('textbox', { name: 'Access Key Secret' }).fill('s3 access secret')await page.getByRole('button', { name: 'Add foreign table' }).click()diff --git a/packages/pg-meta/src/sql/studio/database/fdw.ts b/packages/pg-meta/src/sql/studio/database/fdw.tsindex dc854a03704..44e37537a51 100644--- a/packages/pg-meta/src/sql/studio/database/fdw.ts+++ b/packages/pg-meta/src/sql/studio/database/fdw.ts@@ -8,6 +8,7 @@ import {} from '../../../pg-format'type SimplifiedWrapperMeta = {+ name: stringhandlerName: stringvalidatorName: stringserver: { options: { name: string; encrypted: boolean }[] }@@ -255,6 +256,26 @@ export const getFDWsSql = (): SafeSqlFragment => {return sql}+export function getCreateForeignDataWrapperSql(+ wrapperMeta: SimplifiedWrapperMeta+): SafeSqlFragment {+ return safeSql`+ do $$+ begin+ if not exists (+ select 1 from pg_catalog.pg_foreign_data_wrapper where fdwname = ${literal(wrapperMeta.name)}+ ) then+ execute format(+ 'create foreign data wrapper %I handler %I validator %I',+ ${literal(wrapperMeta.name)},+ ${literal(wrapperMeta.handlerName)},+ ${literal(wrapperMeta.validatorName)}+ );+ end if;+ end $$;+ `+}+export function getCreateFDWSql({wrapperMeta,formState,@@ -270,12 +291,7 @@ export function getCreateFDWSql({}// If mode is skip, the wrapper will skip the last step, binding the schema/tables to foreign data. This could be done later.mode: 'tables' | 'schema' | 'skip'- tables: {- is_new_schema: boolean- schema_name: string- table_name: string- columns: { name: string; type: string }[]- }[]+ tables: WrapperFormTable[]sourceSchema: stringtargetSchema: stringschemaOptions?: SafeSqlFragment[]@@ -287,17 +303,11 @@ export function getCreateFDWSql({'\n')- const createWrapperSql = safeSql`- create foreign data wrapper ${ident(formState.wrapper_name)}- handler ${ident(wrapperMeta.handlerName)}- validator ${ident(wrapperMeta.validatorName)};- `-const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)const unencryptedOptions = wrapperMeta.server.options.filter((option) => !option.encrypted)const createEncryptedKeysSqlArray = encryptedOptions.map((option) => {- const key = `${formState.wrapper_name}_${option.name}`+ const key = `${formState.server_name}_${option.name}`const quotedValue = literal(formState[option.name] || '')return safeSql`@@ -359,9 +369,9 @@ export function getCreateFDWSql({encryptedOptions.map((option) => safeSql`if is_using_old_wrappers then- select id into ${ident(`v_${option.name}`)} from pgsodium.valid_key where name = ${literal(`${formState.wrapper_name}_${option.name}`)} limit 1;+ select id into ${ident(`v_${option.name}`)} from pgsodium.valid_key where name = ${literal(`${formState.server_name}_${option.name}`)} limit 1;else- select id into ${ident(`v_${option.name}`)} from vault.secrets where name = ${literal(`${formState.wrapper_name}_${option.name}`)} limit 1;+ select id into ${ident(`v_${option.name}`)} from vault.secrets where name = ${literal(`${formState.server_name}_${option.name}`)} limit 1;end if;`),@@ -399,8 +409,6 @@ export function getCreateFDWSql({const sql = safeSql`${newSchemasSql}- ${createWrapperSql}-${createEncryptedKeysSql}${createServerSql}@@ -417,31 +425,33 @@ export const getDeleteFDWSql = ({wrapper,wrapperMeta,}: {- wrapper: { id: number; name: string; server_name: string }+ wrapper: { id: number; name: string; server_name: string; server_options?: string[] | null }wrapperMeta: SimplifiedWrapperMeta}): SafeSqlFragment => {const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)+ const currentServerOptions = parseOptionsArray(wrapper.server_options)- const deleteEncryptedSecretsSqlArray = encryptedOptions.map((option) => {- const key = `${wrapper.name}_${option.name}`+ // Secrets are looked up by the id already stored in the server's own option+ // value, never by a guessed name - the naming convention for new secrets has+ // changed more than once across this feature's history, but the stored id is+ // stable regardless of when the wrapper was created.+ const deleteEncryptedSecretsSqlArray = encryptedOptions+ .filter((option) => currentServerOptions[option.name] !== undefined)+ .map((option) => {+ const existingSecretId = currentServerOptions[option.name]- return safeSql`- do $$- begin- if not exists (- select 1 from pg_catalog.pg_foreign_data_wrapper where fdwname = ${literal(wrapper.name)}- ) then+ return safeSql`+ do $$+ beginif ${isUsingOldWrappersSql} then- delete from vault.secrets where key_id = (select id from pgsodium.valid_key where name = ${literal(key)});-- delete from pgsodium.key where name = ${literal(key)};+ delete from vault.secrets where key_id = ${literal(existingSecretId)};+ delete from pgsodium.key where id = ${literal(existingSecretId)};else- delete from vault.secrets where name = ${literal(key)};+ delete from vault.secrets where id = ${literal(existingSecretId)}::uuid;end if;- end if;- end $$;- `- })+ end $$;+ `+ })const deleteEncryptedSecretsSql = joinSqlFragments(deleteEncryptedSecretsSqlArray, '\n')@@ -500,29 +510,18 @@ export const getUpdateFDWSql = ({formState: { [k: string]: string }tables: WrapperFormTable[]}): SafeSqlFragment => {- const ensureWrapperIsNotSharedSql = safeSql`- do $$- begin- if exists (- select 1- from pg_catalog.pg_foreign_server s- join pg_catalog.pg_foreign_data_wrapper w on w.oid = s.srvfdw- where w.fdwname = ${literal(wrapper.name)}- and s.srvname <> ${literal(wrapper.server_name)}- ) then- raise exception 'This wrapper is used by another server and cannot be edited here.';- end if;- end $$;- `-- const nameChanged = formState.wrapper_name !== wrapper.name- const renameWrapperSql = nameChanged- ? safeSql`alter foreign data wrapper ${ident(wrapper.name)} rename to ${ident(formState.wrapper_name)};`+ // wrapperMeta.name is fixed per wrapper type and shared across every server+ // that uses it, so it's never user-editable here - only the server itself+ // (formState.server_name / wrapper.server_name) can be configured per connection.+ const newServerName = formState.server_name || wrapper.server_name+ const isRenamingServer = newServerName !== wrapper.server_name++ // Runs before every other statement so the rest of this transaction can+ // target the server by its new name.+ const renameServerSql = isRenamingServer+ ? safeSql`alter server ${ident(wrapper.server_name)} rename to ${ident(newServerName)};`: safeSql``- // formState.server_name is never actually re-derived from wrapper_name before- // submit (see EditWrapperSheet), so the server itself is never renamed here -- // wrapper.server_name (the real, current name) is the only name we alter/target.const encryptedOptions = wrapperMeta.server.options.filter((option) => option.encrypted)const unencryptedOptions = wrapperMeta.server.options.filter((option) => !option.encrypted)const currentServerOptions = parseOptionsArray(wrapper.server_options)@@ -548,11 +547,10 @@ export const getUpdateFDWSql = ({for (const option of encryptedOptions) {const existingSecretId = currentServerOptions[option.name]const newValue = formState[option.name]- const newSecretName = `${formState.wrapper_name}_${option.name}`+ const newSecretName = `${newServerName}_${option.name}`if (newValue && existingSecretId !== undefined) {- // Secret already exists: update its value (and name, in case the wrapper- // was renamed) in place instead of deleting and recreating it.+ // Secret already exists: update its value in place instead of deleting and recreating it.encryptedOptionSqlArray.push(safeSql`do $$declare@@ -604,7 +602,7 @@ export const getUpdateFDWSql = ({select id::text into v_secret_ref from vault.secrets where name = ${literal(newSecretName)} limit 1;end if;- execute format('alter server ${ident(wrapper.server_name)} options (add ${ident(option.name)} %L)', v_secret_ref);+ execute format('alter server ${ident(newServerName)} options (add ${ident(option.name)} %L)', v_secret_ref);end $$;`)} else if (!newValue && existingSecretId !== undefined) {@@ -627,7 +625,7 @@ export const getUpdateFDWSql = ({const alterServerOptionsSql =serverOptionClauses.length > 0? safeSql`- alter server ${ident(wrapper.server_name)}+ alter server ${ident(newServerName)}options (${joinSqlFragments(serverOptionClauses, ', ')});`: safeSql``@@ -655,7 +653,7 @@ export const getUpdateFDWSql = ({'\n')const createTablesSql = joinSqlFragments(- tablesToCreate.map((table) => buildCreateForeignTableSql(table, wrapper.server_name)),+ tablesToCreate.map((table) => buildCreateForeignTableSql(table, newServerName)),'\n')const dropTablesSql = joinSqlFragments(@@ -676,8 +674,7 @@ export const getUpdateFDWSql = ({)const sql = safeSql`- ${ensureWrapperIsNotSharedSql}- ${renameWrapperSql}+ ${renameServerSql}${alterServerOptionsSql}${encryptedOptionsSql}${newSchemasSql}diff --git a/packages/pg-meta/test/sql/studio/fdw.test.ts b/packages/pg-meta/test/sql/studio/fdw.test.tsindex b850337a672..a317d47ed81 100644--- a/packages/pg-meta/test/sql/studio/fdw.test.ts+++ b/packages/pg-meta/test/sql/studio/fdw.test.ts@@ -19,6 +19,7 @@ test('unencrypted server option values are passed as format() %L arguments', ()const sql = getCreateFDWSql({...baseArgs,wrapperMeta: {+ name: 'wasm_fdw',handlerName: 'wasm_fdw_handler',validatorName: 'wasm_fdw_validator',server: { options: [{ name: 'api_key', encrypted: false }] },@@ -43,6 +44,7 @@ test('encrypted server options still resolve their value through Vault unchangedconst sql = getCreateFDWSql({...baseArgs,wrapperMeta: {+ name: 'wasm_fdw',handlerName: 'wasm_fdw_handler',validatorName: 'wasm_fdw_validator',server: { options: [{ name: 'api_secret', encrypted: true }] },@@ -57,8 +59,14 @@ test('encrypted server options still resolve their value through Vault unchangedtest('deleting a wrapper row drops its server and preserves shared wrapper dependencies', () => {const sql = getDeleteFDWSql({- wrapper: { id: 42, name: 'bigquery_fdw', server_name: 'selected_bigquery_server' },+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'selected_bigquery_server',+ server_options: ['sa_key_id=123e4567-e89b-12d3-a456-426614174000'],+ },wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'sa_key_id', encrypted: true }] },@@ -73,10 +81,63 @@ test('deleting a wrapper row drops its server and preserves shared wrapper depenexpect(sql).toContain("where w.fdwname = 'bigquery_fdw'")expect(sql).toContain("execute format('drop foreign data wrapper if exists %I cascade'")expect(sql).not.toContain('drop foreign data wrapper if exists "bigquery_fdw" cascade')- expect(sql).toContain("where fdwname = 'bigquery_fdw'")+ // Secrets are deleted by the id already stored on the server's own option+ // value - never by a guessed name, since that naming convention has changed+ // more than once across this feature's history (see next two tests).+ expect(sql).toContain(+ "delete from vault.secrets where id = '123e4567-e89b-12d3-a456-426614174000'::uuid"+ )+ expect(sql).toContain(+ "delete from vault.secrets where key_id = '123e4567-e89b-12d3-a456-426614174000'"+ )+ expect(sql).not.toContain('where name =')+})++test('skips secret cleanup entirely when an encrypted option was never set', () => {+ const sql = getDeleteFDWSql({+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'selected_bigquery_server',+ server_options: [],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [{ name: 'sa_key_id', encrypted: true }] },+ },+ })++ expect(sql).not.toContain('vault.secrets')+ expect(sql).not.toContain('pgsodium')+})++test('secret cleanup is deterministic regardless of which era the wrapper was created in', () => {+ // Older wrappers may have named their secrets after the FDW or a+ // wrapper_name-based convention that no longer exists in the app - this must+ // not matter, since cleanup never guesses a name.+ const sql = getDeleteFDWSql({+ wrapper: {+ id: 42,+ name: 'some_legacy_custom_fdw_name',+ server_name: 'some_legacy_custom_fdw_name_server',+ server_options: ['sa_key_id=123e4567-e89b-12d3-a456-426614174000'],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [{ name: 'sa_key_id', encrypted: true }] },+ },+ })++ expect(sql).toContain(+ "delete from vault.secrets where id = '123e4567-e89b-12d3-a456-426614174000'::uuid"+ )})-test('editing a shared wrapper fails before any other statement runs', () => {+test('editing a server does not raise even when other servers share the same FDW', () => {const sql = getUpdateFDWSql({wrapper: {id: 42,@@ -85,6 +146,7 @@ test('editing a shared wrapper fails before any other statement runs', () => {server_options: ['project_id=old-project'],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'project_id', encrypted: false }] },@@ -97,8 +159,13 @@ test('editing a shared wrapper fails before any other statement runs', () => {tables: [],})- expect(sql).toContain("s.srvname <> 'selected_bigquery_server'")- expect(sql.indexOf('raise exception')).toBeLessThan(sql.indexOf('alter server'))+ // A server can be edited regardless of whether other servers share its FDW -+ // the update only ever targets this server's own name, options, and tables.+ expect(sql).not.toContain('raise exception')+ expect(sql).not.toContain('cannot be edited here')+ expect(sql).toContain(+ "alter server selected_bigquery_server\n options (set project_id 'new-project')"+ )})test('updating a wrapper alters the server and FDW instead of dropping and recreating them', () => {@@ -111,6 +178,7 @@ test('updating a wrapper alters the server and FDW instead of dropping and recretables: [],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'project_id', encrypted: false }] },@@ -131,29 +199,62 @@ test('updating a wrapper alters the server and FDW instead of dropping and recreexpect(sql).not.toContain('create foreign data wrapper')})-test('renaming the wrapper name only renames the FDW, not the server', () => {+test('the FDW is never renamed or recreated, since it is shared across every server of its type', () => {const sql = getUpdateFDWSql({wrapper: {id: 42,- name: 'old_wrapper',- server_name: 'old_wrapper_server',+ name: 'bigquery_fdw',+ server_name: 'bigquery_server',server_options: [],tables: [],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [] },},formState: {- wrapper_name: 'new_wrapper',- server_name: 'old_wrapper_server',+ wrapper_name: 'bigquery_fdw',+ server_name: 'bigquery_server',},tables: [],})- expect(sql).toContain('alter foreign data wrapper old_wrapper rename to new_wrapper')- expect(sql).not.toContain('rename to new_wrapper_server')+ expect(sql).not.toContain('rename to')+ expect(sql).not.toContain('create foreign data wrapper')+ expect(sql).not.toContain('drop foreign data wrapper')+})++test('renaming a server emits a rename statement before any clause targeting the new name', () => {+ const sql = getUpdateFDWSql({+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'old_server_name',+ server_options: ['project_id=old-project'],+ tables: [],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [{ name: 'project_id', encrypted: false }] },+ },+ formState: {+ wrapper_name: 'bigquery_fdw',+ server_name: 'new_server_name',+ project_id: 'new-project',+ },+ tables: [],+ })++ expect(sql).toContain('alter server old_server_name rename to new_server_name')+ expect(sql).toContain(+ "alter server new_server_name\n options (set project_id 'new-project')"+ )+ expect(sql).not.toContain('alter server old_server_name\n options')+ expect(sql.indexOf('rename to')).toBeLessThan(sql.indexOf('options (set project_id'))})test('adding a server option not previously set uses ADD, not SET', () => {@@ -166,6 +267,7 @@ test('adding a server option not previously set uses ADD, not SET', () => {tables: [],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'project_id', encrypted: false }] },@@ -191,6 +293,7 @@ test('clearing a server option uses DROP', () => {tables: [],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'project_id', encrypted: false }] },@@ -216,6 +319,7 @@ test('an encrypted option that already has a secret is updated in place via vaultables: [],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'sa_key_id', encrypted: true }] },@@ -258,6 +362,7 @@ test('foreign table diffing: creates new tables, drops removed tables, and skips],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [] },@@ -308,6 +413,7 @@ test('foreign table diffing: retyping a column drops and re-adds it, since ALTER],},wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [] },@@ -334,6 +440,7 @@ test('editing an existing foreign table excludes catalog fields from its optionsconst sql = getUpdateFDWSql({wrapper: { id: 42, name: 'bigquery_fdw', server_name: 'bigquery_server' },wrapperMeta: {+ name: 'bigquery_fdw',handlerName: 'big_query_fdw_handler',validatorName: 'big_query_fdw_validator',server: { options: [{ name: 'project_id', encrypted: false }] },