25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(mysql): set auto-increment start value on table creation
二丫讲梵96eca282b621
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.tsindex 35b7086ee0..7ad4d30b74 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({executeQuery: vi.fn(),listDataTypes: vi.fn(),buildTableStructureChangeSql: vi.fn(),+ buildCreateTableSql: vi.fn(),buildMysqlAutoIncrementSql: vi.fn(),getMysqlTableAutoIncrement: vi.fn(),executeBatch: vi.fn(),@@ -230,6 +231,7 @@ vi.mock("@/lib/backend/api", () => ({executeQuery: mocks.executeQuery,listDataTypes: mocks.listDataTypes,buildTableStructureChangeSql: mocks.buildTableStructureChangeSql,+ buildCreateTableSql: mocks.buildCreateTableSql,buildMysqlAutoIncrementSql: mocks.buildMysqlAutoIncrementSql,getMysqlTableAutoIncrement: mocks.getMysqlTableAutoIncrement,executeBatch: mocks.executeBatch,@@ -280,7 +282,7 @@ function draft(autoIncrement = false, counter?: { value?: string; originalValue?};}-async function mountEditor(autoIncrement = false, counter?: { value?: string; originalValue?: string }, draftOverride?: ReturnType<typeof draft>) {+async function mountEditor(autoIncrement = false, counter?: { value?: string; originalValue?: string }, draftOverride?: ReturnType<typeof draft>, createMode = false) {mocks.ensureConnected.mockResolvedValue(undefined);mocks.listDataTypes.mockResolvedValue([]);mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: [], warnings: [] });@@ -291,7 +293,7 @@ async function mountEditor(autoIncrement = false, counter?: { value?: string; orconnectionId: mocks.connection.id,database: "test",schema: "test",- tableName: "users",+ tableName: createMode ? undefined : "users",draft: draftOverride ?? draft(autoIncrement, counter),});mountedApps.push(app);@@ -321,6 +323,7 @@ beforeEach(() => {mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE users (id varchar(255))", cacheStatus: "remote" });mocks.invalidateObjectDdl.mockResolvedValue(undefined);mocks.loadObjectMetadataFacet.mockResolvedValue({ value: [], cacheStatus: "remote" });+ mocks.buildCreateTableSql.mockResolvedValue({ statements: ["CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT);"], warnings: [] });mocks.getMysqlTableAutoIncrement.mockResolvedValue("10");mocks.buildMysqlAutoIncrementSql.mockImplementation(async ({ value }: { value: string }) => `ALTER TABLE \`test\`.\`users\` AUTO_INCREMENT = ${value};`);mocks.executeBatch.mockResolvedValue({ affected_rows: 0 });@@ -499,3 +502,65 @@ describe("TableStructureEditor MySQL AUTO_INCREMENT counter", () => {expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();});});++describe("TableStructureEditor MySQL creation counter", () => {+ function createDraft(value?: string) {+ const result = draft(true, { value });+ result.newTableName = "users";+ result.columns[0].dataType = "INT";+ result.columns[0].isPrimaryKey = true;+ result.columns[0].isNullable = false;+ return result;+ }++ it("starts blank and submits edits, clears and toggles without reading server metadata", async () => {+ const root = await mountEditor(true, undefined, createDraft(), true);+ const input = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")!;+ expect(input).not.toBeNull();+ expect(input.disabled).toBe(false);+ expect(input.value).toBe("");+ expect(input.placeholder).toBe("1");+ expect(root.textContent).toContain("structureEditor.mysqlAutoIncrementStartHint");+ expect(root.textContent).not.toContain("contextMenu.mysqlAutoIncrementNonemptyHint");+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));+ input.value = "66";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: "66" })));+ const label = Array.from(root.querySelectorAll("label")).find((label) => label.textContent?.includes("structureEditor.autoIncrement"))!;+ const checkbox = label.querySelector<HTMLInputElement>('input[type="checkbox"]')!;+ checkbox.checked = false;+ checkbox.dispatchEvent(new Event("change", { bubbles: true }));+ await vi.waitFor(() => expect(root.querySelector("[data-mysql-auto-increment-editor-trigger]")).toBeNull());+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));+ checkbox.checked = true;+ checkbox.dispatchEvent(new Event("change", { bubbles: true }));+ await nextTick();+ const restored = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")!;+ expect(restored.value).toBe("66");+ restored.value = "";+ restored.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));+ expect(mocks.getMysqlTableAutoIncrement).not.toHaveBeenCalled();+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();+ });++ it("restores a creation draft without losing integer precision", async () => {+ const value = "18446744073709551615";+ const root = await mountEditor(true, undefined, createDraft(value), true);+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: value })));+ expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe(value);+ expect(mocks.getMysqlTableAutoIncrement).not.toHaveBeenCalled();+ });+});++it("renders translated creation warnings and prevents execution", async () => {+ const warning = 'AUTO_INCREMENT column "id" requires a supporting index (first key column for InnoDB).';+ mocks.buildCreateTableSql.mockResolvedValue({ statements: [], warnings: [warning] });+ const value = draft(true);+ value.newTableName = "users";+ const root = await mountEditor(true, undefined, value, true);+ await vi.waitFor(() => expect(root.textContent).toContain("structureEditor.mysqlAutoIncrementRequiresIndex"));+ expect(root.textContent).not.toContain(warning);+ await expect(mountedEditor?.applyChanges()).resolves.toBe(false);+ expect(mocks.executeBatch).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex ef3e843c90..1cc8e70383 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -91,7 +91,7 @@ import {type TablePartitionOperationKind,type TablePartitionSqlOptions,} from "@/lib/table/tableStructureEditorSql";-import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, refreshMysqlAutoIncrementCounterDraft } from "@/lib/table/mysqlAutoIncrementCounter";+import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, refreshMysqlAutoIncrementCounterDraft, translateMysqlAutoIncrementWarning } from "@/lib/table/mysqlAutoIncrementCounter";import { mysqlTableCollationSql, parseMysqlTableCollation } from "@/lib/table/mysqlTableCollation";import { MYSQL_STORAGE_ENGINES_SQL, mysqlTableEngineSql, mysqlTableEngineSqlOption, parseMysqlTableEngineMetadata, refreshMysqlTableEngineDraft, supportsMysqlTableEngine } from "@/lib/table/mysqlTableEngine";import { INCEPTOR_PHYSICAL_OPTIONS, buildInceptorCreateOptions, emptyTablePhysicalOptions, hasTablePhysicalOptions, pruneTablePhysicalOptions, restoreTablePhysicalOptions } from "@/lib/table/tablePhysicalOptions";@@ -1897,7 +1897,7 @@ const tableOwnerRolesLoading = ref(false);const tableOwnerRolesLoadError = ref("");const supportsTableOwner = computed(() => !isCreateMode.value && databaseType.value === "postgres");const canEditMysqlAutoIncrement = computed(() => canEditMysqlAutoIncrementCounter(connection.value, isCreateMode.value, columns.value));-const canBuildMysqlAutoIncrement = computed(() => canEditMysqlAutoIncrement.value && !mysqlAutoIncrementLoading.value && !mysqlAutoIncrementLoadError.value && originalMysqlAutoIncrementValue.value !== undefined);+const canBuildMysqlAutoIncrement = computed(() => !isCreateMode.value && canEditMysqlAutoIncrement.value && !mysqlAutoIncrementLoading.value && !mysqlAutoIncrementLoadError.value && originalMysqlAutoIncrementValue.value !== undefined);const supportsMysqlEngine = computed(() => supportsMysqlTableEngine(connection.value));const hasPersistedMysqlAutoIncrementColumn = computed(() => columns.value.some((column) => !column.markedForDrop && (column.original?.extra ?? "").toLowerCase().includes("auto_increment")));function isMysqlAutoIncrementCounterColumn(column: EditableStructureColumn): boolean {@@ -1905,7 +1905,7 @@ function isMysqlAutoIncrementCounterColumn(column: EditableStructureColumn): boo}function setMysqlAutoIncrement(column: EditableStructureColumn, checked: boolean) {column.extra.autoIncrement = checked;- if (checked && originalMysqlAutoIncrementValue.value === undefined && !mysqlAutoIncrementLoading.value) {+ if (!isCreateMode.value && checked && originalMysqlAutoIncrementValue.value === undefined && !mysqlAutoIncrementLoading.value) {void loadMysqlAutoIncrementCounter(true);}}@@ -2628,6 +2628,7 @@ function structureChangeOptions(): BuildTableStructureChangeSqlOptions {triggers: triggers.value,tableComment: tableComment.value,originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,+ mysqlAutoIncrementValue: isCreateMode.value && canEditMysqlAutoIncrement.value ? mysqlAutoIncrementValue.value || undefined : undefined,mysqlEngine: mysqlTableEngineSqlOption({ value: mysqlTableEngine.value, originalValue: originalMysqlTableEngine.value }, isCreateMode.value, supportsMysqlEngine.value && !mysqlTableEngineLoading.value && !mysqlTableEngineLoadError.value),transwarpCreate: isCreateMode.value && databaseType.value === "transwarp" ? buildInceptorCreateOptions(physicalOptions.value, columns.value) : undefined,tableCollation: mysqlTableDefaultCollation.value || undefined,@@ -2960,6 +2961,8 @@ async function loadVisibleTableComment(force = false, preserveDraft = false) {}async function loadMysqlAutoIncrementCounter(preserveDraft = false) {+ // Creation drafts own their counter; there is no server table to refresh.+ if (isCreateMode.value) return;const requestId = ++mysqlAutoIncrementLoadRequestId;if (!canEditMysqlAutoIncrement.value || !props.connectionId || !props.database || !props.tableName) {mysqlAutoIncrementValue.value = undefined;@@ -6171,8 +6174,8 @@ watch(variant="ghost"size="icon":class="[structureIconButtonClass, 'mr-1 shrink-0']"- :title="t('structureEditor.editMysqlAutoIncrementValue', { value: mysqlAutoIncrementValue || '—' })"- :aria-label="t('structureEditor.editMysqlAutoIncrementValue', { value: mysqlAutoIncrementValue || '—' })"+ :title="t(isCreateMode ? 'structureEditor.editMysqlAutoIncrementStartValue' : 'structureEditor.editMysqlAutoIncrementValue', { value: mysqlAutoIncrementValue || '—' })"+ :aria-label="t(isCreateMode ? 'structureEditor.editMysqlAutoIncrementStartValue' : 'structureEditor.editMysqlAutoIncrementValue', { value: mysqlAutoIncrementValue || '—' })"data-mysql-auto-increment-editor-trigger><Loader2 v-if="mysqlAutoIncrementLoading" :class="[structureIconClass, 'animate-spin text-muted-foreground']" />@@ -6181,22 +6184,22 @@ watch(</Button></PopoverTrigger><PopoverContent align="start" class="w-80 space-y-2 p-3">- <label class="block text-xs font-medium text-foreground">{{ t("structureEditor.mysqlAutoIncrementNextValue") }}</label>+ <label class="block text-xs font-medium text-foreground">{{ t(isCreateMode ? "structureEditor.mysqlAutoIncrementStartValue" : "structureEditor.mysqlAutoIncrementNextValue") }}</label><Input:model-value="mysqlAutoIncrementValue"inputmode="numeric"pattern="[0-9]*"autocomplete="off"data-mysql-auto-increment-counter- :aria-label="t('structureEditor.mysqlAutoIncrementNextValue')"- :placeholder="mysqlAutoIncrementLoading ? t('common.loading') : '—'"+ :aria-label="t(isCreateMode ? 'structureEditor.mysqlAutoIncrementStartValue' : 'structureEditor.mysqlAutoIncrementNextValue')"+ :placeholder="isCreateMode ? '1' : mysqlAutoIncrementLoading ? t('common.loading') : '—'":title="mysqlAutoIncrementLoadError || undefined"class="w-full font-mono"- :disabled="mysqlAutoIncrementLoading || !!mysqlAutoIncrementLoadError || originalMysqlAutoIncrementValue === undefined || saving"+ :disabled="(!isCreateMode && (mysqlAutoIncrementLoading || !!mysqlAutoIncrementLoadError || originalMysqlAutoIncrementValue === undefined)) || saving"@input.capture="onMysqlAutoIncrementInput"/><p v-if="mysqlAutoIncrementLoadError" class="text-xs text-destructive">{{ mysqlAutoIncrementLoadError }}</p>- <p class="text-xs leading-5 text-muted-foreground">{{ t("contextMenu.mysqlAutoIncrementNonemptyHint") }}</p>+ <p class="text-xs leading-5 text-muted-foreground">{{ t(isCreateMode ? "structureEditor.mysqlAutoIncrementStartHint" : "contextMenu.mysqlAutoIncrementNonemptyHint") }}</p></PopoverContent></Popover><label :class="[structurePropertyLabelClass, 'shrink-0']" :title="t('structureEditor.onUpdateCurrentTimestamp')">@@ -6854,7 +6857,7 @@ watch(<div v-if="warnings.length" class="mb-2 space-y-1"><div v-for="warning in warnings" :key="warning" class="flex gap-1.5 rounded-md border border-yellow-300/40 bg-yellow-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-yellow-700 dark:text-yellow-300"><AlertTriangle :class="[structureIconClass, 'mt-0.5 shrink-0']" />- <span>{{ warning }}</span>+ <span>{{ translateMysqlAutoIncrementWarning(t, warning) }}</span></div></div><pre v-if="pendingStatements.length" class="select-text whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2.5 font-mono text-[calc(var(--structure-font-size)+1px)] leading-5" v-html="highlightedSql" />diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex f8b866d79c..3ae2ce7a03 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -4730,6 +4730,12 @@ export default withEnglishFallback({resetDdl: "Verilənlər bazasının DDL-ni bərpa et",extendedProperties: "Genişləndirilmiş",autoIncrement: "Avtomatik artım",+ mysqlAutoIncrementSingleColumn: "MySQL hər cədvəldə yalnız bir avtomatik artan sütuna icazə verir.",+ mysqlAutoIncrementRequiresIndex: 'Avtomatik artan "{column}" sütunu üçün indeks tələb olunur; InnoDB-də bu sütun indeksin ilk sütunu olmalıdır.',+ mysqlAutoIncrementRequiresNativeColumn: "Birbaşa MySQL bağlantısında avtomatik artan sütun tələb olunur.",+ mysqlAutoIncrementStartValue: "Avtomatik artımın başlanğıc dəyəri",+ editMysqlAutoIncrementStartValue: "Avtomatik artımın başlanğıc dəyərini dəyiş (cari: {value})",+ mysqlAutoIncrementStartHint: "Verilənlər bazasının standart dəyərini (adətən 1) istifadə etmək üçün boş saxlayın.",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ə",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 260b4bf1f7..5285507242 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -5585,6 +5585,12 @@ export default {resetDdl: "Restore database DDL",extendedProperties: "Extended",autoIncrement: "Auto Increment",+ mysqlAutoIncrementSingleColumn: "MySQL allows only one auto-increment column per table.",+ mysqlAutoIncrementRequiresIndex: 'Auto-increment column "{column}" requires a supporting index; in InnoDB it must be the first key column.',+ mysqlAutoIncrementRequiresNativeColumn: "An auto-increment column on a native MySQL connection is required.",+ mysqlAutoIncrementStartValue: "Auto-increment starting value",+ editMysqlAutoIncrementStartValue: "Edit auto-increment starting value (current: {value})",+ mysqlAutoIncrementStartHint: "Leave blank to use the database default (usually 1).",mysqlAutoIncrementNextValue: "Next auto-increment value",editMysqlAutoIncrementValue: "Edit next auto-increment value (current: {value})",onUpdateCurrentTimestamp: "Auto Update Time",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 877fe30fe8..3f21e329e8 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -4988,6 +4988,12 @@ export default withEnglishFallback({resetDdl: "Restaurar el DDL de la base de datos",extendedProperties: "Extendido",autoIncrement: "Auto Incremento",+ mysqlAutoIncrementSingleColumn: "MySQL solo permite una columna de autoincremento por tabla.",+ mysqlAutoIncrementRequiresIndex: 'La columna de autoincremento "{column}" requiere un índice; en InnoDB debe ser la primera columna del índice.',+ mysqlAutoIncrementRequiresNativeColumn: "Se requiere una columna de autoincremento en una conexión MySQL nativa.",+ mysqlAutoIncrementStartValue: "Valor inicial de autoincremento",+ editMysqlAutoIncrementStartValue: "Editar el valor inicial de autoincremento (actual: {value})",+ mysqlAutoIncrementStartHint: "Deje en blanco para usar el valor predeterminado de la base de datos (normalmente 1).",mysqlAutoIncrementNextValue: "Siguiente valor de autoincremento",editMysqlAutoIncrementValue: "Editar el siguiente valor de autoincremento (actual: {value})",onUpdateCurrentTimestamp: "Actualización Auto",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex e321ba73c4..e7f295b443 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -5370,6 +5370,12 @@ export default withEnglishFallback({resetDdl: "Pulihkan DDL database",extendedProperties: "Lanjutan",autoIncrement: "Auto Increment",+ mysqlAutoIncrementSingleColumn: "MySQL hanya mengizinkan satu kolom penambahan otomatis per tabel.",+ mysqlAutoIncrementRequiresIndex: 'Kolom penambahan otomatis "{column}" memerlukan indeks; pada InnoDB kolom ini harus menjadi kolom pertama dalam indeks.',+ mysqlAutoIncrementRequiresNativeColumn: "Diperlukan kolom penambahan otomatis pada koneksi MySQL native.",+ mysqlAutoIncrementStartValue: "Nilai awal penambahan otomatis",+ editMysqlAutoIncrementStartValue: "Edit nilai awal penambahan otomatis (saat ini: {value})",+ mysqlAutoIncrementStartHint: "Biarkan kosong untuk menggunakan nilai bawaan basis data (biasanya 1).",mysqlAutoIncrementNextValue: "Nilai auto-increment berikutnya",editMysqlAutoIncrementValue: "Edit nilai auto-increment berikutnya (saat ini: {value})",onUpdateCurrentTimestamp: "Perbarui Waktu Otomatis",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 5f0704de78..e86789ba5c 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -4802,6 +4802,12 @@ export default withEnglishFallback({resetDdl: "Ripristina il DDL del database",extendedProperties: "Esteso",autoIncrement: "Auto Incremento",+ mysqlAutoIncrementSingleColumn: "MySQL consente una sola colonna di incremento automatico per tabella.",+ mysqlAutoIncrementRequiresIndex: 'La colonna di incremento automatico "{column}" richiede un indice; in InnoDB deve essere la prima colonna dell’indice.',+ mysqlAutoIncrementRequiresNativeColumn: "È richiesta una colonna di incremento automatico su una connessione MySQL nativa.",+ mysqlAutoIncrementStartValue: "Valore iniziale di incremento automatico",+ editMysqlAutoIncrementStartValue: "Modifica il valore iniziale di incremento automatico (attuale: {value})",+ mysqlAutoIncrementStartHint: "Lascia vuoto per usare il valore predefinito del database (di solito 1).",mysqlAutoIncrementNextValue: "Valore di auto incremento successivo",editMysqlAutoIncrementValue: "Modifica il valore di auto incremento successivo (attuale: {value})",onUpdateCurrentTimestamp: "Aggiorna Ora Automaticamente",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex bbd09f6342..efd778b294 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -4865,6 +4865,12 @@ export default withEnglishFallback({resetDdl: "データベースの DDL に戻す",extendedProperties: "拡張",autoIncrement: "自動採番",+ mysqlAutoIncrementSingleColumn: "MySQL ではテーブルごとに自動増分列を 1 つだけ設定できます。",+ mysqlAutoIncrementRequiresIndex: "自動増分列「{column}」にはインデックスが必要です。InnoDB ではインデックスの先頭列である必要があります。",+ mysqlAutoIncrementRequiresNativeColumn: "ネイティブ MySQL 接続と自動増分列が必要です。",+ mysqlAutoIncrementStartValue: "自動増分の開始値",+ editMysqlAutoIncrementStartValue: "自動増分の開始値を編集(現在: {value})",+ mysqlAutoIncrementStartHint: "空欄の場合はデータベースの既定値(通常は 1)を使用します。",mysqlAutoIncrementNextValue: "次の自動採番値",editMysqlAutoIncrementValue: "次の自動採番値を編集(現在:{value})",onUpdateCurrentTimestamp: "自動更新時刻",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 31d93401b1..2dffc339c2 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -4845,6 +4845,12 @@ export default withEnglishFallback({resetDdl: "데이터베이스 DDL 복원",extendedProperties: "확장",autoIncrement: "자동 증가",+ mysqlAutoIncrementSingleColumn: "MySQL 테이블에는 자동 증가 열을 하나만 지정할 수 있습니다.",+ mysqlAutoIncrementRequiresIndex: '자동 증가 열 "{column}"에는 인덱스가 필요합니다. InnoDB에서는 인덱스의 첫 번째 열이어야 합니다.',+ mysqlAutoIncrementRequiresNativeColumn: "네이티브 MySQL 연결과 자동 증가 열이 필요합니다.",+ mysqlAutoIncrementStartValue: "자동 증가 시작값",+ editMysqlAutoIncrementStartValue: "자동 증가 시작값 편집 (현재: {value})",+ mysqlAutoIncrementStartHint: "비워 두면 데이터베이스 기본값(일반적으로 1)을 사용합니다.",mysqlAutoIncrementNextValue: "다음 자동 증가 값",editMysqlAutoIncrementValue: "다음 자동 증가 값 편집(현재: {value})",onUpdateCurrentTimestamp: "수정 시간 자동 갱신",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex a521d7ce0d..fd41595e2c 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -4803,6 +4803,12 @@ export default withEnglishFallback({resetDdl: "Restaurar o DDL do banco de dados",extendedProperties: "Estendidas",autoIncrement: "Auto incremento",+ mysqlAutoIncrementSingleColumn: "O MySQL permite apenas uma coluna de incremento automático por tabela.",+ mysqlAutoIncrementRequiresIndex: 'A coluna de incremento automático "{column}" requer um índice; no InnoDB, ela deve ser a primeira coluna do índice.',+ mysqlAutoIncrementRequiresNativeColumn: "É necessária uma coluna de incremento automático em uma conexão MySQL nativa.",+ mysqlAutoIncrementStartValue: "Valor inicial de incremento automático",+ editMysqlAutoIncrementStartValue: "Editar valor inicial de incremento automático (atual: {value})",+ mysqlAutoIncrementStartHint: "Deixe em branco para usar o padrão do banco de dados (geralmente 1).",mysqlAutoIncrementNextValue: "Próximo valor de incremento automático",editMysqlAutoIncrementValue: "Editar o próximo valor de incremento automático (atual: {value})",onUpdateCurrentTimestamp: "Atualizar hora automaticamente",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 07e240d8ea..0101e4c0fc 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -5379,6 +5379,12 @@ export default withEnglishFallback({resetDdl: "Восстановить DDL базы данных",extendedProperties: "Расширенные",autoIncrement: "Автоувеличение",+ mysqlAutoIncrementSingleColumn: "MySQL допускает только один столбец автоинкремента в таблице.",+ mysqlAutoIncrementRequiresIndex: "Столбцу автоинкремента «{column}» нужен индекс; в InnoDB он должен быть первым столбцом индекса.",+ mysqlAutoIncrementRequiresNativeColumn: "Требуется столбец автоинкремента при нативном подключении MySQL.",+ mysqlAutoIncrementStartValue: "Начальное значение автоинкремента",+ editMysqlAutoIncrementStartValue: "Изменить начальное значение автоинкремента (текущее: {value})",+ mysqlAutoIncrementStartHint: "Оставьте пустым для значения по умолчанию базы данных (обычно 1).",mysqlAutoIncrementNextValue: "Следующее значение автоувеличения",editMysqlAutoIncrementValue: "Изменить следующее значение автоувеличения (текущее: {value})",onUpdateCurrentTimestamp: "Автообновление времени",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 7d31b8012c..850835f8c8 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -4632,6 +4632,12 @@ export default withEnglishFallback({resetDdl: "Veritabanı DDL'ini geri yükle",extendedProperties: "Genişletilmiş",autoIncrement: "Otomatik Artan",+ mysqlAutoIncrementSingleColumn: "MySQL her tabloda yalnızca bir otomatik artan sütuna izin verir.",+ mysqlAutoIncrementRequiresIndex: 'Otomatik artan "{column}" sütunu bir dizin gerektirir; InnoDB için dizinin ilk sütunu olmalıdır.',+ mysqlAutoIncrementRequiresNativeColumn: "Yerel MySQL bağlantısında bir otomatik artan sütun gereklidir.",+ mysqlAutoIncrementStartValue: "Otomatik artış başlangıç değeri",+ editMysqlAutoIncrementStartValue: "Otomatik artış başlangıç değerini düzenle (geçerli: {value})",+ mysqlAutoIncrementStartHint: "Veritabanı varsayılanını (genellikle 1) kullanmak için boş bırakın.",mysqlAutoIncrementNextValue: "Sonraki otomatik artan değer",editMysqlAutoIncrementValue: "Sonraki otomatik artan değeri düzenle (geçerli: {value})",onUpdateCurrentTimestamp: "Otomatik Güncelleme Zamanı",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 91e247434e..96e53969f7 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -5577,6 +5577,12 @@ export default withEnglishFallback({resetDdl: "恢复数据库 DDL",extendedProperties: "扩展属性",autoIncrement: "自增",+ mysqlAutoIncrementSingleColumn: "MySQL 每张表只能有一个自增字段。",+ mysqlAutoIncrementRequiresIndex: "自增字段“{column}”必须有有效索引;使用 InnoDB 时,该字段必须位于索引首列。",+ mysqlAutoIncrementRequiresNativeColumn: "需要使用原生 MySQL 连接,并为表配置自增字段。",+ mysqlAutoIncrementStartValue: "自增起始值",+ editMysqlAutoIncrementStartValue: "编辑自增起始值(当前:{value})",+ mysqlAutoIncrementStartHint: "留空使用数据库默认值(通常为 1)。",mysqlAutoIncrementNextValue: "下一个自增值",editMysqlAutoIncrementValue: "编辑下一个自增值(当前:{value})",onUpdateCurrentTimestamp: "自动更新时间",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex c673433820..7bb9864be8 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -4549,6 +4549,12 @@ export default withEnglishFallback({resetDdl: "還原資料庫 DDL",extendedProperties: "擴充屬性",autoIncrement: "自動遞增",+ mysqlAutoIncrementSingleColumn: "MySQL 每張表只能有一個自動遞增欄位。",+ mysqlAutoIncrementRequiresIndex: "自動遞增欄位「{column}」必須有有效索引;使用 InnoDB 時,該欄位必須位於索引首欄。",+ mysqlAutoIncrementRequiresNativeColumn: "需要使用原生 MySQL 連線,並為資料表設定自動遞增欄位。",+ mysqlAutoIncrementStartValue: "自動遞增起始值",+ editMysqlAutoIncrementStartValue: "編輯自動遞增起始值(目前:{value})",+ mysqlAutoIncrementStartHint: "留空使用資料庫預設值(通常為 1)。",mysqlAutoIncrementNextValue: "下一個自動遞增值",editMysqlAutoIncrementValue: "編輯下一個自動遞增值(目前:{value})",onUpdateCurrentTimestamp: "自動更新時間",diff --git a/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts b/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.tsindex 8404d29bac..d9ffbb499d 100644--- a/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts@@ -1,5 +1,8 @@+import { readFileSync } from "node:fs";+import zhCN from "@/i18n/locales/zh-CN";+import { createI18n } from "vue-i18n";import { describe, expect, it, vi } from "vitest";-import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, mysqlAutoIncrementCounterDraft, refreshMysqlAutoIncrementCounterDraft } from "@/lib/table/mysqlAutoIncrementCounter";+import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, mysqlAutoIncrementCounterDraft, refreshMysqlAutoIncrementCounterDraft, translateMysqlAutoIncrementWarning } from "@/lib/table/mysqlAutoIncrementCounter";function existingColumn(autoIncrement: boolean) {return {@@ -37,11 +40,11 @@ describe("MySQL table AUTO_INCREMENT counter", () => {});});- it("is editable only for existing native-MySQL tables with an active auto-increment column draft", () => {+ it("is editable for native-MySQL tables with an active auto-increment column draft", () => {const nativeMysql = { db_type: "mysql", driver_profile: "mysql" } as any;expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [existingColumn(true)])).toBe(true);expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [{ ...existingColumn(true), original: undefined }])).toBe(true);- expect(canEditMysqlAutoIncrementCounter(nativeMysql, true, [existingColumn(true)])).toBe(false);+ expect(canEditMysqlAutoIncrementCounter(nativeMysql, true, [existingColumn(true)])).toBe(true);expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [existingColumn(false)])).toBe(false);expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [{ ...existingColumn(true), markedForDrop: true }])).toBe(false);@@ -93,3 +96,28 @@ describe("MySQL table AUTO_INCREMENT counter", () => {await expect(buildMysqlAutoIncrementCounterStatement({ ...common, originalValue: "1", value: "1e3" })).rejects.toThrow("AUTO_INCREMENT must be a decimal integer");});});++describe("MySQL auto-increment warning translations", () => {+ const i18n = createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": zhCN } });+ const t = (key: string, params: Record<string, unknown> = {}) => i18n.global.t(key, params);+ it("translates backend warnings and preserves unusual column names as text", () => {+ expect(translateMysqlAutoIncrementWarning(t, "MySQL allows only one AUTO_INCREMENT column per table.")).toBe("MySQL 每张表只能有一个自增字段。");+ expect(translateMysqlAutoIncrementWarning(t, "AUTO_INCREMENT requires a native MySQL auto-increment column.")).toBe("需要使用原生 MySQL 连接,并为表配置自增字段。");+ const column = 'id"<tag>\n{value}';+ expect(translateMysqlAutoIncrementWarning(t, `AUTO_INCREMENT column "${column}" requires a supporting index (first key column for InnoDB).`)).toBe(`自增字段“${column}”必须有有效索引;使用 InnoDB 时,该字段必须位于索引首列。`);+ expect(translateMysqlAutoIncrementWarning(t, "Unknown backend warning")).toBe("Unknown backend warning");+ });+ it("defines all warning messages and matching placeholders in every registered locale", () => {+ const registry = readFileSync("apps/desktop/src/i18n/index.ts", "utf8");+ const locales = [...registry.match(/const supportedLocales: Locale\[\] = \[(.*?)\]/)![1].matchAll(/"([^"]+)"/g)].map((match) => match[1]);+ expect(locales.length).toBeGreaterThan(0);+ for (const locale of locales) {+ const source = readFileSync(`apps/desktop/src/i18n/locales/${locale}.ts`, "utf8");+ for (const key of ["mysqlAutoIncrementSingleColumn", "mysqlAutoIncrementRequiresIndex", "mysqlAutoIncrementRequiresNativeColumn"]) {+ const line = source.split("\n").find((line) => line.trimStart().startsWith(`${key}:`));+ expect(line, `${locale}: ${key}`).toBeDefined();+ expect(line!.match(/\{[^}]+\}/g) ?? []).toEqual(key === "mysqlAutoIncrementRequiresIndex" ? ["{column}"] : []);+ }+ }+ });+});diff --git a/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts b/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.tsindex 786110f6b1..bc2a7ab2ba 100644--- a/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts+++ b/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts@@ -1,3 +1,4 @@+import type { BackendErrorTranslate } from "@/i18n/backend-errors";import type { ConnectionConfig, DatabaseType } from "@/types/database";import { supportsNativeMysqlAutoIncrement, type MysqlAutoIncrementSqlOptions } from "@/lib/database/dbAdminSql";import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";@@ -18,8 +19,8 @@ export function refreshMysqlAutoIncrementCounterDraft(serverValue: string | nullreturn { value: current.value, originalValue: server.originalValue };}-export function canEditMysqlAutoIncrementCounter(connection: Pick<ConnectionConfig, "db_type" | "driver_profile"> | undefined, isCreateMode: boolean, columns: readonly EditableStructureColumn[]): boolean {- if (isCreateMode || !supportsNativeMysqlAutoIncrement(connection)) return false;+export function canEditMysqlAutoIncrementCounter(connection: Pick<ConnectionConfig, "db_type" | "driver_profile"> | undefined, _isCreateMode: boolean, columns: readonly EditableStructureColumn[]): boolean {+ if (!supportsNativeMysqlAutoIncrement(connection)) return false;return columns.some((column) => !column.markedForDrop && column.extra.autoIncrement === true);}@@ -38,3 +39,16 @@ export async function buildMysqlAutoIncrementCounterStatement({ enabled, origina}return buildSql({ ...options, databaseType, value });}++/** Translate only recognized structure warnings; preserve other backend diagnostics. */+export function translateMysqlAutoIncrementWarning(t: BackendErrorTranslate, warning: string): string {+ if (warning === "MySQL allows only one AUTO_INCREMENT column per table.") {+ return t("structureEditor.mysqlAutoIncrementSingleColumn");+ }+ if (warning === "AUTO_INCREMENT requires a native MySQL auto-increment column.") {+ return t("structureEditor.mysqlAutoIncrementRequiresNativeColumn");+ }+ const missingIndex = /^AUTO_INCREMENT column "([\s\S]*)" requires a supporting index \(first key column for InnoDB\)\.$/.exec(warning);+ if (missingIndex) return t("structureEditor.mysqlAutoIncrementRequiresIndex", { column: missingIndex[1] });+ return warning;+}diff --git a/apps/desktop/src/lib/table/tableStructureEditorSql.ts b/apps/desktop/src/lib/table/tableStructureEditorSql.tsindex bd7c09c441..dd11c02182 100644--- a/apps/desktop/src/lib/table/tableStructureEditorSql.ts+++ b/apps/desktop/src/lib/table/tableStructureEditorSql.ts@@ -99,6 +99,7 @@ export interface BuildTableStructureChangeSqlOptions {tableComment?: string;originalTableComment?: string;mysqlEngine?: string;+ mysqlAutoIncrementValue?: string;transwarpCreate?: TranswarpCreateTableOptions;/** MySQL only: the table's current default collation. Columns whose collation merely* matches it inherit the table default, so the backend leaves their redundantdiff --git a/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs b/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rsindex a593974da4..3d7b82c456 100644--- a/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs+++ b/crates/dbx-core/src/schema/table_structure_sql/sqlite_rebuild.rs@@ -1520,6 +1520,7 @@ mod tests {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs b/crates/dbx-core/tests/live_mysql_column_name_whitespace.rsindex a2d1145d88..72aac85f0e 100644--- a/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs+++ b/crates/dbx-core/tests/live_mysql_column_name_whitespace.rs@@ -52,6 +52,7 @@ fn change_options(table_name: &str, columns: Vec<EditableStructureColumn>) -> Tatable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-core/tests/live_mysql_generated_columns.rs b/crates/dbx-core/tests/live_mysql_generated_columns.rsindex b82b313552..3761827ce7 100644--- a/crates/dbx-core/tests/live_mysql_generated_columns.rs+++ b/crates/dbx-core/tests/live_mysql_generated_columns.rs@@ -48,6 +48,7 @@ fn change_options(table_name: &str, columns: Vec<EditableStructureColumn>) -> Tatable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-core/tests/live_postgres_concurrent_index.rs b/crates/dbx-core/tests/live_postgres_concurrent_index.rsindex 30b007e8d7..5d3a0bee8b 100644--- a/crates/dbx-core/tests/live_postgres_concurrent_index.rs+++ b/crates/dbx-core/tests/live_postgres_concurrent_index.rs@@ -62,6 +62,7 @@ async fn live_postgres_concurrent_index_builds_valid_index() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -197,6 +198,7 @@ async fn live_postgres_partitioned_parent_concurrent_request_rejected() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: true,foreign_table: false,diff --git a/crates/dbx-core/tests/live_postgres_partitioning.rs b/crates/dbx-core/tests/live_postgres_partitioning.rsindex 56c98a13b7..f0efc3e306 100644--- a/crates/dbx-core/tests/live_postgres_partitioning.rs+++ b/crates/dbx-core/tests/live_postgres_partitioning.rs@@ -314,6 +314,7 @@ async fn live_postgres_create_partitioned_table_executes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rsindex ace0bf2b54..baca994e1e 100644--- a/crates/dbx-core/tests/live_sqlserver_completion.rs+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs@@ -1021,6 +1021,7 @@ async fn live_sqlserver_table_structure_default_changes_drop_existing_constrainttable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-sql-schema/src/db_admin_sql.rs b/crates/dbx-sql-schema/src/db_admin_sql.rsindex ad86fa80f5..d853a9c172 100644--- a/crates/dbx-sql-schema/src/db_admin_sql.rs+++ b/crates/dbx-sql-schema/src/db_admin_sql.rs@@ -652,7 +652,7 @@ fn supports_vacuum_table(database_type: Option<DatabaseType>) -> bool {)}-pub fn build_mysql_auto_increment_sql(options: MysqlAutoIncrementSqlOptions) -> Result<String, String> {+pub(crate) fn validate_mysql_auto_increment_options(options: &MysqlAutoIncrementSqlOptions) -> Result<(), String> {let profile = options.driver_profile.as_deref().map(str::trim).unwrap_or_default();if options.database_type != Some(DatabaseType::Mysql)|| (!profile.is_empty() && !profile.eq_ignore_ascii_case("mysql"))@@ -669,6 +669,13 @@ pub fn build_mysql_auto_increment_sql(options: MysqlAutoIncrementSqlOptions) ->return Err("AUTO_INCREMENT must be a decimal integer from 1 to 18446744073709551615.".to_string());}+ Ok(())+}++pub fn build_mysql_auto_increment_sql(options: MysqlAutoIncrementSqlOptions) -> Result<String, String> {+ validate_mysql_auto_increment_options(&options)?;+ let value = &options.value;+let table = if options.schema.as_deref().is_some_and(|schema| !schema.is_empty()) {format!("{}.{}",@@ -3100,6 +3107,7 @@ mod tests {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,diff --git a/crates/dbx-sql-schema/src/table_structure_sql/comments.rs b/crates/dbx-sql-schema/src/table_structure_sql/comments.rsindex 8065483bae..2c22a8e05a 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/comments.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/comments.rs@@ -235,6 +235,7 @@ mod tests {table_comment: Some("港口资料".to_string()),original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,is_gaussdb_m_mode: false,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.rsindex 3928f965c5..6f3f53ee02 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@@ -6,7 +6,7 @@ use super::column_format::{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};use super::foreign_keys::build_foreign_key_sql_for_new_table;-use super::indexes::build_create_index_statements;+use super::indexes::{build_create_index_statements, mysql_inline_index_definition, normalized_index_type};use super::mysql_engine::{append_mysql_table_option, validate_mysql_engine};use super::transwarp;use super::triggers::build_trigger_sql_for_new_table;@@ -53,6 +53,25 @@ pub(super) fn build_create_table_sql_with_partition_clause(strip_inherited_mysql_column_charsets(&mut options);let mut warnings = Vec::new();warnings.extend(validate_mysql_engine(&options));+ if let Some(value) = &options.mysql_auto_increment_value {+ let counter = crate::db_admin_sql::MysqlAutoIncrementSqlOptions {+ database_type: options.database_type,+ driver_profile: options.driver_profile.clone(),+ schema: options.schema.clone(),+ table_name: options.table_name.clone(),+ value: value.clone(),+ };+ if let Err(error) = crate::db_admin_sql::validate_mysql_auto_increment_options(&counter) {+ warnings.push(error);+ }+ if options.is_gaussdb_m_mode+ || !options.columns.iter().any(|column| {+ !column.marked_for_drop && column.extra.as_ref().is_some_and(|extra| extra.auto_increment == Some(true))+ })+ {+ warnings.push("AUTO_INCREMENT requires a native MySQL auto-increment column.".to_string());+ }+ }// Fail closed: a concurrent-index request on a partitioned parent (or on an// existing index in a hand-built draft) is refused up front instead of// degrading into blocking index DDL.@@ -64,6 +83,57 @@ pub(super) fn build_create_table_sql_with_partition_clause(if active_columns.is_empty() {warnings.push("At least one column is required.".to_string());}+ // MySQL requires the supporting key to exist in the CREATE itself. A later+ // CREATE INDEX cannot rescue a table rejected for ERROR 1075.+ let native_mysql = options.database_type == Some(DatabaseType::Mysql)+ && !options.is_gaussdb_m_mode+ && options+ .driver_profile+ .as_deref()+ .is_none_or(|profile| profile.trim().is_empty() || profile.trim().eq_ignore_ascii_case("mysql"));+ let mut inline_auto_index = None;+ if native_mysql {+ let auto_columns: Vec<_> = active_columns+ .iter()+ .filter(|column| column.extra.as_ref().is_some_and(|extra| extra.auto_increment == Some(true)))+ .collect();+ if auto_columns.len() > 1 {+ warnings.push("MySQL allows only one AUTO_INCREMENT column per table.".to_string());+ } else if let Some(column) = auto_columns.first() {+ // MyISAM also supports a grouped sequence when the auto column is+ // a later key part; InnoDB requires the leading key part.+ let grouped =+ options.mysql_engine.as_deref().is_some_and(|engine| engine.trim().eq_ignore_ascii_case("MyISAM"));+ let primary: Vec<_> = active_columns.iter().filter(|column| column.is_primary_key).collect();+ let primary_supports =+ primary.iter().enumerate().any(|(position, key)| (grouped || position == 0) && key.name == column.name);+ if !primary_supports {+ inline_auto_index = options.indexes.iter().enumerate().find_map(|(position, index)| {+ if index.marked_for_drop+ || index.is_primary+ || !matches!(normalized_index_type(index).as_str(), "" | "BTREE" | "HASH")+ {+ return None;+ }+ let supports =+ index.columns.iter().filter(|key| !clean(key).is_empty()).enumerate().any(|(part, key)| {+ (grouped || part == 0) && clean(key).eq_ignore_ascii_case(&clean(&column.name))+ });+ if supports {+ mysql_inline_index_definition(index).map(|definition| (position, definition))+ } else {+ None+ }+ });+ if inline_auto_index.is_none() {+ warnings.push(format!(+ "AUTO_INCREMENT column \"{}\" requires a supporting index (first key column for InnoDB).",+ column.name+ ));+ }+ }+ }+ }validate_columns(&active_columns, &mut warnings);validate_dameng_identity(&options, &active_columns, &mut warnings);validate_mysql_literal_defaults(&options, &active_columns, &mut warnings);@@ -208,6 +278,10 @@ pub(super) fn build_create_table_sql_with_partition_clause(column_definitions.push(format!("PRIMARY KEY ({pk_list})"));}+ if let Some((_, definition)) = &inline_auto_index {+ column_definitions.push(definition.clone());+ }+let mut create_table = format!("CREATE TABLE {table} (\n {}\n)", column_definitions.join(",\n "));create_table.push_str(&transwarp::create_table_suffix(&options, &active_columns, dialect));let create_table = match partition_clause {@@ -222,6 +296,12 @@ pub(super) fn build_create_table_sql_with_partition_clause(}}+ if let Some(value) = &options.mysql_auto_increment_value {+ if let Some(statement) = statements.last_mut() {+ append_mysql_table_option(statement, &format!("AUTO_INCREMENT = {value}"));+ }+ }+if capabilities.comment {let table_comment = clean(options.table_comment.as_deref().unwrap_or(""));if !table_comment.is_empty() && options.database_type != Some(DatabaseType::Transwarp) {@@ -298,7 +378,12 @@ pub(super) fn build_create_table_sql_with_partition_clause(}}- for index in options.indexes.iter().filter(|index| !index.marked_for_drop && !index.is_primary) {+ for (position, index) in+ options.indexes.iter().enumerate().filter(|(_, index)| !index.marked_for_drop && !index.is_primary)+ {+ if inline_auto_index.as_ref().is_some_and(|(inline_position, _)| *inline_position == position) {+ continue;+ }if !capabilities.create_index {warnings.push(format!("Creating indexes is not supported for {} from this editor.",diff --git a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rsindex 8fea285188..16e6b83796 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs@@ -266,6 +266,22 @@ pub(super) fn mysql_index_parts(index_type: &str) -> (String, String) {}}+/// Inline MySQL index definition for indexes required at CREATE TABLE time.+pub(super) fn mysql_inline_index_definition(index: &EditableStructureIndex) -> Option<String> {+ let name = clean(&index.name);+ let columns: Vec<_> =+ index.columns.iter().map(|column| clean(column)).filter(|column| !column.is_empty()).collect();+ if name.is_empty() || columns.is_empty() {+ return None;+ }+ let unique = if index.is_unique { "UNIQUE " } else { "" };+ let (prefix, using) = mysql_index_parts(&normalized_index_type(index));+ let cols = columns.iter().map(|column| mysql_index_column_sql(column)).collect::<Vec<_>>().join(", ");+ let comment = clean(&index.comment);+ let comment = if comment.is_empty() { String::new() } else { format!(" COMMENT {}", quote_string(&comment)) };+ Some(format!("{unique}{prefix}INDEX {}{using} ({cols}){comment}", quote_ident(StructureDialect::Mysql, &name)))+}+fn gaussdbm_index_parts(index_type: &str) -> (String, String) {match index_type.to_ascii_uppercase().as_str() {"BTREE" | "UBTREE" => (String::new(), " USING UBTREE".to_string()),diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rsindex 032137257c..72f32ec36d 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs@@ -62,6 +62,7 @@ fn structure_change_options(table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -352,6 +353,7 @@ fn index_change_options(table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -436,6 +438,7 @@ fn builds_mysql_column_and_index_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -800,6 +803,7 @@ fn builds_xugu_type_change_with_native_syntax() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1068,6 +1072,7 @@ fn builds_mysql_unsigned_integer_column_with_length_before_attribute() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1107,6 +1112,7 @@ fn doris_table_editor_renames_column_without_mysql_change_syntax() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1171,6 +1177,7 @@ fn dameng_integer_column_omits_mysql_display_width() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1217,6 +1224,7 @@ fn builds_highgo_foreign_key_changes_with_postgres_syntax() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1294,6 +1302,7 @@ fn builds_informix_column_and_index_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1354,6 +1363,7 @@ fn oracle_does_not_generate_drop_sql_for_all_columns() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1430,6 +1440,7 @@ fn oracle_create_table_places_default_before_not_null() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1500,6 +1511,7 @@ fn oracle_create_table_preserves_character_length_units() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1539,6 +1551,7 @@ fn oracle_create_table_uses_unquoted_identifiers_for_new_objects() {table_comment: Some("user table".to_string()),original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1579,6 +1592,7 @@ fn oracle_create_table_leaves_uppercase_regular_identifier_unquoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1618,6 +1632,7 @@ fn oracle_create_table_quotes_special_and_reserved_identifiers() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1660,6 +1675,7 @@ fn oracle_create_table_distinguishes_new_and_referenced_foreign_key_identifiers(table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1703,6 +1719,7 @@ fn oracle_create_table_extracts_single_line_trigger_source_into_the_body() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1738,6 +1755,7 @@ fn oracle_create_table_warns_instead_of_emitting_an_unparsed_trigger_declarationtable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1777,6 +1795,7 @@ fn oracle_existing_quoted_identifiers_keep_exact_spelling() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1813,6 +1832,7 @@ fn oracle_new_identifier_formatting_does_not_change_other_dialects() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1911,6 +1931,7 @@ fn iris_drop_index_includes_table_name() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -1956,6 +1977,7 @@ fn iris_ignores_comment_changes_but_keeps_supported_column_alters() {table_comment: Some("new table description".to_string()),original_table_comment: Some("old table description".to_string()),mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2042,6 +2064,7 @@ fn oracle_compatible_databases_keep_comment_on_sql() {table_comment: Some("new table description".to_string()),original_table_comment: Some("old table description".to_string()),mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2080,6 +2103,7 @@ fn mysql_create_index_with_comment() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2117,6 +2141,7 @@ fn manticoresearch_builds_create_table_sql_only() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2164,6 +2189,7 @@ fn manticoresearch_builds_add_and_drop_column_sql() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2236,6 +2262,7 @@ fn gbase8a_uses_limited_mysql_ddl() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2310,6 +2337,7 @@ fn gbase8a_allows_mysql_style_column_reorder() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2355,6 +2383,7 @@ fn gbase8s_uses_informix_ddl_not_mysql() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2392,6 +2421,7 @@ fn gbase_without_driver_profile_still_uses_mysql_ddl() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2431,6 +2461,7 @@ fn manticoresearch_does_not_drop_id_column() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2503,6 +2534,7 @@ fn manticoresearch_warns_when_existing_column_properties_change() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2542,6 +2574,7 @@ fn manticoresearch_ignores_mysql_column_options() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2584,6 +2617,7 @@ fn manticoresearch_builds_text_column_properties() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2618,6 +2652,7 @@ fn manticoresearch_builds_json_secondary_index_property() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2648,6 +2683,7 @@ fn mysql_create_unique_index_with_comment_and_btree() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2680,6 +2716,7 @@ fn mysql_create_functional_index_preserves_key_part_syntax() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2712,6 +2749,7 @@ fn mysql_add_timestamp_column_drops_invalid_precision() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2744,6 +2782,7 @@ fn mysql_add_timestamp_column_preserves_valid_precision() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2783,6 +2822,7 @@ fn builds_postgres_create_table_with_comments_and_index() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2819,6 +2859,7 @@ fn quotes_expression_like_new_index_columns_without_provenance() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2895,6 +2936,7 @@ fn create_table_trims_table_name_whitespace_for_all_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2936,6 +2978,7 @@ fn warns_for_sqlite_unsafe_column_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -2983,6 +3026,7 @@ fn qualifies_attached_sqlite_table_and_index_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3056,6 +3100,7 @@ fn builds_rqlite_changes_with_sqlite_dialect() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3090,6 +3135,7 @@ fn builds_kingbase_add_column_without_column_keyword() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3159,6 +3205,7 @@ fn builds_mysql_column_reorder_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3219,6 +3266,7 @@ fn mysql_add_column_before_existing_column_does_not_reorder_shifted_column() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3286,6 +3334,7 @@ fn mysql_existing_column_reorder_does_not_reorder_columns_shifted_by_prior_move(table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3365,6 +3414,7 @@ fn mysql_moving_first_column_to_end_uses_single_reorder_statement() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3394,6 +3444,7 @@ fn builds_sql_server_quoted_column_and_index_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3429,6 +3480,7 @@ fn sqlserver_strips_mysql_display_width_from_fixed_integer_types() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3458,6 +3510,7 @@ fn sqlserver_strips_scale_from_float() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3487,6 +3540,7 @@ fn sqlserver_preserves_float_mantissa_bits() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3541,6 +3595,7 @@ fn sqlserver_default_changes_drop_old_constraints_with_isolated_batches() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3762,6 +3817,7 @@ fn sqlserver_unchanged_foreign_key_does_not_warn_when_saving_other_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3796,6 +3852,7 @@ fn sqlserver_add_column_with_identity() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3831,6 +3888,7 @@ fn sqlserver_legacy_column_comment_change_uses_legacy_extended_properties() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3868,6 +3926,7 @@ fn dameng_add_column_with_identity() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3896,6 +3955,7 @@ fn dameng_uppercases_lowercase_column_type() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3931,6 +3991,7 @@ fn dameng_rejects_identity_on_incompatible_type() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -3968,6 +4029,7 @@ fn sqlserver_rejects_identity_on_incompatible_type() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4008,6 +4070,7 @@ fn sqlserver_changed_foreign_key_still_warns_as_unsupported() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4053,6 +4116,7 @@ fn sqlserver_unchanged_identity_extra_does_not_mark_existing_column_changed() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4098,6 +4162,7 @@ fn dameng_unchanged_identity_extra_does_not_mark_existing_column_changed() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4356,6 +4421,7 @@ fn dameng_rejects_adding_second_identity_column() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4413,6 +4479,7 @@ fn sqlserver_existing_column_identity_change_warns_without_unchanged_foreign_keytable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4449,6 +4516,7 @@ fn builds_duckdb_create_table_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4574,6 +4642,7 @@ fn builds_clickhouse_nullable_comment_and_reorder_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -4625,6 +4694,7 @@ fn builds_h2_schema_qualified_existing_column_statements() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5674,6 +5744,7 @@ fn mysql_create_table_with_auto_increment() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5706,6 +5777,7 @@ fn mysql_create_table_keeps_column_charset_collation_and_comment() {table_comment: Some("User accounts".to_string()),original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5742,6 +5814,7 @@ fn mysql_compatible_databases_do_not_emit_mysql_column_charset_clauses() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5775,6 +5848,7 @@ fn mysql_create_table_with_on_update_current_timestamp() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5940,6 +6014,7 @@ fn postgres_create_table_with_identity() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -5975,6 +6050,7 @@ fn dameng_create_table_with_identity() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6006,6 +6082,7 @@ fn dameng_create_table_preserves_character_length_units() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6045,6 +6122,7 @@ fn dameng_alter_column_preserves_character_length_unit() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6085,6 +6163,7 @@ fn dameng_rejects_multiple_identity_columns() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6118,6 +6197,7 @@ fn dameng_rejects_zero_identity_increment() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6152,6 +6232,7 @@ fn sqlserver_create_table_with_identity() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6181,6 +6262,7 @@ fn mysql_quotes_datetime_literal_default() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6210,6 +6292,7 @@ fn mysql_does_not_quote_current_timestamp() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6240,6 +6323,7 @@ fn mysql_does_not_quote_temporal_function_with_parens() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6269,6 +6353,7 @@ fn mysql_date_literal_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6298,6 +6383,7 @@ fn mysql_time_literal_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6327,6 +6413,7 @@ fn non_temporal_types_are_not_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6460,6 +6547,7 @@ fn builds_mysql_foreign_key_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6494,6 +6582,7 @@ fn builds_mysql_composite_foreign_key() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6531,6 +6620,7 @@ fn builds_oracle_foreign_key_with_supported_actions() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6572,6 +6662,7 @@ fn builds_oracle_foreign_key_replacement() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6612,6 +6703,7 @@ fn builds_mysql_trigger_changes() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6643,6 +6735,7 @@ fn builds_sqlserver_trigger_with_multiple_events() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6690,6 +6783,7 @@ fn rebuilds_changed_sqlserver_trigger_from_complete_metadata_source() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6733,6 +6827,7 @@ fn sqlserver_trigger_edit_restores_disabled_state() {partitioned: false,foreign_table: false,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,is_gaussdb_m_mode: false,table_collation: None,@@ -6778,6 +6873,7 @@ fn unchanged_postgres_trigger_does_not_block_column_rename() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6812,6 +6908,7 @@ fn changed_postgres_trigger_remains_unsupported() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6851,6 +6948,7 @@ fn rejects_editing_existing_oracle_trigger_without_complete_source() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6879,6 +6977,7 @@ fn builds_oracle_statement_trigger_without_row_clause() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6919,6 +7018,7 @@ fn drops_existing_oracle_trigger_without_reconstructing_it() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6944,6 +7044,7 @@ fn rejects_unsupported_oracle_compound_trigger_shape() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -6973,6 +7074,7 @@ fn mysql_varchar_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7003,6 +7105,7 @@ fn mysql_char_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7034,6 +7137,7 @@ fn mysql_text_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7063,6 +7167,7 @@ fn mysql_enum_default_is_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7092,6 +7197,7 @@ fn mysql_int_default_is_not_quoted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7231,6 +7337,7 @@ fn mysql_character_column_add_with_charset_collation() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7350,6 +7457,7 @@ fn mysql_numeric_column_omits_charset_collation_in_column_definition() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7397,6 +7505,7 @@ fn mysql_numeric_column_ignores_charset_collation_in_change_detection() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7439,6 +7548,7 @@ fn mysql_character_column_detects_charset_collation_change() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7486,6 +7596,7 @@ fn mysql_character_column_preserves_charset_collation_on_other_change() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7566,6 +7677,7 @@ fn mysql_inherited_column_charset_is_omitted_from_generated_ddl() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7614,6 +7726,7 @@ fn mysql_explicit_column_charset_survives_the_table_default_comparison() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7663,6 +7776,7 @@ fn mysql_inherited_column_charset_does_not_register_as_a_change() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7705,6 +7819,7 @@ fn mysql_collation_switched_away_from_the_table_default_is_emitted() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7752,6 +7867,7 @@ fn mysql_column_charset_switched_to_the_table_default_drops_the_clause() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7796,6 +7912,7 @@ fn mysql_column_charset_is_kept_when_the_table_default_is_unknown() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -7835,6 +7952,7 @@ fn mysql_create_table_omits_inherited_column_charset() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -8544,6 +8662,7 @@ fn mysql_create_table_with_generated_column() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,is_gaussdb_m_mode: false,@@ -8588,6 +8707,7 @@ fn oscar_create_table_with_primary_key_and_comments() {table_comment: Some("user table".to_string()),original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -8787,6 +8907,7 @@ fn oscar_drop_index_with_schema_qualifier() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -8812,6 +8933,7 @@ fn oscar_table_comment_uses_comment_on_table() {table_comment: Some("new comment".to_string()),original_table_comment: Some("old comment".to_string()),mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -8899,6 +9021,7 @@ fn postgres_partitioned_parent_concurrent_request_rejected() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: true,foreign_table: false,@@ -8934,6 +9057,7 @@ fn postgres_partitioned_parent_plain_index_unchanged() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: true,foreign_table: false,@@ -8981,6 +9105,7 @@ fn postgres_create_table_partitioned_concurrent_request_rejected() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: true,foreign_table: false,@@ -9112,6 +9237,7 @@ fn postgres_create_table_concurrent_index() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9232,6 +9358,7 @@ fn gaussdb_m_options(columns: Vec<EditableStructureColumn>) -> TableStructureSqltable_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9470,6 +9597,7 @@ fn gaussdb_m_rebuild_index_unchanged_type_does_not_rebuild() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9521,6 +9649,7 @@ fn mysql_create_table_nullable_timestamp_without_default_gets_explicit_null() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9554,6 +9683,7 @@ fn mysql_create_table_nullable_timestamp_with_default_still_gets_explicit_null()table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9585,6 +9715,7 @@ fn mysql_create_table_nullable_datetime_does_not_gain_null_keyword() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -9616,6 +9747,7 @@ fn mysql_add_column_nullable_timestamp_without_default_gets_explicit_null() {table_comment: None,original_table_comment: None,mysql_engine: None,+ mysql_auto_increment_value: None,transwarp_create: None,partitioned: false,foreign_table: false,@@ -10343,3 +10475,118 @@ fn mysql_literal_default_check_only_covers_defaults_the_draft_emits() {vec!["MySQL does not allow a literal default on text column \"note\". Remove the default, or on MySQL 8.0.13 or later use an expression default such as ('').".to_string()]);}++#[test]+fn mysql_create_table_start_value() {+ let mut col = column("id");+ col.data_type = "BIGINT".to_string();+ col.is_primary_key = true;+ col.is_nullable = false;+ col.extra = Some(ColumnExtra { auto_increment: Some(true), ..Default::default() });+ let mut options = structure_change_options(DatabaseType::Mysql, None, "users", vec![col]);+ options.mysql_engine = Some("InnoDB".to_string());+ options.table_comment = Some("example".to_string());+ let default_result = build_create_table_sql(options.clone());+ assert!(default_result.warnings.is_empty());+ assert!(!default_result.statements[0].contains("AUTO_INCREMENT ="));+ for value in ["1", "66", "9007199254740993", "18446744073709551615"] {+ options.mysql_auto_increment_value = Some(value.to_string());+ let result = build_create_table_sql(options.clone());+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert_eq!(result.statements.len(), 1);+ assert!(result.statements[0].contains(&format!("ENGINE = InnoDB AUTO_INCREMENT = {value} COMMENT = 'example'")));+ }+ for value in ["", "0", "01", "-1", "1.5", "1e3", "18446744073709551616", "1; DROP TABLE users", " 66"] {+ options.mysql_auto_increment_value = Some(value.to_string());+ let result = build_create_table_sql(options.clone());+ assert!(result.statements.is_empty(), "{value}");+ assert!(!result.warnings.is_empty(), "{value}");+ }+ options.mysql_auto_increment_value = Some("66".to_string());+ options.driver_profile = Some("tidb".to_string());+ assert!(build_create_table_sql(options.clone()).statements.is_empty());+ options.driver_profile = None;+ options.columns[0].extra = None;+ assert!(build_create_table_sql(options).statements.is_empty());+}++fn mysql_auto_increment_create_options() -> TableStructureSqlOptions {+ let mut id = column("id");+ id.data_type = "INT".to_string();+ id.is_nullable = false;+ id.extra = Some(ColumnExtra { auto_increment: Some(true), ..Default::default() });+ let mut options = structure_change_options(DatabaseType::Mysql, None, "users", vec![id, column("name")]);+ options.mysql_engine = Some("InnoDB".to_string());+ options+}++#[test]+fn mysql_create_auto_increment_requires_one_column_and_a_supporting_key() {+ for start in [None, Some("6".to_string())] {+ let mut options = mysql_auto_increment_create_options();+ options.mysql_auto_increment_value = start;+ let result = build_create_table_sql(options.clone());+ assert!(result.statements.is_empty());+ assert!(result.warnings.iter().any(|warning| warning.contains("supporting index")));+ options.columns[0].is_primary_key = true;+ assert!(build_create_table_sql(options.clone()).warnings.is_empty());+ options.columns[1].extra = Some(ColumnExtra { auto_increment: Some(true), ..Default::default() });+ let result = build_create_table_sql(options.clone());+ assert!(result.statements.is_empty());+ assert!(result.warnings.iter().any(|warning| warning.contains("only one")));+ options.columns[1].marked_for_drop = true;+ assert!(build_create_table_sql(options).warnings.is_empty());+ }+}++#[test]+fn mysql_create_auto_increment_inlines_ordinary_and_unique_supporting_indexes_once() {+ for unique in [false, true] {+ let mut options = mysql_auto_increment_create_options();+ options.mysql_auto_increment_value = Some("6".to_string());+ let mut supporting = index("key`id", &["id", "name"]);+ supporting.is_unique = unique;+ supporting.index_type = "BTREE".to_string();+ supporting.comment = "id's sequence".to_string();+ options.indexes = vec![supporting, index("name_lookup", &["name"])];+ let result = build_create_table_sql(options);+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert_eq!(result.statements.len(), 2);+ let unique_prefix = if unique { "UNIQUE " } else { "" };+ assert!(+ result.statements[0].contains(&format!(+ "{unique_prefix}INDEX `key``id` USING BTREE (`id`, `name`) COMMENT 'id''s sequence'"+ )),+ "{:?}",+ result.statements+ );+ assert!(result.statements[0].contains("AUTO_INCREMENT = 6"));+ assert!(result.statements[1].contains("name_lookup"));+ assert!(!result.statements[1].contains("key``id"));+ }+}++#[test]+fn mysql_create_auto_increment_checks_key_order_and_ignores_dropped_or_unsuitable_indexes() {+ let mut options = mysql_auto_increment_create_options();+ options.indexes = vec![index("wrong_order", &["name", "id"])];+ assert!(build_create_table_sql(options.clone()).statements.is_empty());+ options.mysql_engine = Some("MyISAM".to_string());+ assert!(build_create_table_sql(options.clone()).warnings.is_empty());+ options.mysql_engine = None; // default InnoDB behavior+ options.indexes[0].columns = vec!["id".to_string()];+ options.indexes[0].marked_for_drop = true;+ assert!(build_create_table_sql(options.clone()).statements.is_empty());+ options.indexes[0].marked_for_drop = false;+ for kind in ["FULLTEXT", "SPATIAL", "RTREE"] {+ options.indexes[0].index_type = kind.to_string();+ assert!(build_create_table_sql(options.clone()).statements.is_empty());+ }+ options.indexes.clear();+ options.columns[0].is_primary_key = true;+ options.columns[1].is_primary_key = true;+ options.columns.swap(0, 1);+ assert!(build_create_table_sql(options.clone()).statements.is_empty());+ options.indexes.push(index("support", &["id"]));+ assert!(build_create_table_sql(options).warnings.is_empty());+}diff --git a/crates/dbx-sql-schema/src/table_structure_sql/types.rs b/crates/dbx-sql-schema/src/table_structure_sql/types.rsindex 68cf4c91c5..7e2925ef83 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/types.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/types.rs@@ -257,6 +257,8 @@ pub struct TableStructureSqlOptions {#[serde(default, skip_serializing_if = "Option::is_none")]pub mysql_engine: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]+ pub mysql_auto_increment_value: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]pub transwarp_create: Option<TranswarpCreateTableOptions>,/// MySQL only: the table's current default collation/// (`information_schema.TABLES.TABLE_COLLATION`). A column whose collation