// @ts-nocheck import { zodResolver } from '@hookform/resolvers/zod' import { useQueryClient } from '@tanstack/react-query' import { Edit, Trash } from 'lucide-react' import { useEffect, useState } from 'react' import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form' import { toast } from 'sonner' import { Button, Card, CardContent, Form, FormControl, FormField, Input, RadioGroupStacked, RadioGroupStackedItem, SheetFooter, SheetHeader, SheetSection, SheetTitle, WarningIcon, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { PageSection, PageSectionContent, PageSectionDescription, PageSectionMeta, PageSectionSummary, PageSectionTitle, } from 'ui-patterns/PageSection' import * as z from 'zod' import InputField from './InputField' import { WrapperMeta } from './Wrappers.types' import { FormattedWrapperTable, getWrapperCreationFormSchema, NewTable } from './Wrappers.utils' import WrapperTableEditor from './WrapperTableEditor' 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 { useSendEventMutation } from '@/data/telemetry/send-event-mutation' import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization' import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' 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 { data: org } = useSelectedOrganizationQuery() const { mutate: sendEvent } = useSendEventMutation() const [selectedTableToEdit, setSelectedTableToEdit] = useState< FormattedWrapperTable | undefined >() const { data: extensions } = useDatabaseExtensionsQuery({ projectRef: project?.ref, connectionString: project?.connectionString, }) const wrappersExtension = extensions?.find((ext) => ext.name === 'wrappers') // The import foreign schema requires a minimum extension version of 0.5.0 const hasRequiredVersionForeignSchema = wrappersExtension?.installed_version ? wrappersExtension?.installed_version >= '0.5.0' : false const { data: schemas } = useSchemasQuery({ projectRef: project?.ref!, connectionString: project?.connectionString, }) const initialValues = { wrapper_name: '', 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 as any), }) const { getValues, setError } = form const { errors, isDirty, isSubmitting } = form.formState useEffect(() => { onDirty(isDirty) }, [onDirty, isDirty]) const { fields: tablesField, append: appendTable, remove: removeTable, insert: insertTable, } = useFieldArray({ control: form.control, name: 'tables', }) const { mutateAsync: createSchema, isPending: isCreatingSchema } = useSchemaCreateMutation() const onUpdateTable = (values: FormattedWrapperTable) => { if (values.index !== undefined) { removeTable(values.index) insertTable(values.index, values) } else { appendTable(values) } setSelectedTableToEdit(undefined) } const { mutateAsync: createFDW, isPending: isCreatingWrapper } = useFDWCreateMutation({ onSuccess: () => { toast.success(`Successfully created ${wrapperMeta?.label} foreign data wrapper`) const { tables } = getValues() const hasNewSchema = (tables as Record[]).some((table) => table.is_new_schema) if (hasNewSchema) invalidateSchemasQuery(queryClient, project?.ref) onClose() form.reset() }, }) 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 } } try { if (mode === 'schema') { await createSchema({ projectRef: project?.ref, connectionString: project?.connectionString, name: wrapperValues.target_schema, }) } await createFDW({ projectRef: project?.ref, connectionString: project?.connectionString, wrapperMeta, formState: { ...wrapperValues, server_name: `${wrapperValues.wrapper_name}_server`, briven_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, }) sendEvent({ action: 'foreign_data_wrapper_created', properties: { wrapperType: wrapperMeta.label, }, groups: { project: project?.ref ?? 'Unknown', organization: org?.slug ?? 'Unknown', }, }) } catch (error) { console.error(error) // The error will be handled by the mutation onError callback (toast.error) } } const isLoading = isCreatingWrapper || isCreatingSchema const wrapper_name = useWatch({ name: 'wrapper_name', control: form.control }) const mode = useWatch({ name: 'mode', control: form.control }) return ( <>
Create a {wrapperMeta.label} wrapper Wrapper Configuration ( 0 ? ( <> Your wrapper's server name will be{' '} {wrapper_name}_server ) : ( '' ) } > )} /> {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' && ( Foreign Tables You can query your data from these foreign tables after the wrapper is created {tablesField.map((t, tableIndex) => { // FIXME: make inference work const table = t as unknown as FormattedWrapperTable return (

{table.schema_name}.{table.table_name}

Columns:{' '} {(table.columns ?? []).map((column: any) => column.name).join(', ')}

) })}
{tablesField.length === 0 && errors.tables && (

{errors.tables.message?.toString()}

)}
)} {mode === 'schema' && ( Foreign Schema You can query your data from the foreign tables in the specified schema after the wrapper is created. {wrapperMeta.sourceSchemaOption && !wrapperMeta.sourceSchemaOption?.readOnly && ( // Hide the field if the source schema is read-only )}
)}
{ setSelectedTableToEdit(undefined) }} onSave={onUpdateTable} initialData={selectedTableToEdit} /> ) }