The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Joshenlim/fe 4509 fdw general UI consolidation and refactor (#51079)
Joshen Lim838fcaaa8954
diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsxindex 0cb3c092324..c8a1bf33f88 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/CreateIcebergWrapperSheet.tsx@@ -204,7 +204,6 @@ export const CreateIcebergWrapperSheet = ({wrapperMeta,formState: {...formValues,- wrapper_name: wrapperMeta.name,supabase_target_schema: values.target_schema,},mode: 'schema',diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsxindex e2427d2ec6c..75d26e58a82 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/CreateWrapperSheet.tsx@@ -1,7 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import { useQueryClient } from '@tanstack/react-query'-import { Edit, Trash } from 'lucide-react'-import { useEffect, useMemo, useState } from 'react'+import { useEffect, useMemo } from 'react'import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form'import { toast } from 'sonner'import {@@ -23,6 +22,7 @@ import { Admonition } from 'ui-patterns/Admonition'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import * as z from 'zod'+import { ForeignTablesSelector } from './ForeignTablesSelector'import { InputField } from './InputField'import { WrapperMeta } from './Wrappers.types'import {@@ -30,14 +30,11 @@ import {getRequiredExtensionsToInstall,getWrapperCreationFormSchema,hasForeignSchemaSupport,- NewTable,} from './Wrappers.utils'-import WrapperTableEditor from './WrapperTableEditor'import { useIsMarketplaceEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { 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,@@ -96,7 +93,6 @@ export const CreateWrapperSheet = ({})const initialValues = {- wrapper_name: wrapperMeta.name,server_name: '',mode: wrapperMeta.tables.length > 0 ? 'tables' : 'schema',source_schema: wrapperMeta.sourceSchemaOption?.defaultValue ?? '',@@ -121,19 +117,12 @@ export const CreateWrapperSheet = ({fields: tablesField,append: appendTable,remove: removeTable,- insert: insertTable,+ update: updateTable,} = useFieldArray({control: form.control,name: 'tables',})- const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(- undefined- )- const [selectedTableFieldIndex, setSelectedTableFieldIndex] = useState<number | undefined>(- undefined- )-const { mutateAsync: enableExtension } = useDatabaseExtensionEnableMutation({ onError: () => {} })const { mutateAsync: createSchema } = useSchemaCreateMutation({ onError: () => {} })const { mutateAsync: createFDW } = useFDWCreateMutation({ onError: () => {} })@@ -159,17 +148,6 @@ export const CreateWrapperSheet = ({if (failure) throw new Error((failure as PromiseRejectedResult).reason.message)}- const onUpdateTable = (values: FormattedWrapperTable) => {- if (selectedTableFieldIndex !== undefined) {- removeTable(selectedTableFieldIndex)- insertTable(selectedTableFieldIndex, values)- } else {- appendTable(values)- }- setSelectedTableToEdit(undefined)- setSelectedTableFieldIndex(undefined)- }-const onSubmit: SubmitHandler<FormSchema> = async (values) => {const { mode, tables = [], ...wrapperValues } = valuesif (mode === 'tables' && tables.length === 0) {@@ -220,7 +198,6 @@ export const CreateWrapperSheet = ({wrapperMeta,formState: {...wrapperValues,- wrapper_name: wrapperMeta.name,supabase_target_schema: mode === 'schema' ? wrapperValues.target_schema : undefined,},mode: mode === 'schema' ? (wrapperMeta.sourceSchemaOption ? 'schema' : 'skip') : 'tables',@@ -409,83 +386,16 @@ export const CreateWrapperSheet = ({{mode === 'tables' && (<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 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>- </FormItemLayout>+ <ForeignTablesSelector+ // getWrapperCreationFormSchema's option fields are dynamic (index+ // signature), which defeats RHF's field-array type inference.+ tables={tablesField as unknown as FormattedWrapperTable[]}+ wrapperTables={wrapperMeta.tables}+ errorMessage={errors.tables?.message?.toString()}+ onAppend={appendTable}+ onUpdate={updateTable}+ onRemove={removeTable}+ /></FormSectionContent></FormSection>)}@@ -554,17 +464,6 @@ export const CreateWrapperSheet = ({</form></Form></div>-- <WrapperTableEditor- visible={selectedTableToEdit != null}- tables={wrapperMeta.tables}- onCancel={() => {- setSelectedTableToEdit(undefined)- setSelectedTableFieldIndex(undefined)- }}- onSave={onUpdateTable}- initialData={selectedTableToEdit}- /></>)}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsxindex a3848216e45..355615bc438 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/EditWrapperSheet.tsx@@ -1,13 +1,11 @@import { zodResolver } from '@hookform/resolvers/zod'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 } from 'react-hook-form'import { toast } from 'sonner'import {Button,- cn,Form,FormControl,FormField,@@ -21,6 +19,7 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import * as z from 'zod'+import { ForeignTablesSelector } from './ForeignTablesSelector'import { InputField } from './InputField'import { WrapperMeta } from './Wrappers.types'import {@@ -28,9 +27,7 @@ import {FormattedWrapperTable,formatWrapperTables,getEditionFormSchema,- NewTable,} from './Wrappers.utils'-import WrapperTableEditor from './WrapperTableEditor'import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import {@@ -66,14 +63,8 @@ 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 [isLoadingSecrets, setIsLoadingSecrets] = useState(false)const [isUpdateConfirmationOpen, setIsUpdateConfirmationOpen] = useState(false)const { mutate: updateFDW, isPending: isSaving } = useFDWUpdateMutation({@@ -114,18 +105,9 @@ export const EditWrapperSheet = ({} = useFieldArray({control: form.control,name: 'tables',+ keyName: '_fieldId',})- const onUpdateTable = (values: FormattedWrapperTable) => {- if (selectedTableFieldIndex !== undefined) {- updateTable(selectedTableFieldIndex, values)- } else {- appendTable(values)- }- setSelectedTableToEdit(undefined)- setSelectedTableFieldIndex(undefined)- }-const onSubmit: SubmitHandler<FormSchema> = async (values) => {const { tables } = valuesif (tables.length === 0) {@@ -262,80 +244,16 @@ export const EditWrapperSheet = ({<FormSection><FormSectionContent className="flex flex-col space-y-2" loading={false}>- <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">- <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 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>- </FormItemLayout>+ <ForeignTablesSelector+ // getEditionFormSchema's option fields are dynamic (index signature),+ // which defeats RHF's field-array type inference.+ tables={tablesField as unknown as FormattedWrapperTable[]}+ wrapperTables={wrapperMeta.tables}+ errorMessage={errors.tables?.message?.toString()}+ onAppend={appendTable}+ onUpdate={updateTable}+ onRemove={removeTable}+ /></FormSectionContent></FormSection></div>@@ -378,13 +296,16 @@ export const EditWrapperSheet = ({}}onConfirm={() => {const { tables, ...values } = getValues()+ const sanitizedTables = (tables as Record<string, unknown>[]).map(+ ({ _fieldId, ...table }) => table+ )updateFDW({projectRef: project?.ref,connectionString: project?.connectionString,wrapper,wrapperMeta,formState: values,- tables,+ tables: sanitizedTables,})setIsUpdateConfirmationOpen(false)}}@@ -396,17 +317,6 @@ export const EditWrapperSheet = ({</ConfirmationModal><DiscardChangesConfirmationDialog {...modalProps} />-- <WrapperTableEditor- visible={selectedTableToEdit != null}- tables={wrapperMeta.tables}- onCancel={() => {- setSelectedTableToEdit(undefined)- setSelectedTableFieldIndex(undefined)- }}- onSave={onUpdateTable}- initialData={selectedTableToEdit}- /></>)}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/ForeignTablesSelector.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/ForeignTablesSelector.tsxnew file mode 100644index 00000000000..0c9120d3669--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/Wrappers/ForeignTablesSelector.tsx@@ -0,0 +1,120 @@+import { Edit, Trash } from 'lucide-react'+import { useState } from 'react'+import { Button, cn } from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import type { Table } from './Wrappers.types'+import { FormattedWrapperTable, NewTable } from './Wrappers.utils'+import { WrapperTableEditor } from './WrapperTableEditor'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'++interface ForeignTablesSelectorProps {+ tables: FormattedWrapperTable[]+ wrapperTables: Table[]+ errorMessage?: string+ onAppend: (values: FormattedWrapperTable) => void+ onUpdate: (index: number, values: FormattedWrapperTable) => void+ onRemove: (index: number) => void+}++export const ForeignTablesSelector = ({+ tables,+ wrapperTables,+ errorMessage,+ onAppend,+ onUpdate,+ onRemove,+}: ForeignTablesSelectorProps) => {+ const [selectedTableToEdit, setSelectedTableToEdit] = useState<FormattedWrapperTable | undefined>(+ undefined+ )+ const [selectedTableFieldIndex, setSelectedTableFieldIndex] = useState<number | undefined>(+ undefined+ )++ const onCancelTableEdit = () => {+ setSelectedTableToEdit(undefined)+ setSelectedTableFieldIndex(undefined)+ }++ const onSaveTable = (values: FormattedWrapperTable) => {+ if (selectedTableFieldIndex !== undefined) {+ onUpdate(selectedTableFieldIndex, values)+ } else {+ onAppend(values)+ }+ onCancelTableEdit()+ }++ return (+ <>+ <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',+ tables.length === 0 &&+ '[&>div:last-child]:flex [&>div:last-child]:items-center [&>div:last-child]:justify-end'+ )}+ >+ <div className="flex flex-col gap-y-2">+ {tables.map((table, tableIndex) => (+ <div+ key={`${table.schema_name}.${table.table_name}-${tableIndex}`}+ 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 foreign table' } }}+ />+ <ButtonTooltip+ icon={<Trash />}+ onClick={() => onRemove(tableIndex)}+ tooltip={{ content: { side: 'bottom', text: 'Remove foreign table' } }}+ />+ </div>+ </div>+ ))}++ <div className="flex justify-end">+ <Button+ onClick={() => {+ setSelectedTableFieldIndex(undefined)+ setSelectedTableToEdit(NewTable)+ }}+ >+ Add foreign table+ </Button>+ </div>++ {tables.length === 0 && errorMessage && (+ <p className="text-sm text-right text-red-900">{errorMessage}</p>+ )}+ </div>+ </FormItemLayout>++ <WrapperTableEditor+ visible={selectedTableToEdit != null}+ tables={wrapperTables}+ onCancel={onCancelTableEdit}+ onSave={onSaveTable}+ initialData={selectedTableToEdit}+ />+ </>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsxindex 5a30aad2341..bb13873456f 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperRow.tsx@@ -63,10 +63,15 @@ export const WrapperRow = ({ wrapper }: WrapperRowProps) => {<TableCell className="space-y-2 p-4!">{_tables?.map((table) => {- const target = table.table ?? table.object ?? table.src_key+ const target =+ (table.table as string | undefined) ??+ (table.object as string | undefined) ??+ (table.src_key as string | undefined) ??+ table.table_name+ const tableId = table.id as stringreturn (- <div key={table.id} className="flex items-center">+ <div key={tableId} className="flex items-center"><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' })}@@ -83,7 +88,7 @@ export const WrapperRow = ({ wrapper }: WrapperRowProps) => {<ChevronRight size={12} strokeWidth={1.5} className="text-foreground-lighter/50" /></Badge>- <Link href={`/project/${ref}/editor/${table.id}`}>+ <Link href={`/project/${ref}/editor/${tableId}`}><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>diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsxindex 3e5ca9aeffc..5d08a92ad6f 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx+++ b/apps/studio/components/interfaces/Integrations/Wrappers/WrapperTableEditor.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import { Check, ChevronsUpDown, XIcon } from 'lucide-react'-import { useEffect, useId, useMemo, useState } from 'react'+import { useEffect, useId, useMemo, useRef, useState } from 'react'import {Control,FieldValues,@@ -33,7 +33,13 @@ import {SelectSeparator,SelectTrigger,SelectValue,- SidePanel,+ Separator,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetSection,+ SheetTitle,} from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import {@@ -49,11 +55,12 @@ import * as z from 'zod'import { ColumnType } from './ColumnType'import type { AvailableColumn, Table, TableOption } from './Wrappers.types'import { getTableFormSchema } from './Wrappers.utils'-import { ActionBar } from '@/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar'import { useSchemasQuery } from '@/data/database/schemas-query'import { useSchemasFilteredForHighAvailability } from '@/hooks/misc/useHighAvailability'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+const FORM_ID = 'wrapper-table-editor-form'+export type WrapperTableEditorProps = {visible: booleanonCancel: () => void@@ -63,7 +70,7 @@ export type WrapperTableEditorProps = {initialData: any}-const WrapperTableEditor = ({+export const WrapperTableEditor = ({visible,onCancel,onSave,@@ -74,12 +81,6 @@ const WrapperTableEditor = ({const listboxId = useId()const [selectedTableIndex, setSelectedTableIndex] = useState<string>('')- useEffect(() => {- if (initialData && Object.keys(initialData).length > 0) {- setSelectedTableIndex(String(initialData.index))- }- }, [initialData])-const selectedTable = selectedTableIndex === '' ? undefined : tables[parseInt(selectedTableIndex)]const handleCancel = () => {@@ -97,92 +98,112 @@ const WrapperTableEditor = ({setSelectedTableIndex('')}+ useEffect(() => {+ if (initialData && Object.keys(initialData).length > 0) {+ setSelectedTableIndex(String(initialData.index))+ }+ }, [initialData])+return (- <SidePanel- key="WrapperTableEditor"- size="medium"- visible={visible}- onCancel={handleCancel}- header={<span>Edit foreign table</span>}- customFooter={- <ActionBar- backButtonLabel="Cancel"- applyButtonLabel="Save"- formId="wrapper-table-editor-form"- closePanel={handleCancel}- />- }- >- <SidePanel.Content>- <div className="my-4 flex flex-col gap-y-6">- <div className="flex flex-col gap-y-2">- <Label className="text-foreground-light">Select a target the table will point to</Label>- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <Button- role="combobox"- aria-expanded={open}- aria-controls={listboxId}- className={cn(- 'w-full justify-between',- !selectedTableIndex && 'text-muted-foreground'- )}- size="small"- iconRight={- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" strokeWidth={1} />- }- >- {!!selectedTableIndex ? tables[Number(selectedTableIndex)].label : '---'}- </Button>- </PopoverTrigger>- <PopoverContent id={listboxId} className="p-0" sameWidthAsTrigger>- <Command>- <CommandInput placeholder="Find a table..." />- <CommandList>- <CommandEmpty>No targets found</CommandEmpty>- <CommandGroup>- <ScrollArea className={(tables ?? []).length > 7 ? 'h-[200px]' : ''}>- {(tables ?? []).map((table, i) => (- <CommandItem- key={table.label}- className="cursor-pointer flex items-center justify-between space-x-2 w-full"- onSelect={() => {- setSelectedTableIndex(String(i))- setOpen(false)- }}- onClick={() => {- setSelectedTableIndex(String(i))- setOpen(false)- }}- >- <div className="space-y-1">- <p>{table.label}</p>- <p className="text-foreground-lighter">{table.description}</p>- </div>- {String(i) === selectedTableIndex && (- <Check className={cn('mr-2 h-4 w-4')} />- )}- </CommandItem>- ))}- </ScrollArea>- </CommandGroup>- </CommandList>- </Command>- </PopoverContent>- </Popover>- </div>+ <Sheet open={visible} onOpenChange={(open) => !open && handleCancel()}>+ <SheetContent size="default" className="flex flex-col h-full">+ <SheetHeader>+ <SheetTitle>Edit foreign table</SheetTitle>+ </SheetHeader>+ <SheetSection className="grow overflow-y-auto p-0">+ <div>+ <div className="px-5 pb-5 flex flex-col gap-y-2">+ <Label className="text-foreground-light">+ Select a target the table will point to+ </Label>+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <Button+ role="combobox"+ aria-expanded={open}+ aria-controls={listboxId}+ className={cn(+ 'w-full justify-between',+ !selectedTableIndex && 'text-muted-foreground'+ )}+ size="small"+ iconRight={+ <ChevronsUpDown+ className="ml-2 h-4 w-4 shrink-0 opacity-50"+ strokeWidth={1}+ />+ }+ >+ {!!selectedTableIndex ? tables[Number(selectedTableIndex)].label : '---'}+ </Button>+ </PopoverTrigger>+ <PopoverContent id={listboxId} className="p-0" sameWidthAsTrigger>+ <Command>+ <CommandInput placeholder="Find a table..." />+ <CommandList>+ <CommandEmpty>No targets found</CommandEmpty>+ <CommandGroup>+ <ScrollArea className={(tables ?? []).length > 7 ? 'h-[200px]' : ''}>+ {(tables ?? []).map((table, i) => (+ <CommandItem+ key={table.label}+ className="cursor-pointer flex items-center justify-between space-x-2 w-full"+ onSelect={() => {+ setSelectedTableIndex(String(i))+ setOpen(false)+ }}+ onClick={() => {+ setSelectedTableIndex(String(i))+ setOpen(false)+ }}+ >+ <div className="space-y-1">+ <p>{table.label}</p>+ <p className="text-foreground-lighter">{table.description}</p>+ </div>+ {String(i) === selectedTableIndex && (+ <Check className={cn('mr-2 h-4 w-4')} />+ )}+ </CommandItem>+ ))}+ </ScrollArea>+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>- {selectedTable && (- <TableForm table={selectedTable} onSubmit={onSubmit} initialData={initialData} />- )}- </div>- </SidePanel.Content>- </SidePanel>+ <Separator />++ {selectedTable && (+ <TableForm+ // A prop change alone won't remount TableForm, so without this+ // key, switching targets would reuse the same instance -+ // leaving its one-time defaults sync (hasSyncedDefaultsRef)+ // and field array permanently stuck on the first target ever+ // selected.+ key={selectedTableIndex}+ table={selectedTable}+ onSubmit={onSubmit}+ initialData={initialData}+ />+ )}+ </div>+ </SheetSection>+ <SheetFooter>+ <Button size="tiny" type="button" onClick={handleCancel}>+ Cancel+ </Button>+ <Button size="tiny" variant="primary" form={FORM_ID} type="submit">+ Save+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>)}-export default WrapperTableEditor-const Option = ({ option, control }: { option: TableOption; control: Control<FieldValues> }) => {if (option.type === 'select') {return (@@ -198,7 +219,6 @@ const Option = ({ option, control }: { option: TableOption; control: Control<Fie<SelectValue placeholder="Select an option" /></SelectTrigger><SelectContent>- <SelectSeparator />{option.options.map((subOption) => (<SelectItem key={subOption.value} value={subOption.value}>{subOption.label}@@ -291,7 +311,6 @@ const TableForm = ({const form = useForm<FormSchema>({defaultValues,resolver: zodResolver(formSchema),- shouldUnregister: true,})const {@@ -305,11 +324,7 @@ const TableForm = ({})const { reset } = form- useEffect(() => {- reset(defaultValues)- // Workaround bug in react-hook-form- replaceColumns(defaultValues.columns ?? [])- }, [reset, replaceColumns, defaultValues])+ const hasSyncedDefaultsRef = useRef(false)const handleSubmit: SubmitHandler<FieldValues> = (values) => {const { schema_name, schema, ...valuesWithoutSchema } = values@@ -332,178 +347,203 @@ const TableForm = ({const { errors } = form.formStateconst schema = useWatch({ name: 'schema', control: form.control })+ useEffect(() => {+ if (isLoading || hasSyncedDefaultsRef.current) return+ hasSyncedDefaultsRef.current = true+ reset(defaultValues)+ // Workaround bug in react-hook-form+ replaceColumns(defaultValues.columns ?? [])+ }, [isLoading, reset, replaceColumns, defaultValues])+return (<Form {...form}><form- id="wrapper-table-editor-form"- onSubmit={form.handleSubmit(handleSubmit)}- className="space-y-4"+ id={FORM_ID}+ onSubmit={(event) => {+ event.stopPropagation()+ form.handleSubmit(handleSubmit)(event)+ }}>{isLoading && <ShimmeringLoader className="py-4" />}- <FormField- control={form.control}- name="schema"- render={({ field }) => (- <FormItemLayout layout="vertical" label="Select a schema for the foreign table">- <FormControl>- <Select- value={field.value}- onValueChange={(schema) => {- field.onChange(schema)- form.resetField('schema_name')- }}- >- <SelectTrigger>- <SelectValue placeholder="Select an option" />- </SelectTrigger>- <SelectContent>- <SelectItem value="custom">Create a new schema</SelectItem>- <SelectSeparator />- {(schemas ?? [])?.map((schema) => {- return (- <SelectItem key={schema.name} value={schema.name}>- {schema.name}- </SelectItem>- )- })}- </SelectContent>- </Select>- </FormControl>- </FormItemLayout>- )}- />- {schema === 'custom' && (+ <div className="flex flex-col gap-y-4 p-5"><FormFieldcontrol={form.control}- name="schema_name"+ name="schema"render={({ field }) => (- <FormItemLayout layout="vertical" label="Schema name">+ <FormItemLayout layout="vertical" label="Select a schema for the foreign table"><FormControl>- <Input {...field} />+ <Select+ value={field.value}+ onValueChange={(schema) => {+ field.onChange(schema)+ form.resetField('schema_name')+ }}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select an option" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="custom">Create a new schema</SelectItem>+ <SelectSeparator />+ {(schemas ?? [])?.map((schema) => {+ return (+ <SelectItem key={schema.name} value={schema.name}>+ {schema.name}+ </SelectItem>+ )+ })}+ </SelectContent>+ </Select></FormControl></FormItemLayout>)}/>- )}- <FormField- control={form.control}- name="table_name"- render={({ field }) => (- <FormItemLayout- layout="vertical"- label="Table name"- description="You can query from this table after the wrapper is enabled."- >- <FormControl>- <Input {...field} />- </FormControl>- </FormItemLayout>+ {schema === 'custom' && (+ <FormField+ control={form.control}+ name="schema_name"+ render={({ field }) => (+ <FormItemLayout layout="vertical" label="Schema name">+ <FormControl>+ <Input {...field} />+ </FormControl>+ </FormItemLayout>+ )}+ />)}- />- {requiredOptions.map((option) => (- <Option key={option.name} option={option} control={form.control} />- ))}- {nonEditableOptions.map((option) => (- <input key={option.name} type="hidden" {...form.register(option.name)} />- ))}- {table.availableColumns != null ? (+<FormFieldcontrol={form.control}- name="selected_columns"- render={() => (+ name="table_name"+ render={({ field }) => (<FormItemLayoutlayout="vertical"- label="Select the columns to be added to your table."+ label="Table name"+ description="You can query from this table after the wrapper is enabled.">- <div>- <MultiSelector- onValuesChange={(selectedColumns) => {- const newColumnFieldsValue: AvailableColumn[] = []-- table.availableColumns!.forEach((availableColumn) => {- if (selectedColumns.includes(availableColumn.name)) {- newColumnFieldsValue.push(availableColumn)- }- })- replaceColumns(newColumnFieldsValue)- }}- values={columnFields.map(- (column) =>- // @ts-expect-error FIXME: cannot make inference work properly- column.name- )}- size="small"- className="w-full"- >- <MultiSelectorTrigger- mode="inline-combobox"- badgeLimit="wrap"- showIcon={false}- deletableBadge- className="w-full"- />- <MultiSelectorContent>- <MultiSelectorList>- {table.availableColumns!.map((availableColumn) => (- <MultiSelectorItem- key={availableColumn.name}- value={availableColumn.name}- >- {availableColumn.name}- </MultiSelectorItem>- ))}- </MultiSelectorList>- </MultiSelectorContent>- </MultiSelector>- </div>+ <FormControl>+ <Input {...field} />+ </FormControl></FormItemLayout>)}/>- ) : (- <div className="flex flex-col gap-y-2">- {columnFields.map((column, columnIndex) => (- <div key={column.id} className="flex items-center gap-x-2">- <FormField- control={form.control}- name={`columns.${columnIndex}.name`}- render={({ field }) => (- <FormItemLayout layout="vertical" label="Name">- <FormControl>- <Input {...field} />- </FormControl>- </FormItemLayout>- )}- />- <ColumnType- control={form.control}- className="w-1/2"- name={`columns.${columnIndex}.type`}- enumTypes={[]}- />- <Button- variant="outline"- icon={<XIcon strokeWidth={1.5} />}- onClick={() => removeColumn(columnIndex)}- className="self-end -translate-y-1.5 px-1.5"- // @ts-expect-error FIXME: cannot make inference work- aria-label={`Remove column ${column.name}`}- />- </div>- ))}- <Button onClick={() => appendColumn({ name: '', type: 'text' })} className="self-start">- Add column- </Button>- {errors.columns != null && errors.columns.message != null && (- <span className="text-red-900 text-sm mt-2">{errors.columns.message.toString()}</span>- )}- </div>- )}- {optionalOptions.map((option) => (- <Option key={option.name} option={option} control={form.control} />- ))}+ {requiredOptions.map((option) => (+ <Option key={option.name} option={option} control={form.control} />+ ))}++ {nonEditableOptions.map((option) => (+ <input key={option.name} type="hidden" {...form.register(option.name)} />+ ))}++ {table.availableColumns != null ? (+ <FormField+ control={form.control}+ name="selected_columns"+ render={() => (+ <FormItemLayout+ layout="vertical"+ label="Select the columns to be added to your table."+ >+ <div>+ <MultiSelector+ onValuesChange={(selectedColumns) => {+ const newColumnFieldsValue: AvailableColumn[] = []++ table.availableColumns!.forEach((availableColumn) => {+ if (selectedColumns.includes(availableColumn.name)) {+ newColumnFieldsValue.push(availableColumn)+ }+ })+ replaceColumns(newColumnFieldsValue)+ }}+ values={columnFields.map(+ (column) =>+ // @ts-expect-error FIXME: cannot make inference work properly+ column.name+ )}+ size="small"+ className="w-full"+ >+ <MultiSelectorTrigger+ mode="inline-combobox"+ badgeLimit="wrap"+ showIcon={false}+ deletableBadge+ className="w-full"+ />+ <MultiSelectorContent>+ <MultiSelectorList>+ {table.availableColumns!.map((availableColumn) => (+ <MultiSelectorItem+ key={availableColumn.name}+ value={availableColumn.name}+ >+ {availableColumn.name}+ </MultiSelectorItem>+ ))}+ </MultiSelectorList>+ </MultiSelectorContent>+ </MultiSelector>+ </div>+ </FormItemLayout>+ )}+ />+ ) : (+ <div className="flex flex-col gap-y-2">+ {columnFields.map((column, columnIndex) => (+ <div key={column.id} className="flex items-center gap-x-2">+ <FormField+ control={form.control}+ name={`columns.${columnIndex}.name`}+ render={({ field }) => (+ <FormItemLayout layout="vertical" label="Name">+ <FormControl>+ <Input {...field} />+ </FormControl>+ </FormItemLayout>+ )}+ />+ <ColumnType+ control={form.control}+ className="w-1/2"+ name={`columns.${columnIndex}.type`}+ enumTypes={[]}+ />+ <Button+ variant="outline"+ icon={<XIcon strokeWidth={1.5} />}+ onClick={() => removeColumn(columnIndex)}+ className="self-end -translate-y-1.5 px-1.5"+ // @ts-expect-error FIXME: cannot make inference work+ aria-label={`Remove column ${column.name}`}+ />+ </div>+ ))}+ <Button+ onClick={() => appendColumn({ name: '', type: 'text' })}+ className="self-start"+ >+ Add column+ </Button>+ {errors.columns != null && errors.columns.message != null && (+ <span className="text-red-900 text-sm mt-2">+ {errors.columns.message.toString()}+ </span>+ )}+ </div>+ )}+ </div>++ <Separator />++ <div className="p-5 flex flex-col gap-y-4">+ {optionalOptions.map((option) => (+ <Option key={option.name} option={option} control={form.control} />+ ))}+ </div></form></Form>)diff --git a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.tsindex 550ff8fc640..b7753dac263 100644--- a/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts+++ b/apps/studio/components/interfaces/Integrations/Wrappers/Wrappers.utils.ts@@ -20,7 +20,7 @@ export const getWrapperCreationFormSchema = (wrapperMeta: WrapperMeta) => {let wrapperSchema = {// Common validation for all wrappersserver_name: z.string().min(1, 'Please provide a name for your server'),- } as Record<string, any>+ } as Record<string, z.ZodTypeAny>// Add wrapper specific optionswrapperMeta.server.options.forEach((option) => {@@ -57,7 +57,7 @@ export const getEditionFormSchema = (wrapperMeta: WrapperMeta) => {tables: z.array(tableSchema, { required_error: 'Please provide at least one table' }).min(1, 'Please provide at least one table'),- } as Record<string, any>+ } as Record<string, z.ZodTypeAny>// Add wrapper specific optionswrapperMeta.server.options.forEach((option) => {@@ -81,7 +81,7 @@ export const getTableFormSchema = (table: Table) => {type: z.string().min(1, 'Required'),})),- } as Record<string, any>+ } as Record<string, z.ZodTypeAny>table.options.forEach((option) => {if (option.required) {@@ -108,6 +108,10 @@ export const getTableFormSchema = (table: Table) => {)}+function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null+}+export const makeValidateRequired = (options: { name: string; required: boolean }[]) => {const requiredOptionsSet = new Set(options.filter((option) => option.required).map((option) => option.name)@@ -118,12 +122,12 @@ export const makeValidateRequired = (options: { name: string; required: boolean)const requiredArrayOptions = Array.from(requiredArrayOptionsSet)- return (values: Record<string, any>) => {+ return (values: Record<string, unknown>) => {const errors = Object.fromEntries(Object.entries(values)- .flatMap(([key, value]) =>+ .flatMap(([key, value]): [string, unknown][] =>Array.isArray(value)- ? [[key, value], ...value.map((v, i) => [`${key}.${i}`, v])]+ ? [[key, value], ...value.map((v, i): [string, unknown] => [`${key}.${i}`, v])]: [[key, value]]).filter(([_key, value]) => {@@ -132,6 +136,7 @@ export const makeValidateRequired = (options: { name: string; required: booleanif (idx !== undefined &&requiredOptionsSet.has(key) &&+ isRecord(value) &&Object.keys(value).some((subKey) => requiredArrayOptionsSet.has(`${key}.${subKey}`))) {const arrayOption = requiredArrayOptions.find((option) => option.startsWith(`${key}.`))@@ -166,7 +171,7 @@ export interface FormattedWrapperTable {schema_name: stringtable_name: stringobject?: string // From options object for Firebase/Stripe- [key: string]: any // For other dynamic options from table.options+ [key: string]: unknown // For other dynamic options from table.options}export const formatWrapperTables = (diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsxindex 06d3ad3744b..45b9684a32d 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx@@ -137,13 +137,13 @@ export const NamespaceWithTables = ({const missingTables = useMemo(() => {return (tablesData || []).filter(- (t) => !tables.find((table) => table.table.split('.')[1] === t)+ (t) => !tables.find((table) => (table.table as string).split('.')[1] === t))}, [tablesData, tables])// Get all tables (connected + missing) for displayconst allTables = useMemo(() => {- const connectedTableNames = tables.map((table) => table.table.split('.')[1])+ const connectedTableNames = tables.map((table) => (table.table as string).split('.')[1])const allTableNames = [...new Set([...connectedTableNames, ...missingTables])]return allTableNames.map((tableName) => ({diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsxindex 3bb5374afb7..a8d50d0cc6f 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx@@ -121,11 +121,11 @@ export const AnalyticBucketDetails = () => {const isPollingForData = pollIntervalNamespaces > 0 || pollIntervalNamespaceTables > 0const namespaces = useMemo(() => {- const fdwNamespaces = wrapperTables.map((t) => t.table.split('.')[0]) as string[]+ const fdwNamespaces = wrapperTables.map((t) => (t.table as string).split('.')[0])const namespaces = uniq([...fdwNamespaces, ...(namespacesData ?? [])])return namespaces.map((namespace) => {- const tables = wrapperTables.filter((t) => t.table.split('.')[0] === namespace)+ const tables = wrapperTables.filter((t) => (t.table as string).split('.')[0] === namespace)const schema = tables[0]?.schemareturn {diff --git a/apps/studio/data/fdw/fdw-delete-mutation.ts b/apps/studio/data/fdw/fdw-delete-mutation.tsindex f7103931b1f..32913f0d968 100644--- a/apps/studio/data/fdw/fdw-delete-mutation.ts+++ b/apps/studio/data/fdw/fdw-delete-mutation.ts@@ -25,7 +25,12 @@ export async function deleteFDW({wrapperMeta,}: FDWDeleteVariables) {const sql = wrapWithTransaction(getDeleteFDWSql({ wrapper, wrapperMeta }))- const { result } = await executeSql({ projectRef, connectionString, sql })+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['delete-fdw'],+ })return result}diff --git a/apps/studio/data/fdw/fdw-update-mutation.ts b/apps/studio/data/fdw/fdw-update-mutation.tsindex 702a47466a3..7887b9e23a2 100644--- a/apps/studio/data/fdw/fdw-update-mutation.ts+++ b/apps/studio/data/fdw/fdw-update-mutation.ts@@ -33,7 +33,12 @@ export async function updateFDW({tables,}: FDWUpdateVariables) {const sql = wrapWithTransaction(getUpdateFDWSql({ wrapper, wrapperMeta, formState, tables }))- const { result } = await executeSql({ projectRef, connectionString, sql })+ const { result } = await executeSql({+ projectRef,+ connectionString,+ sql,+ queryKey: ['update-fdw'],+ })return result}@@ -68,7 +73,7 @@ export const useFDWUpdateMutation = ({async onError(data, variables, context) {if (onError === undefined) {toast.error(- `Failed to update ${variables.wrapper.name} foreign data wrapper: ${data.message}`+ `Failed to update ${variables.wrapperMeta.label} foreign data wrapper: ${data.message}`)} else {onError(data, variables, context)diff --git a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts b/apps/studio/data/storage/iceberg-wrapper-create-mutation.tsindex 22c8db52e16..19288899452 100644--- a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts+++ b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts@@ -54,7 +54,6 @@ export const useIcebergWrapperCreateMutation = () => {connectionString: project?.connectionString,wrapperMeta: wrapperMeta!,formState: {- wrapper_name: wrapperMeta!.name,server_name: getAnalyticsBucketFDWServerName(bucketName),vault_aws_access_key_id: createS3KeyData?.access_key,vault_aws_secret_access_key: createS3KeyData?.secret_key,diff --git a/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts b/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.tsindex 5261fa57141..2cd0385dbb6 100644--- a/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts+++ b/apps/studio/data/storage/s3-vectors-wrapper-create-mutation.ts@@ -80,7 +80,6 @@ export const useS3VectorsWrapperCreateMutation = () => {connectionString: project?.connectionString,wrapperMeta: wrapperMeta!,formState: {- 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-secret-decrypted-value-query.ts b/apps/studio/data/vault/vault-secret-decrypted-value-query.tsindex 304204fcb1b..b2b8238b734 100644--- a/apps/studio/data/vault/vault-secret-decrypted-value-query.ts+++ b/apps/studio/data/vault/vault-secret-decrypted-value-query.ts@@ -89,7 +89,7 @@ export const getDecryptedValues = async () => {const sql = vaultSecretDecryptedValuesQuery(ids)const { result } = await executeSql<{ id: string; decrypted_secret: string }[]>(- { projectRef, connectionString, sql },+ { projectRef, connectionString, sql, queryKey: ['decrypt-secret'] },signal)return result.reduce(diff --git a/apps/studio/routes/__root.tsx b/apps/studio/routes/__root.tsxindex 26bd1707999..de414f0b2b0 100644--- a/apps/studio/routes/__root.tsx+++ b/apps/studio/routes/__root.tsx@@ -420,6 +420,8 @@ function RootComponent() {}function RootDocument({ children }: Readonly<{ children: ReactNode }>) {+ const isTestEnv = process.env.NEXT_PUBLIC_NODE_ENV === 'test'+return (// suppressHydrationWarning is for next-themes: it writes data-theme and// color-scheme onto <html> from localStorage pre-hydration, which the@@ -430,19 +432,21 @@ function RootDocument({ children }: Readonly<{ children: ReactNode }>) {</head><body>{children}- <TanStackDevtools- config={{ position: 'bottom-right' }}- plugins={[- {- name: 'TanStack Router',- render: <TanStackRouterDevtoolsPanel />,- },- {- name: 'TanStack Query',- render: <ReactQueryDevtoolsPanel />,- },- ]}- />+ {!isTestEnv && (+ <TanStackDevtools+ config={{ position: 'bottom-right' }}+ plugins={[+ {+ name: 'TanStack Router',+ render: <TanStackRouterDevtoolsPanel />,+ },+ {+ name: 'TanStack Query',+ render: <ReactQueryDevtoolsPanel />,+ },+ ]}+ />+ )}<Scripts /></body></html>diff --git a/packages/pg-meta/src/sql/studio/database/fdw.ts b/packages/pg-meta/src/sql/studio/database/fdw.tsindex 44e37537a51..dbca21dfaa5 100644--- a/packages/pg-meta/src/sql/studio/database/fdw.ts+++ b/packages/pg-meta/src/sql/studio/database/fdw.ts@@ -5,6 +5,7 @@ import {literal,safeSql,type SafeSqlFragment,+ type SqlFragmentSeparator,} from '../../../pg-format'type SimplifiedWrapperMeta = {@@ -23,6 +24,7 @@ type WrapperExistingTable = {}type WrapperFormTable = {+ id?: string | numberschema_name: stringtable_name: stringcolumns: { name: string; type: string }[]@@ -94,6 +96,20 @@ function getTableOptionsMap(table: Record<string, unknown>): Record<string, stri)}+// Many of this file's SQL fragments are optional (e.g. "only if renaming"),+// but composing them via a fixed multi-line template leaves the template's own+// line breaks behind even when the fragment is empty. Filtering empties out+// before joining keeps the generated SQL free of stray blank lines.+function joinNonEmptyFragments(+ fragments: SafeSqlFragment[],+ separator: SqlFragmentSeparator = '\n'+): SafeSqlFragment {+ return joinSqlFragments(+ fragments.filter((fragment) => fragment.trim().length > 0),+ separator+ )+}+function buildCreateForeignTableSql(table: {schema_name: string@@ -121,8 +137,24 @@ function buildCreateForeignTableSql(`}-function tableKey(schema: string, table: string): string {- return `${schema}.${table}`+function buildRenameForeignTableSql(+ current: WrapperExistingTable,+ desired: WrapperFormTable+): SafeSqlFragment {+ const schemaChanged = desired.schema_name !== current.schema+ const nameChanged = desired.table_name !== current.name++ const setSchemaSql = schemaChanged+ ? safeSql`alter foreign table ${ident(current.schema)}.${ident(current.name)} set schema ${ident(desired.schema_name)};`+ : safeSql``++ // Once SET SCHEMA has run, the table is addressed by its new schema but still its old name.+ const effectiveSchema = schemaChanged ? desired.schema_name : current.schema+ const renameSql = nameChanged+ ? safeSql`alter foreign table ${ident(effectiveSchema)}.${ident(current.name)} rename to ${ident(desired.table_name)};`+ : safeSql``++ return joinNonEmptyFragments([setSchemaSql, renameSql])}// ALTER FOREIGN TABLE doesn't support changing a column's type in place, so a@@ -210,11 +242,7 @@ function buildAlterForeignTableSql(`: safeSql``- return safeSql`- ${dropColumnsSql}- ${addColumnsSql}- ${optionsSql}- `+ return joinNonEmptyFragments([dropColumnsSql, addColumnsSql, optionsSql])}export const getFDWsSql = (): SafeSqlFragment => {@@ -379,7 +407,7 @@ export function getCreateFDWSql({)}execute format(- E'create server ${ident(formState.server_name)} foreign data wrapper ${ident(formState.wrapper_name)} options (${optionsSqlArray});',+ E'create server ${ident(formState.server_name)} foreign data wrapper ${ident(wrapperMeta.name)} options (${optionsSqlArray});',${joinSqlFragments([...encryptedOptions@@ -406,17 +434,16 @@ export function getCreateFDWSql({`}- const sql = safeSql`- ${newSchemasSql}-- ${createEncryptedKeysSql}-- ${createServerSql}-- ${mode === 'tables' ? createTablesSql : safeSql``}-- ${mode === 'schema' ? createImportForeignSchemaSql() : safeSql``}- `+ const sql = joinNonEmptyFragments(+ [+ newSchemasSql,+ createEncryptedKeysSql,+ createServerSql,+ mode === 'tables' ? createTablesSql : safeSql``,+ mode === 'schema' ? createImportForeignSchemaSql() : safeSql``,+ ],+ '\n\n'+ )return sql}@@ -632,19 +659,25 @@ export const getUpdateFDWSql = ({const encryptedOptionsSql = joinSqlFragments(encryptedOptionSqlArray, '\n')const currentTables = wrapper.tables ?? []- const currentTableByKey = new Map(- currentTables.map((table) => [tableKey(table.schema, table.name), table])- )- const desiredTableByKey = new Map(- tables.map((table) => [tableKey(table.schema_name, table.table_name), table])+ const currentTableById = new Map(currentTables.map((table) => [table.id, table]))+ const desiredTableIds = new Set(+ tables.map((table) => table.id).filter((id): id is string | number => id !== undefined))const tablesToCreate = tables.filter(- (table) => !currentTableByKey.has(tableKey(table.schema_name, table.table_name))- )- const tablesToDrop = currentTables.filter(- (table) => !desiredTableByKey.has(tableKey(table.schema, table.name))+ (table) => table.id === undefined || !currentTableById.has(table.id))+ const tablesToDrop = currentTables.filter((table) => !desiredTableIds.has(table.id))+ const matchedTables = tables+ .map((desired) => {+ if (desired.id === undefined) return null+ const current = currentTableById.get(desired.id)+ return current ? { current, desired } : null+ })+ .filter(+ (match): match is { current: WrapperExistingTable; desired: WrapperFormTable } =>+ match !== null+ )const newSchemasSql = joinSqlFragments(tablesToCreate@@ -662,26 +695,27 @@ export const getUpdateFDWSql = ({),'\n')+ const renameTablesSql = joinSqlFragments(+ matchedTables.map(({ current, desired }) => buildRenameForeignTableSql(current, desired)),+ '\n'+ )const alterTablesSql = joinSqlFragments(- tables- .map((desired) => {- const current = currentTableByKey.get(tableKey(desired.schema_name, desired.table_name))- if (!current) return null- return buildAlterForeignTableSql(desired.schema_name, desired.table_name, current, desired)- })- .filter((sql): sql is SafeSqlFragment => sql !== null),+ matchedTables.map(({ current, desired }) =>+ buildAlterForeignTableSql(desired.schema_name, desired.table_name, current, desired)+ ),'\n')- const sql = safeSql`- ${renameServerSql}- ${alterServerOptionsSql}- ${encryptedOptionsSql}- ${newSchemasSql}- ${dropTablesSql}- ${createTablesSql}- ${alterTablesSql}- `+ const sql = joinNonEmptyFragments([+ renameServerSql,+ alterServerOptionsSql,+ encryptedOptionsSql,+ newSchemasSql,+ dropTablesSql,+ createTablesSql,+ renameTablesSql,+ alterTablesSql,+ ])return sql}diff --git a/packages/pg-meta/test/sql/studio/fdw.test.ts b/packages/pg-meta/test/sql/studio/fdw.test.tsindex a317d47ed81..80dd4899a9d 100644--- a/packages/pg-meta/test/sql/studio/fdw.test.ts+++ b/packages/pg-meta/test/sql/studio/fdw.test.ts@@ -373,6 +373,7 @@ test('foreign table diffing: creates new tables, drops removed tables, and skips},tables: [{+ id: 1,schema_name: 'public',table_name: 'unchanged_table',columns: [{ name: 'id', type: 'text' }],@@ -395,6 +396,133 @@ test('foreign table diffing: creates new tables, drops removed tables, and skipsexpect(sql).not.toContain('drop foreign table if exists public.unchanged_table')})+test('foreign table diffing: a table without an id is always treated as new, even if its schema/name match an existing table', () => {+ const sql = getUpdateFDWSql({+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ server_options: [],+ tables: [+ {+ id: 1,+ schema: 'public',+ name: 'orders',+ columns: [{ name: 'id', type: 'text' }],+ options: [],+ },+ ],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [] },+ },+ formState: {+ wrapper_name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ },+ tables: [+ {+ schema_name: 'public',+ table_name: 'orders',+ columns: [{ name: 'id', type: 'text' }],+ is_new_schema: false,+ },+ ],+ })++ expect(sql).toContain('create foreign table public.orders')+ expect(sql).toContain('drop foreign table if exists public.orders')+})++test('foreign table diffing: renaming a table emits an explicit ALTER ... RENAME instead of drop and recreate', () => {+ const sql = getUpdateFDWSql({+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ server_options: [],+ tables: [+ {+ id: 1,+ schema: 'public',+ name: 'accounts',+ columns: [{ name: 'id', type: 'text' }],+ options: [],+ },+ ],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [] },+ },+ formState: {+ wrapper_name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ },+ tables: [+ {+ id: 1,+ schema_name: 'public',+ table_name: 'wot',+ columns: [{ name: 'id', type: 'text' }],+ is_new_schema: false,+ },+ ],+ })++ expect(sql).toContain('alter foreign table public.accounts rename to wot')+ expect(sql).not.toContain('create foreign table')+ expect(sql).not.toContain('drop foreign table')+})++test('foreign table diffing: moving a table to a new schema emits SET SCHEMA before any rename', () => {+ const sql = getUpdateFDWSql({+ wrapper: {+ id: 42,+ name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ server_options: [],+ tables: [+ {+ id: 1,+ schema: 'public',+ name: 'accounts',+ columns: [{ name: 'id', type: 'text' }],+ options: [],+ },+ ],+ },+ wrapperMeta: {+ name: 'bigquery_fdw',+ handlerName: 'big_query_fdw_handler',+ validatorName: 'big_query_fdw_validator',+ server: { options: [] },+ },+ formState: {+ wrapper_name: 'bigquery_fdw',+ server_name: 'bigquery_server',+ },+ tables: [+ {+ id: 1,+ schema_name: 'stripe',+ table_name: 'wot',+ columns: [{ name: 'id', type: 'text' }],+ is_new_schema: false,+ },+ ],+ })++ expect(sql).toContain('alter foreign table public.accounts set schema stripe')+ expect(sql).toContain('alter foreign table stripe.accounts rename to wot')+ expect(sql.indexOf('set schema')).toBeLessThan(sql.indexOf('rename to'))+})+test('foreign table diffing: retyping a column drops and re-adds it, since ALTER COLUMN TYPE is unsupported for foreign tables', () => {const sql = getUpdateFDWSql({wrapper: {@@ -424,6 +552,7 @@ test('foreign table diffing: retyping a column drops and re-adds it, since ALTER},tables: [{+ id: 1,schema_name: 'public',table_name: 'orders',columns: [{ name: 'amount', type: 'numeric' }],