Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): add copied data deletion to Warehouse disable dialog (#51906)

Danny White279434fb7017
diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx
index ec9a4ef3254..1de3cd2281b 100644
--- a/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx
+++ b/apps/studio/components/interfaces/Integrations/Warehouse/OverviewTab.test.tsx
@@ -5,7 +5,6 @@ import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
-import { toast } from 'sonner'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { WarehouseOverviewTab } from './OverviewTab'
@@ -19,7 +18,7 @@ type PublicationDetailsResponse = components['schemas']['PublicationDetailsRespo
type ReplicationSourcesResponse = components['schemas']['SourcesResponse_Output']
type RunQueryBody = components['schemas']['RunQueryBody']
type WarehouseSetupStatusResponse = components['schemas']['WarehouseSetupStatusResponse_Output']
-type WarehouseSetupBody = components['schemas']['WarehouseSetupBody']
+type WarehouseDeleteResponse = components['schemas']['WarehouseDeleteResponse_Output']
type WarehouseSetupResponse = components['schemas']['WarehouseSetupResponse_Output']
// Both integration shells are live, and the flag reads a context plus ConfigCat that
@@ -276,7 +275,7 @@ describe('WarehouseOverviewTab', () => {
}
)
- test('shows the setup failure and retry action', async () => {
+ test('keeps the table picker available after setup fails', async () => {
mockProject()
mockSetupStatus({
setup_status: 'error',
@@ -286,9 +285,9 @@ describe('WarehouseOverviewTab', () => {
customRender(<WarehouseOverviewTab />)
- expect(await screen.findByText('Warehouse setup failed')).toBeInTheDocument()
- expect(screen.getByText('Failed to copy public.orders')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
+ expect(await screen.findByText('Replicated tables picker')).toBeInTheDocument()
+ expect(screen.getByText('Picker error: Failed to copy public.orders')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Submit initial tables' })).toBeInTheDocument()
})
test('shows the latest error when retrying setup fails', async () => {
@@ -307,10 +306,10 @@ describe('WarehouseOverviewTab', () => {
customRender(<WarehouseOverviewTab />)
- await userEvent.click(await screen.findByRole('button', { name: 'Retry' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Submit initial tables' }))
- expect(await screen.findByText('Retry could not be started')).toBeInTheDocument()
- expect(screen.queryByText('Initial setup failed')).not.toBeInTheDocument()
+ expect(await screen.findByText('Picker error: Retry could not be started')).toBeInTheDocument()
+ expect(screen.queryByText('Picker error: Initial setup failed')).not.toBeInTheDocument()
})
test('shows Status, Tables, Connect, then Disable once setup is complete', async () => {
@@ -395,40 +394,109 @@ describe('WarehouseOverviewTab', () => {
expect(mockTrack).not.toHaveBeenCalledWith('warehouse_enabled', expect.anything())
})
- test('disables Warehouse with an empty target list after confirmation', async () => {
+ test('preserves copied Warehouse data by default after confirmation', async () => {
mockSetupStatus({ setup_status: 'complete' })
mockReplicatedTableQueries()
- const setupRequests: WarehouseSetupBody[] = []
+ const deleteRequests: (string | null)[] = []
addAPIMock({
- method: 'post',
- path: '/platform/warehouse/:ref/setup',
+ method: 'delete',
+ path: '/platform/warehouse/:ref',
response: async ({ request }) => {
- setupRequests.push((await request.json()) as WarehouseSetupBody)
- return HttpResponse.json<WarehouseSetupResponse>({ pipeline_id: 1, tables: [] })
+ deleteRequests.push(new URL(request.url).searchParams.get('delete_data'))
+ return HttpResponse.json<WarehouseDeleteResponse>({ status: 'accepted' }, { status: 202 })
},
})
customRender(<WarehouseOverviewTab />)
await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))
- expect(setupRequests).toEqual([])
+ expect(deleteRequests).toEqual([])
const dialog = await screen.findByRole('alertdialog')
- expect(dialog).toHaveTextContent('Copied data remains in DuckLake storage until deleted')
+ expect(dialog).toHaveTextContent('Deletes the copied data and its storage permanently')
+ expect(within(dialog).getByRole('checkbox')).not.toBeChecked()
expect(screen.queryByPlaceholderText('Type the project ref to confirm')).not.toBeInTheDocument()
fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))
- await waitFor(() => expect(setupRequests).toEqual([{ targets: [] }]))
+ await waitFor(() => expect(deleteRequests).toEqual(['false']))
+ })
+
+ test('resets the copied data option when the confirmation is reopened', async () => {
+ mockSetupStatus({ setup_status: 'complete' })
+ mockReplicatedTableQueries()
+ customRender(<WarehouseOverviewTab />)
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))
+ const dialog = await screen.findByRole('alertdialog')
+ await userEvent.click(within(dialog).getByRole('checkbox'))
+ expect(within(dialog).getByRole('checkbox')).toBeChecked()
+ await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+
+ await userEvent.click(screen.getByRole('button', { name: 'Disable Warehouse' }))
+ expect(within(await screen.findByRole('alertdialog')).getByRole('checkbox')).not.toBeChecked()
})
+ test('shows disable progress and polls until Warehouse can be enabled again', async () => {
+ let status: WarehouseSetupStatusResponse['setup_status'] = 'disabling'
+ addAPIMock({
+ method: 'get',
+ path: '/platform/warehouse/:ref/setup-status',
+ response: () =>
+ HttpResponse.json<WarehouseSetupStatusResponse>({
+ setup_status: status,
+ fdw_status: null,
+ tables: [],
+ steps: [],
+ }),
+ })
+ customRender(<WarehouseOverviewTab />)
+ expect(await screen.findByText('Warehouse is being disabled')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Disable Warehouse' })).not.toBeInTheDocument()
+ status = 'disabled'
+ expect(
+ await screen.findByText('Replicated tables picker', {}, { timeout: 5000 })
+ ).toBeInTheDocument()
+ })
+
+ test.each([false, true])(
+ 'retries failed cleanup with the saved delete_data option (%s)',
+ async (shouldDeleteData) => {
+ mockProject()
+ mockSetupStatus({
+ setup_status: 'deletion_failed',
+ error: 'Storage cleanup failed',
+ delete_data: shouldDeleteData,
+ })
+ const deleteRequests: (string | null)[] = []
+ addAPIMock({
+ method: 'delete',
+ path: '/platform/warehouse/:ref',
+ response: ({ request }) => {
+ deleteRequests.push(new URL(request.url).searchParams.get('delete_data'))
+ return HttpResponse.json<APIErrorBody>(
+ { message: 'Cleanup retry failed' },
+ { status: 500 }
+ )
+ },
+ })
+ customRender(<WarehouseOverviewTab />)
+ expect(await screen.findByText('Storage cleanup failed')).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ expect(await screen.findByText('Cleanup retry failed')).toBeInTheDocument()
+ expect(deleteRequests).toEqual([String(shouldDeleteData)])
+ }
+ )
+
test('tracks how much was being replicated when Warehouse is disabled', async () => {
mockSetupStatus({ setup_status: 'complete' })
const { publicationRequests } = mockReplicatedTableQueries()
addAPIMock({
- method: 'post',
- path: '/platform/warehouse/:ref/setup',
- response: () => HttpResponse.json<WarehouseSetupResponse>({ pipeline_id: 1, tables: [] }),
+ method: 'delete',
+ path: '/platform/warehouse/:ref',
+ response: () =>
+ HttpResponse.json<WarehouseDeleteResponse>({ status: 'accepted' }, { status: 202 }),
})
customRender(<WarehouseOverviewTab />)
@@ -450,11 +518,13 @@ describe('WarehouseOverviewTab', () => {
test('shows a disable error and allows retrying from the open confirmation', async () => {
mockSetupStatus({ setup_status: 'complete' })
mockReplicatedTableQueries()
+ const deleteRequests: (string | null)[] = []
let attempts = 0
addAPIMock({
- method: 'post',
- path: '/platform/warehouse/:ref/setup',
- response: () => {
+ method: 'delete',
+ path: '/platform/warehouse/:ref',
+ response: ({ request }) => {
+ deleteRequests.push(new URL(request.url).searchParams.get('delete_data'))
attempts += 1
if (attempts === 1) {
return HttpResponse.json<APIErrorBody>(
@@ -462,7 +532,7 @@ describe('WarehouseOverviewTab', () => {
{ status: 500 }
)
}
- return HttpResponse.json<WarehouseSetupResponse>({ pipeline_id: 1, tables: [] })
+ return HttpResponse.json<WarehouseDeleteResponse>({ status: 'accepted' }, { status: 202 })
},
})
@@ -471,21 +541,70 @@ describe('WarehouseOverviewTab', () => {
await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))
const dialog = await screen.findByRole('alertdialog')
const confirm = within(dialog).getByRole('button', { name: 'Disable Warehouse' })
+ await userEvent.click(
+ within(dialog).getByRole('checkbox', { name: 'Also delete copied Warehouse data' })
+ )
fireEvent.click(confirm)
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith(
- 'Failed to disable Warehouse: Disable request failed'
- )
- )
+ const message = await within(dialog).findByText('Disable request failed')
+ expect(
+ message.compareDocumentPosition(within(dialog).getByRole('checkbox')) &
+ Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy()
expect(dialog).toBeVisible()
expect(confirm).toBeEnabled()
+ expect(within(dialog).getByRole('checkbox')).toBeChecked()
fireEvent.click(confirm)
await waitFor(() => expect(attempts).toBe(2))
+ expect(deleteRequests).toEqual(['true', 'true'])
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ })
+
+ test('explains legacy storage errors below the deletion option and lets users retain data', async () => {
+ mockSetupStatus({ setup_status: 'complete' })
+ mockReplicatedTableQueries()
+ const deleteRequests: (string | null)[] = []
+ addAPIMock({
+ method: 'delete',
+ path: '/platform/warehouse/:ref',
+ response: ({ request }) => {
+ const shouldDeleteData = new URL(request.url).searchParams.get('delete_data')
+ deleteRequests.push(shouldDeleteData)
+ if (shouldDeleteData === 'true') {
+ return HttpResponse.json<APIErrorBody>(
+ { message: 'Legacy Warehouse data must be retained when disabling Warehouse.' },
+ { status: 400 }
+ )
+ }
+ return HttpResponse.json<WarehouseDeleteResponse>({ status: 'accepted' }, { status: 202 })
+ },
+ })
+ customRender(<WarehouseOverviewTab />)
+ await userEvent.click(await screen.findByRole('button', { name: 'Disable Warehouse' }))
+ const dialog = await screen.findByRole('alertdialog')
+ const checkbox = within(dialog).getByRole('checkbox', {
+ name: 'Also delete copied Warehouse data',
+ })
+ await userEvent.click(checkbox)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))
+
+ const message = await within(dialog).findByText(
+ 'Turn this option off to disable Warehouse and keep the copied data.'
+ )
+ expect(within(dialog).getByText('Copied data cannot be deleted')).toBeInTheDocument()
+ expect(
+ checkbox.compareDocumentPosition(message) & Node.DOCUMENT_POSITION_FOLLOWING
+ ).toBeTruthy()
+ expect(dialog).not.toHaveTextContent('Try refreshing')
+ expect(within(dialog).queryByText(/contact support/i)).not.toBeInTheDocument()
+ expect(checkbox).toBeChecked()
+ await userEvent.click(checkbox)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Disable Warehouse' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(deleteRequests).toEqual(['true', 'false'])
})
test('shows a status query failure without blocking an unrelated route', async () => {
diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseDisableCard.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseDisableCard.tsx
index 50fab771006..92fa68bcb37 100644
--- a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseDisableCard.tsx
+++ b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseDisableCard.tsx
@@ -1,6 +1,7 @@
-import { useQueryClient } from '@tanstack/react-query'
+import { zodResolver } from '@hookform/resolvers/zod'
import { useParams } from 'common'
import { useRef, useState } from 'react'
+import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
AlertDialog,
@@ -15,7 +16,12 @@ import {
Button,
Card,
CardContent,
+ Checkbox,
+ Form,
+ FormControl,
+ FormField,
} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { FormLayout } from 'ui-patterns/form/Layout/FormLayout'
import {
PageSection,
@@ -24,16 +30,21 @@ import {
PageSectionSummary,
PageSectionTitle,
} from 'ui-patterns/PageSection'
+import { z } from 'zod'
import { useWarehouseReplicatedTargets } from './useWarehouseReplicatedTargets'
import { type WarehouseSetupTarget } from './Warehouse.utils'
-import { warehouseKeys } from '@/data/warehouse/keys'
-import { useWarehouseSetupMutation } from '@/data/warehouse/warehouse-setup-mutation'
+import { AlertError } from '@/components/ui/AlertError'
+import { useWarehouseDisableMutation } from '@/data/warehouse/warehouse-disable-mutation'
import { useTrack } from '@/lib/telemetry/track'
+const FormSchema = z.object({ shouldDeleteData: z.boolean() })
+type FormValues = z.infer<typeof FormSchema>
+const defaultValues: FormValues = { shouldDeleteData: false }
+
export const WarehouseDisableCard = () => {
const { ref: projectRef } = useParams()
- const queryClient = useQueryClient()
+ const form = useForm<FormValues>({ resolver: zodResolver(FormSchema), defaultValues })
const track = useTrack()
const [isConfirming, setIsConfirming] = useState(false)
@@ -42,7 +53,7 @@ export const WarehouseDisableCard = () => {
// refetches, after which nothing reads as replicated.
const targetsAtConfirm = useRef<WarehouseSetupTarget[] | undefined>(undefined)
- const setupMutation = useWarehouseSetupMutation({
+ const disableMutation = useWarehouseDisableMutation({
onSuccess: async () => {
// Tracked from the mutation's onSuccess, not mutateAsync's: the status refetch swaps this
// card out of the panel, and mutate-level callbacks are skipped once it has unmounted.
@@ -53,22 +64,23 @@ export const WarehouseDisableCard = () => {
tableTargetCount: targets.filter((target) => target.type === 'table').length,
}),
})
- // Disabling also turns off catalog access server-side, which the setup mutation doesn't know
- // to invalidate on its own.
- await queryClient.invalidateQueries({ queryKey: warehouseKeys.catalog(projectRef) })
setIsConfirming(false)
- toast.success('Warehouse disabled')
+ toast.success('Warehouse disable requested')
},
- onError: (error) => toast.error(`Failed to disable Warehouse: ${error.message}`),
+ onError: () => {},
})
- const handleDisable = () => {
+ const handleDisable = ({ shouldDeleteData }: FormValues) => {
if (!projectRef) return undefined
targetsAtConfirm.current = replicatedTargets
// Returned so the dialog stays open on failure and closes once the disable succeeds.
- return setupMutation.mutateAsync({ projectRef, body: { targets: [] } })
+ return disableMutation.mutateAsync({ projectRef, shouldDeleteData })
}
+ const disableError = disableMutation.error
+ const isLegacyStorageError =
+ disableError?.message === 'Legacy Warehouse data must be retained when disabling Warehouse.'
+
return (
<PageSection className="pt-5!">
<PageSectionMeta>
@@ -84,7 +96,14 @@ export const WarehouseDisableCard = () => {
label="Disable Warehouse for this project"
description="Stops replication and removes Warehouse-managed resources."
>
- <Button variant="danger" onClick={() => setIsConfirming(true)}>
+ <Button
+ variant="danger"
+ onClick={() => {
+ form.reset()
+ disableMutation.reset()
+ setIsConfirming(true)
+ }}
+ >
Disable Warehouse
</Button>
</FormLayout>
@@ -101,20 +120,71 @@ export const WarehouseDisableCard = () => {
<AlertDialogDescription asChild>
<div className="space-y-2">
<p>
- Disabling Warehouse stops replication and connections to its endpoint. Its
- pipeline, publication, catalog access, and foreign tables are removed.
+ Stops replication and disconnects the Warehouse endpoint. Removes its pipeline,
+ publication, catalog access, and foreign tables.
</p>
- <p>Copied data remains in DuckLake storage until deleted.</p>
</div>
</AlertDialogDescription>
+ {disableError && !isLegacyStorageError && (
+ <div className="px-5 pb-4">
+ <AlertError
+ subject="Unable to disable Warehouse"
+ showErrorPrefix={false}
+ showInstructions={false}
+ hideContactSupport
+ error={disableError}
+ />
+ </div>
+ )}
+ <div className="border-t px-5 py-4">
+ <Form {...form}>
+ <FormField
+ control={form.control}
+ name="shouldDeleteData"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="flex"
+ label="Also delete copied Warehouse data"
+ description="Deletes the copied data and its storage permanently. Source tables are preserved."
+ >
+ <FormControl>
+ <Checkbox
+ name={field.name}
+ ref={field.ref}
+ onBlur={field.onBlur}
+ checked={field.value}
+ onCheckedChange={(checked) => field.onChange(checked === true)}
+ disabled={disableMutation.isPending}
+ />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ </Form>
+ </div>
+ {isLegacyStorageError && (
+ <div className="px-5 pb-4">
+ <AlertError
+ subject="Copied data cannot be deleted"
+ showErrorPrefix={false}
+ showInstructions={false}
+ hideContactSupport
+ error={{
+ message: 'Turn this option off to disable Warehouse and keep the copied data.',
+ }}
+ />
+ </div>
+ )}
</AlertDialogBody>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="danger"
- loading={setupMutation.isPending}
+ loading={disableMutation.isPending}
disabled={!projectRef}
- onClick={handleDisable}
+ onClick={() => {
+ return form.handleSubmit(handleDisable)()
+ }}
>
Disable Warehouse
</AlertDialogAction>
diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx
index 2b89fb49a35..9114df170a5 100644
--- a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx
+++ b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.test.tsx
@@ -205,6 +205,35 @@ describe('WarehouseSchemaTablePicker', () => {
)
})
+ test('keeps failed tables selected for retry and allows changing them', async () => {
+ mockPickerQueries({ isEditing: false })
+ const requests: WarehouseSetupBody['targets'][] = []
+ customRender(
+ <WarehouseSchemaTablePicker
+ initialTables={[
+ { schema: 'public', name: 'orders' },
+ { schema: 'public', name: 'removed_table' },
+ ]}
+ isSubmitting={false}
+ error={{ message: 'Failed to copy orders' }}
+ onSubmit={(targets) => requests.push(targets)}
+ />
+ )
+
+ expect(await screen.findByText('1 table selected')).toBeInTheDocument()
+ expect(screen.getByText('Failed to copy orders', { exact: false })).toBeInTheDocument()
+ expect(screen.queryByText(/Try refreshing/)).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Enable Warehouse' })).toBeEnabled()
+ await userEvent.click(screen.getByRole('button', { name: 'Enable Warehouse' }))
+ expect(requests).toEqual([[{ type: 'table', schema: 'public', name: 'orders' }]])
+
+ fireEvent.click(screen.getByRole('combobox', { name: 'Select tables to replicate' }))
+ await userEvent.click(screen.getByText('customers'))
+ expect(screen.getByText('2 tables selected')).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: 'Enable Warehouse' }))
+ expect(requests[1]).toEqual([{ type: 'schema', schema: 'public' }])
+ })
+
test('preselects replicated tables and submits a replacement after removal', async () => {
mockPickerQueries({ isEditing: true })
const requests = mockSetupMutation()
diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.tsx
index db8ca6b914e..4ff8112296e 100644
--- a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.tsx
+++ b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSchemaTablePicker.tsx
@@ -18,10 +18,10 @@ import {
buildSelectionFromPublicationTables,
buildWarehouseSetupTargets,
getSchemaTableKey,
- getSelectedTableCount,
hasSelectionChanged,
type SchemaTableSelection,
type SchemaWithTables,
+ type WarehouseSetupTable,
type WarehouseSetupTarget,
} from './Warehouse.utils'
import { AlertError } from '@/components/ui/AlertError'
@@ -31,7 +31,6 @@ import { useReplicationSourcesQuery } from '@/data/replication/sources-query'
import { useTablesQuery } from '@/data/tables/tables-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { WAREHOUSE_PUBLICATION_NAME } from '@/lib/warehouse'
-import type { ResponseError } from '@/types'
export interface WarehouseSchemaTablePickerProps {
onSubmit: (targets: WarehouseSetupTarget[]) => void
@@ -39,7 +38,8 @@ export interface WarehouseSchemaTablePickerProps {
/** Set when editing an already-enabled Warehouse rather than setting one up for the first time. */
isEditing?: boolean
/** Failure from the submit itself, rendered inline rather than as a toast the user can lose. */
- error?: ResponseError | null
+ error?: { message: string } | null
+ initialTables?: Pick<WarehouseSetupTable, 'schema' | 'name'>[]
}
export const WarehouseSchemaTablePicker = ({
@@ -47,6 +47,7 @@ export const WarehouseSchemaTablePicker = ({
isSubmitting,
isEditing = false,
error,
+ initialTables,
}: WarehouseSchemaTablePickerProps) => {
const { ref: projectRef } = useParams()
const { data: project } = useSelectedProjectQuery()
@@ -102,8 +103,11 @@ export const WarehouseSchemaTablePicker = ({
(sourceId !== undefined && publication === undefined && !isPublicationsError))
const initialSelection = useMemo(
- () => (isEditing ? buildSelectionFromPublicationTables(publication?.tables ?? []) : {}),
- [isEditing, publication]
+ () =>
+ buildSelectionFromPublicationTables(
+ isEditing ? (publication?.tables ?? []) : (initialTables ?? [])
+ ),
+ [isEditing, publication, initialTables]
)
const schemasWithTables: SchemaWithTables[] = useMemo(() => {
@@ -115,8 +119,8 @@ export const WarehouseSchemaTablePicker = ({
tables.map((table) => getSchemaTableKey(schema, table))
)
const selection = selectionOverride ?? initialSelection
- const selectedCount = getSelectedTableCount(selection)
const selectedTableKeys = tableKeys.filter((key) => selection[key])
+ const selectedCount = selectedTableKeys.length
const hasChanges = hasSelectionChanged(selection, initialSelection)
const updateSelection = (updater: (current: SchemaTableSelection) => SchemaTableSelection) => {
@@ -215,6 +219,8 @@ export const WarehouseSchemaTablePicker = ({
}
error={error}
projectRef={projectRef}
+ showInstructions={false}
+ hideContactSupport
/>
)}
<Card>
@@ -321,7 +327,7 @@ export const WarehouseSchemaTablePicker = ({
)}
<Button
variant="primary"
- disabled={selectedCount === 0 || !hasChanges}
+ disabled={selectedCount === 0 || (isEditing && !hasChanges)}
loading={isSubmitting}
onClick={handleSubmit}
>
diff --git a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSetupPanel.tsx b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSetupPanel.tsx
index 65ef82b7c20..1c86c34f297 100644
--- a/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSetupPanel.tsx
+++ b/apps/studio/components/interfaces/Integrations/Warehouse/WarehouseSetupPanel.tsx
@@ -3,11 +3,7 @@ import { Button } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import {
- buildRetryTargets,
- isWarehouseSettingUp,
- type WarehouseSetupTarget,
-} from './Warehouse.utils'
+import { isWarehouseSettingUp, type WarehouseSetupTarget } from './Warehouse.utils'
import { WarehouseConnectSection } from './WarehouseConnectSection'
import { WarehouseDisableCard } from './WarehouseDisableCard'
import { WarehouseSchemaTablePicker } from './WarehouseSchemaTablePicker'
@@ -17,6 +13,7 @@ import {
} from './WarehouseTableStatusList'
import { AlertError } from '@/components/ui/AlertError'
import { checkLocalETLNotSetUp } from '@/data/replication/utils'
+import { useWarehouseDisableMutation } from '@/data/warehouse/warehouse-disable-mutation'
import { useWarehouseSetupMutation } from '@/data/warehouse/warehouse-setup-mutation'
import { useWarehouseSetupStatusQuery } from '@/data/warehouse/warehouse-setup-status-query'
import { useTrack } from '@/lib/telemetry/track'
@@ -29,10 +26,14 @@ export const WarehouseSetupPanel = () => {
{ projectRef },
{
refetchInterval: (query) =>
- isWarehouseSettingUp(query.state.data?.setup_status) ? 3000 : false,
+ isWarehouseSettingUp(query.state.data?.setup_status) ||
+ query.state.data?.setup_status === 'disabling'
+ ? 3000
+ : false,
}
)
+ const disableMutation = useWarehouseDisableMutation({ onError: () => {} })
// Rendered inline by the picker rather than as a toast: a setup failure is something the user
// has to act on, so it must not disappear.
const setupMutation = useWarehouseSetupMutation({ onError: () => {} })
@@ -87,7 +88,7 @@ export const WarehouseSetupPanel = () => {
const status = data.setup_status
- if (status === 'not_started') {
+ if (status === 'not_started' || status === 'disabled') {
return (
<WarehouseSchemaTablePicker
onSubmit={handleSetup}
@@ -101,31 +102,56 @@ export const WarehouseSetupPanel = () => {
return <WarehouseEnablingProgress status={data} />
}
- if (status === 'error') {
- const retryTargets = buildRetryTargets(data.tables)
- const failingStep = data.steps.find((step) => step.status === 'error')
+ if (status === 'disabling') {
+ return (
+ <Admonition
+ type="default"
+ title="Warehouse is being disabled"
+ description="Warehouse resources are being removed. This can take a few minutes."
+ />
+ )
+ }
+ if (status === 'deletion_failed') {
return (
<AlertError
- subject="Warehouse setup failed"
+ subject="Failed to disable Warehouse"
showErrorPrefix={false}
+ error={{
+ message: disableMutation.error?.message ?? data.error ?? 'Warehouse cleanup failed.',
+ }}
+ additionalActions={
+ <Button
+ variant="default"
+ loading={disableMutation.isPending}
+ disabled={!projectRef}
+ onClick={() => {
+ if (projectRef) {
+ disableMutation.mutate({ projectRef, shouldDeleteData: data.delete_data ?? false })
+ }
+ }}
+ >
+ Retry
+ </Button>
+ }
+ />
+ )
+ }
+
+ if (status === 'error') {
+ const failingStep = data.steps.find((step) => step.status === 'error')
+
+ return (
+ <WarehouseSchemaTablePicker
+ initialTables={data.tables}
+ onSubmit={handleSetup}
+ isSubmitting={setupMutation.isPending}
error={{
message:
setupMutation.error?.message ??
failingStep?.message ??
'An unknown error occurred while setting up Warehouse.',
}}
- additionalActions={
- retryTargets.length > 0 ? (
- <Button
- variant="default"
- loading={setupMutation.isPending}
- onClick={() => handleSetup(retryTargets)}
- >
- Retry
- </Button>
- ) : undefined
- }
/>
)
}
diff --git a/apps/studio/data/warehouse/warehouse-disable-mutation.ts b/apps/studio/data/warehouse/warehouse-disable-mutation.ts
new file mode 100644
index 00000000000..ccffe1c2dc1
--- /dev/null
+++ b/apps/studio/data/warehouse/warehouse-disable-mutation.ts
@@ -0,0 +1,65 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { warehouseKeys } from './keys'
+import { del, handleError } from '@/data/fetchers'
+import { replicationKeys } from '@/data/replication/keys'
+import type { ResponseError, UseCustomMutationOptions } from '@/types'
+
+export type WarehouseDisableVariables = {
+ projectRef: string
+ shouldDeleteData: boolean
+}
+
+async function disableWarehouse({ projectRef, shouldDeleteData }: WarehouseDisableVariables) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await del('/platform/warehouse/{ref}', {
+ params: {
+ path: { ref: projectRef },
+ query: { delete_data: shouldDeleteData ? 'true' : 'false' },
+ },
+ })
+ if (error) {
+ handleError(error)
+ }
+
+ return data
+}
+
+export type WarehouseDisableData = Awaited<ReturnType<typeof disableWarehouse>>
+
+export const useWarehouseDisableMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<WarehouseDisableData, ResponseError, WarehouseDisableVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<WarehouseDisableData, ResponseError, WarehouseDisableVariables>({
+ mutationFn: (vars) => disableWarehouse(vars),
+ async onSuccess(data, variables, context) {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: warehouseKeys.catalog(variables.projectRef) }),
+ queryClient.invalidateQueries({
+ queryKey: warehouseKeys.setupStatus(variables.projectRef),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: replicationKeys.sources(variables.projectRef),
+ }),
+ ])
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(error, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to disable Warehouse: ${error.message}`)
+ } else {
+ onError(error, variables, context)
+ }
+ },
+ ...options,
+ })
+}