feat(database): group and filter the Modify Table list (#6248)

The Modify Table / Create Table list was one flat list of columns. It now
groups Columns, Keys (the primary key as edited), Foreign Keys, Indexes and
Triggers, each collapsible with its count, and a filter on its toolbar
narrows the rows by name or type. The statements the dialog runs are
unchanged.

Fixes #6128
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-27 03:54:09 +08:00
1 джерело 8968974f42
коміт fd4efff6e3
8 files changed
+257 -21

No files matched your search

+17
Переглянути файл
@@ -954,6 +954,23 @@
padding: 2px 4px;
border-bottom: 1px solid var(--border);
}
.modifyFilter {
flex: 1;
min-width: 0;
}
.modifyGroup {
display: flex;
align-items: center;
gap: var(--space-1);
height: 22px;
padding: 0 6px;
color: var(--fg-muted);
cursor: default;
white-space: nowrap;
}
.modifyGroup:hover {
color: var(--fg);
}
.modifyList {
flex: 1;
overflow: auto;
+136 -16
Переглянути файл
@@ -4,7 +4,14 @@
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { call, commands, type DbColumnInfo, type DbDriver, type DbTableGrant } from "@/platform/ipc";
import {
call,
commands,
type DbColumnInfo,
type DbDriver,
type DbTableDetails,
type DbTableGrant,
} from "@/platform/ipc";
import { highlightInto } from "@/editor/lsp/markdown";
import {
Button,
@@ -14,6 +21,7 @@ import {
Input,
Popup,
Icon,
SearchField,
Select,
T,
Tabs,
@@ -551,7 +559,8 @@ function ModifyTableDialog(props: ModifyProps) {
if (table && !details) void loadDetails(id, schema, table);
}, [details, id, schema, table]);
if (!table) return <ModifyTableForm {...props} initial={null} />;
if (details?.status === "ok") return <ModifyTableForm {...props} initial={details.value.columns} />;
if (details?.status === "ok")
return <ModifyTableForm {...props} initial={details.value.columns} details={details.value} />;
return (
<Dialog
open
@@ -565,6 +574,63 @@ function ModifyTableDialog(props: ModifyProps) {
);
}
/** A read-only row of the Modify Table list (a key, foreign key, index or trigger). */
interface ObjectRow {
key: string;
name: string;
detail: string;
}
/**
* The groups after Columns, as DataGrip lists them: the primary key of the columns as edited,
* then the foreign keys, indexes and triggers the table has (shown, not edited here).
*/
function objectGroups(
columns: readonly ColumnDraft[],
details: DbTableDetails | null | undefined,
): Array<{ id: string; label: string; icon: string; rows: ObjectRow[] }> {
const pk = columns.filter((c) => c.primaryKey && !c.dropped).map((c) => c.name);
const list = (names: readonly string[]) => `(${names.join(", ")})`;
return [
{
id: "keys",
label: "Keys",
icon: "db-key",
rows: pk.length ? [{ key: "primary", name: "PRIMARY KEY", detail: list(pk) }] : [],
},
{
id: "foreignKeys",
label: "Foreign Keys",
icon: "db-foreign-key",
rows: (details?.foreignKeys ?? []).map((fk, i) => ({
key: `fk-${i}`,
name: list(fk.columns),
detail: `→ ${fk.refTable} ${list(fk.refColumns)}`,
})),
},
{
id: "indexes",
label: "Indexes",
icon: "db-index",
rows: (details?.indexes ?? []).map((ix) => ({
key: `ix-${ix.name}`,
name: ix.name,
detail: `${ix.unique ? "UNIQUE " : ""}${list(ix.columns)}`,
})),
},
{
id: "triggers",
label: "Triggers",
icon: "db-trigger",
rows: (details?.triggers ?? []).map((t) => ({
key: `tr-${t.name}`,
name: t.name,
detail: `${t.timing} ${t.events}`.toUpperCase(),
})),
},
];
}
function ModifyTableForm({
id,
schema,
@@ -572,7 +638,8 @@ function ModifyTableForm({
focusColumn,
addColumn,
initial,
}: ModifyProps & { initial: DbColumnInfo[] | null }) {
details,
}: ModifyProps & { initial: DbColumnInfo[] | null; details?: DbTableDetails }) {
const driver = driverOf(id);
const [name, setName] = useState(table ?? "table_name");
const [columns, setColumns] = useState<ColumnDraft[]>(() => {
@@ -611,6 +678,28 @@ function ModifyTableForm({
}
};
const locked = !!current && !canAlterColumn(driver, current);
// The list's filter (names and types) and its collapsed groups.
const [filter, setFilter] = useState("");
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
const query = filter.trim().toLowerCase();
const matches = (...texts: string[]) => !query || texts.some((t) => t.toLowerCase().includes(query));
const shownColumns = columns.filter((c) => matches(c.name, c.dataType));
const groups = objectGroups(columns, details)
.map((g) => ({ ...g, rows: g.rows.filter((r) => matches(r.name, r.detail)) }))
.filter((g) => g.rows.length);
const toggleGroup = (group: string) =>
setCollapsed((c) => {
const next = new Set(c);
if (!next.delete(group)) next.add(group);
return next;
});
const groupHeader = (group: string, label: string, count: number) => (
<div className={styles.modifyGroup} onMouseDown={() => toggleGroup(group)}>
<Icon name={collapsed.has(group) ? "chevron-right" : "chevron-down"} size={12} />
<span>{tx(label)}</span>
<span className={styles.treeType}>{count}</span>
</div>
);
const showGrants = !!table && grantsSupported(driver);
const [tab, setTab] = useState<"columns" | "grants">("columns");
const title = table ? `Modify Table ${table}` : "Create Table";
@@ -672,21 +761,52 @@ function ModifyTableForm({
disabled={!current}
onClick={remove}
/>
<SearchField
variant="bare"
className={styles.modifyFilter}
value={filter}
onChange={setFilter}
placeholder="Filter by name or type"
aria-label="Filter columns"
/>
</div>
<div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}>
{columns.map((c) => (
<div
key={c.key}
role="option"
aria-selected={c.key === selected}
tabIndex={-1}
className={styles.modifyItem}
data-dropped={c.dropped || undefined}
onMouseDown={() => setSelected(c.key)}
>
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
<span className={styles.treeType}>{c.dataType}</span>
<div role="group" aria-label={tx("Columns")}>
{groupHeader("columns", "Columns", shownColumns.length)}
{!collapsed.has("columns") &&
shownColumns.map((c) => (
<div
key={c.key}
role="option"
aria-selected={c.key === selected}
tabIndex={-1}
className={styles.modifyItem}
data-dropped={c.dropped || undefined}
onMouseDown={() => setSelected(c.key)}
>
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
<span className={styles.treeType}>{c.dataType}</span>
</div>
))}
</div>
{groups.map((g) => (
<div key={g.id} role="group" aria-label={tx(g.label)}>
{groupHeader(g.id, g.label, g.rows.length)}
{!collapsed.has(g.id) &&
g.rows.map((r) => (
<div
key={r.key}
role="option"
aria-selected={false}
aria-disabled
className={styles.modifyItem}
>
<Icon name={g.icon} size={16} />
<span className={styles.nodeLabel}>{r.name}</span>
<span className={styles.treeType}>{r.detail}</span>
</div>
))}
</div>
))}
</div>
+79
Переглянути файл
@@ -0,0 +1,79 @@
import { afterEach, describe, expect, it } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { ObjectDialogs } from "./ObjectDialogs";
import { detailsKey, openDialog, useDatabase } from "./store";
const column = (name: string, dataType: string, primaryKey = false) => ({
name,
dataType,
nullable: !primaryKey,
default: null,
primaryKey,
});
function open() {
useDatabase.setState({
details: {
[detailsKey("db", "main", "orders")]: {
status: "ok",
value: {
columns: [column("id", "integer", true), column("customer_id", "integer"), column("note", "text")],
indexes: [{ name: "orders_customer", unique: false, columns: ["customer_id"] }],
foreignKeys: [
{
schema: "main",
table: "orders",
columns: ["customer_id"],
refSchema: "main",
refTable: "customers",
refColumns: ["id"],
},
],
triggers: [],
},
},
},
} as never);
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: "orders" });
render(<ObjectDialogs />);
}
const rows = (group: string) =>
within(screen.getByRole("group", { name: group }))
.queryAllByRole("option")
.map((o) => o.textContent);
afterEach(() => useDatabase.setState({ dialog: null, details: {} } as never));
describe("Modify Table's list (DataGrip)", () => {
it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => {
open();
expect(rows("Columns")).toEqual(["idinteger", "customer_idinteger", "notetext"]);
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
expect(rows("Indexes")).toEqual(["orders_customer(customer_id)"]);
// No triggers: no group.
expect(screen.queryByRole("group", { name: "Triggers" })).toBeNull();
// A group collapses from its header.
fireEvent.mouseDown(within(screen.getByRole("group", { name: "Indexes" })).getByText("Indexes"));
expect(rows("Indexes")).toEqual([]);
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "TEXT" } });
expect(rows("Columns")).toEqual(["notetext"]);
expect(screen.queryByRole("group", { name: "Foreign Keys" })).toBeNull();
fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "customer" } });
expect(rows("Columns")).toEqual(["customer_idinteger"]);
expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]);
});
it("keeps Keys on the primary key as edited in Create Table", () => {
openDialog({ kind: "modifyTable", id: "db", schema: "main", table: null });
render(<ObjectDialogs />);
expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]);
fireEvent.click(screen.getByRole("button", { name: "Add Column" }));
fireEvent.click(screen.getByRole("checkbox", { name: "Primary key" }));
expect(rows("Keys")).toEqual(["PRIMARY KEY(id, column_2)"]);
});
});
+5 -1
Переглянути файл
@@ -4153,5 +4153,9 @@
"Open in Value Editor": "Open in Value Editor",
"Show Aggregate View": "Show Aggregate View",
"Data Extractor": "Data Extractor",
"Export Table to Clipboard": "Export Table to Clipboard"
"Export Table to Clipboard": "Export Table to Clipboard",
"Keys": "Keys",
"Triggers": "Triggers",
"Filter by name or type": "Filter by name or type",
"Filter columns": "Filter columns"
}
+5 -1
Переглянути файл
@@ -10168,5 +10168,9 @@
"Open in Value Editor": "Открыть в редакторе значений",
"Show Aggregate View": "Показать агрегаты",
"Data Extractor": "Экстрактор данных",
"Export Table to Clipboard": "Экспортировать таблицу в буфер обмена"
"Export Table to Clipboard": "Экспортировать таблицу в буфер обмена",
"Keys": "Ключи",
"Triggers": "Триггеры",
"Filter by name or type": "Фильтр по имени или типу",
"Filter columns": "Фильтр столбцов"
}
+5 -1
Переглянути файл
@@ -8829,5 +8829,9 @@
"Open in Value Editor": "Değer Düzenleyicide Aç",
"Show Aggregate View": "Toplam Görünümünü Göster",
"Data Extractor": "Veri Çıkarıcı",
"Export Table to Clipboard": "Tabloyu Panoya Aktar"
"Export Table to Clipboard": "Tabloyu Panoya Aktar",
"Keys": "Anahtarlar",
"Triggers": "Tetikleyiciler",
"Filter by name or type": "Ada veya türe göre filtrele",
"Filter columns": "Sütunları filtrele"
}
+5 -1
Переглянути файл
@@ -9367,5 +9367,9 @@
"Open in Value Editor": "在值編輯器中開啟",
"Show Aggregate View": "顯示彙總檢視",
"Data Extractor": "資料擷取器",
"Export Table to Clipboard": "將表格匯出到剪貼簿"
"Export Table to Clipboard": "將表格匯出到剪貼簿",
"Keys": "鍵",
"Triggers": "觸發器",
"Filter by name or type": "依名稱或類型篩選",
"Filter columns": "篩選欄"
}
+5 -1
Переглянути файл
@@ -10597,5 +10597,9 @@
"Open in Value Editor": "在值编辑器中打开",
"Show Aggregate View": "显示聚合视图",
"Data Extractor": "数据提取器",
"Export Table to Clipboard": "将表导出到剪贴板"
"Export Table to Clipboard": "将表导出到剪贴板",
"Keys": "键",
"Triggers": "触发器",
"Filter by name or type": "按名称或类型过滤",
"Filter columns": "过滤列"
}