feat: add metadata catalog cleanup commands
This commit is contained in:
@@ -123,6 +123,15 @@ export interface CatalogRelationship {
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type CatalogDatabaseMetadataDeleteTarget = "tables" | "relationships";
|
||||
export type CatalogTableMetadataDeleteTarget = "columns" | "relationships";
|
||||
|
||||
export interface CatalogMetadataDeleteCounts {
|
||||
tables: number;
|
||||
columns: number;
|
||||
relationships: number;
|
||||
}
|
||||
|
||||
export type CatalogSyncScope = "tables" | "columns" | "relationships" | "all";
|
||||
export type CatalogSyncState = "queued" | "running" | "awaiting_confirmation" | "applying"
|
||||
| "succeeded" | "failed" | "cancelled" | "interrupted";
|
||||
@@ -228,6 +237,23 @@ export const updateCatalogColumnMetadata = (
|
||||
export const listCatalogRelationships = (databaseId: string) =>
|
||||
apiFetch<CatalogRelationship[]>(`/catalog/databases/${encodeURIComponent(databaseId)}/relationships`);
|
||||
|
||||
export const deleteCatalogDatabaseMetadata = (
|
||||
databaseIds: string[],
|
||||
target: CatalogDatabaseMetadataDeleteTarget,
|
||||
) => apiFetch<CatalogMetadataDeleteCounts>("/catalog/databases/metadata-cleanup", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ databaseIds, target }),
|
||||
});
|
||||
|
||||
export const deleteCatalogTableMetadata = (
|
||||
databaseId: string,
|
||||
tableIds: string[],
|
||||
target: CatalogTableMetadataDeleteTarget,
|
||||
) => apiFetch<CatalogMetadataDeleteCounts>(
|
||||
`/catalog/databases/${encodeURIComponent(databaseId)}/tables/metadata-cleanup`,
|
||||
{ method: "POST", body: JSON.stringify({ tableIds, target }) },
|
||||
);
|
||||
|
||||
export const startCatalogSync = (
|
||||
databaseId: string,
|
||||
version: number,
|
||||
|
||||
@@ -181,6 +181,59 @@ test.each(synchronizationScopes)(
|
||||
},
|
||||
);
|
||||
|
||||
test("selected database Actions confirms and deletes catalog tables for the full selection", async () => {
|
||||
const user = userEvent.setup();
|
||||
let cleanupBody: unknown;
|
||||
const second = makeDatabase({
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
workspaceId: "radiology",
|
||||
workspaceName: "Radiology",
|
||||
databaseName: "radiology",
|
||||
});
|
||||
server.use(http.post("/api/catalog/databases/metadata-cleanup", async ({ request }) => {
|
||||
cleanupBody = await request.json();
|
||||
return HttpResponse.json({ tables: 8, columns: 42, relationships: 5 });
|
||||
}));
|
||||
renderPage({ rows: [makeDatabase(), second] });
|
||||
|
||||
const firstRow = await screen.findByRole("row", { name: /Policlinico San Donato/ });
|
||||
const secondRow = await screen.findByRole("row", { name: /Radiology/ });
|
||||
await user.click(within(firstRow).getByRole("checkbox"));
|
||||
await user.click(within(secondRow).getByRole("checkbox"));
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
|
||||
expect(await screen.findByRole("menuitem", { name: "Delete all tables" })).toBeEnabled();
|
||||
expect(screen.getByRole("menuitem", { name: "Delete all relationships" })).toBeEnabled();
|
||||
await user.click(screen.getByRole("menuitem", { name: "Delete all tables" }));
|
||||
|
||||
expect(screen.getByText("Delete all catalog tables for 2 databases?")).toBeVisible();
|
||||
expect(screen.getByText(/database configurations and source databases are unchanged/i)).toBeVisible();
|
||||
expect(cleanupBody).toBeUndefined();
|
||||
|
||||
await user.click(within(secondRow).getByRole("checkbox"));
|
||||
expect(screen.queryByText(/Delete all catalog tables for/)).not.toBeInTheDocument();
|
||||
expect(cleanupBody).toBeUndefined();
|
||||
await user.click(within(secondRow).getByRole("checkbox"));
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
await user.click(await screen.findByRole("menuitem", { name: "Delete all tables" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Delete catalog tables" })).toHaveFocus());
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Actions" })).toHaveFocus());
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
await user.click(await screen.findByRole("menuitem", { name: "Delete all tables" }));
|
||||
await user.click(screen.getByRole("button", { name: "Delete catalog tables" }));
|
||||
|
||||
await waitFor(() => expect(cleanupBody).toEqual({
|
||||
databaseIds: [
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
"44444444-4444-4444-8444-444444444444",
|
||||
],
|
||||
target: "tables",
|
||||
}));
|
||||
await waitFor(() => expect(screen.queryByText("2 selected")).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(screen.getByRole("textbox", { name: "Search databases" })).toHaveFocus());
|
||||
});
|
||||
|
||||
test("presents completed synchronization steps as success and skips unneeded confirmation", async () => {
|
||||
const user = userEvent.setup();
|
||||
const run = {
|
||||
@@ -580,7 +633,7 @@ test("filters catalog tables as the operator types", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("selected table exposes a direct Synchronize columns action and sends its id", async () => {
|
||||
test("selected table Actions exposes cleanup commands and sends synchronization ids", async () => {
|
||||
const user = userEvent.setup();
|
||||
let startBody: unknown;
|
||||
const run = makeSyncRun("columns", [patientsTable.id]);
|
||||
@@ -601,10 +654,11 @@ test("selected table exposes a direct Synchronize columns action and sends its i
|
||||
const tableRow = await screen.findByRole("row", { name: /patients/ });
|
||||
await user.click(within(tableRow).getByRole("checkbox"));
|
||||
|
||||
const synchronizeColumns = screen.getByRole("button", { name: "Synchronize columns" });
|
||||
expect(synchronizeColumns).toBeVisible();
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
const synchronizeColumns = await screen.findByRole("menuitem", { name: "Synchronize columns" });
|
||||
expect(synchronizeColumns).toBeEnabled();
|
||||
expect(screen.queryByRole("button", { name: "Actions" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("menuitem", { name: "Delete all columns" })).toBeEnabled();
|
||||
expect(screen.getByRole("menuitem", { name: "Delete all relationships" })).toBeEnabled();
|
||||
await user.click(synchronizeColumns);
|
||||
|
||||
await waitFor(() => expect(startBody).toEqual({
|
||||
@@ -615,6 +669,54 @@ test("selected table exposes a direct Synchronize columns action and sends its i
|
||||
await waitFor(() => expect(screen.queryByText("1 selected")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
test("selected table Actions confirms and deletes incoming and outgoing relationships", async () => {
|
||||
const user = userEvent.setup();
|
||||
let cleanupBody: unknown;
|
||||
server.use(
|
||||
http.get("/api/catalog/databases/:databaseId/tables", () => HttpResponse.json([patientsTable])),
|
||||
http.post("/api/catalog/databases/:databaseId/tables/metadata-cleanup", async ({ request }) => {
|
||||
cleanupBody = await request.json();
|
||||
return HttpResponse.json({ tables: 0, columns: 0, relationships: 2 });
|
||||
}),
|
||||
);
|
||||
const { client } = renderPage({
|
||||
rows: [makeDatabase({ connectionStatus: "reachable", testedVersion: 3 })],
|
||||
});
|
||||
const unselectedColumnQuery = [
|
||||
"catalog-columns",
|
||||
patientsTable.databaseId,
|
||||
"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
] as const;
|
||||
client.setQueryData(unselectedColumnQuery, []);
|
||||
|
||||
await user.click(await screen.findByRole("button", { name: "View Policlinico San Donato" }));
|
||||
await user.click(screen.getByRole("tab", { name: "Tables" }));
|
||||
const tableRow = await screen.findByRole("row", { name: /patients/ });
|
||||
await user.click(within(tableRow).getByRole("checkbox"));
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
await user.click(await screen.findByRole("menuitem", { name: "Delete all relationships" }));
|
||||
|
||||
expect(screen.getByText("Delete all relationships for 1 table?")).toBeVisible();
|
||||
expect(screen.getByText(/incoming and outgoing relationships/i)).toBeVisible();
|
||||
expect(cleanupBody).toBeUndefined();
|
||||
|
||||
await user.click(within(tableRow).getByRole("checkbox"));
|
||||
expect(screen.queryByText("Delete all relationships for 1 table?")).not.toBeInTheDocument();
|
||||
expect(cleanupBody).toBeUndefined();
|
||||
await user.click(within(tableRow).getByRole("checkbox"));
|
||||
await user.click(screen.getByRole("button", { name: "Actions" }));
|
||||
await user.click(await screen.findByRole("menuitem", { name: "Delete all relationships" }));
|
||||
await user.click(screen.getByRole("button", { name: "Delete relationships" }));
|
||||
|
||||
await waitFor(() => expect(cleanupBody).toEqual({
|
||||
tableIds: [patientsTable.id],
|
||||
target: "relationships",
|
||||
}));
|
||||
await waitFor(() => expect(screen.queryByText("1 selected")).not.toBeInTheDocument());
|
||||
expect(client.getQueryState(unselectedColumnQuery)?.isInvalidated).toBe(true);
|
||||
await waitFor(() => expect(screen.getByRole("textbox", { name: "Search tables" })).toHaveFocus());
|
||||
});
|
||||
|
||||
test("navigates purely from a database to its tables and edits review metadata", async () => {
|
||||
const user = userEvent.setup();
|
||||
let patchBody: unknown;
|
||||
|
||||
@@ -13,12 +13,14 @@ import { ApiError, apiErrorMessage } from "../api/client";
|
||||
import {
|
||||
createCatalogDatabase,
|
||||
deleteCatalogDatabase,
|
||||
deleteCatalogDatabaseMetadata,
|
||||
listCatalogDatabases,
|
||||
replaceCatalogDatabaseSecrets,
|
||||
startCatalogSync,
|
||||
testCatalogDatabase,
|
||||
updateCatalogDatabase,
|
||||
type CatalogDatabase,
|
||||
type CatalogDatabaseMetadataDeleteTarget,
|
||||
type CatalogSecretName,
|
||||
type CatalogSyncScope,
|
||||
type CatalogSyncRun,
|
||||
@@ -588,6 +590,28 @@ export function DatabaseManagementPage({
|
||||
}
|
||||
}, [queryClient, rememberSyncRun]);
|
||||
|
||||
const deleteSelectedMetadata = useCallback(async (
|
||||
selected: CatalogDatabase[],
|
||||
target: CatalogDatabaseMetadataDeleteTarget,
|
||||
) => {
|
||||
try {
|
||||
const databaseIds = selected.map((row) => row.id!);
|
||||
const counts = await deleteCatalogDatabaseMetadata(databaseIds, target);
|
||||
await Promise.all(databaseIds.flatMap((databaseId) => [
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-tables", databaseId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-columns", databaseId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-relationships", databaseId] }),
|
||||
]));
|
||||
await queryClient.invalidateQueries({ queryKey: DATABASE_QUERY_KEY });
|
||||
toast.success(target === "tables"
|
||||
? `Deleted ${counts.tables} catalog tables, ${counts.columns} columns, and ${counts.relationships} relationships`
|
||||
: `Deleted ${counts.relationships} catalog relationships`);
|
||||
} catch (error) {
|
||||
toast.error(apiErrorMessage(error));
|
||||
throw error;
|
||||
}
|
||||
}, [queryClient]);
|
||||
|
||||
const syncDatabase = useCallback(async (scope: CatalogSyncScope) => {
|
||||
if (!activeRow?.id || !activeRow.configured) return;
|
||||
try {
|
||||
@@ -677,6 +701,7 @@ export function DatabaseManagementPage({
|
||||
onOpenSync={openSync}
|
||||
onTestSelected={testSelected}
|
||||
onSyncSelected={syncSelected}
|
||||
onDeleteMetadataSelected={deleteSelectedMetadata}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,11 @@ import "ag-grid-community/styles/ag-grid.css";
|
||||
import "ag-grid-community/styles/ag-theme-alpine.css";
|
||||
import { ChevronDown, Eye, Pencil, RefreshCw, Trash2, X } from "lucide-react";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import type { CatalogDatabase, CatalogSyncScope } from "../../api/catalog-databases";
|
||||
import type {
|
||||
CatalogDatabase,
|
||||
CatalogDatabaseMetadataDeleteTarget,
|
||||
CatalogSyncScope,
|
||||
} from "../../api/catalog-databases";
|
||||
import { statusLabel } from "./model";
|
||||
import { databaseSyncItemClass, databaseSyncScopes } from "./DatabaseSyncMenu";
|
||||
|
||||
@@ -31,6 +35,10 @@ interface DatabaseGridProps {
|
||||
onOpenSync: (row: CatalogDatabase) => void;
|
||||
onTestSelected: (rows: CatalogDatabase[]) => Promise<void>;
|
||||
onSyncSelected: (rows: CatalogDatabase[], scope: CatalogSyncScope) => Promise<void>;
|
||||
onDeleteMetadataSelected: (
|
||||
rows: CatalogDatabase[],
|
||||
target: CatalogDatabaseMetadataDeleteTarget,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
interface DatabaseGridContext {
|
||||
@@ -146,11 +154,14 @@ export function DatabaseGrid({
|
||||
onOpenSync,
|
||||
onTestSelected,
|
||||
onSyncSelected,
|
||||
onDeleteMetadataSelected,
|
||||
}: DatabaseGridProps) {
|
||||
const compact = useCompactViewport();
|
||||
const gridRef = useRef<AgGridReact<CatalogDatabase>>(null);
|
||||
const actionsTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [selectedRows, setSelectedRows] = useState<CatalogDatabase[]>([]);
|
||||
const [action, setAction] = useState<"test" | "sync" | null>(null);
|
||||
const [action, setAction] = useState<"test" | "sync" | "delete" | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<CatalogDatabaseMetadataDeleteTarget | null>(null);
|
||||
const context = useMemo<DatabaseGridContext>(
|
||||
() => ({ canManage, onView, onEdit, onDelete, onOpenSync }),
|
||||
[canManage, onView, onEdit, onDelete, onOpenSync],
|
||||
@@ -236,12 +247,25 @@ export function DatabaseGrid({
|
||||
}).length;
|
||||
const canTestSelection = canManage && selectedRows.length > 0 && selectedRows.every((row) => row.configured && row.id && !row.activeSyncRun);
|
||||
const canSyncSelection = canManage && selectedRows.length > 0 && selectedRows.every((row) => row.configured && row.id && row.connectionStatus === "reachable" && row.testedVersion === row.version && !row.activeSyncRun);
|
||||
const perform = async (kind: "test" | "sync", operation: () => Promise<void>) => {
|
||||
const canDeleteMetadataSelection = canManage && selectedRows.length > 0
|
||||
&& selectedRows.every((row) => row.configured && row.id && !row.activeSyncRun);
|
||||
useEffect(() => {
|
||||
if (!pendingDelete) return;
|
||||
const timer = window.setTimeout(() => document.getElementById("database-cleanup-confirm-button")?.focus(), 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [pendingDelete]);
|
||||
const closeDeleteConfirmation = () => {
|
||||
setPendingDelete(null);
|
||||
window.setTimeout(() => actionsTriggerRef.current?.focus(), 0);
|
||||
};
|
||||
const perform = async (kind: "test" | "sync" | "delete", operation: () => Promise<void>) => {
|
||||
setAction(kind);
|
||||
try {
|
||||
await operation();
|
||||
gridRef.current?.api.deselectAll();
|
||||
setSelectedRows([]);
|
||||
setPendingDelete(null);
|
||||
if (kind === "delete") window.setTimeout(() => searchInputRef.current?.focus(), 0);
|
||||
} finally { setAction(null); }
|
||||
};
|
||||
|
||||
@@ -249,32 +273,81 @@ export function DatabaseGrid({
|
||||
<section aria-label="Workspace databases" className="mx-3 mb-4 mt-4 flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border bg-card sm:mx-5">
|
||||
<div className="flex min-h-12 flex-wrap items-center gap-3 border-b border-border px-3 py-2">
|
||||
{selectedRows.length > 0 ? (
|
||||
<>
|
||||
<span className="text-sm font-semibold">{selectedRows.length} selected</span>
|
||||
{hiddenSelected ? <span className="text-xs text-muted-foreground">{hiddenSelected} hidden by filter</span> : null}
|
||||
<Menu.Root>
|
||||
<Menu.Trigger className="inline-flex h-8 items-center justify-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium hover:bg-muted disabled:pointer-events-none disabled:opacity-50" disabled={action !== null}>Actions <ChevronDown className="size-4" /></Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Positioner side="bottom" align="start" sideOffset={4}>
|
||||
<Menu.Popup className="z-50 min-w-64 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none">
|
||||
<Menu.Item className="rounded-md px-3 py-2 text-sm outline-none data-[highlighted]:bg-muted data-[disabled]:opacity-45" disabled={!canTestSelection} onClick={() => void perform("test", () => onTestSelected(selectedRows))}>Test connections</Menu.Item>
|
||||
<Menu.Separator className="my-1 h-px bg-border" />
|
||||
{databaseSyncScopes.map(({ scope, label }) => (
|
||||
pendingDelete ? (
|
||||
<div
|
||||
role="group"
|
||||
aria-labelledby="database-cleanup-confirmation"
|
||||
className="flex min-w-0 flex-1 flex-wrap items-center gap-2"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape" && action === null) closeDeleteConfirmation();
|
||||
}}
|
||||
>
|
||||
<div className="mr-auto min-w-56">
|
||||
<p id="database-cleanup-confirmation" className="text-sm font-semibold">
|
||||
{pendingDelete === "tables"
|
||||
? `Delete all catalog tables for ${selectedRows.length} database${selectedRows.length === 1 ? "" : "s"}?`
|
||||
: `Delete all relationships for ${selectedRows.length} database${selectedRows.length === 1 ? "" : "s"}?`}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{pendingDelete === "tables"
|
||||
? "Columns and relationships will also be removed. Database configurations and source databases are unchanged."
|
||||
: "Catalog tables, columns, database configurations, and source databases are unchanged."}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" variant="ghost" disabled={action !== null} onClick={closeDeleteConfirmation}>Cancel</Button>
|
||||
<Button
|
||||
id="database-cleanup-confirm-button"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={action !== null}
|
||||
onClick={() => void perform("delete", () => onDeleteMetadataSelected(selectedRows, pendingDelete))}
|
||||
>
|
||||
<Trash2 />{pendingDelete === "tables" ? "Delete catalog tables" : "Delete relationships"}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-sm font-semibold">{selectedRows.length} selected</span>
|
||||
{hiddenSelected ? <span className="text-xs text-muted-foreground">{hiddenSelected} hidden by filter</span> : null}
|
||||
<Menu.Root>
|
||||
<Menu.Trigger ref={actionsTriggerRef} className="inline-flex h-8 items-center justify-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium hover:bg-muted disabled:pointer-events-none disabled:opacity-50" disabled={action !== null}>Actions <ChevronDown className="size-4" /></Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Positioner side="bottom" align="start" sideOffset={4}>
|
||||
<Menu.Popup className="z-50 min-w-64 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none">
|
||||
<Menu.Item className="rounded-md px-3 py-2 text-sm outline-none data-[highlighted]:bg-muted data-[disabled]:opacity-45" disabled={!canTestSelection} onClick={() => void perform("test", () => onTestSelected(selectedRows))}>Test connections</Menu.Item>
|
||||
<Menu.Separator className="my-1 h-px bg-border" />
|
||||
{databaseSyncScopes.map(({ scope, label }) => (
|
||||
<Menu.Item
|
||||
key={scope}
|
||||
className={databaseSyncItemClass}
|
||||
disabled={!canSyncSelection}
|
||||
onClick={() => void perform("sync", () => onSyncSelected(selectedRows, scope))}
|
||||
>
|
||||
{label}
|
||||
</Menu.Item>
|
||||
))}
|
||||
<Menu.Separator className="my-1 h-px bg-border" />
|
||||
<Menu.Item
|
||||
key={scope}
|
||||
className={databaseSyncItemClass}
|
||||
disabled={!canSyncSelection}
|
||||
onClick={() => void perform("sync", () => onSyncSelected(selectedRows, scope))}
|
||||
className="rounded-md px-3 py-2 text-sm text-destructive outline-none data-[highlighted]:bg-destructive/10 data-[disabled]:opacity-45"
|
||||
disabled={!canDeleteMetadataSelection}
|
||||
onClick={() => setPendingDelete("tables")}
|
||||
>
|
||||
{label}
|
||||
Delete all tables
|
||||
</Menu.Item>
|
||||
))}
|
||||
</Menu.Popup>
|
||||
</Menu.Positioner>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
<Button type="button" variant="ghost" disabled={action !== null} onClick={() => { gridRef.current?.api.deselectAll(); setSelectedRows([]); }}><X />Clear</Button>
|
||||
</>
|
||||
<Menu.Item
|
||||
className="rounded-md px-3 py-2 text-sm text-destructive outline-none data-[highlighted]:bg-destructive/10 data-[disabled]:opacity-45"
|
||||
disabled={!canDeleteMetadataSelection}
|
||||
onClick={() => setPendingDelete("relationships")}
|
||||
>
|
||||
Delete all relationships
|
||||
</Menu.Item>
|
||||
</Menu.Popup>
|
||||
</Menu.Positioner>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
<Button type="button" variant="ghost" disabled={action !== null} onClick={() => { gridRef.current?.api.deselectAll(); setSelectedRows([]); }}><X />Clear</Button>
|
||||
</>
|
||||
)
|
||||
) : <><span className="thot-label whitespace-nowrap">Workspace databases</span><input
|
||||
ref={searchInputRef}
|
||||
className="h-8 min-w-40 flex-1 rounded-md border border-input bg-background px-2.5 text-sm outline-none transition focus:border-primary/60 focus:ring-3 focus:ring-ring/15"
|
||||
@@ -308,7 +381,10 @@ export function DatabaseGrid({
|
||||
getRowId={({ data }) => data.workspaceId}
|
||||
rowSelection={{ mode: "multiRow", selectAll: "filtered", enableClickSelection: false }}
|
||||
selectionColumnDef={{ width: 44, maxWidth: 44, pinned: "left" }}
|
||||
onSelectionChanged={({ api }) => setSelectedRows(api.getSelectedRows())}
|
||||
onSelectionChanged={({ api }) => {
|
||||
if (pendingDelete && action === null) setPendingDelete(null);
|
||||
setSelectedRows(api.getSelectedRows());
|
||||
}}
|
||||
rowHeight={44}
|
||||
headerHeight={38}
|
||||
animateRows={false}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Menu } from "@base-ui/react/menu";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AgGridReact } from "ag-grid-react";
|
||||
import type { ColDef, ICellRendererParams } from "ag-grid-community";
|
||||
import { ArrowLeft, Columns3, Pencil, RefreshCw, Save, X } from "lucide-react";
|
||||
import { ArrowLeft, ChevronDown, Columns3, Pencil, RefreshCw, Save, Trash2, X } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { ApiError, apiErrorMessage } from "../../api/client";
|
||||
import {
|
||||
deleteCatalogTableMetadata,
|
||||
listCatalogTables,
|
||||
startCatalogSync,
|
||||
updateCatalogTableMetadata,
|
||||
type CatalogDatabase,
|
||||
type CatalogSyncRun,
|
||||
type CatalogTable,
|
||||
type CatalogTableMetadataDeleteTarget,
|
||||
} from "../../api/catalog-databases";
|
||||
import type { DatabaseNavigationState } from "./model";
|
||||
import { DatabaseColumns } from "./DatabaseColumns";
|
||||
@@ -74,11 +77,14 @@ export function DatabaseTables({
|
||||
const [editorVersion, setEditorVersion] = useState<number | null>(null);
|
||||
const [stale, setStale] = useState(false);
|
||||
const [staleBannerOpen, setStaleBannerOpen] = useState(true);
|
||||
const [busy, setBusy] = useState<"sync" | "save" | null>(null);
|
||||
const [busy, setBusy] = useState<"sync" | "save" | "delete" | null>(null);
|
||||
const [pendingDelete, setPendingDelete] = useState<CatalogTableMetadataDeleteTarget | null>(null);
|
||||
const [columnNavigation, setColumnNavigation] = useState<DatabaseNavigationState>({ dirty: false, busy: false });
|
||||
const gridRef = useRef<AgGridReact<CatalogTable>>(null);
|
||||
const originRef = useRef<HTMLButtonElement | null>(null);
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
const actionsTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const activeTable = activeTableId ? data.find((table) => table.id === activeTableId) : undefined;
|
||||
const editorFingerprint = JSON.stringify([description, generatedDescription]);
|
||||
const editorDirty = Boolean(activeTableId && editorFingerprint !== baseline);
|
||||
@@ -93,6 +99,15 @@ export function DatabaseTables({
|
||||
setStale(true);
|
||||
setStaleBannerOpen(true);
|
||||
}, [activeTable, activeTableId, busy, editorVersion]);
|
||||
useEffect(() => {
|
||||
if (!pendingDelete) return;
|
||||
const timer = window.setTimeout(() => document.getElementById("table-cleanup-confirm-button")?.focus(), 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [pendingDelete]);
|
||||
const closeDeleteConfirmation = () => {
|
||||
setPendingDelete(null);
|
||||
window.setTimeout(() => actionsTriggerRef.current?.focus(), 0);
|
||||
};
|
||||
|
||||
const openTable = (table: CatalogTable, section: "overview" | "columns", origin: HTMLButtonElement) => {
|
||||
originRef.current = origin;
|
||||
@@ -168,6 +183,26 @@ export function DatabaseTables({
|
||||
toast.success(scope === "all" ? "Full schema synchronization started" : scope === "columns" ? "Column synchronization started" : "Table synchronization started");
|
||||
} catch (error) { toast.error(apiErrorMessage(error)); } finally { setBusy(null); }
|
||||
};
|
||||
const deleteMetadata = async (target: CatalogTableMetadataDeleteTarget) => {
|
||||
setBusy("delete");
|
||||
try {
|
||||
const counts = await deleteCatalogTableMetadata(databaseId, selectedIds, target);
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-columns", databaseId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-relationships", databaseId] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["catalog-databases"] }),
|
||||
]);
|
||||
gridRef.current?.api.deselectAll();
|
||||
setSelectedIds([]);
|
||||
setPendingDelete(null);
|
||||
window.setTimeout(() => searchInputRef.current?.focus(), 0);
|
||||
toast.success(target === "columns"
|
||||
? `Deleted ${counts.columns} catalog columns`
|
||||
: `Deleted ${counts.relationships} catalog relationships`);
|
||||
} catch (error) {
|
||||
toast.error(apiErrorMessage(error));
|
||||
} finally { setBusy(null); }
|
||||
};
|
||||
|
||||
const columns = useMemo<ColDef<CatalogTable>[]>(() => [
|
||||
{ field: "name", headerName: "Name", minWidth: 250, flex: 1, cellClass: "font-mono text-xs" },
|
||||
@@ -258,24 +293,80 @@ export function DatabaseTables({
|
||||
<div className="mx-3 mb-4 mt-4 flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border bg-card sm:mx-5">
|
||||
<div className="flex min-h-12 flex-wrap items-center gap-3 border-b border-border px-3 py-2">
|
||||
{selectedIds.length > 0 ? (
|
||||
<>
|
||||
<span className="text-sm font-semibold">{selectedIds.length} selected</span>
|
||||
{visibleSelected !== selectedIds.length ? <span className="text-xs text-muted-foreground">{selectedIds.length - visibleSelected} hidden by filter</span> : null}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={!canManage || !bindingReady || busy !== null || Boolean(currentRun)}
|
||||
title={!bindingReady ? "Test the current database binding before synchronizing columns" : undefined}
|
||||
onClick={() => void synchronize("columns", selectedIds)}
|
||||
pendingDelete ? (
|
||||
<div
|
||||
role="group"
|
||||
aria-labelledby="table-cleanup-confirmation"
|
||||
className="flex min-w-0 flex-1 flex-wrap items-center gap-2"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape" && busy === null) closeDeleteConfirmation();
|
||||
}}
|
||||
>
|
||||
<RefreshCw className={busy === "sync" ? "animate-spin" : ""} />Synchronize columns
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => { gridRef.current?.api.deselectAll(); setSelectedIds([]); }}><X />Clear</Button>
|
||||
</>
|
||||
<div className="mr-auto min-w-56">
|
||||
<p id="table-cleanup-confirmation" className="text-sm font-semibold">
|
||||
{pendingDelete === "columns"
|
||||
? `Delete all catalog columns for ${selectedIds.length} table${selectedIds.length === 1 ? "" : "s"}?`
|
||||
: `Delete all relationships for ${selectedIds.length} table${selectedIds.length === 1 ? "" : "s"}?`}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{pendingDelete === "columns"
|
||||
? "Only columns belonging to the selected catalog tables will be removed."
|
||||
: "All incoming and outgoing relationships for the selected catalog tables will be removed."}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" variant="ghost" disabled={busy !== null} onClick={closeDeleteConfirmation}>Cancel</Button>
|
||||
<Button
|
||||
id="table-cleanup-confirm-button"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={busy !== null}
|
||||
onClick={() => void deleteMetadata(pendingDelete)}
|
||||
>
|
||||
<Trash2 />{pendingDelete === "columns" ? "Delete columns" : "Delete relationships"}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-sm font-semibold">{selectedIds.length} selected</span>
|
||||
{visibleSelected !== selectedIds.length ? <span className="text-xs text-muted-foreground">{selectedIds.length - visibleSelected} hidden by filter</span> : null}
|
||||
<Menu.Root>
|
||||
<Menu.Trigger ref={actionsTriggerRef} className="inline-flex h-8 items-center justify-center gap-2 rounded-md border border-input bg-background px-3 text-sm font-medium hover:bg-muted disabled:pointer-events-none disabled:opacity-50" disabled={busy !== null}>Actions <ChevronDown className="size-4" /></Menu.Trigger>
|
||||
<Menu.Portal>
|
||||
<Menu.Positioner side="bottom" align="start" sideOffset={4}>
|
||||
<Menu.Popup className="z-50 min-w-64 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none">
|
||||
<Menu.Item
|
||||
className="rounded-md px-3 py-2 text-sm outline-none data-[highlighted]:bg-muted data-[disabled]:opacity-45"
|
||||
disabled={!canManage || !bindingReady || busy !== null || Boolean(currentRun)}
|
||||
onClick={() => void synchronize("columns", selectedIds)}
|
||||
>
|
||||
Synchronize columns
|
||||
</Menu.Item>
|
||||
<Menu.Separator className="my-1 h-px bg-border" />
|
||||
<Menu.Item
|
||||
className="rounded-md px-3 py-2 text-sm text-destructive outline-none data-[highlighted]:bg-destructive/10 data-[disabled]:opacity-45"
|
||||
disabled={!canManage || busy !== null || Boolean(currentRun)}
|
||||
onClick={() => setPendingDelete("columns")}
|
||||
>
|
||||
Delete all columns
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
className="rounded-md px-3 py-2 text-sm text-destructive outline-none data-[highlighted]:bg-destructive/10 data-[disabled]:opacity-45"
|
||||
disabled={!canManage || busy !== null || Boolean(currentRun)}
|
||||
onClick={() => setPendingDelete("relationships")}
|
||||
>
|
||||
Delete all relationships
|
||||
</Menu.Item>
|
||||
</Menu.Popup>
|
||||
</Menu.Positioner>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
<Button type="button" variant="ghost" onClick={() => { gridRef.current?.api.deselectAll(); setSelectedIds([]); }}><X />Clear</Button>
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<span className="thot-label whitespace-nowrap">Catalog tables</span>
|
||||
<input className="h-8 min-w-40 flex-1 rounded-md border border-input bg-background px-2.5 text-sm outline-none focus:border-primary/60 focus:ring-3 focus:ring-ring/15" aria-label="Search tables" placeholder="Search" value={search} onChange={(event) => setSearch(event.target.value)} />
|
||||
<input ref={searchInputRef} className="h-8 min-w-40 flex-1 rounded-md border border-input bg-background px-2.5 text-sm outline-none focus:border-primary/60 focus:ring-3 focus:ring-ring/15" aria-label="Search tables" placeholder="Search" value={search} onChange={(event) => setSearch(event.target.value)} />
|
||||
<span
|
||||
aria-live="polite"
|
||||
className="whitespace-nowrap text-xs tabular-nums text-muted-foreground"
|
||||
@@ -300,7 +391,10 @@ export function DatabaseTables({
|
||||
defaultColDef={{ sortable: true, filter: true, resizable: true }}
|
||||
getRowId={({ data: table }) => table.id}
|
||||
rowSelection={{ mode: "multiRow", selectAll: "filtered", enableClickSelection: false }}
|
||||
onSelectionChanged={({ api }) => setSelectedIds(api.getSelectedRows().map((table) => table.id))}
|
||||
onSelectionChanged={({ api }) => {
|
||||
if (pendingDelete && busy === null) setPendingDelete(null);
|
||||
setSelectedIds(api.getSelectedRows().map((table) => table.id));
|
||||
}}
|
||||
onModelUpdated={({ api }) => setDisplayedCount(api.getDisplayedRowCount())}
|
||||
rowHeight={44}
|
||||
headerHeight={38}
|
||||
|
||||
Reference in New Issue
Block a user