Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(mysql): editable generated columns in the table structure editor

Stormb351c0f3b8be
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index 9437f3df91..e18bb23a3c 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -14,7 +14,35 @@ import { Input } from "@/components/ui/input";
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 {
+ AlertTriangle,
+ Check,
+ ChevronDown,
+ ChevronLeft,
+ ChevronRight,
+ ChevronUp,
+ ClipboardList,
+ Copy,
+ Database,
+ Info,
+ KeyRound,
+ ListChevronsUpDown,
+ Loader2,
+ Maximize2,
+ Pencil,
+ Plus,
+ RefreshCw,
+ RotateCcw,
+ Rows3,
+ Save,
+ Search,
+ Settings,
+ SlidersHorizontal,
+ SquareFunction,
+ Trash2,
+ UserRound,
+ X,
+} from "@lucide/vue";
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";
@@ -124,6 +152,7 @@ import {
isSqlServerIdentityCompatibleDataType,
mysqlEnumDataType,
parseExtraToColumnExtra,
+ parseMysqlGeneratedColumnExtra,
rehydrateColumnDraftsFromMetadata,
resolveInsertColumnIndex,
restoreCharacterLengthUnitsAfterSave,
@@ -1876,6 +1905,50 @@ function setMysqlAutoIncrement(column: EditableStructureColumn, checked: boolean
void loadMysqlAutoIncrementCounter(true);
}
}
+
+// MySQL generated columns (issue #11208). Tri-state mirrors the backend contract:
+// `undefined` inherits the original definition, an empty expression removes the
+// attribute, otherwise the clause renders from the edited values.
+function hasOriginalMysqlGeneratedColumn(column: EditableStructureColumn): boolean {
+ return structureDialect.value === "mysql" && !!column.original?.extra && !!parseMysqlGeneratedColumnExtra(column.original.extra);
+}
+
+function isMysqlGeneratedChecked(column: EditableStructureColumn): boolean {
+ return structureDialect.value === "mysql" && column.extra.generated !== undefined;
+}
+
+function isMysqlGeneratedActive(column: EditableStructureColumn): boolean {
+ return isMysqlGeneratedChecked(column) && (column.extra.generated?.expression.trim() ?? "") !== "";
+}
+
+function setMysqlGenerated(column: EditableStructureColumn, checked: boolean) {
+ // Only manage the generated flag here. Conflicting attributes (DEFAULT,
+ // AUTO_INCREMENT, ON UPDATE) stay in the draft: they are disabled in the UI
+ // while generated, and stripped from the SQL payload only while the
+ // generated attribute is active, so unchecking restores them untouched.
+ if (checked) {
+ // Re-checking after an accidental uncheck restores the original expression
+ // and storage instead of starting from a blank VIRTUAL draft.
+ const original = column.original?.extra ? parseMysqlGeneratedColumnExtra(column.original.extra) : undefined;
+ column.extra.generated = original ? { ...original } : { expression: "", storage: "STORED" };
+ return;
+ }
+ // Dropping the attribute must be explicit for a column that was generated,
+ // otherwise `undefined` would inherit the original definition back.
+ column.extra.generated = hasOriginalMysqlGeneratedColumn(column) ? { expression: "" } : undefined;
+}
+
+function updateMysqlGeneratedExpression(column: EditableStructureColumn, expression: string) {
+ if (column.extra.generated) {
+ column.extra.generated.expression = expression;
+ }
+}
+
+function updateMysqlGeneratedStorage(column: EditableStructureColumn, storage: string) {
+ if (column.extra.generated) {
+ column.extra.generated.storage = storage === "STORED" ? "STORED" : "VIRTUAL";
+ }
+}
function isSqliteAutoIncrement(column: EditableStructureColumn): boolean {
return structureDialect.value === "sqlite" && column.isPrimaryKey && isSqliteIntegerType(column.dataType) && column.extra.autoIncrement === true;
}
@@ -2515,13 +2588,25 @@ function structureChangeOptions(): BuildTableStructureChangeSqlOptions {
// User-entered names are normalized here so the preview and the executed
// batch agree: MySQL rejects identifiers that end with a space (ERROR 1166),
// while a metadata name the user never touched keeps its exact spelling.
- columns: columns.value.map((column) => ({
- ...column,
- name: draftColumnNameForSql(column.name, column.original?.name),
- // Do not let a draft created by an older build submit properties that the
- // current database cannot represent (notably PostgreSQL-style identity on openGauss).
- ...(showExtendedProperties.value ? {} : { extra: {} }),
- })),
+ columns: columns.value.map((column) => {
+ const normalized = {
+ ...column,
+ name: draftColumnNameForSql(column.name, column.original?.name),
+ // Do not let a draft created by an older build submit properties that the
+ // current database cannot represent (notably PostgreSQL-style identity on openGauss).
+ ...(showExtendedProperties.value ? {} : { extra: {} }),
+ };
+ // MySQL generated columns cannot carry DEFAULT / AUTO_INCREMENT /
+ // ON UPDATE CURRENT_TIMESTAMP; drop them from the payload only while the
+ // generated attribute is active, so unchecking "virtual" leaves the
+ // draft (and the diff) exactly as the user last saw it.
+ if (isMysqlGeneratedActive(column) && normalized.extra) {
+ const { autoIncrement: _autoIncrement, onUpdateCurrentTimestamp: _onUpdate, ...restExtra } = normalized.extra;
+ normalized.extra = restExtra;
+ normalized.defaultValue = "";
+ }
+ return normalized;
+ }),
indexes: sanitizeStructureIndexesForCapabilities(indexes.value, structureCapabilities.value),
foreignKeys: foreignKeys.value,
triggers: triggers.value,
@@ -4418,7 +4503,7 @@ function isColumnNullableDisabled(column: EditableStructureColumn): boolean {
}
function isColumnDefaultDisabled(column: EditableStructureColumn): boolean {
- return column.markedForDrop || (!!column.original && !structureCapabilities.value.alterDefault);
+ return column.markedForDrop || (!!column.original && !structureCapabilities.value.alterDefault) || isMysqlGeneratedActive(column);
}
function isColumnCommentDisabled(column: EditableStructureColumn): boolean {
@@ -6018,8 +6103,44 @@ watch(
</label>
</template>
<template v-else-if="structureDialect === 'mysql'">
+ <label :class="[structurePropertyLabelClass, 'shrink-0 pr-1']" :title="t('structureEditor.virtual')">
+ <input :checked="isMysqlGeneratedChecked(column)" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" @change="setMysqlGenerated(column, ($event.target as HTMLInputElement).checked)" />
+ <span>{{ t("structureEditor.virtual") }}</span>
+ </label>
+ <Popover v-if="isMysqlGeneratedChecked(column)">
+ <PopoverTrigger as-child>
+ <Button variant="ghost" size="icon" :class="[structureIconButtonClass, 'mr-1 shrink-0']" :title="t('structureEditor.generatedExpression')" :aria-label="t('structureEditor.generatedExpression')" data-mysql-generated-expression-trigger>
+ <SquareFunction :class="structureIconClass" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" class="w-96 space-y-2 p-3">
+ <label class="block text-xs font-medium text-foreground">{{ t("structureEditor.generatedExpression") }}</label>
+ <Input
+ :model-value="column.extra.generated?.expression ?? ''"
+ class="w-full font-mono"
+ :placeholder="t('structureEditor.generatedExpressionPlaceholder')"
+ data-mysql-generated-expression
+ :aria-label="t('structureEditor.generatedExpression')"
+ @update:model-value="(v) => updateMysqlGeneratedExpression(column, String(v ?? ''))"
+ />
+ <p v-if="!isMysqlGeneratedActive(column)" class="text-xs text-destructive">{{ t("structureEditor.generatedExpressionEmptyHint") }}</p>
+ <div class="flex items-center gap-2">
+ <label class="text-xs text-muted-foreground">{{ t("structureEditor.generatedStorage") }}</label>
+ <Select :model-value="column.extra.generated?.storage ?? 'VIRTUAL'" @update:model-value="(v) => updateMysqlGeneratedStorage(column, String(v ?? 'VIRTUAL'))">
+ <SelectTrigger class="h-[var(--structure-control-height)] w-28 rounded-[6px] px-[var(--structure-control-px)] text-[length:var(--structure-font-size)] focus-visible:border-ring/50 focus-visible:ring-1 focus-visible:ring-ring/25">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="VIRTUAL">{{ t("structureEditor.generatedStorageVirtual") }}</SelectItem>
+ <SelectItem value="STORED">{{ t("structureEditor.generatedStorageStored") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("structureEditor.generatedExpressionHint") }}</p>
+ </PopoverContent>
+ </Popover>
<label :class="[structurePropertyLabelClass, 'shrink-0 pr-1']" :title="t('structureEditor.autoIncrement')">
- <input :checked="column.extra.autoIncrement" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" @change="setMysqlAutoIncrement(column, ($event.target as HTMLInputElement).checked)" />
+ <input :checked="column.extra.autoIncrement" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" :disabled="isMysqlGeneratedActive(column)" @change="setMysqlAutoIncrement(column, ($event.target as HTMLInputElement).checked)" />
<span>{{ t("structureEditor.autoIncrement") }}</span>
</label>
<Popover v-if="isMysqlAutoIncrementCounterColumn(column)">
@@ -6057,7 +6178,7 @@ watch(
</PopoverContent>
</Popover>
<label :class="[structurePropertyLabelClass, 'flex-1 basis-0']" :title="t('structureEditor.onUpdateCurrentTimestamp')">
- <input v-model="column.extra.onUpdateCurrentTimestamp" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" />
+ <input v-model="column.extra.onUpdateCurrentTimestamp" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" :disabled="isMysqlGeneratedActive(column)" />
<span class="min-w-0 truncate">{{ t("structureEditor.onUpdateCurrentTimestamp") }}</span>
</label>
</template>
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts
new file mode 100644
index 0000000000..cc3b16ab06
--- /dev/null
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts
@@ -0,0 +1,513 @@
+// @vitest-environment happy-dom
+
+import { createApp, nextTick, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ connection: {
+ id: "structure-generated-test",
+ name: "MySQL",
+ db_type: "mysql",
+ driver_profile: "mysql",
+ driver_label: "MySQL",
+ },
+ ensureConnected: vi.fn(),
+ executeQuery: vi.fn(),
+ listDataTypes: vi.fn(),
+ buildTableStructureChangeSql: vi.fn(),
+ buildMysqlAutoIncrementSql: vi.fn(),
+ getMysqlTableAutoIncrement: vi.fn(),
+ executeBatch: vi.fn(),
+ updateEditorSettings: vi.fn(),
+ loadObjectDdl: vi.fn(),
+ invalidateObjectDdl: vi.fn(),
+ loadObjectMetadataFacet: vi.fn(),
+ invalidateObjectMetadataCache: vi.fn(),
+ invalidateTableMetadataCache: vi.fn(),
+ toast: vi.fn(),
+}));
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+
+vi.mock("@lucide/vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Icon = defineComponent({ name: "Icon", setup: () => () => h("span") });
+ return {
+ AlertTriangle: Icon,
+ Check: Icon,
+ ChevronDown: Icon,
+ ChevronUp: Icon,
+ ClipboardList: Icon,
+ Copy: Icon,
+ Database: Icon,
+ Info: Icon,
+ Keyboard: Icon,
+ KeyRound: Icon,
+ ListChevronsUpDown: Icon,
+ Loader2: Icon,
+ Maximize2: Icon,
+ Pencil: Icon,
+ Plus: Icon,
+ RefreshCw: Icon,
+ Rows3: Icon,
+ Save: Icon,
+ Search: Icon,
+ Settings: Icon,
+ SlidersHorizontal: Icon,
+ SquareFunction: Icon,
+ Trash2: Icon,
+ UserRound: Icon,
+ X: Icon,
+ };
+});
+
+vi.mock("@/components/ui/button", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Button: defineComponent({
+ name: "Button",
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("button", attrs, slots.default?.()),
+ }),
+ };
+});
+vi.mock("@/components/ui/input", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Input: defineComponent({
+ name: "Input",
+ inheritAttrs: false,
+ props: { modelValue: { type: [String, Number], default: "" } },
+ emits: ["update:modelValue"],
+ setup:
+ (props, { attrs, emit }) =>
+ () =>
+ h("input", {
+ ...attrs,
+ value: props.modelValue,
+ onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value),
+ }),
+ }),
+ };
+});
+vi.mock("@/components/ui/badge", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Badge: defineComponent({
+ name: "Badge",
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("span", attrs, slots.default?.()),
+ }),
+ };
+});
+vi.mock("@/components/ui/tabs", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ const Button = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("button", attrs, slots.default?.()),
+ });
+ return { Tabs: Div, TabsContent: Div, TabsList: Div, TabsTrigger: Button };
+});
+vi.mock("@/components/ui/dropdown-menu", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ const Button = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("button", attrs, slots.default?.()),
+ });
+ return { DropdownMenu: Div, DropdownMenuCheckboxItem: Div, DropdownMenuContent: Div, DropdownMenuItem: Button, DropdownMenuTrigger: Div };
+});
+vi.mock("@/components/ui/popover", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ return { Popover: Div, PopoverContent: Div, PopoverTrigger: Div };
+});
+vi.mock("@/components/ui/tooltip", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ return { Tooltip: Div, TooltipContent: Div, TooltipTrigger: Div };
+});
+vi.mock("@/components/ui/searchable-select", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ SearchableSelect: defineComponent({
+ name: "SearchableSelect",
+ inheritAttrs: false,
+ props: {
+ modelValue: { type: String, default: "" },
+ options: { type: Array, default: () => [] },
+ allowCustom: { type: Boolean, default: false },
+ },
+ emits: ["update:modelValue"],
+ setup:
+ (props, { attrs, emit }) =>
+ () =>
+ h("button", {
+ ...attrs,
+ type: "button",
+ "data-searchable-select": "true",
+ "data-model-value": props.modelValue,
+ "data-options": JSON.stringify(props.options),
+ "data-allow-custom": String(props.allowCustom),
+ onClick: () => emit("update:modelValue", "custom_domain"),
+ }),
+ }),
+ };
+});
+vi.mock("@/components/ui/select", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ return { Select: Div, SelectContent: Div, SelectItem: Div, SelectTrigger: Div, SelectValue: Div };
+});
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ ensureConnected: mocks.ensureConnected,
+ getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
+ }),
+}));
+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: vi.fn() }) }));
+vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ tableStructureRefreshVersion: () => 0 }) }));
+vi.mock("@/stores/historyStore", () => ({ useHistoryStore: () => ({ add: vi.fn() }) }));
+vi.mock("@/stores/settingsStore", () => ({
+ useSettingsStore: () => ({
+ editorSettings: { structureEditorDensity: "compact", sqlFormatter: {}, tableColumnTemplateFields: [], generateSqlQuoteIdentifiers: true },
+ updateEditorSettings: mocks.updateEditorSettings,
+ }),
+}));
+vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/lib/sql/sqlHighlighter", () => ({ createShikiSqlHighlighter: vi.fn(async () => (sql: string) => sql) }));
+vi.mock("@/lib/metadata/objectDdlCache", () => ({
+ loadObjectDdl: mocks.loadObjectDdl,
+ invalidateObjectDdl: mocks.invalidateObjectDdl,
+}));
+vi.mock("@/lib/metadata/objectMetadataCache", () => ({ loadObjectMetadataFacet: mocks.loadObjectMetadataFacet, invalidateObjectMetadataCache: mocks.invalidateObjectMetadataCache }));
+vi.mock("@/lib/metadata/tableMetadataCache", () => ({ invalidateTableMetadataCache: mocks.invalidateTableMetadataCache }));
+vi.mock("@/lib/backend/api", () => ({
+ executeQuery: mocks.executeQuery,
+ listDataTypes: mocks.listDataTypes,
+ buildTableStructureChangeSql: mocks.buildTableStructureChangeSql,
+ buildMysqlAutoIncrementSql: mocks.buildMysqlAutoIncrementSql,
+ getMysqlTableAutoIncrement: mocks.getMysqlTableAutoIncrement,
+ executeBatch: mocks.executeBatch,
+}));
+
+import TableStructureEditor from "@/components/structure/TableStructureEditor.vue";
+
+const mountedApps: App[] = [];
+
+type ColumnSeed = {
+ name: string;
+ extra?: Record<string, unknown>;
+ originalExtra?: string | null;
+ originalDefault?: string | null;
+ hasOriginal?: boolean;
+};
+
+function draftWithColumns(columns: ColumnSeed[]) {
+ return {
+ initialized: true,
+ activeTab: "columns" as const,
+ newTableName: "",
+ tableComment: "",
+ originalTableComment: "",
+ columns: columns.map((column, index) => ({
+ id: column.hasOriginal === false ? `new:${index}` : `existing:${column.name}`,
+ name: column.name,
+ dataType: "int",
+ isNullable: true,
+ defaultValue: "",
+ comment: "",
+ isPrimaryKey: false,
+ characterSet: "",
+ collation: "",
+ extra: column.extra ?? {},
+ defaultValue: column.originalDefault ?? "",
+ original: {
+ name: column.name,
+ data_type: "int",
+ is_nullable: true,
+ column_default: column.originalDefault ?? null,
+ is_primary_key: false,
+ extra: column.originalExtra ?? null,
+ comment: null,
+ },
+ originalPosition: index,
+ markedForDrop: false,
+ })),
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ };
+}
+
+async function mountEditor(draft: ReturnType<typeof draftWithColumns>) {
+ mocks.ensureConnected.mockResolvedValue(undefined);
+ mocks.listDataTypes.mockResolvedValue([]);
+ mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: [], warnings: [] });
+
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ schema: "test",
+ tableName: "user",
+ draft,
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await nextTick();
+ await Promise.resolve();
+ await nextTick();
+ return root;
+}
+
+async function lastPreviewColumns(): Promise<Array<{ name: string; defaultValue: string; extra: Record<string, unknown> }>> {
+ await vi.waitFor(() => expect(mocks.buildTableStructureChangeSql).toHaveBeenCalled(), { timeout: 3000 });
+ await nextTick();
+ const options = mocks.buildTableStructureChangeSql.mock.calls.at(-1)![0] as {
+ columns: Array<{ name: string; defaultValue: string; extra: Record<string, unknown> }>;
+ };
+ return options.columns;
+}
+
+/** Wait until the debounced SQL preview submitted a newer request than `calls`. */
+async function waitForPreviewCalls(calls: number): Promise<void> {
+ await vi.waitFor(() => expect(mocks.buildTableStructureChangeSql.mock.calls.length).toBeGreaterThan(calls), { timeout: 3000 });
+ await nextTick();
+}
+
+function virtualCheckbox(root: HTMLElement): HTMLInputElement {
+ const input = root.querySelector<HTMLInputElement>('label[title="structureEditor.virtual"] input');
+ expect(input).not.toBeNull();
+ return input!;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.connection.db_type = "mysql";
+ mocks.connection.driver_profile = "mysql";
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE user (id int)", cacheStatus: "remote" });
+ mocks.loadObjectMetadataFacet.mockResolvedValue({ value: [], cacheStatus: "remote" });
+ mocks.getMysqlTableAutoIncrement.mockResolvedValue(null);
+ mocks.buildMysqlAutoIncrementSql.mockResolvedValue("");
+ mocks.executeBatch.mockResolvedValue({ affected_rows: 0 });
+});
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("TableStructureEditor MySQL generated columns", () => {
+ it("shows a hydrated generated column as checked with its expression", async () => {
+ const root = await mountEditor(
+ draftWithColumns([
+ {
+ name: "total",
+ extra: { generated: { expression: "`price` * `quantity`", storage: "STORED" } },
+ originalExtra: "GENERATED ALWAYS AS (`price` * `quantity`) STORED",
+ },
+ ]),
+ );
+
+ expect(virtualCheckbox(root).checked).toBe(true);
+ const expressionInput = root.querySelector<HTMLInputElement>("[data-mysql-generated-expression]");
+ expect(expressionInput?.value).toBe("`price` * `quantity`");
+ });
+
+ it("unchecking a generated column sends an explicit empty expression (removal)", async () => {
+ const root = await mountEditor(
+ draftWithColumns([
+ {
+ name: "total",
+ extra: { generated: { expression: "`price` * `quantity`", storage: "STORED" } },
+ originalExtra: "GENERATED ALWAYS AS (`price` * `quantity`) STORED",
+ },
+ ]),
+ );
+
+ const checkbox = virtualCheckbox(root);
+ checkbox.checked = false;
+ checkbox.dispatchEvent(new Event("change"));
+
+ const columns = await lastPreviewColumns();
+ expect(columns[0]!.extra.generated).toEqual({ expression: "" });
+ });
+
+ it("checking virtual keeps conflicting attributes in the draft until the expression is active", async () => {
+ const root = await mountEditor(
+ draftWithColumns([
+ {
+ name: "total",
+ extra: { autoIncrement: true, onUpdateCurrentTimestamp: true },
+ originalExtra: "auto_increment on update current_timestamp",
+ },
+ ]),
+ );
+
+ const checkbox = virtualCheckbox(root);
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event("change"));
+
+ // Expression still empty: the attribute is not active, so the conflicting
+ // attributes remain in the payload untouched.
+ let calls = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await waitForPreviewCalls(calls);
+ let columns = await lastPreviewColumns();
+ expect(columns[0]!.extra.generated).toEqual({ expression: "", storage: "STORED" });
+ expect(columns[0]!.extra.autoIncrement).toBe(true);
+ expect(columns[0]!.extra.onUpdateCurrentTimestamp).toBe(true);
+
+ // Fill the expression: the attribute becomes active and the conflicting
+ // attributes are stripped from the SQL payload (MySQL rejects them on
+ // generated columns).
+ const input = root.querySelector<HTMLInputElement>("[data-mysql-generated-expression]");
+ expect(input).not.toBeNull();
+ input!.value = "`price` * `quantity`";
+ input!.dispatchEvent(new Event("input"));
+
+ calls = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await waitForPreviewCalls(calls);
+ columns = await lastPreviewColumns();
+ expect(columns[0]!.extra.generated).toEqual({ expression: "`price` * `quantity`", storage: "STORED" });
+ expect(columns[0]!.extra.autoIncrement).toBeUndefined();
+ expect(columns[0]!.extra.onUpdateCurrentTimestamp).toBeUndefined();
+ // The expression editor entry is visible while the checkbox stays checked.
+ expect(root.querySelector("[data-mysql-generated-expression-trigger]")).not.toBeNull();
+ });
+
+ it("unchecking virtual restores the original defaults instead of silently dropping them", async () => {
+ const root = await mountEditor(
+ draftWithColumns([
+ {
+ name: "total",
+ extra: { autoIncrement: true },
+ originalExtra: "auto_increment",
+ originalDefault: "0",
+ },
+ ]),
+ );
+
+ const checkbox = virtualCheckbox(root);
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event("change"));
+
+ // While the attribute is not active yet, the original default and
+ // AUTO_INCREMENT stay in the payload — checking must not erase them.
+ const calls = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await waitForPreviewCalls(calls);
+ const columns = await lastPreviewColumns();
+ expect(columns[0]!.extra.generated).toEqual({ expression: "", storage: "STORED" });
+ expect(columns[0]!.extra.autoIncrement).toBe(true);
+ expect(columns[0]!.defaultValue).toBe("0");
+
+ checkbox.checked = false;
+ checkbox.dispatchEvent(new Event("change"));
+
+ // Unchecking restores the exact pre-check state: no pending change at
+ // all, so the preview stops requesting SQL and saving emits no MODIFY
+ // that would silently drop the default.
+ const callsAfterUncheck = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 600));
+ expect(mocks.buildTableStructureChangeSql.mock.calls.length).toBe(callsAfterUncheck);
+ const pending = root.querySelector("[data-mysql-generated-expression-trigger]");
+ expect(pending).toBeNull();
+ });
+
+ it("re-checking virtual after an accidental uncheck restores the original expression", async () => {
+ const root = await mountEditor(
+ draftWithColumns([
+ {
+ name: "total",
+ extra: { generated: { expression: "`price` * `quantity`", storage: "STORED" } },
+ originalExtra: "GENERATED ALWAYS AS (`price` * `quantity`) STORED",
+ },
+ ]),
+ );
+
+ const checkbox = virtualCheckbox(root);
+ checkbox.checked = false;
+ checkbox.dispatchEvent(new Event("change"));
+ await nextTick();
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event("change"));
+ await nextTick();
+
+ // The original expression and storage survive the uncheck/re-check cycle.
+ const expressionInput = root.querySelector<HTMLInputElement>("[data-mysql-generated-expression]");
+ expect(expressionInput?.value).toBe("`price` * `quantity`");
+
+ // The restored draft equals the original definition, so no change is
+ // pending and the preview stops requesting SQL — no spurious MODIFY.
+ const calls = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 600));
+ expect(mocks.buildTableStructureChangeSql.mock.calls.length).toBe(calls);
+ });
+
+ it("unchecking virtual on a plain column leaves no generated payload", async () => {
+ const root = await mountEditor(draftWithColumns([{ name: "total" }]));
+
+ const checkbox = virtualCheckbox(root);
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event("change"));
+
+ const calls = mocks.buildTableStructureChangeSql.mock.calls.length;
+ await waitForPreviewCalls(calls);
+ const columns = await lastPreviewColumns();
+ expect(columns[0]!.extra.generated).toEqual({ expression: "", storage: "STORED" });
+
+ checkbox.checked = false;
+ checkbox.dispatchEvent(new Event("change"));
+
+ // Back to the untouched draft: no change is pending, so the preview
+ // stops requesting SQL entirely.
+ await new Promise((resolve) => setTimeout(resolve, 600));
+ expect(mocks.buildTableStructureChangeSql.mock.calls.length).toBe(calls + 1);
+ });
+});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 13d2d09ad6..32b59f3da8 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -4682,6 +4682,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Növbəti avtomatik artım dəyəri",
editMysqlAutoIncrementValue: "Növbəti avtomatik artım dəyərini redaktə et (cari: {value})",
onUpdateCurrentTimestamp: "Vaxtı avtomatik yenilə",
+ virtual: "Virtual",
+ generatedExpression: "Generasiya ifadəsi",
+ generatedExpressionPlaceholder: "məs. `price` * `quantity`",
+ generatedExpressionEmptyHint: "İfadə daxil edilənə qədər sütun adi sütun kimi saxlanılır.",
+ generatedStorage: "Saxlama",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "İfade deterministik olmalıdır: dəyişən, alt sorğu və ya qeyri-deterministik funksiya istifadə edilə bilməz.",
identity: "İdentifikator",
identitySeed: "Başlanğıc dəyər",
identityIncrement: "Artım",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 08bdd1a4a2..ee9728409f 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -5513,6 +5513,14 @@ export default {
mysqlAutoIncrementNextValue: "Next auto-increment value",
editMysqlAutoIncrementValue: "Edit next auto-increment value (current: {value})",
onUpdateCurrentTimestamp: "Auto Update Time",
+ virtual: "Virtual",
+ generatedExpression: "Generation expression",
+ generatedExpressionPlaceholder: "e.g. `price` * `quantity`",
+ generatedExpressionEmptyHint: "The column is saved as a plain column until an expression is provided.",
+ generatedStorage: "Storage",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "The expression must be deterministic: no variables, subqueries, or non-deterministic functions.",
identity: "Identity",
identitySeed: "Seed",
identityIncrement: "Increment",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 6fd9274971..69f6545832 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -4915,6 +4915,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Siguiente valor de autoincremento",
editMysqlAutoIncrementValue: "Editar el siguiente valor de autoincremento (actual: {value})",
onUpdateCurrentTimestamp: "Actualización Auto",
+ virtual: "Virtual",
+ generatedExpression: "Expresión de generación",
+ generatedExpressionPlaceholder: "p. ej. `price` * `quantity`",
+ generatedExpressionEmptyHint: "La columna se guardará como una columna normal hasta que se proporcione una expresión.",
+ generatedStorage: "Almacenamiento",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "La expresión debe ser determinista: sin variables, subconsultas ni funciones no deterministas.",
identity: "Identidad",
identitySeed: "Semilla",
identityIncrement: "Incremento",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 6bda976b5b..5879dbc463 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -5322,6 +5322,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Nilai auto-increment berikutnya",
editMysqlAutoIncrementValue: "Edit nilai auto-increment berikutnya (saat ini: {value})",
onUpdateCurrentTimestamp: "Perbarui Waktu Otomatis",
+ virtual: "Virtual",
+ generatedExpression: "Ekspresi generasi",
+ generatedExpressionPlaceholder: "mis. `price` * `quantity`",
+ generatedExpressionEmptyHint: "Kolom akan disimpan sebagai kolom biasa sampai ekspresi diisi.",
+ generatedStorage: "Penyimpanan",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "Ekspresi harus deterministik: tanpa variabel, subquery, atau fungsi non-deterministik.",
identity: "Identity",
identitySeed: "Seed",
identityIncrement: "Increment",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 22d5c6da2e..1043b5ca3f 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -4729,6 +4729,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Valore di auto incremento successivo",
editMysqlAutoIncrementValue: "Modifica il valore di auto incremento successivo (attuale: {value})",
onUpdateCurrentTimestamp: "Aggiorna Ora Automaticamente",
+ virtual: "Virtuale",
+ generatedExpression: "Espressione di generazione",
+ generatedExpressionPlaceholder: "es. `price` * `quantity`",
+ generatedExpressionEmptyHint: "La colonna viene salvata come colonna normale finché non viene fornita un'espressione.",
+ generatedStorage: "Archiviazione",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "L'espressione deve essere deterministica: niente variabili, sottoquery o funzioni non deterministiche.",
identity: "Identità",
identitySeed: "Seed",
identityIncrement: "Incremento",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index e421bf3d57..c874078082 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -4793,6 +4793,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "次の自動採番値",
editMysqlAutoIncrementValue: "次の自動採番値を編集(現在:{value})",
onUpdateCurrentTimestamp: "自動更新時刻",
+ virtual: "仮想",
+ generatedExpression: "生成式",
+ generatedExpressionPlaceholder: "例: `price` * `quantity`",
+ generatedExpressionEmptyHint: "式が未入力の場合、この列は通常の列として保存されます。",
+ generatedStorage: "ストレージ",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "式は決定的である必要があります: 変数、サブクエリ、非決定的関数は使用できません。",
identity: "ID列",
identitySeed: "開始値",
identityIncrement: "増分",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index b5d64b36b1..66ff1d88b6 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -4773,6 +4773,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "다음 자동 증가 값",
editMysqlAutoIncrementValue: "다음 자동 증가 값 편집(현재: {value})",
onUpdateCurrentTimestamp: "수정 시간 자동 갱신",
+ virtual: "가상",
+ generatedExpression: "생성 표현식",
+ generatedExpressionPlaceholder: "예: `price` * `quantity`",
+ generatedExpressionEmptyHint: "표현식을 입력하지 않으면 일반 컬럼으로 저장됩니다.",
+ generatedStorage: "스토리지",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "표현식은 결정적이어야 합니다: 변수, 서브쿼리, 비결정적 함수는 사용할 수 없습니다.",
identity: "ID",
identitySeed: "시드",
identityIncrement: "증가분",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 779d7b7434..e7d2112acc 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -4731,6 +4731,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Próximo valor de incremento automático",
editMysqlAutoIncrementValue: "Editar o próximo valor de incremento automático (atual: {value})",
onUpdateCurrentTimestamp: "Atualizar hora automaticamente",
+ virtual: "Virtual",
+ generatedExpression: "Expressão de geração",
+ generatedExpressionPlaceholder: "ex.: `price` * `quantity`",
+ generatedExpressionEmptyHint: "A coluna será salva como uma coluna comum até que uma expressão seja informada.",
+ generatedStorage: "Armazenamento",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "A expressão deve ser determinística: sem variáveis, subconsultas ou funções não determinísticas.",
identity: "Identidade",
identitySeed: "Valor inicial",
identityIncrement: "Incremento",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 6ea0610b94..34c282a216 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -5307,6 +5307,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Следующее значение автоувеличения",
editMysqlAutoIncrementValue: "Изменить следующее значение автоувеличения (текущее: {value})",
onUpdateCurrentTimestamp: "Автообновление времени",
+ virtual: "Виртуальная",
+ generatedExpression: "Выражение генерации",
+ generatedExpressionPlaceholder: "напр. `price` * `quantity`",
+ generatedExpressionEmptyHint: "Пока выражение не задано, колонка будет сохранена как обычная.",
+ generatedStorage: "Хранение",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "Выражение должно быть детерминированным: без переменных, подзапросов и недетерминированных функций.",
identity: "Идентичность",
identitySeed: "Начальное значение",
identityIncrement: "Шаг",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 555513bcc4..2621ec831a 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -4584,6 +4584,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "Sonraki otomatik artan değer",
editMysqlAutoIncrementValue: "Sonraki otomatik artan değeri düzenle (geçerli: {value})",
onUpdateCurrentTimestamp: "Otomatik Güncelleme Zamanı",
+ virtual: "Sanal",
+ generatedExpression: "Üretim ifadesi",
+ generatedExpressionPlaceholder: "örn. `price` * `quantity`",
+ generatedExpressionEmptyHint: "Bir ifade girilene kadar sütun normal sütun olarak kaydedilir.",
+ generatedStorage: "Depolama",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "İfade deterministik olmalıdır: değişken, alt sorgu veya deterministik olmayan işlev kullanılamaz.",
identity: "Kimlik (Identity)",
identitySeed: "Başlangıç",
identityIncrement: "Artış",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index e3e8e5f86e..bc9572fd3d 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -5505,6 +5505,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "下一个自增值",
editMysqlAutoIncrementValue: "编辑下一个自增值(当前:{value})",
onUpdateCurrentTimestamp: "自动更新时间",
+ virtual: "虚拟",
+ generatedExpression: "生成表达式",
+ generatedExpressionPlaceholder: "如:`price` * `quantity`",
+ generatedExpressionEmptyHint: "未填写表达式时,该列将按普通列保存。",
+ generatedStorage: "存储类型",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "表达式必须是确定性的:不能使用变量、子查询或非确定性函数。",
identity: "标识列",
identitySeed: "起始值",
identityIncrement: "增量",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index f7903e086a..a55d461ce0 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -4477,6 +4477,14 @@ export default withEnglishFallback({
mysqlAutoIncrementNextValue: "下一個自動遞增值",
editMysqlAutoIncrementValue: "編輯下一個自動遞增值(目前:{value})",
onUpdateCurrentTimestamp: "自動更新時間",
+ virtual: "虛擬",
+ generatedExpression: "生成表達式",
+ generatedExpressionPlaceholder: "如:`price` * `quantity`",
+ generatedExpressionEmptyHint: "未填寫表達式時,該列將按普通列儲存。",
+ generatedStorage: "儲存類型",
+ generatedStorageVirtual: "VIRTUAL",
+ generatedStorageStored: "STORED",
+ generatedExpressionHint: "表達式必須是確定性的:不能使用變數、子查詢或非確定性函數。",
identity: "識別欄位",
identitySeed: "起始值",
identityIncrement: "增量",
diff --git a/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.spec.ts b/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.spec.ts
index 3bfb8e6b41..df9014332c 100644
--- a/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.spec.ts
@@ -30,6 +30,7 @@ import {
matchesCopySourceColumnSearch,
mysqlEnumDataType,
parseExtraToColumnExtra,
+ parseMysqlGeneratedColumnExtra,
rehydrateColumnDraftsFromMetadata,
resolveInsertColumnIndex,
restoreCharacterLengthUnitsAfterSave,
@@ -533,6 +534,33 @@ describe("tableStructureEditorState", () => {
expect(parseExtraToColumnExtra("identity(1,1)", "postgres")).toEqual({});
});
+ it("parses mysql generated-column metadata into the editable extra", () => {
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS (`price` * `quantity`) STORED", "mysql")).toEqual({
+ generated: { expression: "`price` * `quantity`", storage: "STORED" },
+ });
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS (lower(`name`)) VIRTUAL", "mysql")).toEqual({
+ generated: { expression: "lower(`name`)", storage: "VIRTUAL" },
+ });
+ // MariaDB PERSISTENT normalizes to STORED, matching the backend introspection.
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS (`a` + 1) PERSISTENT", "mysql")).toEqual({
+ generated: { expression: "`a` + 1", storage: "STORED" },
+ });
+ // Storage omitted: MySQL defaults to VIRTUAL.
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS (json_extract(`doc`, '$.x'))", "mysql")).toEqual({
+ generated: { expression: "json_extract(`doc`, '$.x')", storage: "VIRTUAL" },
+ });
+ // Plain columns and identity columns stay untouched.
+ expect(parseMysqlGeneratedColumnExtra("auto_increment")).toBeUndefined();
+ expect(parseMysqlGeneratedColumnExtra("GENERATED ALWAYS AS IDENTITY")).toBeUndefined();
+ expect(parseMysqlGeneratedColumnExtra("")).toBeUndefined();
+ // Identity extras for postgres must not leak into the mysql branch.
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS IDENTITY", "postgres")).toEqual({
+ identity: { generation: "ALWAYS" },
+ });
+ // Other dialects never parse mysql generated columns.
+ expect(parseExtraToColumnExtra("GENERATED ALWAYS AS (1) STORED", "sqlite")).toEqual({});
+ });
+
it("keeps mysql unsigned attributes in the editable base type", () => {
expect(splitDataType("int(11) unsigned")).toEqual({ baseType: "int unsigned", params: "11" });
expect(splitDataType("bigint(20) unsigned zerofill")).toEqual({
diff --git a/apps/desktop/src/lib/table/tableStructureEditorSql.ts b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
index 51429ea33f..bd7c09c441 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorSql.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
@@ -6,10 +6,17 @@ export interface ColumnIdentity {
increment?: number;
}
+export interface ColumnGenerated {
+ /** Generation expression without the surrounding parentheses; empty means "not generated". */
+ expression: string;
+ storage?: "VIRTUAL" | "STORED";
+}
+
export interface ColumnExtra {
autoIncrement?: boolean;
onUpdateCurrentTimestamp?: boolean;
identity?: ColumnIdentity;
+ generated?: ColumnGenerated;
manticoreIndexed?: boolean;
manticoreStored?: boolean;
manticoreAttribute?: boolean;
diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.ts
index 707dbb14f4..4b672cd54b 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts
@@ -815,6 +815,32 @@ export function supportsTableStructureExtendedProperties(databaseType?: Database
);
}
+/**
+ * Extracts a MySQL generated-column definition from a raw `extra` string such
+ * as `GENERATED ALWAYS AS (`price` * `quantity`) STORED`. Returns undefined
+ * for plain columns and identity columns (`GENERATED ... AS IDENTITY`, no
+ * parenthesized expression). MariaDB `PERSISTENT` is normalized to `STORED`,
+ * matching the MySQL driver's introspection output.
+ */
+export function parseMysqlGeneratedColumnExtra(extra: string): { expression: string; storage: "VIRTUAL" | "STORED" } | undefined {
+ const marker = "generated always as";
+ const lower = extra.toLowerCase();
+ const index = lower.indexOf(marker);
+ if (index < 0) return undefined;
+ const rest = extra.slice(index + marker.length).trimStart();
+ if (!rest.startsWith("(")) return undefined;
+ const close = rest.lastIndexOf(")");
+ if (close <= 0) return undefined;
+ const expression = rest.slice(1, close).trim();
+ if (!expression) return undefined;
+ const tail = rest
+ .slice(close + 1)
+ .trim()
+ .toUpperCase();
+ const storage = tail.startsWith("STORED") || tail.startsWith("PERSISTENT") ? "STORED" : "VIRTUAL";
+ return { expression, storage };
+}
+
export function parseExtraToColumnExtra(extra: string | null | undefined, databaseType?: DatabaseType): ColumnExtra {
const result: ColumnExtra = {};
if (!extra) return result;
@@ -828,6 +854,10 @@ export function parseExtraToColumnExtra(extra: string | null | undefined, databa
if (databaseType === "mysql" && lower.includes("on update current_timestamp")) {
result.onUpdateCurrentTimestamp = true;
}
+ if (databaseType === "mysql") {
+ const generated = parseMysqlGeneratedColumnExtra(extra);
+ if (generated) result.generated = generated;
+ }
} else if (databaseType === "postgres" || databaseType === "gaussdb" || databaseType === "kwdb" || databaseType === "questdb" || databaseType === "highgo" || databaseType === "uxdb" || databaseType === "vastbase" || databaseType === "kingbase") {
const identityMatch = lower.match(/generated\s+(by\s+default|always)\s+as\s+identity/i);
if (identityMatch) {
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs
index e42f0a3124..063944c854 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs
@@ -1,7 +1,8 @@
use super::column_format::{
clickhouse_column_type, column_data_type, column_definition, has_dameng_identity,
- is_dameng_identity_compatible_type, is_mysql_character_data_type, original_is_mysql_generated_column,
- original_mysql_generated_clause,
+ is_dameng_identity_compatible_type, is_mysql_character_data_type, normalize_generation_expression,
+ normalize_mysql_generated_storage, original_is_mysql_generated_column, original_mysql_generated_clause,
+ original_mysql_generated_values, strip_outer_parentheses,
};
use super::columns::{build_add_column_sql, build_drop_column_sql};
use super::comments::build_sqlserver_column_comment_sql_for_profile;
@@ -97,7 +98,7 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Ta
return TableStructureSqlResult { statements, warnings };
};
- if !has_existing_column_attribute_change(&options.column) && !has_column_extra_change(&options.column) {
+ if !has_existing_column_attribute_change(&options.column) && !has_column_extra_change(dialect, &options.column) {
warnings.push("No changes detected for this column.".to_string());
return TableStructureSqlResult { statements, warnings };
}
@@ -145,7 +146,7 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Ta
));
return TableStructureSqlResult { statements, warnings };
}
- if !has_rename && !has_attribute_change && !has_column_extra_change(&options.column) {
+ if !has_rename && !has_attribute_change && !has_column_extra_change(dialect, &options.column) {
return TableStructureSqlResult { statements, warnings };
}
@@ -192,6 +193,7 @@ fn is_column_extra_empty(extra: &ColumnExtra) -> bool {
!extra.auto_increment.unwrap_or(false)
&& !extra.on_update_current_timestamp.unwrap_or(false)
&& extra.identity.is_none()
+ && !extra.generated.as_ref().is_some_and(|generated| !generated.expression.trim().is_empty())
&& !extra.manticore_indexed.unwrap_or(false)
&& !extra.manticore_stored.unwrap_or(false)
&& !extra.manticore_attribute.unwrap_or(false)
@@ -350,9 +352,10 @@ pub(super) fn validate_dameng_existing_identity_change(
}
}
-pub(super) fn has_column_extra_change(column: &EditableStructureColumn) -> bool {
+pub(super) fn has_column_extra_change(dialect: StructureDialect, column: &EditableStructureColumn) -> bool {
let Some(original) = &column.original else { return false };
let current_extra = column.extra.as_ref();
+ let is_mysql = dialect == StructureDialect::Mysql;
match (current_extra, original.extra.as_deref()) {
// Neither has extra → no change
(None, None | Some("")) => false,
@@ -364,6 +367,12 @@ pub(super) fn has_column_extra_change(column: &EditableStructureColumn) -> bool
original_has_auto_increment(orig)
|| orig_lower.contains("on update")
|| original_has_identity(orig)
+ // MySQL-only: PostgreSQL-family introspection reports generated
+ // columns in the same `generated always as (...) stored` shape,
+ // which the structure editor of those dialects never parses
+ // into `extra.generated` — treating it as a change would flag
+ // untouched PG generated columns on every save.
+ || (is_mysql && original_mysql_generated_values(orig).is_some())
|| indexed
|| stored
|| attribute
@@ -396,11 +405,37 @@ pub(super) fn has_column_extra_change(column: &EditableStructureColumn) -> bool
curr_has_ai != orig_has_ai
|| curr_has_on_update != orig_has_on_update
|| identity_changed
+ || (is_mysql && mysql_generated_changed(curr, orig))
|| curr_manticore != orig_manticore
}
}
}
+/// Edit detection for MySQL generated columns. `None` inherits the original
+/// definition (no change); an empty edited expression removes the attribute
+/// (changed only when the original was generated); otherwise the expression is
+/// compared whitespace- and case-insensitively and the storage normalized, so
+/// an untouched column does not register a spurious `MODIFY`.
+fn mysql_generated_changed(curr: &ColumnExtra, orig: &str) -> bool {
+ match &curr.generated {
+ Some(generated) => {
+ // Same single-layer unwrapping the renderer applies, so wrapping
+ // parentheses typed by hand do not produce a no-op MODIFY.
+ let edited = strip_outer_parentheses(generated.expression.trim());
+ match original_mysql_generated_values(orig) {
+ Some((original_expression, original_storage)) if !edited.is_empty() => {
+ let edited_normalized = normalize_generation_expression(edited);
+ let edited_storage = normalize_mysql_generated_storage(generated.storage.as_deref());
+ edited_normalized != original_expression || edited_storage != original_storage
+ }
+ Some(_) => true,
+ None => !edited.is_empty(),
+ }
+ }
+ None => false,
+ }
+}
+
pub(super) fn build_mysql_existing_column_sql(
table: &str,
column: &EditableStructureColumn,
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs b/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs
index 984ecf74d0..13dac7c2e2 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs
@@ -53,8 +53,7 @@ pub(super) fn column_definition(dialect: StructureDialect, column: &EditableStru
parts.push(format!("COLLATE {}", quote_ident(dialect, &column.collation)));
}
}
- let mysql_generated_clause =
- (dialect == StructureDialect::Mysql).then(|| original_mysql_generated_clause(column)).flatten();
+ let mysql_generated_clause = (dialect == StructureDialect::Mysql).then(|| mysql_generated_clause(column)).flatten();
if let Some(generated_clause) = mysql_generated_clause.as_ref() {
parts.push(generated_clause.clone());
}
@@ -98,6 +97,132 @@ pub(super) fn column_definition(dialect: StructureDialect, column: &EditableStru
parts.join(" ")
}
+/// Renders the MySQL `GENERATED ALWAYS AS (...) ...` clause for a column.
+///
+/// The edited `extra.generated` value wins when present: an empty expression
+/// removes the generated-column attribute (rendering no clause), otherwise the
+/// clause is rebuilt from the edited expression and storage. When the field is
+/// absent (legacy payloads) the clause is inherited from the original
+/// definition so untouched generated columns round-trip verbatim.
+pub(super) fn mysql_generated_clause(column: &EditableStructureColumn) -> Option<String> {
+ match column.extra.as_ref().and_then(|extra| extra.generated.as_ref()) {
+ Some(generated) => render_mysql_generated_clause(&generated.expression, generated.storage.as_deref()),
+ None => original_mysql_generated_clause(column),
+ }
+}
+
+fn render_mysql_generated_clause(expression: &str, storage: Option<&str>) -> Option<String> {
+ let expression = strip_outer_parentheses(expression.trim());
+ if expression.is_empty() {
+ return None;
+ }
+ let storage = normalize_mysql_generated_storage(storage);
+ Some(format!("GENERATED ALWAYS AS ({expression}) {storage}"))
+}
+
+/// Removes one pair of enclosing parentheses when they wrap the whole
+/// expression, so a user-entered `(a + b)` does not render as `AS ((a + b))`.
+/// Edit detection strips the same single layer before comparing, so typing
+/// wrapping parentheses by hand does not register a spurious `MODIFY`.
+pub(super) fn strip_outer_parentheses(expression: &str) -> &str {
+ let trimmed = expression.trim();
+ if !trimmed.starts_with('(') || !trimmed.ends_with(')') {
+ return trimmed;
+ }
+ let mut depth = 0i32;
+ for (index, ch) in trimmed.char_indices() {
+ match ch {
+ '(' => depth += 1,
+ ')' => {
+ depth -= 1;
+ if depth == 0 && index != trimmed.len() - 1 {
+ // The first pair closes before the end: not a full wrap.
+ return trimmed;
+ }
+ }
+ _ => {}
+ }
+ }
+ trimmed[1..trimmed.len() - 1].trim()
+}
+
+/// MariaDB reports `PERSISTENT`, which is an alias of `STORED`; introspection
+/// already normalizes it, and unknown values fall back to the MySQL default.
+pub(super) fn normalize_mysql_generated_storage(storage: Option<&str>) -> &'static str {
+ match storage.map(str::trim).unwrap_or("").to_ascii_lowercase().as_str() {
+ "stored" | "persistent" => "STORED",
+ _ => "VIRTUAL",
+ }
+}
+
+/// Normalizes a generation expression for edit detection: whitespace is
+/// collapsed and keywords/identifiers compare case-insensitively, while the
+/// contents of quoted string literals ('...' and "...") keep their exact
+/// spelling — a user editing only the case of a literal ('Yes' → 'yes') must
+/// still register as a change, because MySQL stores and evaluates that
+/// difference verbatim.
+pub(super) fn normalize_generation_expression(expression: &str) -> String {
+ let mut normalized = String::with_capacity(expression.len());
+ let mut chars = expression.chars().peekable();
+ let mut pending_space = false;
+ while let Some(ch) = chars.next() {
+ // MySQL treats double quotes as string quotes unless ANSI_QUOTES is
+ // enabled; either way the quoted text must keep its exact spelling.
+ if ch == '\'' || ch == '"' {
+ if pending_space && !normalized.is_empty() {
+ normalized.push(' ');
+ }
+ pending_space = false;
+ normalized.push(ch);
+ // Copy the quoted text verbatim; a doubled quote is an escape inside it.
+ while let Some(quoted_ch) = chars.next() {
+ normalized.push(quoted_ch);
+ if quoted_ch == ch {
+ if chars.peek() == Some(&ch) {
+ normalized.push(chars.next().expect("peeked escaped quote"));
+ } else {
+ break;
+ }
+ }
+ }
+ } else if ch.is_whitespace() {
+ pending_space = !normalized.is_empty();
+ } else {
+ if pending_space && !normalized.is_empty() {
+ normalized.push(' ');
+ }
+ pending_space = false;
+ normalized.extend(ch.to_lowercase());
+ }
+ }
+ normalized
+}
+
+/// Parses a MySQL generated-column clause out of a raw `extra` string into
+/// (whitespace-normalized lowercase expression, normalized storage), so edit
+/// detection can compare drafts against the introspected definition.
+pub(super) fn original_mysql_generated_values(extra: &str) -> Option<(String, &'static str)> {
+ let lower = extra.to_ascii_lowercase();
+ let marker = "generated always as";
+ let start = lower.find(marker)? + marker.len();
+ let rest = extra[start..].trim_start();
+ let expression = rest.strip_prefix('(')?;
+ let close = expression.rfind(')')?;
+ let expression = strip_outer_parentheses(expression[..close].trim());
+ if expression.is_empty() {
+ return None;
+ }
+ let normalized = normalize_generation_expression(expression);
+ // `close` indexes the stripped string where `rest` keeps the leading
+ // parenthesis, so the text after `)` starts one byte later in `rest`.
+ let tail = rest[close + 2..].trim().to_ascii_lowercase();
+ let storage = match tail.split_whitespace().next() {
+ Some(token) => normalize_mysql_generated_storage(Some(token)),
+ None => "VIRTUAL",
+ };
+ Some((normalized, storage))
+}
+
pub(super) fn original_mysql_generated_clause(column: &EditableStructureColumn) -> Option<String> {
let extra = column.original.as_ref()?.extra.as_deref()?.trim();
let normalized = extra.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_lowercase();
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs b/crates/dbx-sql-schema/src/table_structure_sql/columns.rs
index 00d1860827..7aefdcbf85 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/columns.rs
@@ -12,7 +12,8 @@ use super::column_alter::{
};
use super::column_format::{
column_definition, has_dameng_identity, is_dameng_identity_compatible_type, is_mysql_character_data_type,
- original_is_mysql_generated_column, original_mysql_generated_clause,
+ normalize_mysql_generated_storage, original_is_mysql_generated_column, original_mysql_generated_clause,
+ original_mysql_generated_values,
};
use super::comments::build_sqlserver_column_comment_sql_for_profile;
use super::dialect::{capabilities_for, database_label, is_oracle_like, StructureDialect};
@@ -31,6 +32,77 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
let database_label = database_label(options.database_type);
let active_columns: Vec<_> = options.columns.iter().filter(|column| !column.marked_for_drop).collect();
+ if dialect == StructureDialect::Mysql {
+ // A generated column whose expression was left empty renders as a plain
+ // column; surface the silent drop of the user's intent instead.
+ for column in &active_columns {
+ // An empty expression on a formerly generated column is the explicit
+ // "remove the attribute" edit, not a mistake — warn only when the
+ // column was plain before, where a missing expression drops the
+ // user's intent of adding a generated column.
+ let removes_generated_attribute = column
+ .original
+ .as_ref()
+ .and_then(|original| original.extra.as_deref())
+ .and_then(original_mysql_generated_values)
+ .is_some();
+ if !removes_generated_attribute
+ && column
+ .extra
+ .as_ref()
+ .and_then(|extra| extra.generated.as_ref())
+ .is_some_and(|generated| generated.expression.trim().is_empty())
+ {
+ warnings.push(format!(
+ "Column \"{}\" is marked as generated but its expression is empty; the generated-column clause was omitted from the DDL.",
+ column.name
+ ));
+ }
+ // MySQL rejects several generated-column conversions via MODIFY:
+ // a plain column may only become a STORED generated column, only a
+ // STORED generated column may become plain again, and VIRTUAL and
+ // STORED cannot be switched (those need DROP + ADD). Surface the
+ // rejected shape as a warning instead of emitting DDL the server
+ // will refuse.
+ let original_generated = column
+ .original
+ .as_ref()
+ .and_then(|original| original.extra.as_deref())
+ .and_then(original_mysql_generated_values);
+ if let Some(generated) = column.extra.as_ref().and_then(|extra| extra.generated.as_ref()) {
+ if !generated.expression.trim().is_empty() {
+ match original_generated {
+ // The conversion restriction applies to MODIFY of an
+ // existing plain column; ADD accepts VIRTUAL freely.
+ None if column.original.is_some() => {
+ if normalize_mysql_generated_storage(generated.storage.as_deref()) == "VIRTUAL" {
+ warnings.push(format!(
+ "Column \"{}\": MySQL only allows converting a plain column into a STORED generated column; a VIRTUAL generated column requires dropping and re-adding the column.",
+ column.name
+ ));
+ }
+ }
+ None => {}
+ Some((_, original_storage)) => {
+ if normalize_mysql_generated_storage(generated.storage.as_deref()) != original_storage {
+ warnings.push(format!(
+ "Column \"{}\": MySQL cannot switch a generated column between VIRTUAL and STORED in place; the column must be dropped and re-added.",
+ column.name
+ ));
+ }
+ }
+ }
+ }
+ } else if let Some((_, original_storage)) = original_generated {
+ if original_storage == "VIRTUAL" {
+ warnings.push(format!(
+ "Column \"{}\": MySQL only allows converting a STORED generated column back to a plain column; removing a VIRTUAL generated attribute requires dropping and re-adding the column.",
+ column.name
+ ));
+ }
+ }
+ }
+ }
if dialect == StructureDialect::Dameng {
let identity_columns: Vec<_> = active_columns.iter().filter(|column| has_dameng_identity(column)).collect();
if identity_columns.len() > 1
@@ -191,7 +263,7 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
.is_some_and(|change| mysql_orphans_auto_increment_column(options, column, change));
if !has_existing_column_attribute_change(column)
- && !has_column_extra_change(column)
+ && !has_column_extra_change(dialect, column)
&& !has_position_change
&& !clears_orphaned_auto_increment
{
@@ -207,7 +279,7 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
|| (is_mysql_character_data_type(&column.data_type)
&& (column.character_set.trim() != original.character_set.as_deref().unwrap_or("")
|| column.collation.trim() != original.collation.as_deref().unwrap_or("")))
- || has_column_extra_change(column);
+ || has_column_extra_change(dialect, column);
if has_comment_change && !capabilities.comment {
warnings.push(format!(
"Column comments are not supported for {database_label} from this editor; the comment change for \"{}\" was ignored.",
@@ -232,6 +304,9 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
if dialect == StructureDialect::Mysql
&& original_is_mysql_generated_column(column)
&& original_mysql_generated_clause(column).is_none()
+ // An edited generated value no longer depends on the introspected
+ // expression, so the column may be altered (or un-generated) safely.
+ && column.extra.as_ref().and_then(|extra| extra.generated.as_ref()).is_none()
{
warnings.push(format!(
"Column \"{}\" is generated, but its generation expression could not be loaded; no ALTER statement was generated to avoid removing the generated-column definition.",
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
index 3aae6188d3..3928f965c5 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
@@ -1,7 +1,7 @@
use super::column_format::{
column_data_type, column_extra_clause, has_dameng_identity, is_dameng_identity_compatible_type,
- is_mysql_character_data_type, is_mysql_timestamp_type, mysql_on_update_current_timestamp_clause,
- strip_inherited_mysql_column_charsets,
+ is_mysql_character_data_type, is_mysql_timestamp_type, mysql_generated_clause,
+ mysql_on_update_current_timestamp_clause, strip_inherited_mysql_column_charsets,
};
use super::comments::{build_sqlserver_column_comment_sql_for_profile, build_sqlserver_table_comment_sql_for_profile};
use super::dialect::{capabilities_for, database_label, StructureDialect};
@@ -131,14 +131,20 @@ pub(super) fn build_create_table_sql_with_partition_clause(
parts.push(format!("COLLATE {}", quote_ident(dialect, &column.collation)));
}
}
+ let generated_clause = (dialect == StructureDialect::Mysql).then(|| mysql_generated_clause(column)).flatten();
+ if let Some(clause) = generated_clause.as_ref() {
+ parts.push(clause.clone());
+ }
// Oracle's column grammar is `col type [DEFAULT expr] [inline constraint ...]`, so the
// DEFAULT clause has to precede NOT NULL. Emitting `NOT NULL DEFAULT ...` leaves the
// parser looking for the closing parenthesis of the column list and fails with
// ORA-00907 (t8y2/dbx#9477). Scoped to Oracle: every other engine keeps the historical
// NOT NULL-then-DEFAULT order.
let default_value = normalize_default(Some(&column.default_value));
- let default_clause = (!default_value.is_empty() && dialect != StructureDialect::ManticoreSearch)
- .then(|| format!("DEFAULT {}", format_default_for_sql(dialect, &column.data_type, &default_value)));
+ // Generated columns cannot carry a DEFAULT in MySQL.
+ let default_clause =
+ (!default_value.is_empty() && dialect != StructureDialect::ManticoreSearch && generated_clause.is_none())
+ .then(|| format!("DEFAULT {}", format_default_for_sql(dialect, &column.data_type, &default_value)));
if dialect == StructureDialect::Oracle {
if let Some(clause) = default_clause.clone() {
parts.push(clause);
@@ -161,17 +167,21 @@ pub(super) fn build_create_table_sql_with_partition_clause(
{
parts.push("NULL".to_string());
}
- if let Some(extra_clause) = column_extra_clause(dialect, column) {
- parts.push(extra_clause);
+ if generated_clause.is_none() {
+ if let Some(extra_clause) = column_extra_clause(dialect, column) {
+ parts.push(extra_clause);
+ }
}
if dialect != StructureDialect::Oracle {
if let Some(clause) = default_clause {
parts.push(clause);
}
}
- if let Some(on_update) = column.extra.as_ref().and_then(|e| e.on_update_current_timestamp).filter(|v| *v) {
- if on_update && dialect == StructureDialect::Mysql {
- parts.push(mysql_on_update_current_timestamp_clause(&column.data_type));
+ if generated_clause.is_none() {
+ if let Some(on_update) = column.extra.as_ref().and_then(|e| e.on_update_current_timestamp).filter(|v| *v) {
+ if on_update && dialect == StructureDialect::Mysql {
+ parts.push(mysql_on_update_current_timestamp_clause(&column.data_type));
+ }
}
}
if dialect == StructureDialect::Mysql && capabilities.comment && !clean(&column.comment).is_empty() {
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
index 8c3776fe26..032137257c 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
@@ -7961,6 +7961,605 @@ fn mysql_generated_column_change_is_blocked_without_expression_metadata() {
assert!(result.warnings[0].contains("generation expression could not be loaded"));
}
+#[test]
+fn postgres_generated_column_extra_shape_is_not_an_mysql_extra_change() {
+ // PostgreSQL-family introspection reports generated columns in the same
+ // `generated always as (...) stored` shape, but the structure editor of
+ // those dialects never parses it into `extra.generated`. The MySQL-only
+ // generated-column diff must not flag these columns as changed.
+ let mut total = column("total");
+ total.data_type = "numeric(12,2)".to_string();
+ total.extra = Some(ColumnExtra::default());
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "numeric(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("generated always as (price * quantity) stored".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result = build_table_structure_change_sql(structure_change_options(
+ DatabaseType::Postgres,
+ None,
+ "products",
+ vec![total],
+ ));
+
+ assert_eq!(result.statements, Vec::<String>::new());
+ assert_eq!(result.warnings, Vec::<String>::new());
+}
+
+#[test]
+fn mysql_add_column_with_generated_expression_stored() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * `quantity`".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` ADD COLUMN `total` decimal(14,2) GENERATED ALWAYS AS (`price` * `quantity`) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_add_column_with_generated_expression_defaults_to_virtual() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated { expression: "`price` * `quantity`".to_string(), storage: None }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` ADD COLUMN `total` decimal(14,2) GENERATED ALWAYS AS (`price` * `quantity`) VIRTUAL;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_modify_generated_column_expression_change() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * `quantity` * 2".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` MODIFY COLUMN `total` decimal(12,2) GENERATED ALWAYS AS (`price` * `quantity` * 2) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_modify_generated_column_storage_change() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * `quantity`".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * `quantity`) VIRTUAL".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ // MySQL rejects switching a generated column between VIRTUAL and STORED
+ // in place; the DDL is still emitted but a warning explains the rejection.
+ assert_eq!(result.warnings.len(), 1);
+ assert!(result.warnings[0].contains("cannot switch a generated column between VIRTUAL and STORED"));
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` MODIFY COLUMN `total` decimal(12,2) GENERATED ALWAYS AS (`price` * `quantity`) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_generated_column_removed_becomes_plain_column() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ // An explicit empty expression removes the generated-column attribute.
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated { expression: String::new(), storage: None }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(result.statements, vec!["ALTER TABLE `products` MODIFY COLUMN `total` decimal(12,2);"]);
+}
+
+#[test]
+fn mysql_plain_column_becomes_generated() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * `quantity`".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: None,
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` MODIFY COLUMN `total` decimal(12,2) GENERATED ALWAYS AS (`price` * `quantity`) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_unchanged_generated_column_with_explicit_values_is_not_modified() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ // Explicitly echoing the introspected definition must not register a change.
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * `quantity`".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(result.statements, Vec::<String>::new());
+}
+
+#[test]
+fn mysql_generated_column_comparison_ignores_case_and_whitespace() {
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: " `PRICE` * `quantity` ".to_string(),
+ storage: Some("stored".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.statements, Vec::<String>::new());
+}
+
+#[test]
+fn mysql_generated_expression_with_wrapping_parentheses_is_normalized() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "(`price` * `quantity`)".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` ADD COLUMN `total` decimal(14,2) GENERATED ALWAYS AS (`price` * `quantity`) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_generated_literal_case_change_is_detected() {
+ // MySQL stores string literals verbatim, so editing only the case of a
+ // literal is a real change and must not be swallowed by the
+ // case-insensitive comparison of keywords and identifiers.
+ let mut flag = column("flag");
+ flag.data_type = "varchar(3)".to_string();
+ flag.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "if(`status`, 'yes', 'No')".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ flag.original = Some(ColumnInfo {
+ name: "flag".to_string(),
+ data_type: "varchar(3)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (IF(`status`, 'Yes', 'No')) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ flag.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![flag]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `products` MODIFY COLUMN `flag` varchar(3) GENERATED ALWAYS AS (if(`status`, 'yes', 'No')) STORED;"
+ ]
+ );
+}
+
+#[test]
+fn mysql_generated_keyword_case_change_is_ignored_but_literal_is_not() {
+ // Keyword/identifier case differences must stay invisible (drivers may
+ // rewrite them), while the literal keeps its exact spelling.
+ let mut flag = column("flag");
+ flag.data_type = "varchar(3)".to_string();
+ flag.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: " IF(`status`, 'Yes', 'No')".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ flag.original = Some(ColumnInfo {
+ name: "flag".to_string(),
+ data_type: "varchar(3)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (if(`status`, 'Yes', 'No')) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ flag.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![flag]));
+
+ // Only whitespace and keyword case differ → no statement.
+ assert_eq!(result.statements, Vec::<String>::new());
+}
+
+#[test]
+fn mysql_generated_wrapping_parentheses_typed_by_hand_do_not_modify() {
+ // The renderer strips one layer of wrapping parentheses; edit detection
+ // compares with the same contract, so re-typing them is not a change and
+ // must not emit a no-op MODIFY (a STORED rebuild is not free).
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "(price * qty)".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(12,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (price * qty) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.statements, Vec::<String>::new());
+ assert_eq!(result.warnings, Vec::<String>::new());
+}
+
+#[test]
+fn mysql_generated_double_quoted_literal_case_change_is_detected() {
+ // MySQL treats double quotes as string quotes unless ANSI_QUOTES is on;
+ // either way the quoted text must keep its exact spelling in comparisons.
+ let mut flag = column("flag");
+ flag.data_type = "varchar(3)".to_string();
+ flag.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "IF(`status`, \"yes\", 'No')".to_string(),
+ storage: Some("STORED".to_string()),
+ }),
+ ..Default::default()
+ });
+ flag.original = Some(ColumnInfo {
+ name: "flag".to_string(),
+ data_type: "varchar(3)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (IF(`status`, \"Yes\", 'No')) STORED".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ flag.original_position = Some(0);
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![flag]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(result.statements.len(), 1);
+ assert!(result.statements[0].contains("\"yes\""));
+}
+
+#[test]
+fn mysql_plain_to_virtual_generated_warns() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(14,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: None,
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * 2".to_string(),
+ storage: Some("VIRTUAL".to_string()),
+ }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings.len(), 1);
+ assert!(result.warnings[0].contains("only allows converting a plain column into a STORED generated column"));
+}
+
+#[test]
+fn mysql_generated_storage_switch_warns() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(14,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * 2) VIRTUAL".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated { expression: "`price` * 2".to_string(), storage: Some("STORED".to_string()) }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings.len(), 1);
+ assert!(result.warnings[0].contains("cannot switch a generated column between VIRTUAL and STORED"));
+}
+
+#[test]
+fn mysql_virtual_to_plain_warns() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(14,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: Some("GENERATED ALWAYS AS (`price` * 2) VIRTUAL".to_string()),
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+ total.extra = Some(ColumnExtra { ..Default::default() });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert!(result.warnings.iter().any(|warning| warning.contains("removing a VIRTUAL generated attribute")));
+}
+
+#[test]
+fn mysql_plain_to_stored_generated_and_back_do_not_warn() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.original = Some(ColumnInfo {
+ name: "total".to_string(),
+ data_type: "decimal(14,2)".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: None,
+ comment: None,
+ ..Default::default()
+ });
+ total.original_position = Some(0);
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated { expression: "`price` * 2".to_string(), storage: Some("STORED".to_string()) }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert!(result.statements.iter().any(|statement| statement.contains("GENERATED ALWAYS AS (`price` * 2) STORED")));
+}
+
+#[test]
+fn mysql_empty_generated_expression_warns_and_omits_clause() {
+ let mut total = column("total");
+ total.data_type = "decimal(14,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated { expression: " ".to_string(), storage: Some("STORED".to_string()) }),
+ ..Default::default()
+ });
+
+ let result =
+ build_table_structure_change_sql(structure_change_options(DatabaseType::Mysql, None, "products", vec![total]));
+
+ assert_eq!(result.warnings.len(), 1);
+ assert!(result.warnings[0].contains("expression is empty"));
+ assert_eq!(result.statements, vec!["ALTER TABLE `products` ADD COLUMN `total` decimal(14,2);"]);
+}
+
+#[test]
+fn mysql_create_table_with_generated_column() {
+ let mut price = column("price");
+ price.data_type = "decimal(10,2)".to_string();
+ let mut total = column("total");
+ total.data_type = "decimal(12,2)".to_string();
+ total.extra = Some(ColumnExtra {
+ generated: Some(ColumnGenerated {
+ expression: "`price` * 2".to_string(),
+ storage: Some("VIRTUAL".to_string()),
+ }),
+ ..Default::default()
+ });
+
+ let result = build_create_table_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::Mysql),
+ driver_profile: None,
+ schema: None,
+ table_name: "products".to_string(),
+ columns: vec![price, total],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ mysql_engine: None,
+ transwarp_create: None,
+ partitioned: false,
+ is_gaussdb_m_mode: false,
+ table_collation: None,
+ foreign_table: false,
+ });
+
+ assert_eq!(result.warnings, Vec::<String>::new());
+ assert_eq!(
+ result.statements,
+ vec![
+ "CREATE TABLE `products` (\n `price` decimal(10,2),\n `total` decimal(12,2) GENERATED ALWAYS AS (`price` * 2) VIRTUAL\n);"
+ ]
+ );
+}
+
// ---- Oscar (神通) ----
// 神通 v7 是 Oracle 兼容方言,且实测支持 ALTER TABLE DROP/ADD PRIMARY KEY(与 Dameng 一致,
// 不同于 Oracle)。DDL 生成走 StructureDialect::Oscar,与 Dameng 共享 Oracle-like 分支。
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/types.rs b/crates/dbx-sql-schema/src/table_structure_sql/types.rs
index 1e66c5f992..68cf4c91c5 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/types.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/types.rs
@@ -39,6 +39,13 @@ pub struct ColumnExtra {
pub on_update_current_timestamp: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<ColumnIdentity>,
+ /// MySQL generated column. Tri-state: `None` inherits the original
+ /// definition (legacy payloads), `Some` with an empty `expression`
+ /// removes the generated-column attribute, otherwise the clause is
+ /// rendered from these values. MariaDB `PERSISTENT` is reported by
+ /// introspection as `STORED`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub generated: Option<ColumnGenerated>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manticore_indexed: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -49,6 +56,18 @@ pub struct ColumnExtra {
pub manticore_secondary_index: Option<bool>,
}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ColumnGenerated {
+ /// Generation expression without the surrounding parentheses. An empty
+ /// (or whitespace-only) value means the column is not generated.
+ #[serde(default)]
+ pub expression: String,
+ /// `VIRTUAL` or `STORED`; `None` renders as the MySQL default `VIRTUAL`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub storage: Option<String>,
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColumnIdentity {