25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(structure): sort index drafts by their key-column list
Xsyl.waya913d2dd8324
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex e5a749d6cd..2b05dd2a2a 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -125,6 +125,7 @@ import { PARTITION_TREE_INDENT_PX, flattenPgPartitionNodes, pgPartitionBoundTextimport { formatBytes } from "@/lib/database/serverMetrics";import { hasTableStructureRefreshWork, unloadedTableStructureRefreshScope, visibleTableStructureRefreshScope, type TableStructureRefreshScope } from "@/lib/table/tableStructureMetadataLoading";import { canAddTableStructureColumn, getTableStructureCapabilities, hasLocalTableColumnOrderChange, isPhysicalTableColumnOrderChange, sanitizeStructureIndexesForCapabilities, supportsLocalTableColumnReorder } from "@/lib/table/tableStructureCapabilities";+import { sortStructureIndexesByColumns, type StructureIndexColumnSort } from "@/lib/table/structureIndexSort";import { getConcurrentIndexAvailability, concurrentIndexNamesInStatements, normalizeUnsupportedConcurrentIndexes, type ConcurrentIndexAvailability } from "@/lib/table/concurrentIndexAvailability";import { orderedColumnIndexes, uniqueDataGridColumnOrderKeys } from "@/lib/dataGrid/dataGridColumnOrder";import { loadTableDataGridColumnOrder, notifyTableDataGridColumnOrderChanged, removeTableDataGridColumnOrder, saveTableDataGridColumnOrder, tableDataGridColumnOrderScopeKey } from "@/lib/dataGrid/dataGridColumnLayoutStorage";@@ -590,6 +591,12 @@ let copySourceTablesRequestId = 0;let copySourceColumnsRequestId = 0;let copySourceTableSearchTimer: ReturnType<typeof setTimeout> | undefined;const indexes = ref<EditableStructureIndex[]>([]);+const indexColumnSort = ref<StructureIndexColumnSort | null>(null);+const displayedIndexes = computed(() => (indexColumnSort.value ? sortStructureIndexesByColumns(indexes.value, indexColumnSort.value) : indexes.value));++function toggleIndexColumnSort() {+ indexColumnSort.value = indexColumnSort.value === "asc" ? "desc" : indexColumnSort.value === "desc" ? null : "asc";+}/** PostgreSQL partitioned parent (`relkind = 'p'`): `CREATE INDEX CONCURRENTLY`* is rejected by the server on such tables, so the option is disabled here and* the SQL builder refuses any concurrent request on it (fail closed). */@@ -5075,7 +5082,9 @@ function scrollToIndexSearchMatch(direction: 1 | -1 = 1) {return;}const rows = Array.from(rootRef.value?.querySelectorAll<HTMLElement>("[data-index-row-index]") ?? []);- const matches = indexes.value.map((index, rowIndex) => ({ index, rowIndex })).filter(({ index }) => indexMatchesSearch(index));+ // DOM rows render in displayedIndexes order, which differs from indexes.value+ // once the column-list sort is active.+ const matches = displayedIndexes.value.map((index, rowIndex) => ({ index, rowIndex })).filter(({ index }) => indexMatchesSearch(index));if (!matches.length) return;const currentIndex = highlightedIndexId.value ? matches.findIndex(({ index }) => index.id === highlightedIndexId.value) : -1;const nextMatch = matches[(currentIndex + direction + matches.length) % matches.length] ?? matches[0];@@ -5414,10 +5423,12 @@ function newIndexDraft(): EditableStructureIndex {function addIndex() {if (!structureCapabilities.value.createIndex || indexesLoading.value) return;activeTab.value = "indexes";- indexes.value.push(newIndexDraft());+ const draft = newIndexDraft();+ indexes.value.push(draft);void nextTick(() => {- const indexRows = rootRef.value?.querySelectorAll<HTMLElement>('[data-new-index-row="true"]');- const row = indexRows?.[indexRows.length - 1];+ // The sorted DOM order is not the insertion order; focus the row belonging+ // to this draft instead of the last rendered new-index row.+ const row = Array.from(rootRef.value?.querySelectorAll<HTMLElement>("[data-index-row-id]") ?? []).find((candidate) => candidate.dataset.indexRowId === draft.id);const input = row?.querySelector<HTMLInputElement>("[data-index-name-input]");row?.scrollIntoView({ block: "nearest" });input?.focus();@@ -8159,19 +8170,24 @@ watch(<thv-for="(label, i) in indexColLabels":key="i"- :class="[structureHeaderCellClass, { 'text-center': i === 2 || i === 7 }]"+ :class="[structureHeaderCellClass, { 'text-center': i === 2 || i === 7, 'cursor-pointer select-none': i === 1 }]"+ :aria-sort="i === 1 ? (indexColumnSort === 'asc' ? 'ascending' : indexColumnSort === 'desc' ? 'descending' : 'none') : undefined":style="{width: indexColWidths[i] + 'px',minWidth: indexColWidths[i] + 'px',}"+ @click="i === 1 && toggleIndexColumnSort()">- {{ label }}- <div v-if="i < indexColLabels.length - 1" class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30" :class="resizing?.col === i ? 'bg-primary/30' : ''" @mousedown="onIndexColResize($event, i)" />+ <span class="inline-flex items-center gap-1">+ {{ label }}+ <span v-if="i === 1" class="text-[10px] text-muted-foreground">{{ indexColumnSort === "asc" ? "▲" : indexColumnSort === "desc" ? "▼" : "↕" }}</span>+ </span>+ <div v-if="i < indexColLabels.length - 1" class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30" :class="resizing?.col === i ? 'bg-primary/30' : ''" @mousedown="onIndexColResize($event, i)" @click.stop /></th></tr></thead><tbody>- <tr v-for="(index, rowIndex) in indexes" :key="index.id" :class="indexRowClass(index)" :data-new-index-row="!index.original ? 'true' : undefined" :data-index-row-index="rowIndex">+ <tr v-for="(index, rowIndex) in displayedIndexes" :key="index.id" :class="indexRowClass(index)" :data-index-row-id="index.id" :data-new-index-row="!index.original ? 'true' : undefined" :data-index-row-index="rowIndex"><td :class="[structureCellClass, 'structure-index-name']"><div class="flex min-w-0 items-center gap-1"><KeyRound :class="[structureIconClass, 'structure-column-key-icon shrink-0']" :title="index.isPrimary ? 'PRIMARY' : index.isUnique ? 'UNIQUE' : index.indexType || 'INDEX'" />diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.tsindex 50529e5781..9824e5a0b3 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts@@ -426,6 +426,70 @@ describe("TableStructureEditor column index actions", () => {expect(mocks.executeBatch).not.toHaveBeenCalled();});+ it("navigates index search matches in sorted row order", async () => {+ const indexDrafts = createIndexDrafts([+ { name: "idx_z", columns: ["z"], is_unique: false, is_primary: false },+ { name: "idx_a", columns: ["a"], is_unique: false, is_primary: false },+ ]);+ const draft = savedIndexDraft(indexDrafts[0]!);+ draft.indexes = indexDrafts;++ const root = await mountStructureEditor(draft);+ const rows = [...root.querySelectorAll<HTMLElement>("[data-index-row-id]")];+ expect(rows.map((row) => row.dataset.indexRowId)).toEqual(["existing:idx_z", "existing:idx_a"]);+ const scrollSpies = new Map(rows.map((row) => [row.dataset.indexRowId!, vi.fn()]));+ for (const row of rows) row.scrollIntoView = scrollSpies.get(row.dataset.indexRowId!)!;++ root.querySelector<HTMLElement>("th[aria-sort]")!.click();+ await settle();+ expect([...root.querySelectorAll<HTMLElement>("[data-index-row-id]")].map((row) => row.dataset.indexRowId)).toEqual(["existing:idx_a", "existing:idx_z"]);++ const search = root.querySelector<HTMLInputElement>('input[placeholder="structureEditor.searchIndexes"]')!;+ search.value = "idx";+ search.dispatchEvent(new Event("input", { bubbles: true }));+ await settle();+ search.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+ await settle();++ expect(root.querySelector<HTMLElement>("[data-index-row-id].structure-column-search-current")?.dataset.indexRowId).toBe("existing:idx_a");+ expect(scrollSpies.get("existing:idx_a")).toHaveBeenCalledOnce();+ expect(scrollSpies.get("existing:idx_z")).not.toHaveBeenCalled();+ });++ it("focuses the newly added index when sorted before an older draft", async () => {+ const seedDraft: EditableStructureIndex = {+ id: "new:seed",+ name: "idx_seed",+ columns: ["z"],+ nameEdited: true,+ isUnique: false,+ isPrimary: false,+ filter: "",+ indexType: "BTREE",+ includedColumns: [],+ comment: "",+ concurrently: false,+ columnOpclasses: [],+ markedForDrop: false,+ };+ const draft = savedIndexDraft(seedDraft);+ draft.indexes = [...createIndexDrafts([{ name: "idx_a", columns: ["a"], is_unique: false, is_primary: false }]), seedDraft];++ const root = await mountStructureEditor(draft);+ root.querySelector<HTMLElement>("th[aria-sort]")!.click();+ await settle();++ const addButton = [...root.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("structureEditor.addIndex"));+ expect(addButton).toBeDefined();+ addButton!.click();+ await settle();++ const activeInput = document.activeElement as HTMLInputElement | null;+ expect(activeInput?.matches("[data-index-name-input]")).toBe(true);+ expect(activeInput?.closest<HTMLElement>("[data-index-row-id]")?.dataset.indexRowIndex).toBe("0");+ expect(activeInput?.value).toBe("");+ });+it("builds a composite index in selection order and appends fields without duplicates", async () => {loadMetadata();const root = await mountStructureEditor();diff --git a/apps/desktop/src/lib/__tests__/table/structureIndexSort.spec.ts b/apps/desktop/src/lib/__tests__/table/structureIndexSort.spec.tsnew file mode 100644index 0000000000..921545f3c4--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/structureIndexSort.spec.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vitest";+import { sortStructureIndexesByColumns } from "@/lib/table/structureIndexSort";++function index(id: string, columns: string[], isPrimary = false) {+ return { id, columns, isPrimary };+}++describe("sortStructureIndexesByColumns", () => {+ const indexes = [index("composite", ["last_name", "first_name"]), index("primary", ["id"], true), index("id", ["id"]), index("last_name", ["last_name"])];++ it("sorts by the joined key-column list and keeps the primary key first", () => {+ expect(sortStructureIndexesByColumns(indexes, "asc").map((item) => item.id)).toEqual(["primary", "id", "last_name", "composite"]);+ });++ it("reverses the maintenance indexes but never moves the primary key", () => {+ expect(sortStructureIndexesByColumns(indexes, "desc").map((item) => item.id)).toEqual(["primary", "composite", "last_name", "id"]);+ });++ it("compares column names case-insensitively", () => {+ expect(sortStructureIndexesByColumns([index("upper", ["B"]), index("lower", ["a"])], "asc").map((item) => item.id)).toEqual(["lower", "upper"]);+ });+});diff --git a/apps/desktop/src/lib/table/structureIndexSort.ts b/apps/desktop/src/lib/table/structureIndexSort.tsnew file mode 100644index 0000000000..053d511e94--- /dev/null+++ b/apps/desktop/src/lib/table/structureIndexSort.ts@@ -0,0 +1,16 @@+export type StructureIndexColumnSort = "asc" | "desc";++/**+ * Sorts index drafts by their key-column list (#12550). The joined column list+ * keeps composite indexes grouped by their leading column; the primary key+ * always stays first because it is the table identity, not a maintenance index.+ */+export function sortStructureIndexesByColumns<T extends { columns: readonly string[]; isPrimary: boolean }>(indexes: readonly T[], direction: StructureIndexColumnSort): T[] {+ const factor = direction === "asc" ? 1 : -1;+ const sorted = [...indexes].sort((left, right) => {+ const leftKey = left.columns.join("\u0000").toLowerCase();+ const rightKey = right.columns.join("\u0000").toLowerCase();+ return leftKey.localeCompare(rightKey) * factor;+ });+ return [...sorted.filter((index) => index.isPrimary), ...sorted.filter((index) => !index.isPrimary)];+}