import { zodResolver } from '@hookform/resolvers/zod' import { useQueryClient } from '@tanstack/react-query' import { useEffect } from 'react' import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form' import { toast } from 'sonner' import { Button, cn, Form, FormControl, FormField, Input, RadioGroupStacked, RadioGroupStackedItem, Separator, SheetFooter, SheetHeader, SheetTitle, WarningIcon, } from 'ui' 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 { FormattedWrapperTable, getWrapperCreationFormSchema, hasForeignSchemaSupport, } from './Wrappers.utils' import { RequiredExtensionsSection } from '@/components/interfaces/Integrations/Integration/RequiredExtensionsSection' import { useInstallRequiredExtensions } from '@/components/interfaces/Integrations/Integration/useInstallRequiredExtensions' import { FormSection, FormSectionContent, FormSectionLabel, } from '@/components/ui/Forms/FormSection' import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-extensions-query' import { useSchemaCreateMutation } from '@/data/database/schema-create-mutation' import { invalidateSchemasQuery, useSchemasQuery } from '@/data/database/schemas-query' import { useFDWCreateMutation } from '@/data/fdw/fdw-create-mutation' import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' import type { StudioError } from '@/lib/errors/studio-errors' import { useTrack } from '@/lib/telemetry/track' const FORM_ID = 'create-wrapper-form' export interface CreateWrapperSheetProps { wrapperMeta: WrapperMeta onDirty: (isDirty: boolean) => void onClose: () => void onCloseWithConfirmation: () => void } export const CreateWrapperSheet = ({ wrapperMeta, onDirty, onClose, onCloseWithConfirmation, }: CreateWrapperSheetProps) => { const queryClient = useQueryClient() const { data: project } = useSelectedProjectQuery() const track = useTrack() const { requiredExtensionsToInstall, needsExtensions, isExtensionDataLoading, installRequiredExtensions, } = useInstallRequiredExtensions() const { data: extensions } = useDatabaseExtensionsQuery({ projectRef: project?.ref, connectionString: project?.connectionString, }) const wrappersExtension = extensions?.find((ext) => ext.name === 'wrappers') const hasRequiredVersionForeignSchema = hasForeignSchemaSupport(wrappersExtension) const { data: schemas } = useSchemasQuery({ projectRef: project?.ref!, connectionString: project?.connectionString, }) const initialValues = { server_name: '', mode: wrapperMeta.tables.length > 0 ? 'tables' : 'schema', source_schema: wrapperMeta.sourceSchemaOption?.defaultValue ?? '', target_schema: '', ...Object.fromEntries( wrapperMeta.server.options.map((option) => [option.name, option.defaultValue ?? '']) ), tables: [] as Array, } const formSchema = getWrapperCreationFormSchema(wrapperMeta) type FormSchema = z.infer const form = useForm({ defaultValues: initialValues, resolver: zodResolver(formSchema), }) const { getValues, setError } = form const { errors, isDirty, isSubmitting } = form.formState const { fields: tablesField, append: appendTable, remove: removeTable, update: updateTable, } = useFieldArray({ control: form.control, name: 'tables', }) const { mutateAsync: createSchema } = useSchemaCreateMutation({ onError: () => {} }) const { mutateAsync: createFDW } = useFDWCreateMutation({ onError: () => {} }) const onSubmit: SubmitHandler = async (values) => { const { mode, tables = [], ...wrapperValues } = values if (mode === 'tables' && tables.length === 0) { setError('tables', { type: 'validate', message: 'Please provide at least one table.', }) return } if (mode === 'schema') { const foundSchema = schemas?.find((s) => s.name === wrapperValues.target_schema) if (foundSchema) { setError('target_schema', { type: 'validate', message: 'This schema already exists. Please specify a unique schema name.', }) return } } if (isExtensionDataLoading) return const toastId = toast.loading( needsExtensions ? `Installing extensions ${(requiredExtensionsToInstall ?? []).map((e) => e.name).join(', ')}…` : `Creating ${wrapperMeta.label} wrapper…` ) try { if (needsExtensions) { await installRequiredExtensions() toast.loading(`Creating ${wrapperMeta.label} wrapper…`, { id: toastId }) } if (mode === 'schema') { toast.loading(`Creating schema "${wrapperValues.target_schema}"…`, { id: toastId }) await createSchema({ projectRef: project?.ref, connectionString: project?.connectionString, name: wrapperValues.target_schema, }) toast.loading(`Creating ${wrapperMeta.label} wrapper…`, { id: toastId }) } await createFDW({ projectRef: project?.ref, connectionString: project?.connectionString, wrapperMeta, formState: { ...wrapperValues, supabase_target_schema: mode === 'schema' ? wrapperValues.target_schema : undefined, }, mode: mode === 'schema' ? (wrapperMeta.sourceSchemaOption ? 'schema' : 'skip') : 'tables', tables, sourceSchema: wrapperValues.source_schema, targetSchema: wrapperValues.target_schema, }) const { tables: formTables } = getValues() const hasNewSchema = (formTables as Record[]).some((t) => t.is_new_schema) if (hasNewSchema) invalidateSchemasQuery(queryClient, project?.ref) track('foreign_data_wrapper_created', { wrapperType: wrapperMeta.label }) toast.success(`Successfully created ${wrapperMeta.label} foreign data wrapper`, { id: toastId, }) onClose() form.reset() } catch (error) { toast.error( `Failed to create ${wrapperMeta.label} wrapper: ${(error as StudioError).message}`, { id: toastId } ) } } const mode = useWatch({ name: 'mode', control: form.control }) useEffect(() => { onDirty(isDirty) }, [onDirty, isDirty]) return ( <>
Create a {wrapperMeta.label} wrapper connection
{needsExtensions && ( )}
Server configuration} > ( )} /> {wrapperMeta.label} configuration} > {wrapperMeta.server.options .filter((option) => !option.hidden) .map((option) => ( ))} Data target} > (

Create foreign tables to query data from {wrapperMeta.label}.

{wrapperMeta.tables.length === 0 ? (
This wrapper doesn't support using foreign tables.
) : null}

Create all foreign tables from {wrapperMeta.label} in a specified schema.

{wrapperMeta.canTargetSchema ? ( hasRequiredVersionForeignSchema ? null : (
This feature requires the{' '} wrappers extension to be of minimum version of 0.5.0.
) ) : (
This wrapper doesn't support using a foreign schema.
)}
)} />
{mode === 'tables' && ( )} {mode === 'schema' && ( div>span]:text-balance')} > {wrapperMeta.sourceSchemaOption && !wrapperMeta.sourceSchemaOption?.readOnly && ( // Hide the field if the source schema is read-only )}
)}
) }