feat(structure): improve type colors and index editing

This commit is contained in:
weekhy authored and GitHub committed 2026-10-04 00:04:49 +08:00
1 parent da1094df93
commit fa7dde7c03
33 files changed
+1631 -132

No files matched your search

+6
View File
@@ -1015,6 +1015,12 @@ const specialPageTabs = computed(() => ({
}));
provide(GROUP_TAB_BAR_PORTAL, createGroupTabBarPortal(computed(() => !isDetachedWindowContext && (driverStoreActive.value || pluginCenterActive.value || settingsStore.settingsPageActive))));
provide(EDITOR_TOOLBAR_ACTIONS, {
canNewQuery: canCreateNewQuery,
newQuery: (groupId: string) => {
queryStore.focusGroup(groupId);
newQueryContextSource.value = "tab";
void newQuery();
},
explainMode,
blockDangerousRedisCommands,
databaseRequiredSignalFor: (tabId: string) => (databaseRequiredTabId.value === tabId ? databaseRequiredSignal.value : 0),
@@ -12193,6 +12193,8 @@ defineExpose({
toggleDdl: toggleTableInfo,
showTableInfo,
toggleTableInfo,
canOpenTableStructureEditor,
openTableStructureEditor,
multiRowTranspose,
setMultiRowTranspose,
toggleMultiRowTranspose,
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";
import { createApp, defineComponent, h, markRaw, nextTick, ref, type App, type PropType } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -95,6 +95,7 @@ function mountGrid(
};
const host = document.createElement("div");
const grid = ref<{ canOpenTableStructureEditor: boolean; openTableStructureEditor: (tab: TableInfoTab) => void }>();
document.body.append(host);
const Root = defineComponent({
setup() {
@@ -105,6 +106,7 @@ function mountGrid(
{
default: () =>
h(DataGrid, {
ref: grid,
result,
databaseType: options.databaseType ?? "mysql",
context: options.context ?? "table-data",
@@ -123,7 +125,7 @@ function mountGrid(
app.component("RecycleScroller", RecycleScroller);
app.mount(host);
mountedApps.push({ app, host });
return { host, openTableStructure };
return { host, openTableStructure, grid };
}
async function settle() {
@@ -153,6 +155,15 @@ afterEach(() => {
});
describe("DataGrid edit-table-structure shortcut", () => {
it("exposes columns navigation to the table header even when the information drawer is closed", async () => {
const { host, openTableStructure, grid } = mountGrid({ tableInfoTab: "indexes" });
await settle();
expect(host.querySelector("[data-edit-table-structure]")).toBeNull();
expect(grid.value?.canOpenTableStructureEditor).toBe(true);
grid.value!.openTableStructureEditor("columns");
expect(openTableStructure).toHaveBeenCalledExactlyOnceWith("connection-1", "app", "public", "users", "columns", undefined, "warehouse", "table");
});
it("opens the existing structure editor route for an eligible table-data grid", async () => {
const { host, openTableStructure } = mountGrid();
await settle();
@@ -219,6 +230,7 @@ describe("DataGrid edit-table-structure shortcut", () => {
expect(event.defaultPrevented).toBe(false);
expect(bubbled).toHaveBeenCalledOnce();
expect(openTableStructure).not.toHaveBeenCalled();
expect(host.querySelector("[data-edit-table-structure]")).toBeNull();
});
it("leaves editable text targets untouched", async () => {
@@ -268,7 +280,7 @@ describe("DataGrid edit-table-structure shortcut", () => {
const { host, openTableStructure } = mountGrid({ tableInfoTab: "triggers", autoShowTableInfo: true });
await settle();
const editButton = host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("contextMenu.editStructure")}"]`);
const editButton = host.querySelector<HTMLButtonElement>(`.table-info-action-button[aria-label="${i18n.global.t("contextMenu.editStructure")}"]`);
expect(editButton).not.toBeNull();
editButton!.click();
await settle();
@@ -36,6 +36,7 @@ import {
X,
Pin,
Pencil,
PencilRuler,
Rows3,
Hash,
SquareDashed,
@@ -220,6 +221,8 @@ type DataGridHandle = DataGridColumnLayoutHandle & {
openExtractorConfiguration: () => void;
showDdl: boolean;
toggleDdl: (tab?: TableInfoTab) => void;
canOpenTableStructureEditor: boolean;
openTableStructureEditor: (tab: TableInfoTab) => void;
multiRowTranspose: boolean;
setMultiRowTranspose: (value: boolean) => void;
exportCsv: () => Promise<void>;
@@ -2691,6 +2694,12 @@ defineExpose({
</button>
<span v-if="showDataColumnsChip && activeDataTabTableMeta" class="inline-flex shrink-0 items-center rounded border border-border bg-muted/30 px-2 py-0.5 font-medium text-muted-foreground tabular-nums"> {{ activeDataTabTableMeta.columns.length }} {{ t("tree.columns") }} </span>
<span class="ml-auto" />
<LightTooltip v-if="dataGridRef?.canOpenTableStructureEditor" :text="t('contextMenu.editStructure')" side="bottom" nowrap>
<Button data-edit-table-structure variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :aria-label="t('contextMenu.editStructure')" @click="dataGridRef?.openTableStructureEditor('columns')">
<PencilRuler class="h-3.5 w-3.5" />
<span v-if="!dataToolbarCompact">{{ t("contextMenu.editStructure") }}</span>
</Button>
</LightTooltip>
<DataGridColumnLayoutPopover v-if="activeTab.result?.columns.length" :grid="dataGridRef" trigger-class="px-1.5" />
<Button v-if="activeTab.result && activeDataTabTableMeta && activeTab.connectionId" variant="ghost" size="sm" class="h-5 text-xs px-1.5 shrink-0" :class="{ 'bg-accent': dataGridRef?.showDdl }" :title="dataToolbarCompact ? t('grid.tableInfo') : undefined" @click="dataGridRef?.toggleDdl()"
><TableProperties class="h-3.5 w-3.5" /><span v-if="!dataToolbarCompact">{{ t("grid.tableInfo") }}</span></Button
@@ -27,7 +27,7 @@ const TAB_DRAG_HORIZONTAL_THRESHOLD = 24;
</script>
<script setup lang="ts">
import { computed, nextTick, onUnmounted, ref, watch } from "vue";
import { computed, inject, nextTick, onUnmounted, ref, watch } from "vue";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
import {
@@ -54,6 +54,7 @@ import {
Pencil,
Pin,
PlugZap,
Plus,
RotateCcw,
RotateCw,
Search,
@@ -75,6 +76,7 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import TabExecutionStatus from "@/components/layout/TabExecutionStatus.vue";
import TabModeIcon from "@/components/layout/TabModeIcon.vue";
import ReadOnlySessionControl from "@/components/connection/ReadOnlySessionControl.vue";
import { EDITOR_TOOLBAR_ACTIONS } from "./editorToolbarActions";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore";
@@ -127,6 +129,8 @@ const { t } = useI18n();
const queryStore = useQueryStore();
const settingsStore = useSettingsStore();
const connectionStore = useConnectionStore();
const toolbar = inject(EDITOR_TOOLBAR_ACTIONS, null);
const canNewQuery = computed(() => toolbar?.canNewQuery.value ?? false);
const { toast } = useToast();
const tabsContainerRef = ref<HTMLElement | null>(null);
const { hasTabOverflow, scrollThumbLeftPercent, scrollThumbWidthPercent, isScrollbarDragging, updateScrollButtons, onTabsWheel, startScrollbarDrag } = useTabScroll(tabsContainerRef);
@@ -1617,6 +1621,14 @@ watch([() => props.specialPageTabs?.settingsActive, () => props.specialPageTabs?
>
<!-- Compact vertical toolbar: search, tab organization, collapse. -->
<div v-if="isVerticalLayout" class="flex h-9 shrink-0 items-center gap-0.5 border-b p-1" :class="isTabBarCollapsed ? 'justify-center' : ''">
<Tooltip v-if="canNewQuery">
<TooltipTrigger as-child>
<button type="button" data-new-query-tab :class="verticalTabToolbarButtonClass" :aria-label="t('toolbar.newQuery')" @click="toolbar?.newQuery(groupId)">
<Plus class="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent>{{ t("toolbar.newQuery") }}</TooltipContent>
</Tooltip>
<div v-if="!isTabBarCollapsed" class="relative min-w-0 flex-1">
<Search class="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input v-model="tabSearchQuery" type="search" :placeholder="t('tabs.searchOpenTabs')" class="h-7 w-full pl-7 text-sm" />
@@ -1918,7 +1930,21 @@ watch([() => props.specialPageTabs?.settingsActive, () => props.specialPageTabs?
</template>
</div>
</div>
<div v-if="showOverflowControl" class="tab-overflow-control absolute right-0 top-0 z-30 flex h-full items-center">
<Tooltip v-if="!isVerticalLayout && canNewQuery">
<TooltipTrigger as-child>
<button
type="button"
data-new-query-tab
class="mx-0.5 inline-flex h-7 w-7 shrink-0 self-center items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
:aria-label="t('toolbar.newQuery')"
@click="toolbar?.newQuery(groupId)"
>
<Plus class="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent>{{ t("toolbar.newQuery") }}</TooltipContent>
</Tooltip>
<div v-if="showOverflowControl" class="tab-overflow-control absolute top-0 z-30 flex h-full items-center" :class="canNewQuery ? 'right-8' : 'right-0'">
<Popover v-model:open="tabOverflowOpen">
<PopoverTrigger as-child>
<button type="button" class="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border/60 bg-background text-foreground/70 hover:border-border hover:text-foreground" :aria-label="t('tabs.openTabs')" :title="t('tabs.openTabs')">
@@ -7,7 +7,16 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { ConnectionConfig, QueryTab } from "@/types/database";
vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: { render: () => null } }));
vi.mock("@/components/grid/DataGrid.vue", () => ({ default: { render: () => null } }));
const mocks = vi.hoisted(() => ({ openTableStructureEditor: vi.fn() }));
vi.mock("@/components/grid/DataGrid.vue", () => ({
__esModule: true,
default: {
setup(_props: unknown, { expose }: { expose: (value: unknown) => void }) {
expose({ canOpenTableStructureEditor: true, openTableStructureEditor: mocks.openTableStructureEditor });
return () => null;
},
},
}));
import ContentArea from "../ContentArea.vue";
import { useConnectionStore } from "@/stores/connectionStore";
@@ -76,6 +85,16 @@ async function mountDataTab() {
}
describe("table data header navigation", () => {
it("opens the columns editor from the header beside the table controls", async () => {
const { host, tab } = await mountDataTab();
tab.result = { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };
await vi.waitFor(() => expect(host.querySelector("[data-edit-table-structure]")).not.toBeNull());
const button = host.querySelector<HTMLButtonElement>("[data-edit-table-structure]")!;
expect(button.closest("[data-grid-root]")).toBeNull();
button.click();
expect(mocks.openTableStructureEditor).toHaveBeenCalledWith("columns");
});
it.each([false, true])("opens the connection browser, reusing an existing tab: %s", async (alreadyOpen) => {
const { host, store, tab } = await mountDataTab();
const existingId = alreadyOpen ? store.openDatabaseBrowser(connection.id) : undefined;
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { createApp, nextTick } from "vue";
import { createApp, nextTick, ref } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { createI18n } from "vue-i18n";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -42,6 +42,7 @@ vi.mock("@/components/icons/DatabaseIcon.vue", () => ({
}));
import EditorGroupTabBar from "../EditorGroupTabBar.vue";
import { createNoopEditorToolbarActions, EDITOR_TOOLBAR_ACTIONS, type EditorToolbarActions } from "../editorToolbarActions";
import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import type { ConnectionConfig } from "@/types/database";
@@ -64,6 +65,7 @@ function mountBar(
activePinia: ReturnType<typeof createPinia>,
onActivateTab?: (tabId: string) => void,
specialPageTabs?: { settingsOpen: boolean; settingsActive: boolean; driverStoreOpen: boolean; driverStoreActive: boolean; pluginCenterOpen: boolean; pluginCenterActive: boolean; driverUpdateCount: number },
toolbarActions?: EditorToolbarActions,
): Mounted {
const store = useQueryStore();
const host = createHost();
@@ -78,6 +80,7 @@ function mountBar(
// instance the test drives — otherwise drag validation runs against an
// empty store and silently early-returns.
app.use(activePinia);
if (toolbarActions) app.provide(EDITOR_TOOLBAR_ACTIONS, toolbarActions);
app.use(
createI18n({
legacy: false,
@@ -167,6 +170,25 @@ describe("EditorGroupTabBar behavior", () => {
setActivePinia(pinia);
});
it("opens a new query through the app action for this editor group", async () => {
const store = useQueryStore();
const id = store.createTab("pg-1", "app", "users", "data", "public");
const actions = createNoopEditorToolbarActions();
actions.canNewQuery = ref(true);
actions.newQuery = vi.fn();
const { app, host } = mountBar(store.groups[0].id, [id], id, pinia, undefined, undefined, actions);
await settle();
const buttons = host.querySelectorAll<HTMLButtonElement>("[data-new-query-tab]");
expect(buttons).toHaveLength(1);
buttons[0].click();
expect(actions.newQuery).toHaveBeenCalledExactlyOnceWith(store.groups[0].id);
actions.canNewQuery.value = false;
await settle();
expect(host.querySelector("[data-new-query-tab]")).toBeNull();
app.unmount();
host.remove();
});
it("offers duplicate without rename on a data tab", async () => {
const store = useQueryStore();
const id = store.createTab("pg-1", "app", "users", "data", "public");
@@ -21,6 +21,8 @@ export interface SpecialPageTabsState {
}
export interface EditorToolbarActions {
canNewQuery: Ref<boolean>;
newQuery(groupId: string): void;
explainMode: Ref<"explain" | "autotrace">;
blockDangerousRedisCommands: Ref<boolean>;
/** Highlights the database selector of the tab that needs a database choice. */
@@ -71,6 +73,8 @@ export function createNoopEditorToolbarActions(): EditorToolbarActions {
value: { settingsOpen: false, settingsActive: false, driverStoreOpen: false, driverStoreActive: false, pluginCenterOpen: false, pluginCenterActive: false, driverUpdateCount: 0 },
} as Ref<SpecialPageTabsState>;
return {
canNewQuery: { value: false } as Ref<boolean>,
newQuery: noop,
explainMode: mode,
blockDangerousRedisCommands: flag,
databaseRequiredSignalFor: () => 0,
@@ -0,0 +1,141 @@
<script setup lang="ts">
import { computed, nextTick, ref } from "vue";
import { useI18n } from "vue-i18n";
import { ChevronDown, Search, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
interface ColumnOption {
name: string;
dataType: string;
disabled?: boolean;
}
const props = defineProps<{
selected: string[];
options: ColumnOption[];
placeholder: string;
triggerClass?: string;
}>();
const emit = defineEmits<{ toggle: [name: string] }>();
const { t } = useI18n();
const open = ref(false);
const search = ref("");
const searchInput = ref<HTMLInputElement | null>(null);
const optionInputs = ref<HTMLInputElement[]>([]);
const selectedPositions = computed(() => new Map(props.selected.map((name, position) => [name, position + 1])));
const visibleOptions = computed(() => {
const query = search.value.trim().toLowerCase();
return props.options
.filter((column) => !query || column.name.toLowerCase().includes(query) || column.dataType.toLowerCase().includes(query))
.sort((left, right) => (selectedPositions.value.get(left.name) ?? Number.MAX_SAFE_INTEGER) - (selectedPositions.value.get(right.name) ?? Number.MAX_SAFE_INTEGER));
});
function onOpenChange(value: boolean) {
open.value = value;
if (!value) search.value = "";
}
function focusSearch(event: Event) {
event.preventDefault();
void nextTick(() => searchInput.value?.focus());
}
function focusOption(event: KeyboardEvent, direction: 1 | -1) {
const options = visibleOptions.value.flatMap((column) => {
const input = optionInputs.value.find((item) => item.dataset.indexColumn === column.name);
return input && !input.disabled ? [input] : [];
});
if (!options.length) return;
const position = options.indexOf(event.target as HTMLInputElement);
const target = position < 0 ? (direction === 1 ? options[0] : options[options.length - 1]) : options[(position + direction + options.length) % options.length];
event.preventDefault();
target?.focus();
}
</script>
<template>
<Popover :open="open" @update:open="onOpenChange">
<PopoverTrigger as-child>
<Button type="button" variant="outline" :class="[triggerClass, 'w-full min-w-0 justify-between gap-2']" :aria-label="placeholder" :title="selected.join(', ')" data-index-column-trigger>
<span class="min-w-0 flex-1 truncate text-left">{{ selected.join(", ") || placeholder }}</span>
<span v-if="selected.length > 1" class="shrink-0 text-[11px] font-medium tabular-nums text-muted-foreground">{{ selected.length }}</span>
<ChevronDown class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
side="bottom"
:side-offset="6"
:collision-padding="12"
class="index-column-picker w-[360px] max-w-[calc(100vw-24px)] gap-0 overflow-hidden rounded-md p-0"
:aria-label="placeholder"
data-index-column-picker
@open-auto-focus="focusSearch"
@keydown.down="focusOption($event, 1)"
@keydown.up="focusOption($event, -1)"
>
<div class="shrink-0 border-b p-2.5">
<div class="flex h-8 items-center gap-2 rounded-md border border-input bg-background px-2 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring/25">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input ref="searchInput" v-model="search" type="text" class="min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" :placeholder="t('grid.searchColumns')" :aria-label="t('grid.searchColumns')" data-index-column-search />
<button
v-if="search"
type="button"
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
:aria-label="t('structureEditor.clearColumnSearch')"
@click="
search = '';
searchInput?.focus();
"
>
<X class="h-3 w-3" />
</button>
</div>
<div class="mt-2 flex items-center justify-between text-[11px] text-muted-foreground">
<span>{{ t("structureEditor.indexSelectedColumns", { count: selected.length }) }}</span>
<span>{{ t("structureEditor.dataType") }}</span>
</div>
</div>
<div class="index-column-options min-h-0 overflow-y-auto overscroll-contain p-1" :aria-label="placeholder" role="group">
<label
v-for="column in visibleOptions"
:key="column.name"
class="index-column-option grid min-h-8 grid-cols-[14px_20px_minmax(0,1fr)_auto] items-center gap-1.5 rounded-sm px-2 py-1.5 text-xs focus-within:ring-1 focus-within:ring-inset focus-within:ring-ring/50"
:class="column.disabled ? 'cursor-not-allowed opacity-45' : selectedPositions.has(column.name) ? 'bg-accent/50 hover:bg-accent/80' : 'hover:bg-accent/40'"
:data-selected="selectedPositions.has(column.name)"
:title="column.name + (column.dataType ? ' (' + column.dataType + ')' : '')"
>
<input ref="optionInputs" type="checkbox" class="h-3.5 w-3.5 shrink-0 cursor-inherit accent-primary" :checked="selectedPositions.has(column.name)" :disabled="column.disabled" :aria-label="column.name" :data-index-column="column.name" @change="emit('toggle', column.name)" />
<span class="text-center text-[10px] font-medium tabular-nums text-muted-foreground" aria-hidden="true">{{ selectedPositions.get(column.name) ?? "" }}</span>
<span class="min-w-0 truncate font-mono" :class="{ 'font-medium': selectedPositions.has(column.name) }">{{ column.name }}</span>
<span class="max-w-28 truncate text-right font-mono text-[10px] text-muted-foreground">
<slot name="type" :column="column">{{ column.dataType }}</slot>
</span>
</label>
<div v-if="!visibleOptions.length" class="px-3 py-7 text-center text-xs text-muted-foreground">{{ t("structureEditor.noMatchingIndexColumns") }}</div>
</div>
</PopoverContent>
</Popover>
</template>
<style scoped>
.index-column-picker {
max-height: min(400px, var(--reka-popover-content-available-height, 400px));
}
.index-column-options {
max-height: 300px;
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.index-column-options::-webkit-scrollbar {
width: 6px;
}
.index-column-options::-webkit-scrollbar-thumb {
border-radius: 4px;
background: var(--border);
}
</style>
@@ -43,6 +43,7 @@ vi.mock("@lucide/vue", async () => {
AlertTriangle: Icon,
Check: Icon,
ChevronDown: Icon,
ChevronRight: Icon,
ChevronUp: Icon,
ClipboardList: Icon,
Copy: Icon,
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
import StructureIndexColumnPicker from "./StructureIndexColumnPicker.vue";
import { computed, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, shallowRef, watch } from "vue";
import { uuid } from "@/lib/common/utils";
@@ -12,7 +13,7 @@ import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { AlertTriangle, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, ClipboardList, Copy, Database, Info, KeyRound, ListChevronsUpDown, Loader2, Maximize2, Pencil, Plus, RefreshCw, RotateCcw, Rows3, Save, Search, Settings, SlidersHorizontal, Trash2, UserRound, X } from "@lucide/vue";
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { SearchableSelect } from "@/components/ui/searchable-select";
@@ -95,8 +96,11 @@ import {
dataTypeLengthUnitValue,
defaultNewColumnDataType,
filterStructureIndexColumnOptions,
generateIndexName,
generateUniqueIndexName,
generateUniqueShortIndexName,
structureIndexKind,
specialIndexColumnIssue,
type StructureIndexKind,
getColumnEditorControls,
getDataTypeOptions,
POSTGRES_GEOMETRY_TYPES,
@@ -976,7 +980,7 @@ const structureDensityMetrics: Record<
> = {
compact: {
columns: [28, 168, 136, 82, 60, 52, 108, 220, 80, 120, 144, 108],
indexes: [120, 180, 60, 88, 124, 144, 120, 84, 70],
indexes: [280, 180, 60, 88, 124, 144, 120, 84, 70],
minColumnWidth: 24,
minLengthColumnWidth: 140,
minIndexColumnWidth: 48,
@@ -994,7 +998,7 @@ const structureDensityMetrics: Record<
},
standard: {
columns: [32, 200, 160, 104, 72, 64, 128, 260, 90, 140, 160, 136],
indexes: [148, 224, 72, 108, 148, 180, 148, 100, 84],
indexes: [320, 224, 72, 108, 148, 180, 148, 100, 84],
minColumnWidth: 28,
minLengthColumnWidth: 156,
minIndexColumnWidth: 60,
@@ -1012,7 +1016,7 @@ const structureDensityMetrics: Record<
},
comfortable: {
columns: [36, 232, 188, 116, 84, 76, 152, 300, 100, 160, 188, 148],
indexes: [176, 260, 84, 124, 176, 216, 176, 116, 104],
indexes: [360, 260, 84, 124, 176, 216, 176, 116, 104],
minColumnWidth: 32,
minLengthColumnWidth: 176,
minIndexColumnWidth: 64,
@@ -1305,6 +1309,10 @@ function onIndexColResize(e: MouseEvent, col: number) {
const connection = computed(() => (props.connectionId ? store.getConfig(props.connectionId) : undefined));
const databaseType = computed(() => tableStructureDatabaseTypeForConnection(connection.value));
const usesNativeMysqlIndexNames = computed(() => {
const profile = connection.value?.driver_profile?.trim().toLowerCase();
return databaseType.value === "mysql" && connection.value?.db_type === "mysql" && (!profile || profile === "mysql");
});
const supportsCharacterLengthUnits = computed(() => databaseType.value === "dameng" || databaseType.value === "oracle");
const usesMysql8SafeDefaults = computed(() => databaseType.value === "mysql" && connection.value?.db_type === "mysql" && connection.value.driver_profile === "mysql");
const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type, connection.value?.database_info?.productVersion));
@@ -1334,59 +1342,60 @@ const indexTypeOptions = computed(() => {
interface DefaultValuePreset {
label: string;
value: string;
dataType: string | null;
}
const defaultValuePresets = computed((): DefaultValuePreset[] => {
const universal: DefaultValuePreset[] = [
{ label: "''", value: "''" },
{ label: "NULL", value: "NULL" },
{ label: "0", value: "0" },
{ label: "1", value: "1" },
{ label: "''", value: "''", dataType: "text" },
{ label: "NULL", value: "NULL", dataType: null },
{ label: "0", value: "0", dataType: "int" },
{ label: "1", value: "1", dataType: "int" },
];
const dialectPresets: Record<string, DefaultValuePreset[]> = {
mysql: [
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE" },
{ label: "CURRENT_TIME", value: "CURRENT_TIME" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE", dataType: "date" },
{ label: "CURRENT_TIME", value: "CURRENT_TIME", dataType: "time" },
],
postgres: [
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE" },
{ label: "now()", value: "now()" },
{ label: "gen_random_uuid()", value: "gen_random_uuid()" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE", dataType: "date" },
{ label: "now()", value: "now()", dataType: "timestamp" },
{ label: "gen_random_uuid()", value: "gen_random_uuid()", dataType: "uuid" },
],
sqlite: [
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE" },
{ label: "CURRENT_TIME", value: "CURRENT_TIME" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE", dataType: "date" },
{ label: "CURRENT_TIME", value: "CURRENT_TIME", dataType: "time" },
],
duckdb: [
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE", dataType: "date" },
],
sqlserver: [
{ label: "GETDATE()", value: "GETDATE()" },
{ label: "GETUTCDATE()", value: "GETUTCDATE()" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "NEWID()", value: "NEWID()" },
{ label: "GETDATE()", value: "GETDATE()", dataType: "datetime" },
{ label: "GETUTCDATE()", value: "GETUTCDATE()", dataType: "datetime" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "NEWID()", value: "NEWID()", dataType: "uuid" },
],
oracle: [
{ label: "SYSDATE", value: "SYSDATE" },
{ label: "SYSTIMESTAMP", value: "SYSTIMESTAMP" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "SYSDATE", value: "SYSDATE", dataType: "date" },
{ label: "SYSTIMESTAMP", value: "SYSTIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
],
h2: [
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE" },
{ label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP", dataType: "timestamp" },
{ label: "CURRENT_DATE", value: "CURRENT_DATE", dataType: "date" },
],
clickhouse: [
{ label: "now()", value: "now()" },
{ label: "today()", value: "today()" },
{ label: "now()", value: "now()", dataType: "timestamp" },
{ label: "today()", value: "today()", dataType: "date" },
],
informix: [
{ label: "CURRENT", value: "CURRENT" },
{ label: "TODAY", value: "TODAY" },
{ label: "CURRENT", value: "CURRENT", dataType: "timestamp" },
{ label: "TODAY", value: "TODAY", dataType: "date" },
],
};
@@ -1473,7 +1482,8 @@ const columnOrdinalIndicatorWidth = computed(() => {
// Reserve a full em per digit plus the primary-key icon, its gap, padding,
// and divider. The indicator is shared by every row, so it must fit the
// largest ordinal even when that row is a primary-key column.
const requiredWidth = metric.fontSize * digitCount + metric.iconSize + columnOrdinalIndicatorGap + columnOrdinalIndicatorTrailingChrome;
const iconCount = Math.max(1, ...columns.value.map((column) => columnIndexIndicators(column).length));
const requiredWidth = metric.fontSize * digitCount + (metric.iconSize + columnOrdinalIndicatorGap) * iconCount + columnOrdinalIndicatorTrailingChrome;
return Math.max(metric.columns[0], requiredWidth);
});
const columnActionsWidth = computed(() => {
@@ -1519,6 +1529,95 @@ function structureColumnSelectionClass(key: string): string {
return key !== "actions" && selectedStructureColumnKeys.value.has(key) ? "structure-grid-column-selected" : "";
}
function normalizedStructureDataType(dataType: string): string {
return dataTypeBaseInputValue(databaseType.value, dataType)
.replace(/["'`\[\]]/g, "")
.trim()
.toLowerCase();
}
function structureDataTypeToneClass(dataType: string): string {
const type = normalizedStructureDataType(dataType);
if (!type) return "structure-data-type-other";
if (/^(?:bool|boolean)$/.test(type)) return "structure-data-type-boolean";
if (/^(?:enum|set)(?:\b|$)/.test(type)) return "structure-data-type-enum";
if (/^(?:json|jsonb|xml)\b/.test(type)) return "structure-data-type-json";
if (/^(?:date|time|timestamp|timestamptz|datetime|smalldatetime|interval|year)\b/.test(type)) return "structure-data-type-temporal";
if (/^(?:tinyblob|mediumblob|longblob|blob|binary|varbinary|bytea|image|raw|long raw)\b/.test(type)) return "structure-data-type-binary";
if (/^(?:geometry|geometrycollection|geography|point|line|linestring|lseg|box|path|polygon|circle|multipoint|multilinestring|multipolygon)\b/.test(type)) return "structure-data-type-spatial";
if (/^(?:number|numeric|decimal|dec|float|double|real|money|smallmoney)\b/.test(type)) return "structure-data-type-real";
if (/^(?:tinyint|smallint|mediumint|int|integer|bigint|serial|bigserial|bit)\b/.test(type)) return "structure-data-type-numeric";
if (/^(?:char|varchar|varchar2|nvarchar|nchar|text|tinytext|mediumtext|longtext|clob|nclob|string|uuid|uniqueidentifier)\b/.test(type)) return "structure-data-type-text";
return "structure-data-type-other";
}
function structureDefaultValueToneClass(value: string | null | undefined, dataType: string | null): string {
const text = value?.trim() ?? "";
if (dataType === null || !text || /^null$/i.test(text)) return "structure-data-type-null";
return structureDataTypeToneClass(dataType);
}
function structureColumnComparisonKey(name: string): string {
return tableStructureIdentifierComparisonKey(name, databaseType.value, connection.value?.database_info);
}
function indexContainsColumn(index: EditableStructureIndex, column: EditableStructureColumn): boolean {
const names = [column.name, column.original?.name].filter((name): name is string => !!name).map(structureColumnComparisonKey);
return index.columns.some((name) => names.includes(structureColumnComparisonKey(name)));
}
function columnIndexes(column: EditableStructureColumn): EditableStructureIndex[] {
if (!column.name.trim() || column.markedForDrop) return [];
return indexes.value.filter((index) => !index.markedForDrop && !index.isPrimary && indexContainsColumn(index, column));
}
const indexKindOrder: StructureIndexKind[] = ["primary", "unique", "index", "fulltext", "spatial"];
function indexIconClass(kind: StructureIndexKind): string {
return {
primary: "text-amber-600 dark:text-amber-400",
unique: "text-red-600 dark:text-red-400",
index: "text-green-700 dark:text-green-300",
fulltext: "text-purple-600 dark:text-purple-300",
spatial: "text-cyan-700 dark:text-cyan-300",
}[kind];
}
function columnIndexKind(column: EditableStructureColumn): StructureIndexKind | "none" {
if (column.markedForDrop) return "none";
if (column.isPrimaryKey) return "primary";
const memberships = columnIndexes(column);
return indexKindOrder.find((kind) => memberships.some((index) => structureIndexKind(index) === kind)) ?? "none";
}
function columnIndexIndicators(column: EditableStructureColumn): { kind: StructureIndexKind; title: string }[] {
if (column.markedForDrop) return [];
const memberships = columnIndexes(column);
return indexKindOrder.flatMap((kind) => {
const titles = memberships.filter((index) => structureIndexKind(index) === kind).map(indexTitle);
if (kind === "primary" && column.isPrimaryKey)
titles.unshift(
`PRIMARY (${columns.value
.filter((item) => item.isPrimaryKey && !item.markedForDrop)
.map((item) => item.name)
.join(", ")})`,
);
return titles.length ? [{ kind, title: titles.join("\n") }] : [];
});
}
function indexTitle(index: EditableStructureIndex): string {
return `${index.isPrimary ? "PRIMARY" : index.isUnique ? "UNIQUE" : index.indexType || "INDEX"} ${index.name} (${index.columns.join(", ")})`;
}
function columnIndexTitle(column: EditableStructureColumn): string {
return columnIndexIndicators(column)
.map((indicator) => indicator.title)
.join("\n");
}
function structureColumnClipboardValue(column: EditableStructureColumn, key: string): string {
switch (key) {
case "name":
@@ -2128,7 +2227,15 @@ function restoreDraft(draft: TableStructureEditorDraft) {
// Existing-index edits never support Concurrent (the checkbox is disabled and
// the core builder rejects the request), so a stale `concurrently: true`
// saved in a restored draft must not be submitted or deadlock the save.
indexes.value = cloneDraftValue(draft.indexes || []).map((index) => (index.original ? { ...index, concurrently: false } : index));
indexes.value = cloneDraftValue(draft.indexes || []).map((index) => {
if (index.original) index.concurrently = false;
// Older drafts have no naming seed. Preserve their saved names until regeneration.
if (index.autoNameColumn === undefined) {
if (index.name) index.nameEdited = true;
else index.nameEdited ??= false;
}
return index;
});
// Re-run the availability normalization against the current inputs (e.g. a
// re-activated editor may already carry an unknown/unsupported partition
// status): restored new-index Concurrent choices that became illegal are
@@ -2152,12 +2259,15 @@ function restoreDraft(draft: TableStructureEditorDraft) {
} else {
const activeScope = visibleTableStructureRefreshScope(draft.activeTab || "columns");
if (activeScope.columns) loadedMetadataFacets.add("columns");
if (activeScope.indexes || draft.indexes?.length) loadedMetadataFacets.add("indexes");
// Older field-tab drafts did not load indexes alongside columns.
if (draft.activeTab === "indexes" || draft.indexes?.length) loadedMetadataFacets.add("indexes");
if (activeScope.foreignKeys || draft.foreignKeys?.length) loadedMetadataFacets.add("foreign-keys");
if (activeScope.constraints || constraintsLoaded.value) loadedMetadataFacets.add("constraints");
if (activeScope.triggers || triggersLoaded.value) loadedMetadataFacets.add("triggers");
if (activeScope.tableComment) loadedMetadataFacets.add("comment");
}
// Some older snapshots have incomplete facet flags but already contain index edits.
if (indexes.value.length) loadedMetadataFacets.add("indexes");
structureScrollPositions = cloneDraftValue(draft.scrollPositions || {});
restoringDraft = false;
draftHydrated = !needsColumnDraftMetadataHydration();
@@ -2446,6 +2556,20 @@ async function refreshSqlPreview() {
sqlPreviewPending.value = false;
return;
}
const indexWarnings = indexes.value
.filter((index) => !index.markedForDrop && needsIndexColumnValidation(index))
.flatMap((index) => {
const issue = indexColumnsIssue(index);
return issue ? [`${index.name || t("structureEditor.addIndex")}: ${t(`structureEditor.${issue}`)}`] : [];
});
if (indexWarnings.length) {
pendingStatements.value = [];
warnings.value = indexWarnings;
sqliteSchemaRevision.value = undefined;
sqlPreviewLoading.value = false;
sqlPreviewPending.value = false;
return;
}
// Layer B: a stale `concurrently: true` whose availability is no longer
// enabled must never reach the SQL builder, even if normalization was
// skipped (race, restored draft, non-UI caller).
@@ -2928,7 +3052,8 @@ async function loadStructure(
if (!options.preserveDraft) clearColumnSelection();
}
await loadMysqlAutoIncrementCounter(options.preserveDraft === true);
// Loading missing index metadata must not rebase a restored column counter again.
if (!options.preserveDraft || effectiveScope.columns) await loadMysqlAutoIncrementCounter(options.preserveDraft === true);
const nextTableComment = await tableCommentPromise;
if (nextTableComment !== undefined) {
@@ -2978,7 +3103,8 @@ async function loadStructure(
const nextConstraints = constraintsResult.status === "fulfilled" ? constraintsResult.value : undefined;
const nextTriggers = triggersResult.status === "fulfilled" ? triggersResult.value : undefined;
if (nextIndexes) {
indexes.value = createIndexDrafts(nextIndexes);
// An empty lazy load changes no draft data and should not trigger another save.
if (nextIndexes.length || indexes.value.length) indexes.value = createIndexDrafts(nextIndexes);
loadedMetadataFacets.add("indexes");
}
if (nextForeignKeys) {
@@ -3823,6 +3949,11 @@ function columnRowClass(column: EditableStructureColumn, index: number) {
const isSelected = selectedColumnIds.value.has(column.id) && !column.markedForDrop;
return {
"bg-destructive/5 opacity-60": column.markedForDrop,
"structure-column-primary-key": columnIndexKind(column) === "primary",
"structure-column-unique-key": columnIndexKind(column) === "unique",
"structure-column-index-key": columnIndexKind(column) === "index",
"structure-column-fulltext-key": columnIndexKind(column) === "fulltext",
"structure-column-spatial-key": columnIndexKind(column) === "spatial",
"structure-column-search-match": isSearchMatch,
// Reuse the existing search-current highlight for the active/selected row.
"structure-column-search-current": highlightedColumnId.value === column.id || isSelected,
@@ -3915,8 +4046,14 @@ function indexFieldMatchesSearch(value: string | null | undefined): boolean {
function indexRowClass(index: EditableStructureIndex) {
const isSearchMatch = filteredIndexRowIds.value.has(index.id);
const kind = structureIndexKind(index);
return {
"bg-destructive/5 opacity-60": index.markedForDrop,
"structure-index-primary-key": kind === "primary",
"structure-index-unique-key": kind === "unique",
"structure-index-normal-key": kind === "index",
"structure-index-fulltext-key": kind === "fulltext",
"structure-index-spatial-key": kind === "spatial",
"structure-column-search-match": isSearchMatch,
"structure-column-search-current": highlightedIndexId.value === index.id,
};
@@ -4059,6 +4196,7 @@ function columnContextMenuItems(column: EditableStructureColumn): ContextMenuIte
const count = targets.length;
const allDroppable = targets.every((item) => !item.original || canDropColumn(item));
return [
...columnIndexContextMenuItems(targets),
{
label: isBatchContext ? t("structureEditor.copySelectedColumns", { count }) : t("structureEditor.copyColumn"),
icon: Copy,
@@ -4101,6 +4239,120 @@ function clearColumnContextMenuTarget() {
columnContextMenuTarget.value = null;
}
function canUseColumnIndexActions(targets: EditableStructureColumn[]): boolean {
return !loading.value && !saving.value && !indexesLoading.value && !secondaryMetadataErrors.value.indexes && (isCreateMode.value || loadedMetadataFacets.has("indexes")) && targets.length > 0 && targets.every((column) => columnIsSelectable(column) && !!column.name.trim());
}
function setColumnsPrimaryKey(targets: EditableStructureColumn[]) {
if (!canUseColumnIndexActions(targets) || targets.some(isPrimaryKeyDisabled)) return;
for (const column of targets) {
column.isPrimaryKey = true;
column.isNullable = false;
}
sqlPreviewCollapsed.value = false;
}
function createIndexFromColumns(targets: EditableStructureColumn[], isUnique: boolean, indexType = "") {
if (!canUseColumnIndexActions(targets) || !structureCapabilities.value.createIndex || specialIndexColumnIssue(structureDialect.value, indexType, targets, isUnique)) return;
const index = newIndexDraft();
index.columns = targets.map((column) => column.name.trim());
index.isUnique = isUnique;
index.indexType = indexType;
refreshAutoIndexName(index);
indexes.value.push(index);
sqlPreviewCollapsed.value = false;
}
function addColumnsToIndex(index: EditableStructureIndex, targets: EditableStructureColumn[]) {
if (!canUseColumnIndexActions(targets) || !canEditIndexDraft(index) || !canAddColumnsToIndex(index, targets)) return;
for (const column of targets) {
if (indexContainsColumn(index, column)) continue;
// Operator classes are positional; preserve existing entries when extending a key.
index.columnOpclasses = index.columns.map((_, position) => index.columnOpclasses?.[position] ?? null);
index.columns.push(column.name.trim());
index.columnOpclasses.push(null);
index.includedColumns = index.includedColumns.filter((name) => structureColumnComparisonKey(name) !== structureColumnComparisonKey(column.name));
}
refreshAutoIndexName(index);
sqlPreviewCollapsed.value = false;
}
function columnIndexContextMenuItems(targets: EditableStructureColumn[]): ContextMenuItem[] {
if (!tableMetadataCapabilities.value.indexes) return [];
const disabled = () => !canUseColumnIndexActions(targets);
const primaryColumns = columns.value.filter((column) => column.isPrimaryKey && !column.markedForDrop);
const createItems: ContextMenuItem[] = [
{
label: t("structureEditor.createPrimaryIndex"),
icon: KeyRound,
iconClass: "text-amber-600 dark:text-amber-400",
disabled: () => disabled() || primaryColumns.length > 0 || targets.some(isPrimaryKeyDisabled),
action: () => setColumnsPrimaryKey(targets),
},
...([false, true] as const).map(
(unique): ContextMenuItem => ({
label: t(unique ? "structureEditor.createUniqueIndex" : "structureEditor.createNormalIndex"),
icon: KeyRound,
iconClass: indexIconClass(unique ? "unique" : "index"),
disabled: () =>
disabled() ||
!structureCapabilities.value.createIndex ||
indexes.value.some(
(index) =>
!index.markedForDrop &&
!index.isPrimary &&
index.isUnique === unique &&
!index.filter &&
(!index.indexType || index.indexType.toUpperCase() === "BTREE") &&
index.columns.length === targets.length &&
index.columns.every((name, position) => structureColumnComparisonKey(name) === structureColumnComparisonKey(targets[position].name)),
),
action: () => createIndexFromColumns(targets, unique),
}),
),
...["FULLTEXT", "SPATIAL"]
.filter((type) => indexTypeOptions.value.includes(type))
.map(
(type): ContextMenuItem => ({
label: t(type === "FULLTEXT" ? "structureEditor.createFulltextIndex" : "structureEditor.createSpatialIndex"),
icon: KeyRound,
iconClass: indexIconClass(type === "FULLTEXT" ? "fulltext" : "spatial"),
disabled: () => disabled() || !structureCapabilities.value.createIndex || !!specialIndexColumnIssue(structureDialect.value, type, targets),
action: () => createIndexFromColumns(targets, false, type),
}),
),
];
const addItems: ContextMenuItem[] = indexes.value
.filter((index) => !index.markedForDrop && !index.isPrimary)
.map((index) => ({
label: `${index.name || t("structureEditor.addIndex")} (${index.columns.join(", ")})`,
icon: KeyRound,
iconClass: indexIconClass(structureIndexKind(index)),
disabled: () => disabled() || !canEditIndexDraft(index) || !canAddColumnsToIndex(index, targets) || targets.every((column) => indexContainsColumn(index, column)),
action: () => addColumnsToIndex(index, targets),
}));
if (primaryColumns.length)
addItems.unshift({
label: `PRIMARY (${primaryColumns.map((column) => column.name).join(", ")})`,
icon: KeyRound,
iconClass: "text-amber-600 dark:text-amber-400",
disabled: () => disabled() || targets.every((column) => column.isPrimaryKey) || targets.some(isPrimaryKeyDisabled),
action: () => setColumnsPrimaryKey(targets),
});
return [
{ label: targets.length > 1 ? t("structureEditor.createCompositeIndex", { count: targets.length }) : t("structureEditor.createColumnIndex"), icon: Plus, disabled, children: createItems },
{ label: t("structureEditor.addColumnsToIndex"), icon: KeyRound, disabled: () => disabled() || !addItems.length, children: addItems },
{
label: t("structureEditor.manageIndexes"),
icon: Settings,
action: () => {
activeTab.value = "indexes";
},
},
{ label: "", separator: true },
];
}
function isColumnNameDisabled(column: EditableStructureColumn): boolean {
return column.markedForDrop || (!!column.original && !structureCapabilities.value.renameColumn);
}
@@ -4165,10 +4417,8 @@ function isManticoreColumnPropertyDisabled(column: EditableStructureColumn): boo
return !canEditManticoreColumnProperties(databaseType.value, !!column.original) || column.markedForDrop;
}
function addIndex() {
if (!structureCapabilities.value.createIndex || indexesLoading.value) return;
activeTab.value = "indexes";
indexes.value.push({
function newIndexDraft(): EditableStructureIndex {
return {
id: `new:${uuid()}`,
name: "",
columns: [],
@@ -4182,7 +4432,13 @@ function addIndex() {
concurrently: false,
columnOpclasses: [],
markedForDrop: false,
});
};
}
function addIndex() {
if (!structureCapabilities.value.createIndex || indexesLoading.value) return;
activeTab.value = "indexes";
indexes.value.push(newIndexDraft());
void nextTick(() => {
const indexRows = rootRef.value?.querySelectorAll<HTMLElement>('[data-new-index-row="true"]');
const row = indexRows?.[indexRows.length - 1];
@@ -4201,28 +4457,29 @@ function existingIndexNamesForDraft(index: EditableStructureIndex): string[] {
return indexes.value.filter((item) => item.id !== index.id && !item.markedForDrop).map((item) => item.name);
}
function generatedIndexNameForDraft(index: EditableStructureIndex, columnsForName = index.columns): string {
const name = generateUniqueIndexName(structureIndexTableName(), columnsForName, existingIndexNamesForDraft(index));
// GaussDB M-mode expects lowercase index names (MySQL-compatible).
function generatedIndexNameForDraft(index: EditableStructureIndex): string {
const firstColumn = index.autoNameColumn ?? index.columns[0] ?? "";
const existingNames = existingIndexNamesForDraft(index);
if (usesNativeMysqlIndexNames.value) return generateUniqueShortIndexName(firstColumn, existingNames, { ...index, maxLength: 64 });
// Index names can be schema-wide outside MySQL. Retain the original table-qualified rule.
const name = generateUniqueIndexName(structureIndexTableName(), firstColumn ? [firstColumn] : [], existingNames);
return connection.value?.driver_profile?.toLowerCase() === "gaussdb-m" ? name.toLowerCase() : name;
}
function refreshAutoIndexName(index: EditableStructureIndex, previousColumns = index.columns) {
if (index.original || index.nameEdited) return;
const isGaussdbM = connection.value?.driver_profile?.toLowerCase() === "gaussdb-m";
const previousName = generateIndexName(structureIndexTableName(), previousColumns);
const previousUniqueName = generateUniqueIndexName(structureIndexTableName(), previousColumns, existingIndexNamesForDraft(index));
const currentName = index.name.trim();
if (currentName) {
if (isGaussdbM) {
if (currentName.toLowerCase() !== previousName.toLowerCase() && currentName.toLowerCase() !== previousUniqueName.toLowerCase()) return;
} else if (currentName !== previousName && currentName !== previousUniqueName) {
return;
}
}
function refreshAutoIndexName(index: EditableStructureIndex, typeChanged = false) {
if (index.original || index.nameEdited !== false) return;
index.autoNameColumn ??= index.columns[0];
if (index.name && !typeChanged) return;
index.name = generatedIndexNameForDraft(index);
}
function regenerateIndexName(index: EditableStructureIndex) {
if (!canEditIndexDraft(index) || !index.columns.length) return;
index.autoNameColumn = index.columns[0];
index.name = generatedIndexNameForDraft(index);
index.nameEdited = !!index.original;
}
function onIndexNameInput(index: EditableStructureIndex, value: string | number) {
index.name = String(value ?? "");
index.nameEdited = true;
@@ -4235,18 +4492,63 @@ const availableColumnNames = computed(() =>
.filter(Boolean),
);
const colSearch = ref("");
function filteredIndexColumnNames(selectedColumns: readonly string[]): string[] {
return filterStructureIndexColumnOptions(availableColumnNames.value, selectedColumns, colSearch.value);
function indexColumnPickerOptions(index: EditableStructureIndex, included = false) {
const selected = included ? index.includedColumns : index.columns;
return filterStructureIndexColumnOptions(availableColumnNames.value, selected).map((name) => {
const column = columns.value.find((item) => item.name === name && !item.markedForDrop);
return { name, dataType: column?.dataType ?? "", disabled: !included && !canToggleIndexColumn(index, name) };
});
}
function toggleIndexColumn(index: EditableStructureIndex, col: string) {
const previousColumns = [...index.columns];
if (!canEditIndexDraft(index) || !canToggleIndexColumn(index, col)) return;
const i = index.columns.indexOf(col);
if (i >= 0) index.columns.splice(i, 1);
else index.columns.push(col);
refreshAutoIndexName(index, previousColumns);
index.columnOpclasses = index.columns.map((_, position) => index.columnOpclasses?.[position] ?? null);
if (i >= 0) {
index.columns.splice(i, 1);
index.columnOpclasses.splice(i, 1);
} else {
index.columns.push(col);
index.columnOpclasses.push(null);
}
refreshAutoIndexName(index);
}
function indexColumnsIssue(index: EditableStructureIndex, names = index.columns, indexType = index.indexType, isUnique = index.isUnique) {
const fields = names.flatMap((name) => {
const column = columns.value.find((item) => !item.markedForDrop && [item.name, item.original?.name].some((value) => value && structureColumnComparisonKey(value) === structureColumnComparisonKey(name)));
return column ? [column] : [];
});
return specialIndexColumnIssue(structureDialect.value, indexType, fields, isUnique);
}
function needsIndexColumnValidation(index: EditableStructureIndex): boolean {
if (indexChanged(index)) return true;
// Untouched server metadata must not block unrelated edits under newer UI rules.
return columns.value.some((column) => indexContainsColumn(index, column) && (!column.original || column.markedForDrop || column.dataType !== column.original.data_type || column.isNullable !== column.original.is_nullable));
}
function canToggleIndexColumn(index: EditableStructureIndex, name: string): boolean {
return index.columns.includes(name) || !indexColumnsIssue(index, [...index.columns, name]);
}
function canAddColumnsToIndex(index: EditableStructureIndex, targets: EditableStructureColumn[]): boolean {
const names = [...index.columns, ...targets.filter((column) => !indexContainsColumn(index, column)).map((column) => column.name.trim())];
return !indexColumnsIssue(index, names);
}
function onIndexUniqueChange(index: EditableStructureIndex, unique: boolean) {
if (!canEditIndexDraft(index) || indexColumnsIssue(index, index.columns, index.indexType, unique)) return;
index.isUnique = unique;
refreshAutoIndexName(index, true);
}
function onIndexTypeChange(index: EditableStructureIndex, value: unknown) {
const type = String(value ?? "");
if (!canEditIndexDraft(index) || indexColumnsIssue(index, index.columns, type, false)) return;
index.indexType = type;
if (structureIndexKind({ indexType: type }) === "fulltext" || structureIndexKind({ indexType: type }) === "spatial") index.isUnique = false;
refreshAutoIndexName(index, true);
}
function toggleIncludedColumn(index: EditableStructureIndex, col: string) {
@@ -5030,12 +5332,6 @@ watch(secondaryMetadataLoading, (value) => {
scheduleSqlPreviewRefresh();
});
watch([() => props.tableName, newTableName], () => {
for (const index of indexes.value) {
refreshAutoIndexName(index);
}
});
watch(refreshVersion, (version, previous) => {
if (version === previous || !version || isCreateMode.value) return;
if (skipNextRefreshVersion) {
@@ -5404,7 +5700,7 @@ watch(
<div class="flex min-w-0 items-center">
<div class="flex shrink-0 items-center justify-center gap-1 border-r pr-0.5 text-muted-foreground" :style="{ width: columnOrdinalIndicatorWidth + 'px' }">
<span class="tabular-nums">{{ index + 1 }}</span>
<KeyRound v-if="column.isPrimaryKey" :class="[structureIconClass, 'shrink-0 text-amber-500']" />
<KeyRound v-for="indicator in columnIndexIndicators(column)" :key="indicator.kind" :class="[structureIconClass, indexIconClass(indicator.kind), 'shrink-0']" :title="indicator.title" :aria-label="indicator.title" :data-index-kind="indicator.kind" />
</div>
<div class="flex min-w-0 items-center gap-0.5 pl-0.5">
<Button
@@ -5468,9 +5764,9 @@ watch(
</div>
</td>
<td :class="[structureCellClass, structureColumnSelectionClass('name')]">
<Input v-model="column.name" :class="[structureControlClass, columnSearchFieldClass(column, column.name)]" :disabled="isColumnNameDisabled(column)" data-column-name-input @blur="commitColumnNameInput(column)" />
<Input v-model="column.name" :class="[structureControlClass, columnSearchFieldClass(column, column.name)]" :title="columnIndexTitle(column) || undefined" :disabled="isColumnNameDisabled(column)" data-column-name-input @blur="commitColumnNameInput(column)" />
</td>
<td :class="[structureCellClass, structureColumnSelectionClass('type')]">
<td :class="[structureCellClass, 'structure-column-data-type', structureDataTypeToneClass(column.dataType), structureColumnSelectionClass('type')]">
<SearchableSelect
v-if="!isColumnTypeDisabled(column)"
:model-value="dataTypeBaseInputValue(databaseType, column.dataType)"
@@ -5484,7 +5780,14 @@ watch(
:display-name="gaussdbMDataTypeDisplayName"
:trigger-class="[structureMonoControlClass, 'w-full']"
@update:model-value="(v: string) => updateColumnDataType(column, v)"
/>
>
<template #option-label="{ option, label }">
<span :class="['structure-data-type-option block truncate font-mono', structureDataTypeToneClass(option)]">{{ label }}</span>
</template>
<template #custom-option-label="{ value }">
<span :class="['structure-data-type-option block truncate font-mono', structureDataTypeToneClass(value)]">{{ value }}</span>
</template>
</SearchableSelect>
<Input v-else :model-value="gaussdbMDataTypeDisplayName(dataTypeBaseInputValue(databaseType, column.dataType))" :class="[structureMonoControlClass, 'w-full']" disabled />
</td>
<td v-if="columnEditorControls.length" :class="[structureCellClass, structureColumnSelectionClass('length')]">
@@ -5578,7 +5881,7 @@ watch(
"
/>
</td>
<td v-if="columnEditorControls.defaultValue" :class="[structureCellClass, structureColumnSelectionClass('defaultValue')]">
<td v-if="columnEditorControls.defaultValue" :class="[structureCellClass, 'structure-column-default-value', structureDefaultValueToneClass(column.defaultValue, column.dataType), structureColumnSelectionClass('defaultValue')]">
<div class="flex min-w-0 items-center gap-1">
<Input v-model="column.defaultValue" :class="[structureMonoControlClass, 'flex-1']" :disabled="isColumnDefaultDisabled(column)" />
<DropdownMenu>
@@ -5587,9 +5890,9 @@ watch(
<ChevronDown :class="structureIconClass" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="max-h-56 min-w-36 overflow-y-auto">
<DropdownMenuContent align="end" class="max-h-56 w-max min-w-36 max-w-[calc(100vw-1rem)] overflow-y-auto">
<DropdownMenuItem v-for="preset in defaultValuePresets" :key="preset.value" @click="column.defaultValue = preset.value">
<code class="font-mono text-[length:var(--structure-font-size)]">{{ preset.label }}</code>
<code :class="['structure-data-type-option block truncate font-mono text-[length:var(--structure-font-size)]', structureDefaultValueToneClass(preset.value, preset.dataType)]">{{ preset.label }}</code>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -5874,62 +6177,78 @@ watch(
</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">
<td :class="structureCellClass">
<Input :model-value="index.name" :class="[structureControlClass, indexSearchFieldClass(index, index.name)]" :disabled="!canEditIndexDraft(index)" data-index-name-input @update:model-value="(value: string | number) => onIndexNameInput(index, value)" />
<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'" />
<Input
:model-value="index.name"
:class="[structureControlClass, 'flex-1', { 'disabled:opacity-100': index.isPrimary }, indexSearchFieldClass(index, index.name)]"
:title="index.name"
:disabled="!canEditIndexDraft(index)"
data-index-name-input
@update:model-value="(value: string | number) => onIndexNameInput(index, value)"
/>
<LightTooltip v-if="!index.isPrimary" :text="t('structureEditor.regenerateIndexName')" side="top" nowrap>
<Button
type="button"
variant="ghost"
size="icon"
:class="[structureActionButtonClass, 'shrink-0']"
:disabled="!canEditIndexDraft(index) || !index.columns.length"
:aria-label="t('structureEditor.regenerateIndexName')"
data-regenerate-index-name
@click="regenerateIndexName(index)"
>
<RefreshCw :class="structureIconClass" />
</Button>
</LightTooltip>
</div>
</td>
<td :class="[structureCellClass, 'overflow-hidden']">
<DropdownMenu v-if="canEditIndexDraft(index)">
<DropdownMenuTrigger as-child>
<Button variant="outline" :class="[structureMonoControlClass, 'w-full justify-between']">
<span class="truncate">{{ toColumnNames(index.columns) || t("structureEditor.indexColumnsPlaceholder") }}</span>
<ChevronDown :class="[structureIconClass, 'ml-1 shrink-0 opacity-50']" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent class="max-h-56 min-w-44 overflow-y-auto" side="bottom" :side-offset="2" :avoid-collisions="false" @interactOutside="colSearch = ''">
<div class="px-[var(--structure-cell-px)] pb-1 pt-0.5">
<Input v-model="colSearch" :class="structureControlClass" :placeholder="t('grid.search')" @click.stop />
</div>
<DropdownMenuCheckboxItem v-for="col in filteredIndexColumnNames(index.columns)" :key="col" :checked="index.columns.includes(col)" :class="index.columns.includes(col) ? 'bg-primary/10' : ''" @select.prevent @click="toggleIndexColumn(index, col)">
{{ col }}
</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
<StructureIndexColumnPicker v-if="canEditIndexDraft(index)" :selected="index.columns" :options="indexColumnPickerOptions(index)" :placeholder="t('structureEditor.indexColumnsPlaceholder')" :trigger-class="structureMonoControlClass" @toggle="toggleIndexColumn(index, $event)">
<template #type="{ column }">
<span :class="[structureDataTypeToneClass(column.dataType), 'structure-data-type-option']">{{ column.dataType }}</span>
</template>
</StructureIndexColumnPicker>
<span v-else class="font-mono text-[length:var(--structure-font-size)] text-muted-foreground">{{ toColumnNames(index.columns) }}</span>
</td>
<td :class="structureCellClass">
<label class="flex items-center gap-1.5">
<input v-model="index.isUnique" type="checkbox" :class="structureCheckboxClass" :disabled="!canEditIndexDraft(index)" />
<input
:checked="index.isUnique"
type="checkbox"
:class="structureCheckboxClass"
:disabled="!canEditIndexDraft(index) || !!indexColumnsIssue(index, index.columns, index.indexType, true)"
data-index-unique
@change="onIndexUniqueChange(index, ($event.target as HTMLInputElement).checked)"
/>
<span>{{ index.isUnique ? t("structureEditor.yes") : t("structureEditor.no") }}</span>
</label>
</td>
<td :class="structureCellClass">
<Select v-if="indexTypeOptions.length > 0" :model-value="index.indexType || 'BTREE'" :disabled="!canEditIndexDraft(index)" @update:model-value="(v: any) => (index.indexType = String(v ?? ''))">
<Select v-if="indexTypeOptions.length > 0" :model-value="index.indexType || 'BTREE'" :disabled="!canEditIndexDraft(index)" data-index-type @update:model-value="(value: unknown) => onIndexTypeChange(index, value)">
<SelectTrigger class="structure-grid-control h-[var(--structure-control-height)] w-full rounded-[6px] px-[var(--structure-control-px)] font-mono text-[length:var(--structure-font-size)] focus-visible:border-ring/50 focus-visible:ring-1 focus-visible:ring-ring/25">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="opt in indexTypeOptions" :key="opt" :value="opt">{{ opt }}</SelectItem>
<SelectItem v-for="opt in indexTypeOptions" :key="opt" :value="opt" :disabled="!!indexColumnsIssue(index, index.columns, opt, false)">{{ opt }}</SelectItem>
</SelectContent>
</Select>
<Input v-else v-model="index.indexType" :class="structureMonoControlClass" placeholder="BTREE" :disabled="!canEditIndexDraft(index) || !structureCapabilities.indexType" />
<Input v-else :model-value="index.indexType" :class="structureMonoControlClass" placeholder="BTREE" :disabled="!canEditIndexDraft(index) || !structureCapabilities.indexType" @update:model-value="(value: unknown) => onIndexTypeChange(index, value)" />
</td>
<td :class="[structureCellClass, 'overflow-hidden']">
<DropdownMenu v-if="canEditIndexDraft(index) && structureCapabilities.indexInclude">
<DropdownMenuTrigger as-child>
<Button variant="outline" :class="[structureMonoControlClass, 'w-full justify-between']">
<span class="truncate">{{ index.includedColumns.join(", ") || t("structureEditor.includedColumnsPlaceholder") }}</span>
<ChevronDown :class="[structureIconClass, 'ml-1 shrink-0 opacity-50']" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent class="max-h-56 min-w-44 overflow-y-auto" side="bottom" :side-offset="2" :avoid-collisions="false" @interactOutside="colSearch = ''">
<div class="px-[var(--structure-cell-px)] pb-1 pt-0.5">
<Input v-model="colSearch" :class="structureControlClass" :placeholder="t('grid.search')" @click.stop />
</div>
<DropdownMenuCheckboxItem v-for="col in filteredIndexColumnNames(index.includedColumns)" :key="col" :checked="index.includedColumns.includes(col)" :class="index.includedColumns.includes(col) ? 'bg-primary/10' : ''" @select.prevent @click="toggleIncludedColumn(index, col)">
{{ col }}
</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
<StructureIndexColumnPicker
v-if="canEditIndexDraft(index) && structureCapabilities.indexInclude"
:selected="index.includedColumns"
:options="indexColumnPickerOptions(index, true)"
:placeholder="t('structureEditor.includedColumnsPlaceholder')"
:trigger-class="structureMonoControlClass"
@toggle="toggleIncludedColumn(index, $event)"
>
<template #type="{ column }">
<span :class="[structureDataTypeToneClass(column.dataType), 'structure-data-type-option']">{{ column.dataType }}</span>
</template>
</StructureIndexColumnPicker>
<span v-else class="text-[length:var(--structure-font-size)] text-muted-foreground">{{ index.includedColumns.join(", ") }}</span>
</td>
<td :class="structureCellClass">
@@ -6825,6 +7144,161 @@ watch(
box-shadow: none;
}
.structure-column-primary-key,
.structure-index-primary-key {
--structure-key-color: #d97706;
}
.structure-column-unique-key,
.structure-index-unique-key {
--structure-key-color: #dc2626;
}
.structure-column-index-key,
.structure-index-normal-key {
--structure-key-color: #15803d;
}
.structure-column-fulltext-key,
.structure-index-fulltext-key {
--structure-key-color: #9333ea;
}
.structure-column-spatial-key,
.structure-index-spatial-key {
--structure-key-color: #0e7490;
}
.structure-column-key-icon {
color: var(--structure-key-color);
}
.structure-column-primary-key > td:first-child,
.structure-column-unique-key > td:first-child,
.structure-column-index-key > td:first-child,
.structure-column-fulltext-key > td:first-child,
.structure-column-spatial-key > td:first-child {
box-shadow: inset 3px 0 0 var(--structure-key-color);
}
.structure-column-primary-key > td:nth-child(2) :deep(.structure-grid-control),
.structure-column-unique-key > td:nth-child(2) :deep(.structure-grid-control),
.structure-column-index-key > td:nth-child(2) :deep(.structure-grid-control),
.structure-column-fulltext-key > td:nth-child(2) :deep(.structure-grid-control),
.structure-column-spatial-key > td:nth-child(2) :deep(.structure-grid-control),
.structure-index-name :deep(.structure-grid-control) {
color: var(--structure-key-color);
font-weight: 600;
}
.structure-column-data-type,
.structure-column-default-value,
.structure-data-type-option {
--structure-type-color: var(--muted-foreground);
}
.structure-data-type-option {
color: var(--structure-type-color);
font-weight: 500;
}
.structure-data-type-numeric,
.structure-data-type-boolean {
--structure-type-color: #2563eb;
}
.structure-data-type-real {
--structure-type-color: #6366d1;
}
.structure-data-type-text,
.structure-data-type-json {
--structure-type-color: #15803d;
}
.structure-data-type-temporal {
--structure-type-color: #b45309;
}
.structure-data-type-binary {
--structure-type-color: #9333b8;
}
.structure-data-type-enum,
.structure-data-type-other {
--structure-type-color: #737323;
}
.structure-data-type-spatial {
--structure-type-color: #0e7490;
}
.structure-data-type-null {
--structure-type-color: var(--muted-foreground);
}
.dark .structure-column-primary-key,
.dark .structure-index-primary-key {
--structure-key-color: #fbbf24;
}
.dark .structure-column-unique-key,
.dark .structure-index-unique-key {
--structure-key-color: #f87171;
}
.dark .structure-column-index-key,
.dark .structure-index-normal-key {
--structure-key-color: #86efac;
}
.dark .structure-column-fulltext-key,
.dark .structure-index-fulltext-key {
--structure-key-color: #d8b4fe;
}
.dark .structure-column-spatial-key,
.dark .structure-index-spatial-key {
--structure-key-color: #67e8f9;
}
.dark .structure-data-type-numeric,
.dark .structure-data-type-boolean {
--structure-type-color: #93c5fd;
}
.dark .structure-data-type-real {
--structure-type-color: #a5b4fc;
}
.dark .structure-data-type-text,
.dark .structure-data-type-json {
--structure-type-color: #86efac;
}
.dark .structure-data-type-temporal {
--structure-type-color: #fcd34d;
}
.dark .structure-data-type-binary {
--structure-type-color: #d8b4fe;
}
.dark .structure-data-type-enum,
.dark .structure-data-type-other {
--structure-type-color: #d4d486;
}
.dark .structure-data-type-spatial {
--structure-type-color: #67e8f9;
}
.structure-column-data-type :deep(.structure-grid-control),
.structure-column-default-value :deep(.structure-grid-control) {
color: var(--structure-type-color);
font-weight: 500;
}
/* --primary is rgb/oklch; use color-mix like DataGrid, not channel-based hsl wrappers. */
.structure-column-search-match > td:first-child {
box-shadow: inset 3px 0 0 color-mix(in oklab, var(--primary) 55%, transparent);
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
name: "MySQL",
db_type: "mysql",
driver_label: "MySQL",
driver_profile: "",
},
ensureConnected: vi.fn(),
executeQuery: vi.fn(),
@@ -200,7 +201,23 @@ vi.mock("@/components/ui/select", async () => {
() =>
h("div", attrs, slots.default?.()),
});
return { Select: Div, SelectContent: Div, SelectItem: Div, SelectTrigger: Div, SelectValue: Div };
const Select = defineComponent({
inheritAttrs: false,
props: { modelValue: { type: String, default: "" } },
emits: ["update:modelValue"],
setup:
(props, { attrs, slots, emit }) =>
() =>
h("div", attrs, [
h(
"select",
{ value: props.modelValue, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value) },
["BTREE", "FULLTEXT", "SPATIAL"].map((value) => h("option", { value }, value)),
),
slots.default?.(),
]),
});
return { Select, SelectContent: Div, SelectItem: Div, SelectTrigger: Div, SelectValue: Div };
});
vi.mock("@/components/editor/EditorSearchPanel.vue", async () => {
const { defineComponent, h } = await import("vue");
@@ -254,8 +271,9 @@ vi.mock("@/lib/backend/api", () => ({
}));
import TableStructureEditor from "@/components/structure/TableStructureEditor.vue";
import { createColumnDrafts } from "@/lib/table/tableStructureEditorState";
import { createColumnDrafts, createIndexDrafts } from "@/lib/table/tableStructureEditorState";
import type { TableStructureEditorDraft } from "@/types/database";
import type { BuildTableStructureChangeSqlOptions, EditableStructureIndex } from "@/lib/table/tableStructureEditorSql";
const mountedApps: App[] = [];
@@ -276,13 +294,13 @@ async function settle() {
}
}
async function mountStructureEditor(draft?: TableStructureEditorDraft) {
async function mountStructureEditor(draft?: TableStructureEditorDraft, tableName = "users") {
const root = document.createElement("div");
document.body.append(root);
const app = createApp(TableStructureEditor, {
connectionId: mocks.connection.id,
database: "test",
tableName: "users",
tableName,
draft,
});
mountedApps.push(app);
@@ -299,6 +317,8 @@ async function mountStructureEditor(draft?: TableStructureEditorDraft) {
beforeEach(() => {
vi.clearAllMocks();
mocks.connection.db_type = "mysql";
mocks.connection.driver_profile = "";
mocks.ensureConnected.mockResolvedValue(undefined);
mocks.executeQuery.mockResolvedValue({ columns: [], rows: [] });
mocks.executeBatch.mockResolvedValue({ rowsAffected: 0 });
@@ -310,6 +330,423 @@ beforeEach(() => {
mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE users (id bigint)", cacheStatus: "remote" });
});
describe("TableStructureEditor column index actions", () => {
const fields = [
{ name: "id", data_type: "bigint", nullable: false, default_value: null, comment: "" },
{ name: "email", data_type: "varchar(255)", nullable: true, default_value: null, comment: "" },
{ name: "region", data_type: "varchar(32)", nullable: true, default_value: null, comment: "" },
{ name: "metadata", data_type: "json", nullable: true, default_value: null, comment: "" },
{ name: "location", data_type: "point", nullable: false, default_value: null, comment: "" },
{ name: "area", data_type: "polygon", nullable: true, default_value: null, comment: "" },
];
const columnMetadata = fields.map(({ nullable, default_value, ...column }) => ({ ...column, is_nullable: nullable, column_default: default_value, is_primary_key: false }));
function loadMetadata(indexes: unknown[] = []) {
mocks.loadObjectMetadataFacet.mockImplementation(async (_request, facet) => ({ value: facet === "columns" ? columnMetadata : facet === "indexes" ? indexes : facet === "comment" ? "" : [], cacheStatus: "remote" }));
}
function savedIndexDraft(index: EditableStructureIndex): TableStructureEditorDraft {
return {
initialized: true,
dirty: true,
activeTab: "indexes",
newTableName: "",
tableComment: "",
originalTableComment: "",
columns: createColumnDrafts(columnMetadata, "mysql"),
indexes: [index],
foreignKeys: [],
triggers: [],
loadedMetadataFacets: ["columns", "indexes", "comment"],
};
}
function fieldRow(root: HTMLElement, name: string): HTMLElement {
const input = [...root.querySelectorAll<HTMLInputElement>("[data-column-name-input]")].find((item) => item.value === name);
if (!input) throw new Error(`Missing field ${name}`);
return input.closest<HTMLElement>("tr")!;
}
function menuButton(label: string): HTMLButtonElement {
const button = [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")].find((item) => item.textContent?.trim() === label);
if (!button) throw new Error(`Missing menu item ${label}`);
return button;
}
async function openSubmenu(row: HTMLElement, label: string) {
row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2 }));
await settle();
menuButton(label).dispatchEvent(new MouseEvent("mouseenter"));
await settle();
}
function latestDraft(): BuildTableStructureChangeSqlOptions {
return mocks.buildTableStructureChangeSql.mock.calls.at(-1)?.[0];
}
function indexRow(root: HTMLElement, position = 0): HTMLElement {
return root.querySelector<HTMLElement>(`[data-index-row-index="${position}"]`)!;
}
async function expectIndexName(root: HTMLElement, name: string) {
await vi.waitFor(() => expect(indexRow(root).querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe(name));
}
it("loads index membership on the fields tab and creates a unique index as a draft", async () => {
loadMetadata([{ name: "idx_email", columns: ["email"], is_unique: false, is_primary: false }]);
const root = await mountStructureEditor();
expect(fieldRow(root, "email").classList.contains("structure-column-index-key")).toBe(true);
expect(mocks.loadObjectMetadataFacet.mock.calls.some((call) => call[1] === "indexes")).toBe(true);
await openSubmenu(fieldRow(root, "region"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createUniqueIndex").click();
await vi.waitFor(() => expect(latestDraft().indexes).toEqual(expect.arrayContaining([expect.objectContaining({ columns: ["region"], isUnique: true, isPrimary: false })])));
expect(fieldRow(root, "region").classList.contains("structure-column-unique-key")).toBe(true);
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("builds a composite index in selection order and appends fields without duplicates", async () => {
loadMetadata();
const root = await mountStructureEditor();
fieldRow(root, "email").click();
fieldRow(root, "region").dispatchEvent(new MouseEvent("click", { bubbles: true, metaKey: true }));
await openSubmenu(fieldRow(root, "region"), "structureEditor.createCompositeIndex");
menuButton("structureEditor.createNormalIndex").click();
await vi.waitFor(() => expect(latestDraft().indexes[0]?.columns).toEqual(["email", "region"]));
expect(fieldRow(root, "email").classList.contains("structure-column-index-key")).toBe(true);
expect(fieldRow(root, "region").classList.contains("structure-column-index-key")).toBe(true);
await openSubmenu(fieldRow(root, "id"), "structureEditor.addColumnsToIndex");
menuButton(`${latestDraft().indexes[0].name} (email, region)`).click();
await vi.waitFor(() => expect(latestDraft().indexes[0]?.columns).toEqual(["email", "region", "id"]));
expect(latestDraft().indexes[0]?.columnOpclasses).toEqual([null, null, null]);
await openSubmenu(fieldRow(root, "id"), "structureEditor.addColumnsToIndex");
expect(menuButton(`${latestDraft().indexes[0].name} (email, region, id)`).disabled).toBe(true);
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("creates one composite primary key and makes its members non-nullable", async () => {
loadMetadata();
const root = await mountStructureEditor();
fieldRow(root, "id").click();
fieldRow(root, "email").dispatchEvent(new MouseEvent("click", { bubbles: true, metaKey: true }));
await openSubmenu(fieldRow(root, "email"), "structureEditor.createCompositeIndex");
menuButton("structureEditor.createPrimaryIndex").click();
await vi.waitFor(() =>
expect(
latestDraft()
.columns.filter((column) => column.isPrimaryKey)
.map((column) => [column.name, column.isNullable]),
).toEqual([
["id", false],
["email", false],
]),
);
expect(latestDraft().indexes).toEqual([]);
await openSubmenu(fieldRow(root, "region"), "structureEditor.createColumnIndex");
expect(menuButton("structureEditor.createPrimaryIndex").disabled).toBe(true);
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("colors every member of a composite unique index and ignores dropped indexes", async () => {
loadMetadata([{ name: "uniq_email_region", columns: ["email", "region"], is_unique: true, is_primary: false }]);
const root = await mountStructureEditor();
expect(fieldRow(root, "email").classList.contains("structure-column-unique-key")).toBe(true);
expect(fieldRow(root, "region").classList.contains("structure-column-unique-key")).toBe(true);
expect(fieldRow(root, "id").classList.contains("structure-column-unique-key")).toBe(false);
const drop = [...root.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "structureEditor.drop" && button.closest("tr")?.querySelector("[data-index-name-input]"));
expect(drop).toBeDefined();
drop!.click();
await settle();
expect(fieldRow(root, "email").classList.contains("structure-column-unique-key")).toBe(false);
expect(fieldRow(root, "region").classList.contains("structure-column-unique-key")).toBe(false);
});
it("keeps names stable for field changes and updates only the automatic type prefix", async () => {
loadMetadata();
const root = await mountStructureEditor();
await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createNormalIndex").click();
await expectIndexName(root, "idx_email");
indexRow(root).querySelector<HTMLElement>('[data-index-column="region"]')!.click();
await expectIndexName(root, "idx_email");
const unique = indexRow(root).querySelector<HTMLInputElement>("[data-index-unique]")!;
unique.checked = true;
unique.dispatchEvent(new Event("change"));
await expectIndexName(root, "uk_email");
const type = indexRow(root).querySelector<HTMLSelectElement>("[data-index-type] select")!;
type.value = "FULLTEXT";
type.dispatchEvent(new Event("change"));
await expectIndexName(root, "ft_email");
expect(unique.disabled).toBe(true);
expect(indexRow(root).classList.contains("structure-index-fulltext-key")).toBe(true);
expect(fieldRow(root, "email").classList.contains("structure-column-fulltext-key")).toBe(true);
const name = indexRow(root).querySelector<HTMLInputElement>("[data-index-name-input]")!;
name.value = "custom_search";
name.dispatchEvent(new Event("input"));
indexRow(root).querySelector<HTMLElement>('[data-index-column="region"]')!.click();
await expectIndexName(root, "custom_search");
indexRow(root).querySelector<HTMLButtonElement>("[data-regenerate-index-name]")!.click();
await expectIndexName(root, "ft_email");
type.value = "BTREE";
type.dispatchEvent(new Event("change"));
await expectIndexName(root, "idx_email");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("keeps existing names stable unless regeneration is explicitly requested", async () => {
loadMetadata([{ name: "legacy_email", columns: ["email"], is_unique: true, is_primary: false }]);
const root = await mountStructureEditor();
indexRow(root).querySelector<HTMLElement>('[data-index-column="region"]')!.click();
await expectIndexName(root, "legacy_email");
indexRow(root).querySelector<HTMLButtonElement>("[data-regenerate-index-name]")!.click();
await expectIndexName(root, "uk_email");
indexRow(root).querySelector<HTMLElement>('[data-index-column="region"]')!.click();
await expectIndexName(root, "uk_email");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("remembers the first selected field even after removing every original member", async () => {
loadMetadata();
const root = await mountStructureEditor();
await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createNormalIndex").click();
await expectIndexName(root, "idx_email");
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="region"]')!.click();
await settle();
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="email"]')!.click();
await expectIndexName(root, "idx_email");
const unique = indexRow(root).querySelector<HTMLInputElement>("[data-index-unique]")!;
unique.checked = true;
unique.dispatchEvent(new Event("change"));
await expectIndexName(root, "uk_email");
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="region"]')!.click();
await settle();
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="location"]')!.click();
await expectIndexName(root, "uk_email");
await vi.waitFor(() => expect(latestDraft().indexes[0]).toMatchObject({ columns: ["location"], autoNameColumn: "email" }));
indexRow(root).querySelector<HTMLButtonElement>("[data-regenerate-index-name]")!.click();
await expectIndexName(root, "uk_location");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each([undefined, false, true])("preserves a legacy saved name without a naming seed (nameEdited=%s)", async (nameEdited) => {
loadMetadata();
const [index] = createIndexDrafts([{ name: "USERS_EMAIL_REGION_IDX", columns: ["email", "region"], is_unique: false, is_primary: false }]);
delete index.original;
index.nameEdited = nameEdited;
const draft = savedIndexDraft(index);
const snapshot = JSON.stringify(draft);
const root = await mountStructureEditor(draft);
await expectIndexName(root, "USERS_EMAIL_REGION_IDX");
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="email"]')!.click();
const unique = indexRow(root).querySelector<HTMLInputElement>("[data-index-unique]")!;
unique.checked = true;
unique.dispatchEvent(new Event("change"));
await vi.waitFor(() => expect(latestDraft().indexes[0]).toMatchObject({ name: "USERS_EMAIL_REGION_IDX", columns: ["region"], isUnique: true }));
expect(JSON.stringify(draft)).toBe(snapshot);
indexRow(root).querySelector<HTMLButtonElement>("[data-regenerate-index-name]")!.click();
await expectIndexName(root, "uk_region");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("restores the new naming seed even when its original field is no longer selected", async () => {
loadMetadata();
const [index] = createIndexDrafts([{ name: "idx_email", columns: ["region"], is_unique: false, is_primary: false }]);
delete index.original;
index.nameEdited = false;
index.autoNameColumn = "email";
const root = await mountStructureEditor(savedIndexDraft(index));
const unique = indexRow(root).querySelector<HTMLInputElement>("[data-index-unique]")!;
unique.checked = true;
unique.dispatchEvent(new Event("change"));
await expectIndexName(root, "uk_email");
await vi.waitFor(() => expect(latestDraft().indexes[0]).toMatchObject({ columns: ["region"], autoNameColumn: "email" }));
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each([undefined, true])("supports legacy blank drafts without overwriting a manually cleared name (nameEdited=%s)", async (nameEdited) => {
loadMetadata();
const [index] = createIndexDrafts([{ name: "", columns: [], is_unique: false, is_primary: false }]);
delete index.original;
index.nameEdited = nameEdited;
const root = await mountStructureEditor(savedIndexDraft(index));
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="email"]')!.click();
await expectIndexName(root, nameEdited ? "" : "idx_email");
await vi.waitFor(() => expect(latestDraft().indexes[0].columns).toEqual(["email"]));
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each([undefined, ["columns", "comment"]] as const)("preserves saved index edits with incomplete legacy facet flags (%s)", async (facets) => {
loadMetadata([{ name: "server_index", columns: ["id"], is_unique: false, is_primary: false }]);
const [index] = createIndexDrafts([{ name: "pending_email", columns: ["email", "region"], is_unique: true, is_primary: false }]);
delete index.original;
const draft = savedIndexDraft(index);
draft.activeTab = "columns";
draft.loadedMetadataFacets = facets ? [...facets] : undefined;
const root = await mountStructureEditor(draft);
await expectIndexName(root, "pending_email");
await vi.waitFor(() => expect(latestDraft().indexes).toEqual([expect.objectContaining({ name: "pending_email", columns: ["email", "region"], isUnique: true })]));
expect(mocks.loadObjectMetadataFacet.mock.calls.filter((call) => call[1] === "indexes")).toHaveLength(0);
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each(["postgres", "sqlite", "oracle", "sqlserver"])("retains table-qualified automatic names on %s", async (databaseType) => {
mocks.connection.db_type = databaseType;
loadMetadata();
for (const table of ["users", "orders"]) {
const root = await mountStructureEditor(undefined, table);
await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createNormalIndex").click();
await expectIndexName(root, `${table.toUpperCase()}_EMAIL_IDX`);
indexRow(root).querySelector<HTMLInputElement>('[data-index-column="region"]')!.click();
await expectIndexName(root, `${table.toUpperCase()}_EMAIL_IDX`);
}
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each([
["Doris", "doris", "doris"],
["Doris MySQL profile", "mysql", "doris"],
["StarRocks", "starrocks", "starrocks"],
["StarRocks MySQL profile", "mysql", "starrocks"],
["GoldenDB", "goldendb", "goldendb"],
["SunDB", "sundb", "sundb"],
["Databend", "databend", "databend"],
] as const)("retains table-qualified automatic names on %s", async (_label, databaseType, driverProfile) => {
mocks.connection.db_type = databaseType;
mocks.connection.driver_profile = driverProfile;
loadMetadata();
const root = await mountStructureEditor();
await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createNormalIndex").click();
await expectIndexName(root, "USERS_EMAIL_IDX");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("preserves lowercase table-qualified naming for GaussDB M-mode", async () => {
mocks.connection.db_type = "gaussdb";
mocks.connection.driver_profile = "gaussdb-m";
loadMetadata();
const root = await mountStructureEditor();
await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
menuButton("structureEditor.createNormalIndex").click();
await expectIndexName(root, "users_email_idx");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("keeps untouched historical special indexes out of validation for unrelated edits", async () => {
// Drivers may expose aliases that the newer frontend type whitelist does not recognize.
const columnsWithAlias = columnMetadata.map((column) => (column.name === "email" ? { ...column, data_type: "character varying(255)" } : column));
const indexes = [{ name: "legacy_search", columns: ["email"], is_unique: false, is_primary: false, index_type: "FULLTEXT" }];
mocks.loadObjectMetadataFacet.mockImplementation(async (_request, facet) => ({ value: facet === "columns" ? columnsWithAlias : facet === "indexes" ? indexes : facet === "comment" ? "" : [], cacheStatus: "remote" }));
const root = await mountStructureEditor();
expect(mocks.buildTableStructureChangeSql).not.toHaveBeenCalled();
const name = fieldRow(root, "region").querySelector<HTMLInputElement>("[data-column-name-input]")!;
name.value = "region_code";
name.dispatchEvent(new Event("input"));
await vi.waitFor(() => expect(latestDraft().columns.some((column) => column.name === "region_code")).toBe(true));
expect(latestDraft().indexes[0]).toMatchObject({ name: "legacy_search", columns: ["email"], original: indexes[0] });
expect(root.textContent).not.toContain("structureEditor.fulltextIndexColumns");
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("still validates a changed field used by an existing spatial index", async () => {
loadMetadata([{ name: "legacy_location", columns: ["location"], is_unique: false, is_primary: false, index_type: "SPATIAL" }]);
const root = await mountStructureEditor();
const nullable = fieldRow(root, "location").querySelectorAll<HTMLInputElement>('input[type="checkbox"]')[0];
nullable.checked = true;
nullable.dispatchEvent(new Event("change"));
await vi.waitFor(() => expect(root.textContent).toContain("structureEditor.spatialIndexNullable"));
expect(mocks.buildTableStructureChangeSql).not.toHaveBeenCalled();
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it("shows selected checkboxes in index order and preserves selection when searching by name or type", async () => {
loadMetadata([{ name: "uk_region_email", columns: ["region", "email"], is_unique: true, is_primary: false }]);
const root = await mountStructureEditor();
const picker = indexRow(root).querySelector<HTMLElement>("[data-index-column-picker]")!;
const inputs = () => [...picker.querySelectorAll<HTMLInputElement>("[data-index-column]")];
expect(
inputs()
.slice(0, 2)
.map((input) => [input.dataset.indexColumn, input.checked]),
).toEqual([
["region", true],
["email", true],
]);
const search = picker.querySelector<HTMLInputElement>("[data-index-column-search]")!;
search.value = "varchar";
search.dispatchEvent(new Event("input"));
await settle();
expect(inputs().map((input) => input.dataset.indexColumn)).toEqual(["region", "email"]);
search.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
expect(document.activeElement).toBe(inputs()[0]);
inputs()[0].dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
expect(document.activeElement).toBe(inputs()[1]);
search.value = "missing_field";
search.dispatchEvent(new Event("input"));
await settle();
expect(picker.textContent).toContain("structureEditor.noMatchingIndexColumns");
search.value = "";
search.dispatchEvent(new Event("input"));
await settle();
expect(
inputs()
.filter((input) => input.checked)
.map((input) => input.dataset.indexColumn),
).toEqual(["region", "email"]);
inputs()[0].click();
await settle();
expect(
inputs()
.filter((input) => input.checked)
.map((input) => input.dataset.indexColumn),
).toEqual(["email"]);
await expectIndexName(root, "uk_region_email");
});
it("shows distinct indicators for multiple index kinds on the same field", async () => {
loadMetadata([
{ name: "uk_email", columns: ["email"], is_unique: true, is_primary: false },
{ name: "idx_email_region", columns: ["email", "region"], is_unique: false, is_primary: false },
{ name: "ft_email", columns: ["email"], is_unique: false, is_primary: false, index_type: "FULLTEXT" },
{ name: "sp_location", columns: ["location"], is_unique: false, is_primary: false, index_type: "SPATIAL" },
]);
const root = await mountStructureEditor();
expect([...fieldRow(root, "email").querySelectorAll<HTMLElement>("[data-index-kind]")].map((icon) => icon.dataset.indexKind)).toEqual(["unique", "index", "fulltext"]);
expect(fieldRow(root, "email").classList.contains("structure-column-unique-key")).toBe(true);
expect(fieldRow(root, "location").classList.contains("structure-column-spatial-key")).toBe(true);
expect(indexRow(root, 3).classList.contains("structure-index-spatial-key")).toBe(true);
});
it("disables incompatible special indexes and adding another column to a spatial index", async () => {
loadMetadata();
const root = await mountStructureEditor();
await openSubmenu(fieldRow(root, "metadata"), "structureEditor.createColumnIndex");
expect(menuButton("structureEditor.createFulltextIndex").disabled).toBe(true);
expect(menuButton("structureEditor.createSpatialIndex").disabled).toBe(true);
await openSubmenu(fieldRow(root, "area"), "structureEditor.createColumnIndex");
expect(menuButton("structureEditor.createSpatialIndex").disabled).toBe(true);
await openSubmenu(fieldRow(root, "location"), "structureEditor.createColumnIndex");
expect(menuButton("structureEditor.createSpatialIndex").disabled).toBe(false);
menuButton("structureEditor.createSpatialIndex").click();
await expectIndexName(root, "sp_location");
await openSubmenu(fieldRow(root, "email"), "structureEditor.addColumnsToIndex");
expect(menuButton("sp_location (location)").disabled).toBe(true);
// The action guard also protects against a stale/programmatically invoked menu item.
indexRow(root).querySelector<HTMLElement>('[data-index-column="email"]')!.click();
await vi.waitFor(() => expect(latestDraft().indexes[0]?.columns).toEqual(["location"]));
const nullable = fieldRow(root, "location").querySelectorAll<HTMLInputElement>('input[type="checkbox"]')[0];
nullable.checked = true;
nullable.dispatchEvent(new Event("change"));
await vi.waitFor(() => expect(root.textContent).toContain("structureEditor.spatialIndexNullable"));
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
});
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
@@ -437,6 +874,21 @@ describe("restored structure snapshots after external DDL", () => {
expect(columnsFacetCalls()).toHaveLength(1);
});
it("loads missing indexes for legacy field-tab drafts without overwriting pending columns", async () => {
const indexes = [{ name: "legacy_id_idx", columns: ["id"], is_unique: false, is_primary: false }];
mocks.loadObjectMetadataFacet.mockImplementation(async (_request, facet) => ({ value: facet === "columns" ? rebuiltColumns : facet === "indexes" ? indexes : facet === "comment" ? "" : [], cacheStatus: "remote" }));
const draft = restoredDraft(true);
delete draft.loadedMetadataFacets;
draft.columns[0].name = "local_id";
const root = await mountStructureEditor(draft);
await vi.waitFor(() => expect(root.querySelector<HTMLInputElement>("[data-index-name-input]")?.value).toBe("legacy_id_idx"));
const field = root.querySelector<HTMLInputElement>("[data-column-name-input]")!;
expect(field.value).toBe("local_id");
expect(field.closest("tr")?.classList.contains("structure-column-index-key")).toBe(true);
expect(columnsFacetCalls()).toHaveLength(0);
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
it.each([true, undefined])("preserves restored edits when dirty is %s", async (dirty) => {
mocks.loadObjectMetadataFacet.mockImplementation(async (_request, facet) => ({ value: facet === "columns" ? rebuiltColumns : facet === "comment" ? "" : [], cacheStatus: "remote" }));
const draft = restoredDraft(dirty);
@@ -21,4 +21,14 @@ describe("TableStructureEditor selected-row styles", () => {
const gridControlRule = rules.find(({ selectors }) => selectors.includes(".structure-edit-grid :deep(.structure-grid-control)"));
expect(gridControlRule?.declarations).toContain("background-color: transparent;");
});
it("keeps HeidiSQL-style column type and key tone hooks wired", () => {
expect(source).toContain("structureDataTypeToneClass(column.dataType)");
expect(source).toContain("structure-column-primary-key");
expect(source).toContain("structure-column-unique-key");
for (const className of ["structure-data-type-numeric", "structure-data-type-text", "structure-data-type-temporal", "structure-data-type-json", "structure-data-type-binary", "structure-data-type-boolean", "structure-data-type-enum", "structure-data-type-spatial"]) {
expect(scopedStyle).toContain(className);
}
});
});
+17
View File
@@ -5114,6 +5114,23 @@ export default {
searchIndexes: "Search index",
nextIndexMatch: "Go to next matching index",
addIndex: "Add Index",
createColumnIndex: "Create index",
createCompositeIndex: "Create composite index ({count} columns)",
createPrimaryIndex: "Primary key (PRIMARY)",
createUniqueIndex: "Unique index (UNIQUE)",
createNormalIndex: "Index (INDEX)",
createFulltextIndex: "Full-text index (FULLTEXT)",
createSpatialIndex: "Spatial index (SPATIAL)",
addColumnsToIndex: "Add to index",
manageIndexes: "Edit indexes",
regenerateIndexName: "Regenerate index name",
indexSelectedColumns: "{count} columns selected",
noMatchingIndexColumns: "No matching columns",
clearColumnSearch: "Clear column search",
specialIndexUnique: "Full-text and spatial indexes cannot be unique.",
fulltextIndexColumns: "Full-text indexes require CHAR, VARCHAR, or TEXT columns.",
spatialIndexColumn: "A spatial index requires a single geometry column.",
spatialIndexNullable: "MySQL spatial index columns must be NOT NULL.",
addForeignKey: "Add Foreign Key",
addTrigger: "Add Trigger",
columnName: "Column",
+17
View File
@@ -4667,6 +4667,23 @@ export default withEnglishFallback({
searchIndexes: "Buscar índice",
nextIndexMatch: "Ir al siguiente índice coincidente",
addIndex: "Agregar índice",
createColumnIndex: "Crear índice",
createCompositeIndex: "Crear índice compuesto ({count} columnas)",
createPrimaryIndex: "Clave primaria (PRIMARY)",
createUniqueIndex: "Índice único (UNIQUE)",
createNormalIndex: "Índice (INDEX)",
createFulltextIndex: "Índice de texto completo (FULLTEXT)",
createSpatialIndex: "Índice espacial (SPATIAL)",
addColumnsToIndex: "Agregar a un índice existente",
manageIndexes: "Editar índices",
regenerateIndexName: "Regenerar nombre del índice",
indexSelectedColumns: "{count} columnas seleccionadas",
noMatchingIndexColumns: "No hay columnas coincidentes",
clearColumnSearch: "Borrar búsqueda de columnas",
specialIndexUnique: "Los índices de texto completo y espaciales no pueden ser únicos.",
fulltextIndexColumns: "Los índices de texto completo requieren columnas CHAR, VARCHAR o TEXT.",
spatialIndexColumn: "Un índice espacial requiere una sola columna de tipo geométrico.",
spatialIndexNullable: "Las columnas de índices espaciales de MySQL deben ser NOT NULL.",
addForeignKey: "Agregar clave foránea",
addTrigger: "Agregar disparador",
columnName: "Columna",
+17
View File
@@ -4486,6 +4486,23 @@ export default withEnglishFallback({
searchIndexes: "Cerca indice",
nextIndexMatch: "Vai al prossimo indice corrispondente",
addIndex: "Aggiungi Indice",
createColumnIndex: "Crea indice",
createCompositeIndex: "Crea indice composto ({count} colonne)",
createPrimaryIndex: "Chiave primaria (PRIMARY)",
createUniqueIndex: "Indice univoco (UNIQUE)",
createNormalIndex: "Indice (INDEX)",
createFulltextIndex: "Indice full-text (FULLTEXT)",
createSpatialIndex: "Indice spaziale (SPATIAL)",
addColumnsToIndex: "Aggiungi a un indice esistente",
manageIndexes: "Modifica indici",
regenerateIndexName: "Rigenera nome indice",
indexSelectedColumns: "{count} colonne selezionate",
noMatchingIndexColumns: "Nessuna colonna corrispondente",
clearColumnSearch: "Cancella ricerca colonne",
specialIndexUnique: "Gli indici full-text e spaziali non possono essere univoci.",
fulltextIndexColumns: "Gli indici full-text richiedono colonne CHAR, VARCHAR o TEXT.",
spatialIndexColumn: "Un indice spaziale richiede una sola colonna di tipo geometrico.",
spatialIndexNullable: "Le colonne degli indici spaziali MySQL devono essere NOT NULL.",
addForeignKey: "Aggiungi Chiave Esterna",
addTrigger: "Aggiungi Trigger",
columnName: "Colonna",
+17
View File
@@ -4550,6 +4550,23 @@ export default withEnglishFallback({
searchIndexes: "インデックスを検索",
nextIndexMatch: "次の一致するインデックスへ移動",
addIndex: "インデックスを追加",
createColumnIndex: "インデックスを作成",
createCompositeIndex: "複合インデックスを作成({count} 列)",
createPrimaryIndex: "主キー(PRIMARY)",
createUniqueIndex: "一意インデックス(UNIQUE)",
createNormalIndex: "インデックス(INDEX)",
createFulltextIndex: "全文インデックス(FULLTEXT)",
createSpatialIndex: "空間インデックス(SPATIAL)",
addColumnsToIndex: "既存のインデックスに追加",
manageIndexes: "インデックスを編集",
regenerateIndexName: "インデックス名を再生成",
indexSelectedColumns: "{count} 列を選択中",
noMatchingIndexColumns: "一致する列がありません",
clearColumnSearch: "列の検索をクリア",
specialIndexUnique: "全文インデックスと空間インデックスに一意制約は設定できません。",
fulltextIndexColumns: "全文インデックスには CHAR、VARCHAR、TEXT 型の列が必要です。",
spatialIndexColumn: "空間インデックスには幾何型の列を 1 つだけ指定してください。",
spatialIndexNullable: "MySQL の空間インデックスの列は NOT NULL である必要があります。",
addForeignKey: "外部キーを追加",
addTrigger: "トリガーを追加",
columnName: "列",
+17
View File
@@ -4392,6 +4392,23 @@ export default withEnglishFallback({
searchIndexes: "인덱스 검색",
nextIndexMatch: "다음 일치 인덱스로 이동",
addIndex: "인덱스 추가",
createColumnIndex: "인덱스 생성",
createCompositeIndex: "복합 인덱스 생성 ({count}개 컬럼)",
createPrimaryIndex: "기본 키 (PRIMARY)",
createUniqueIndex: "고유 인덱스 (UNIQUE)",
createNormalIndex: "일반 인덱스 (INDEX)",
createFulltextIndex: "전문 인덱스 (FULLTEXT)",
createSpatialIndex: "공간 인덱스 (SPATIAL)",
addColumnsToIndex: "기존 인덱스에 추가",
manageIndexes: "인덱스 편집",
regenerateIndexName: "인덱스 이름 다시 생성",
indexSelectedColumns: "{count}개 컬럼 선택됨",
noMatchingIndexColumns: "일치하는 컬럼이 없습니다",
clearColumnSearch: "컬럼 검색 지우기",
specialIndexUnique: "전문 인덱스와 공간 인덱스에는 고유 제약 조건을 설정할 수 없습니다.",
fulltextIndexColumns: "전문 인덱스에는 CHAR, VARCHAR 또는 TEXT 컬럼이 필요합니다.",
spatialIndexColumn: "공간 인덱스에는 기하 형식의 컬럼 하나만 지정해야 합니다.",
spatialIndexNullable: "MySQL 공간 인덱스 컬럼은 NOT NULL이어야 합니다.",
addForeignKey: "외래 키 추가",
addTrigger: "트리거 추가",
columnName: "컬럼",
+17
View File
@@ -4488,6 +4488,23 @@ export default withEnglishFallback({
searchIndexes: "Pesquisar índice",
nextIndexMatch: "Ir para o próximo índice correspondente",
addIndex: "Adicionar índice",
createColumnIndex: "Criar índice",
createCompositeIndex: "Criar índice composto ({count} colunas)",
createPrimaryIndex: "Chave primária (PRIMARY)",
createUniqueIndex: "Índice único (UNIQUE)",
createNormalIndex: "Índice (INDEX)",
createFulltextIndex: "Índice de texto completo (FULLTEXT)",
createSpatialIndex: "Índice espacial (SPATIAL)",
addColumnsToIndex: "Adicionar a um índice existente",
manageIndexes: "Editar índices",
regenerateIndexName: "Gerar nome do índice novamente",
indexSelectedColumns: "{count} colunas selecionadas",
noMatchingIndexColumns: "Nenhuma coluna correspondente",
clearColumnSearch: "Limpar pesquisa de colunas",
specialIndexUnique: "Índices de texto completo e espaciais não podem ser únicos.",
fulltextIndexColumns: "Índices de texto completo exigem colunas CHAR, VARCHAR ou TEXT.",
spatialIndexColumn: "Um índice espacial exige uma única coluna de tipo geométrico.",
spatialIndexNullable: "As colunas de índices espaciais do MySQL devem ser NOT NULL.",
addForeignKey: "Adicionar chave estrangeira",
addTrigger: "Adicionar trigger",
columnName: "Coluna",
+17
View File
@@ -4919,6 +4919,23 @@ export default withEnglishFallback({
searchIndexes: "Поиск индекса",
nextIndexMatch: "Перейти к следующему совпадению индекса",
addIndex: "Добавить индекс",
createColumnIndex: "Создать индекс",
createCompositeIndex: "Создать составной индекс ({count} столбцов)",
createPrimaryIndex: "Первичный ключ (PRIMARY)",
createUniqueIndex: "Уникальный индекс (UNIQUE)",
createNormalIndex: "Индекс (INDEX)",
createFulltextIndex: "Полнотекстовый индекс (FULLTEXT)",
createSpatialIndex: "Пространственный индекс (SPATIAL)",
addColumnsToIndex: "Добавить в существующий индекс",
manageIndexes: "Редактировать индексы",
regenerateIndexName: "Сгенерировать имя индекса заново",
indexSelectedColumns: "Выбрано столбцов: {count}",
noMatchingIndexColumns: "Нет подходящих столбцов",
clearColumnSearch: "Очистить поиск столбцов",
specialIndexUnique: "Полнотекстовые и пространственные индексы не могут быть уникальными.",
fulltextIndexColumns: "Для полнотекстовых индексов требуются столбцы CHAR, VARCHAR или TEXT.",
spatialIndexColumn: "Пространственный индекс должен содержать один столбец геометрического типа.",
spatialIndexNullable: "Столбцы пространственных индексов MySQL должны иметь ограничение NOT NULL.",
addForeignKey: "Добавить внешний ключ",
addTrigger: "Добавить триггер",
columnName: "Столбец",
+17
View File
@@ -5107,6 +5107,23 @@ export default withEnglishFallback({
searchIndexes: "搜索索引",
nextIndexMatch: "定位下一个匹配索引",
addIndex: "新增索引",
createColumnIndex: "创建索引",
createCompositeIndex: "创建复合索引({count} 个字段)",
createPrimaryIndex: "主键(PRIMARY)",
createUniqueIndex: "唯一索引(UNIQUE)",
createNormalIndex: "普通索引(INDEX)",
createFulltextIndex: "全文索引(FULLTEXT)",
createSpatialIndex: "空间索引(SPATIAL)",
addColumnsToIndex: "加入已有索引",
manageIndexes: "编辑索引",
regenerateIndexName: "重新生成名称",
indexSelectedColumns: "已选 {count} 个字段",
noMatchingIndexColumns: "没有匹配的字段",
clearColumnSearch: "清除字段搜索",
specialIndexUnique: "全文索引和空间索引不支持唯一约束。",
fulltextIndexColumns: "全文索引仅支持 CHAR、VARCHAR 和 TEXT 类字段。",
spatialIndexColumn: "空间索引只能包含一个几何类型字段。",
spatialIndexNullable: "MySQL 空间索引字段必须设为不可为空。",
addForeignKey: "新增外键",
addTrigger: "新增触发器",
columnName: "字段名",
+17
View File
@@ -4238,6 +4238,23 @@ export default withEnglishFallback({
searchIndexes: "搜尋索引",
nextIndexMatch: "定位下一個符合索引",
addIndex: "新增索引",
createColumnIndex: "建立索引",
createCompositeIndex: "建立複合索引({count} 個欄位)",
createPrimaryIndex: "主鍵(PRIMARY)",
createUniqueIndex: "唯一索引(UNIQUE)",
createNormalIndex: "一般索引(INDEX)",
createFulltextIndex: "全文索引(FULLTEXT)",
createSpatialIndex: "空間索引(SPATIAL)",
addColumnsToIndex: "加入現有索引",
manageIndexes: "編輯索引",
regenerateIndexName: "重新產生索引名稱",
indexSelectedColumns: "已選 {count} 個欄位",
noMatchingIndexColumns: "沒有符合的欄位",
clearColumnSearch: "清除欄位搜尋",
specialIndexUnique: "全文索引和空間索引不支援唯一約束。",
fulltextIndexColumns: "全文索引僅支援 CHAR、VARCHAR 和 TEXT 類型的欄位。",
spatialIndexColumn: "空間索引只能包含一個幾何類型欄位。",
spatialIndexNullable: "MySQL 空間索引欄位必須設為不可為空。",
addForeignKey: "新增外鍵",
addTrigger: "新增觸發器",
columnName: "欄位",
@@ -16,6 +16,11 @@ import {
draftColumnNameForSql,
getDataTypeLengthUnitOptions,
getDefaultLengthForType,
generateIndexName,
generateUniqueIndexName,
generateShortIndexName,
generateUniqueShortIndexName,
specialIndexColumnIssue,
hasExistingColumnTypeChange,
isDataTypeLengthDisabled,
isDamengIdentityCompatibleDataType,
@@ -36,6 +41,74 @@ import {
} from "@/lib/table/tableStructureEditorState";
describe("tableStructureEditorState", () => {
describe("index naming", () => {
it("uses a lowercase type prefix and the initial field name", () => {
expect(generateShortIndexName("Prop_Code")).toBe("idx_prop_code");
expect(generateShortIndexName("email", { isUnique: true })).toBe("uk_email");
expect(generateShortIndexName("title", { indexType: "FULLTEXT" })).toBe("ft_title");
expect(generateShortIndexName("location", { indexType: "SPATIAL" })).toBe("sp_location");
expect(generateShortIndexName("id", { isPrimary: true })).toBe("PRIMARY");
expect(generateShortIndexName("")).toBe("");
});
it("keeps long names deterministic and distinguishes truncated column names", () => {
const name = generateShortIndexName("a".repeat(90));
expect(name).toHaveLength(63);
expect(name).toMatch(/^idx_.*_[0-9a-f]{8}$/);
expect(generateShortIndexName("a".repeat(90))).toBe(name);
expect(generateShortIndexName("a".repeat(89) + "b")).not.toBe(name);
expect(generateShortIndexName("a".repeat(90), { maxLength: 64 })).toHaveLength(64);
});
it("resolves case-insensitive collisions while retaining type prefixes and limits", () => {
expect(generateUniqueShortIndexName("email", ["IDX_EMAIL", "idx_email_2"])).toBe("idx_email_3");
expect(generateUniqueShortIndexName("email", ["UK_EMAIL"], { isUnique: true })).toBe("uk_email_2");
const base = generateShortIndexName("a".repeat(90));
const next = generateUniqueShortIndexName("a".repeat(90), [base]);
expect(next).toHaveLength(63);
expect(next).toMatch(/^idx_.*_[0-9a-f]{8}_2$/);
});
it("preserves legacy callers and table-qualified names for shared namespaces", () => {
expect(generateIndexName("users", ["email"])).toBe("USERS_EMAIL_IDX");
expect(generateIndexName("orders", ["email"])).toBe("ORDERS_EMAIL_IDX");
expect(generateIndexName("users", ["email", "region"])).toBe("USERS_EMAIL_REGION_IDX");
expect(generateUniqueIndexName("users", ["email"], ["USERS_EMAIL_IDX"])).toBe("USERS_EMAIL_IDX_2");
});
it("preserves Chinese field names and provides deterministic names for symbols", () => {
const field = "\u5c5e\u6027";
expect(generateShortIndexName(field)).toBe(`idx_${field}`);
expect(generateUniqueShortIndexName(field, [`uk_${field}`], { isUnique: true })).toBe(`uk_${field}_2`);
const longName = generateShortIndexName(field.repeat(40), { maxLength: 64 });
expect(longName).toHaveLength(64);
expect(longName).toMatch(/_[0-9a-f]{8}$/);
expect(generateShortIndexName("---")).toMatch(/^idx_column_[0-9a-f]{8}$/);
expect(generateShortIndexName("---")).not.toBe(generateShortIndexName("+++"));
expect(generateShortIndexName("\u{10400}")).toMatch(/^idx_column_[0-9a-f]{8}$/);
});
});
describe("special index columns", () => {
const field = (dataType: string, isNullable = false) => ({ dataType, isNullable });
it("allows composite text searches but rejects JSON, numbers, and unique fulltext", () => {
expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field("varchar(255)"), field("longtext")])).toBeNull();
for (const type of ["json", "int", "blob"]) expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field(type)])).toBe("fulltextIndexColumns");
expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field("text")], true)).toBe("specialIndexUnique");
});
it("requires one non-null geometry for MySQL spatial indexes", () => {
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("point")])).toBeNull();
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("polygon", true)])).toBe("spatialIndexNullable");
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("point"), field("geometry")])).toBe("spatialIndexColumn");
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("varchar(64)")])).toBe("spatialIndexColumn");
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("geography")])).toBe("spatialIndexColumn");
expect(specialIndexColumnIssue("sqlserver", "SPATIAL", [field("geography", true)])).toBeNull();
expect(specialIndexColumnIssue("postgres", "GIST", [field("geometry", true)])).toBeNull();
});
});
describe("DuckDB type parameters", () => {
it.each([
"TINYINT",
@@ -3,7 +3,7 @@ import { hasTableStructureRefreshWork, unloadedTableStructureRefreshScope, visib
describe("table structure metadata loading", () => {
it.each([
["columns", { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
["columns", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
["indexes", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
["foreignKeys", { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, partitions: false, tableComment: true }],
["constraints", { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, partitions: false, tableComment: true }],
@@ -38,6 +38,8 @@ export interface EditableStructureIndex {
name: string;
columns: string[];
nameEdited?: boolean;
/** First selected field, retained when a composite index's members change. */
autoNameColumn?: string;
isUnique: boolean;
isPrimary: boolean;
filter: string;
@@ -1257,6 +1257,35 @@ export function toColumnNames(columns: string[]): string {
const AUTO_INDEX_NAME_MAX_LENGTH = 63;
export type StructureIndexKind = "primary" | "unique" | "index" | "fulltext" | "spatial";
type IndexNamingOptions = Partial<Pick<EditableStructureIndex, "isPrimary" | "isUnique" | "indexType">> & { maxLength?: number };
export function structureIndexKind(index: IndexNamingOptions): StructureIndexKind {
if (index.isPrimary) return "primary";
if (index.indexType?.trim().toUpperCase() === "FULLTEXT") return "fulltext";
if (index.indexType?.trim().toUpperCase() === "SPATIAL") return "spatial";
return index.isUnique ? "unique" : "index";
}
export type SpecialIndexColumnIssue = "specialIndexUnique" | "fulltextIndexColumns" | "spatialIndexColumn" | "spatialIndexNullable";
export function specialIndexColumnIssue(dialect: string, indexType: string, columns: readonly Pick<EditableStructureColumn, "dataType" | "isNullable">[], isUnique = false): SpecialIndexColumnIssue | null {
const type = indexType.trim().toUpperCase();
const fulltext = dialect === "mysql" && type === "FULLTEXT";
const spatial = (dialect === "mysql" || dialect === "sqlserver") && type === "SPATIAL";
if (!fulltext && !spatial) return null;
if (isUnique) return "specialIndexUnique";
if (!columns.length) return null;
const types = columns.map((column) => splitDataType(column.dataType).baseType.toLowerCase());
if (fulltext && types.some((value) => !/^(?:char|varchar|tinytext|text|mediumtext|longtext)$/.test(value))) return "fulltextIndexColumns";
if (spatial) {
const validType = dialect === "mysql" ? /^(?:geometry|point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection|geomcollection)$/ : /^(?:geometry|geography)$/;
if (columns.length !== 1 || !validType.test(types[0])) return "spatialIndexColumn";
if (dialect === "mysql" && columns[0].isNullable) return "spatialIndexNullable";
}
return null;
}
function normalizeIndexNamePart(value: string): string {
const trimmed = value.trim();
const unquoted = (trimmed.startsWith("[") && trimmed.endsWith("]")) || (trimmed.startsWith("`") && trimmed.endsWith("`")) || (trimmed.startsWith('"') && trimmed.endsWith('"')) ? trimmed.slice(1, -1) : trimmed;
@@ -1275,6 +1304,7 @@ function truncateIndexName(value: string, maxLength = AUTO_INDEX_NAME_MAX_LENGTH
return `${value.slice(0, maxLength - suffix.length).replace(/_+$/g, "")}${suffix}`;
}
// Keep the original API and table-qualified naming for existing callers and dialects.
export function generateIndexName(tableName: string, columns: string[], maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
const parts = [tableName, ...columns].map(normalizeIndexNamePart).filter(Boolean);
if (parts.length === 0) return "";
@@ -1297,6 +1327,53 @@ export function generateUniqueIndexName(tableName: string, columns: string[], ex
return base;
}
function indexNameHash(value: string): string {
// Keep long names deterministic and distinguish columns beyond the cutoff.
let hash = 2166136261;
for (let i = 0; i < value.length; i++) hash = Math.imul(hash ^ value.charCodeAt(i), 16777619);
return (hash >>> 0).toString(16).padStart(8, "0");
}
function truncateShortIndexName(value: string, maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
if (value.length <= maxLength) return value;
const suffix = `_${indexNameHash(value)}`;
if (maxLength <= suffix.length) return value.slice(0, maxLength);
return `${value.slice(0, maxLength - suffix.length).replace(/_+$/g, "")}${suffix}`;
}
export function generateShortIndexName(columnName: string, options: IndexNamingOptions = {}): string {
if (options.isPrimary) return "PRIMARY";
if (!columnName.trim()) return "";
// MySQL permits BMP Unicode identifiers, but not supplementary characters.
const normalized = columnName
.trim()
.replace(/[^\p{L}\p{N}]+/gu, "_")
.replace(/[\uD800-\uDFFF]/g, "_")
.replace(/_+/g, "_")
.replace(/^_+|_+$/g, "")
.toLowerCase();
const name = normalized || `column_${indexNameHash(columnName)}`;
const prefix = { primary: "pk", unique: "uk", index: "idx", fulltext: "ft", spatial: "sp" }[structureIndexKind(options)];
return truncateShortIndexName(`${prefix}_${name}`, options.maxLength);
}
export function generateUniqueShortIndexName(columnName: string, existingNames: Iterable<string>, options: IndexNamingOptions = {}): string {
const maxLength = options.maxLength ?? AUTO_INDEX_NAME_MAX_LENGTH;
const base = generateShortIndexName(columnName, options);
if (!base) return "";
if (options.isPrimary) return base;
const taken = new Set([...existingNames].map((name) => name.trim().toLowerCase()).filter(Boolean));
if (!taken.has(base.toLowerCase())) return base;
for (let counter = 2; ; counter++) {
const suffix = `_${counter}`;
const stem = generateShortIndexName(columnName, { ...options, maxLength: Math.max(1, maxLength - suffix.length) });
const candidate = `${stem}${suffix}`;
if (!taken.has(candidate.toLowerCase())) return candidate;
}
}
export function splitDataType(raw: string): { baseType: string; params: string } {
const trimmed = raw.trim();
const parenIdx = trimmed.indexOf("(");
@@ -14,7 +14,7 @@ export interface TableStructureRefreshScope {
export function visibleTableStructureRefreshScope(activeTab: TableInfoTab): TableStructureRefreshScope {
switch (activeTab) {
case "columns":
return { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
case "indexes":
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
case "foreignKeys":