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): edit table auto-increment counter

t8y2277386ec81d2
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
index ed4656e528..105ef4d4a7 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
@@ -8,12 +8,16 @@ const mocks = vi.hoisted(() => ({
id: "structure-charset-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(),
@@ -222,19 +226,25 @@ 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[] = [];
+let mountedEditor: { applyChanges: () => Promise<boolean> } | undefined;
-function draft() {
+function draft(autoIncrement = false, counter?: { value?: string; originalValue?: string }) {
return {
initialized: true,
activeTab: "columns" as const,
newTableName: "",
tableComment: "",
originalTableComment: "",
+ mysqlAutoIncrementValue: counter?.value,
+ originalMysqlAutoIncrementValue: counter?.originalValue,
columns: [
{
id: "existing:id",
@@ -246,14 +256,14 @@ function draft() {
isPrimaryKey: false,
characterSet: "utf8mb3",
collation: "utf8mb3_uca1400_ai_ci",
- extra: "",
+ extra: { autoIncrement },
original: {
name: "id",
data_type: "VARCHAR",
is_nullable: true,
column_default: null,
is_primary_key: false,
- extra: null,
+ extra: autoIncrement ? "auto_increment" : null,
comment: null,
},
originalPosition: 0,
@@ -266,7 +276,7 @@ function draft() {
};
}
-async function mountEditor() {
+async function mountEditor(autoIncrement = false, counter?: { value?: string; originalValue?: string }) {
mocks.ensureConnected.mockResolvedValue(undefined);
mocks.listDataTypes.mockResolvedValue([]);
mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: [], warnings: [] });
@@ -278,10 +288,10 @@ async function mountEditor() {
database: "test",
schema: "test",
tableName: "users",
- draft: draft(),
+ draft: draft(autoIncrement, counter),
});
mountedApps.push(app);
- app.mount(root);
+ mountedEditor = app.mount(root) as unknown as { applyChanges: () => Promise<boolean> };
await nextTick();
await Promise.resolve();
await nextTick();
@@ -303,9 +313,13 @@ beforeEach(() => {
mocks.connection.db_type = "mysql";
mocks.connection.name = "MySQL";
mocks.connection.driver_label = "MySQL";
+ mocks.connection.driver_profile = "mysql";
mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE users (id varchar(255))", cacheStatus: "remote" });
mocks.invalidateObjectDdl.mockResolvedValue(undefined);
mocks.loadObjectMetadataFacet.mockResolvedValue({ value: [], cacheStatus: "remote" });
+ mocks.getMysqlTableAutoIncrement.mockResolvedValue("10");
+ mocks.buildMysqlAutoIncrementSql.mockImplementation(async ({ value }: { value: string }) => `ALTER TABLE \`test\`.\`users\` AUTO_INCREMENT = ${value};`);
+ mocks.executeBatch.mockResolvedValue({ affected_rows: 0 });
});
afterEach(() => {
@@ -333,3 +347,98 @@ describe("TableStructureEditor charset/collation column width", () => {
expect(triggerClass.split(",")).not.toEqual(expect.arrayContaining(["w-28"]));
});
});
+
+describe("TableStructureEditor MySQL AUTO_INCREMENT counter", () => {
+ it("loads and renders the server value as a decimal string only for an existing auto-increment column", async () => {
+ const root = await mountEditor(true);
+ await vi.waitFor(() => expect(mocks.getMysqlTableAutoIncrement).toHaveBeenCalledWith("structure-charset-test", "test", "users"));
+
+ const input = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]");
+ expect(input?.value).toBe("10");
+ expect(input?.disabled).toBe(false);
+ });
+
+ it("refreshes a restored clean counter draft from the server", async () => {
+ mocks.getMysqlTableAutoIncrement.mockResolvedValueOnce("30");
+ const root = await mountEditor(true, { value: "10", originalValue: "10" });
+
+ await vi.waitFor(() => expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe("30"));
+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
+ });
+
+ it("keeps a restored dirty value while rebasing its server baseline", async () => {
+ mocks.getMysqlTableAutoIncrement.mockResolvedValueOnce("15");
+ const root = await mountEditor(true, { value: "20", originalValue: "10" });
+ const input = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")!;
+
+ await vi.waitFor(() => expect(input.value).toBe("20"));
+ await vi.waitFor(() => expect(mocks.buildMysqlAutoIncrementSql).toHaveBeenCalledWith(expect.objectContaining({ value: "20" })));
+ mocks.buildMysqlAutoIncrementSql.mockClear();
+ input.value = "15";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
+ });
+
+ it("keeps NULL or failed optional metadata from enabling a counter edit", async () => {
+ mocks.getMysqlTableAutoIncrement.mockResolvedValueOnce(null);
+ const nullRoot = await mountEditor(true);
+ await vi.waitFor(() => expect(mocks.getMysqlTableAutoIncrement).toHaveBeenCalled());
+ expect(nullRoot.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.disabled).toBe(true);
+
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+ mocks.getMysqlTableAutoIncrement.mockRejectedValueOnce(new Error("permission denied"));
+ const errorRoot = await mountEditor(true);
+ await vi.waitFor(() => expect(errorRoot.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.title).toBe("permission denied"));
+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
+
+ const structureStatement = "ALTER TABLE `test`.`users` COMMENT = 'ordinary edit';";
+ mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: [structureStatement], warnings: [] });
+ const commentInput = Array.from(errorRoot.querySelectorAll<HTMLInputElement>("input")).find((input) => !input.hasAttribute("data-mysql-auto-increment-counter"))!;
+ commentInput.value = "ordinary edit";
+ commentInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(mocks.buildTableStructureChangeSql).toHaveBeenCalled());
+ await vi.waitFor(() => expect(Array.from(errorRoot.querySelectorAll("button")).find((button) => button.textContent?.includes("structureEditor.apply"))?.disabled).toBe(false));
+ await expect(mountedEditor?.applyChanges()).resolves.toBe(true);
+ expect(mocks.executeBatch.mock.calls[mocks.executeBatch.mock.calls.length - 1]?.[2]).toEqual([structureStatement]);
+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
+ });
+
+ it("appends validated counter DDL and preserves the draft when execution fails", async () => {
+ const root = await mountEditor(true);
+ await vi.waitFor(() => expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe("10"));
+ const input = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")!;
+ input.value = "9007199254740993";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(mocks.buildMysqlAutoIncrementSql).toHaveBeenCalledWith(expect.objectContaining({ value: "9007199254740993" })));
+
+ mocks.executeBatch.mockRejectedValueOnce(new Error("ALTER command denied"));
+ await expect(mountedEditor?.applyChanges()).resolves.toBe(false);
+ await vi.waitFor(() => expect(root.textContent).toContain("ALTER command denied"));
+ expect(input.value).toBe("9007199254740993");
+ });
+
+ it("does not treat the requested value as persisted when the post-save metadata refresh fails", async () => {
+ const persistedColumn = draft(true).columns[0]!.original;
+ mocks.loadObjectMetadataFacet.mockImplementation(async (_request, facet: string) => ({
+ value: facet === "columns" ? [persistedColumn] : [],
+ cacheStatus: "remote",
+ }));
+ const root = await mountEditor(true);
+ await vi.waitFor(() => expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe("10"));
+ const input = root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")!;
+ input.value = "20";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(mocks.buildMysqlAutoIncrementSql).toHaveBeenCalledWith(expect.objectContaining({ value: "20" })));
+ const metadataCallsBeforeSave = mocks.getMysqlTableAutoIncrement.mock.calls.length;
+ mocks.getMysqlTableAutoIncrement.mockRejectedValueOnce(new Error("refresh denied"));
+ mocks.buildMysqlAutoIncrementSql.mockClear();
+
+ await expect(mountedEditor?.applyChanges()).resolves.toBe(true);
+ await vi.waitFor(() => expect(mocks.getMysqlTableAutoIncrement.mock.calls.length).toBeGreaterThan(metadataCallsBeforeSave));
+ await vi.waitFor(() => expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.title).toBe("refresh denied"));
+ expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe("20");
+ expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index aacb729736..7c0d702d08 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -32,6 +32,7 @@ import { invalidateObjectDdl, loadObjectDdl } from "@/lib/metadata/objectDdlCach
import { invalidateObjectMetadataCache, loadObjectMetadataFacet, type ObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";
import { invalidateTableMetadataCache } from "@/lib/metadata/tableMetadataCache";
import { type BuildTableStructureChangeSqlOptions, type EditableStructureColumn, type EditableStructureForeignKey, type EditableStructureIndex, type EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql";
+import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, refreshMysqlAutoIncrementCounterDraft } from "@/lib/table/mysqlAutoIncrementCounter";
import { PRESET_FIELDS_TEMPLATE_ID, createTableColumnTemplateDrafts } from "@/lib/table/tableColumnTemplates";
import { getMysqlDataTypeHelp } from "@/lib/table/mysqlDataTypeHelp";
import { getPostgresDataTypeHelp, gaussdbMTypeDisplayName } from "@/lib/table/postgresDataTypeHelp";
@@ -912,6 +913,10 @@ const canAddColumn = computed(() => canAddTableStructureColumn(databaseType.valu
const newTableName = ref("");
const tableComment = ref("");
const originalTableComment = ref("");
+const mysqlAutoIncrementValue = ref<string>();
+const originalMysqlAutoIncrementValue = ref<string>();
+const mysqlAutoIncrementLoading = ref(false);
+const mysqlAutoIncrementLoadError = ref("");
const tableOwner = ref("");
const originalTableOwner = ref("");
const tableOwnerLoading = ref(false);
@@ -920,6 +925,8 @@ const tableOwnerRoles = ref<string[]>([]);
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 tableOwnerOptions = computed(() => {
const owner = tableOwner.value;
if (!owner || tableOwnerRoles.value.includes(owner)) return tableOwnerRoles.value;
@@ -942,6 +949,7 @@ let sqlPreviewRequestId = 0;
let structureLoadRequestId = 0;
let tableOwnerLoadRequestId = 0;
let tableOwnerRolesLoadRequestId = 0;
+let mysqlAutoIncrementLoadRequestId = 0;
let dataTypeOptionsRequestId = 0;
let sqlPreviewDebounceTimer: ReturnType<typeof setTimeout> | undefined;
let deferredSqlPreviewRefresh = false;
@@ -1127,6 +1135,8 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {
newTableName: newTableName.value,
tableComment: tableComment.value,
originalTableComment: originalTableComment.value,
+ mysqlAutoIncrementValue: mysqlAutoIncrementValue.value,
+ originalMysqlAutoIncrementValue: originalMysqlAutoIncrementValue.value,
tableOwner: tableOwner.value,
originalTableOwner: originalTableOwner.value,
columns: cloneDraftValue(columns.value),
@@ -1157,6 +1167,8 @@ function restoreDraft(draft: TableStructureEditorDraft) {
newTableName.value = draft.newTableName || "";
tableComment.value = draft.tableComment || "";
originalTableComment.value = draft.originalTableComment || "";
+ mysqlAutoIncrementValue.value = draft.mysqlAutoIncrementValue;
+ originalMysqlAutoIncrementValue.value = draft.originalMysqlAutoIncrementValue;
tableOwner.value = draft.tableOwner || "";
originalTableOwner.value = draft.originalTableOwner || "";
columns.value = cloneDraftValue(draft.columns || []);
@@ -1243,7 +1255,15 @@ function hasPendingStructureChanges(): boolean {
return !!newTableName.value.trim() || !!tableComment.value.trim() || columns.value.length > 0 || indexes.value.length > 0 || foreignKeys.value.length > 0 || triggers.value.length > 0;
}
const scope = captureStructureRefreshScope();
- return scope.columns || scope.indexes || scope.foreignKeys || scope.triggers || scope.tableComment || (supportsTableOwner.value && tableOwner.value.trim() !== originalTableOwner.value.trim());
+ return (
+ scope.columns ||
+ scope.indexes ||
+ scope.foreignKeys ||
+ scope.triggers ||
+ scope.tableComment ||
+ (canBuildMysqlAutoIncrement.value && mysqlAutoIncrementValue.value !== originalMysqlAutoIncrementValue.value) ||
+ (supportsTableOwner.value && tableOwner.value.trim() !== originalTableOwner.value.trim())
+ );
}
function clearSqlPreviewState() {
@@ -1426,18 +1446,30 @@ async function refreshSqlPreview() {
sqlPreviewLoading.value = true;
const options = structureChangeOptions();
try {
- const result = isCreateMode.value ? await api.buildCreateTableSql(options) : hasSqliteTypeChange.value ? await api.previewSqliteTableStructureChange(props.connectionId, props.database, options) : await api.buildTableStructureChangeSql(options);
- const ownerResult = supportsTableOwner.value
- ? await api.buildTableOwnerChangeSql({
- databaseType: databaseType.value,
- schema: metadataSchema.value,
- tableName: props.tableName || "",
- owner: tableOwner.value,
- originalOwner: originalTableOwner.value,
- })
- : { statements: [], warnings: [] };
+ const [result, ownerResult, mysqlAutoIncrementStatement] = await Promise.all([
+ isCreateMode.value ? api.buildCreateTableSql(options) : hasSqliteTypeChange.value ? api.previewSqliteTableStructureChange(props.connectionId, props.database, options) : api.buildTableStructureChangeSql(options),
+ supportsTableOwner.value
+ ? api.buildTableOwnerChangeSql({
+ databaseType: databaseType.value,
+ schema: metadataSchema.value,
+ tableName: props.tableName || "",
+ owner: tableOwner.value,
+ originalOwner: originalTableOwner.value,
+ })
+ : Promise.resolve({ statements: [], warnings: [] }),
+ buildMysqlAutoIncrementCounterStatement({
+ enabled: canBuildMysqlAutoIncrement.value,
+ originalValue: originalMysqlAutoIncrementValue.value,
+ value: mysqlAutoIncrementValue.value,
+ databaseType: databaseType.value,
+ driverProfile: connection.value?.driver_profile,
+ schema: props.schema || props.database,
+ tableName: props.tableName || "",
+ buildSql: api.buildMysqlAutoIncrementSql,
+ }),
+ ]);
if (requestId !== sqlPreviewRequestId) return;
- pendingStatements.value = [...result.statements, ...ownerResult.statements];
+ pendingStatements.value = [...result.statements, ...ownerResult.statements, ...(mysqlAutoIncrementStatement ? [mysqlAutoIncrementStatement] : [])];
warnings.value = [...result.warnings, ...ownerResult.warnings];
sqliteSchemaRevision.value = "schemaRevision" in result && typeof result.schemaRevision === "string" ? result.schemaRevision : undefined;
} catch (e: any) {
@@ -1505,6 +1537,11 @@ function resetState() {
newTableName.value = "";
tableComment.value = "";
originalTableComment.value = "";
+ mysqlAutoIncrementValue.value = undefined;
+ originalMysqlAutoIncrementValue.value = undefined;
+ mysqlAutoIncrementLoadRequestId += 1;
+ mysqlAutoIncrementLoading.value = false;
+ mysqlAutoIncrementLoadError.value = "";
tableOwner.value = "";
originalTableOwner.value = "";
tableOwnerLoadRequestId += 1;
@@ -1578,6 +1615,32 @@ function loadCachedTableComment(request: ReturnType<typeof ddlRequest>, force =
return loadObjectMetadataFacet(request, "comment", () => fetchTableCommentValue(request.connectionId, request.database, request.schema, request.tableName, request.catalog), { force });
}
+async function loadMysqlAutoIncrementCounter(preserveDraft = false) {
+ const requestId = ++mysqlAutoIncrementLoadRequestId;
+ if (!canEditMysqlAutoIncrement.value || !props.connectionId || !props.database || !props.tableName) {
+ mysqlAutoIncrementValue.value = undefined;
+ originalMysqlAutoIncrementValue.value = undefined;
+ mysqlAutoIncrementLoading.value = false;
+ mysqlAutoIncrementLoadError.value = "";
+ return;
+ }
+ mysqlAutoIncrementLoading.value = true;
+ mysqlAutoIncrementLoadError.value = "";
+ try {
+ await store.ensureConnected(props.connectionId);
+ const value = await api.getMysqlTableAutoIncrement(props.connectionId, props.database, props.tableName);
+ if (requestId !== mysqlAutoIncrementLoadRequestId) return;
+ const draft = refreshMysqlAutoIncrementCounterDraft(value, { value: mysqlAutoIncrementValue.value, originalValue: originalMysqlAutoIncrementValue.value }, preserveDraft);
+ originalMysqlAutoIncrementValue.value = draft.originalValue;
+ mysqlAutoIncrementValue.value = draft.value;
+ } catch (error: any) {
+ if (requestId !== mysqlAutoIncrementLoadRequestId) return;
+ mysqlAutoIncrementLoadError.value = error?.message || String(error);
+ } finally {
+ if (requestId === mysqlAutoIncrementLoadRequestId) mysqlAutoIncrementLoading.value = false;
+ }
+}
+
async function loadTableOwner(force = false, preserveDraft = false) {
const connectionId = props.connectionId;
const database = props.database;
@@ -1712,6 +1775,8 @@ async function loadStructure(
if (!options.preserveDraft) clearColumnSelection();
}
+ await loadMysqlAutoIncrementCounter(options.preserveDraft === true);
+
const nextTableComment = await tableCommentPromise;
if (nextTableComment !== undefined) {
originalTableComment.value = nextTableComment;
@@ -1792,6 +1857,7 @@ async function refreshStructureAfterSave(scope: TableStructureRefreshScope, char
console.warn("[DBX][structure-editor:post-save-refresh-failed]", e);
} finally {
postSaveRefreshing.value = false;
+ if (mysqlAutoIncrementValue.value !== originalMysqlAutoIncrementValue.value) scheduleSqlPreviewRefresh();
if (activeTab.value === "ddl") void fetchDdl(true);
}
}
@@ -3291,6 +3357,7 @@ onMounted(() => {
if (props.draft?.initialized) {
void hydrateRestoredDraftFromDatabase().then(() => {
applyInitialStructureTarget();
+ void loadMysqlAutoIncrementCounter(true);
void loadActiveTableStructureMetadataIfNeeded();
});
} else if (isCreateMode.value) {
@@ -3313,6 +3380,7 @@ onActivated(() => {
applyInitialStructureTarget();
void hydrateRestoredDraftFromDatabase().then(() => {
applyInitialStructureTarget();
+ void loadMysqlAutoIncrementCounter(true);
void loadActiveTableStructureMetadataIfNeeded();
});
}
@@ -3422,7 +3490,25 @@ watch([() => props.connectionId, () => props.database, databaseType], () => {
});
watch(
- [isCreateMode, () => props.connectionId, () => props.database, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, tableOwner, columns, indexes, foreignKeys, triggers],
+ [
+ isCreateMode,
+ () => props.connectionId,
+ () => props.database,
+ databaseType,
+ () => props.schema,
+ () => props.tableName,
+ newTableName,
+ tableComment,
+ mysqlAutoIncrementValue,
+ originalMysqlAutoIncrementValue,
+ mysqlAutoIncrementLoading,
+ mysqlAutoIncrementLoadError,
+ tableOwner,
+ columns,
+ indexes,
+ foreignKeys,
+ triggers,
+ ],
() => {
scheduleSqlPreviewRefresh();
syncDraftToParent();
@@ -3539,6 +3625,26 @@ watch([activeTab, ddlLoading], ([tab, loading]) => {
</Tooltip>
</div>
+ <div v-if="canEditMysqlAutoIncrement" class="flex shrink-0 items-center gap-2">
+ <label class="shrink-0 font-medium text-muted-foreground">AUTO_INCREMENT</label>
+ <Input
+ v-model="mysqlAutoIncrementValue"
+ inputmode="numeric"
+ autocomplete="off"
+ data-mysql-auto-increment-counter
+ :placeholder="mysqlAutoIncrementLoading ? t('common.loading') : '—'"
+ :title="mysqlAutoIncrementLoadError || undefined"
+ :class="[structureMonoControlClass, 'max-w-[220px]']"
+ :disabled="mysqlAutoIncrementLoading || !!mysqlAutoIncrementLoadError || originalMysqlAutoIncrementValue === undefined || saving"
+ />
+ <Tooltip v-if="mysqlAutoIncrementLoadError">
+ <TooltipTrigger as-child>
+ <AlertTriangle :class="[structureIconClass, 'shrink-0 text-destructive']" />
+ </TooltipTrigger>
+ <TooltipContent>{{ mysqlAutoIncrementLoadError }}</TooltipContent>
+ </Tooltip>
+ </div>
+
<div v-if="supportsTableOwner" class="flex shrink-0 items-center gap-2">
<label class="flex shrink-0 items-center gap-1 font-medium text-muted-foreground">
<UserRound :class="structureIconClass" />
diff --git a/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts b/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts
new file mode 100644
index 0000000000..5769737d3f
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/mysqlAutoIncrementCounter.spec.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it, vi } from "vitest";
+import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, mysqlAutoIncrementCounterDraft, refreshMysqlAutoIncrementCounterDraft } from "@/lib/table/mysqlAutoIncrementCounter";
+
+function existingColumn(autoIncrement: boolean) {
+ return {
+ original: { name: "id" },
+ markedForDrop: false,
+ extra: { autoIncrement },
+ } as any;
+}
+
+describe("MySQL table AUTO_INCREMENT counter", () => {
+ it("keeps present and NULL metadata distinct without numeric conversion", () => {
+ expect(mysqlAutoIncrementCounterDraft("9007199254740993")).toEqual({
+ value: "9007199254740993",
+ originalValue: "9007199254740993",
+ });
+ expect(mysqlAutoIncrementCounterDraft("18446744073709551615")).toEqual({
+ value: "18446744073709551615",
+ originalValue: "18446744073709551615",
+ });
+ expect(mysqlAutoIncrementCounterDraft(null)).toEqual({ value: undefined, originalValue: undefined });
+ });
+
+ it("refreshes restored clean drafts and rebases restored dirty drafts on live metadata", () => {
+ expect(refreshMysqlAutoIncrementCounterDraft("30", { value: "10", originalValue: "10" }, true)).toEqual({
+ value: "30",
+ originalValue: "30",
+ });
+ expect(refreshMysqlAutoIncrementCounterDraft("15", { value: "20", originalValue: "10" }, true)).toEqual({
+ value: "20",
+ originalValue: "15",
+ });
+ expect(refreshMysqlAutoIncrementCounterDraft(null, { value: "20", originalValue: "10" }, true)).toEqual({
+ value: "20",
+ originalValue: undefined,
+ });
+ });
+
+ it("is editable only for existing native-MySQL tables with an active existing auto-increment column", () => {
+ const nativeMysql = { db_type: "mysql", driver_profile: "mysql" } as any;
+ expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [existingColumn(true)])).toBe(true);
+ expect(canEditMysqlAutoIncrementCounter(nativeMysql, true, [existingColumn(true)])).toBe(false);
+ expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [existingColumn(false)])).toBe(false);
+ expect(canEditMysqlAutoIncrementCounter(nativeMysql, false, [{ ...existingColumn(true), markedForDrop: true }])).toBe(false);
+
+ for (const connection of [
+ { db_type: "jdbc", driver_profile: "mysql" },
+ { db_type: "mysql", driver_profile: "mariadb" },
+ { db_type: "mysql", driver_profile: "tidb" },
+ { db_type: "mysql", driver_profile: "oceanbase" },
+ { db_type: "mysql", driver_profile: "dolt" },
+ { db_type: "goldendb", driver_profile: "goldendb" },
+ ] as const) {
+ expect(canEditMysqlAutoIncrementCounter(connection as any, false, [existingColumn(true)])).toBe(false);
+ }
+ });
+
+ it("emits no DDL when unchanged and delegates changed values to the existing builder", async () => {
+ const buildSql = vi.fn(async ({ value }: { value: string }) => `ALTER TABLE \`sales\`.\`events\` AUTO_INCREMENT = ${value};`);
+ const common = {
+ enabled: true,
+ originalValue: "1",
+ databaseType: "mysql" as const,
+ driverProfile: "mysql",
+ schema: "sales",
+ tableName: "events",
+ buildSql,
+ };
+
+ await expect(buildMysqlAutoIncrementCounterStatement({ ...common, value: "1" })).resolves.toBeUndefined();
+ expect(buildSql).not.toHaveBeenCalled();
+
+ await expect(buildMysqlAutoIncrementCounterStatement({ ...common, value: "18446744073709551615" })).resolves.toContain("18446744073709551615");
+ expect(buildSql).toHaveBeenCalledWith(expect.objectContaining({ value: "18446744073709551615" }));
+ });
+
+ it("does not emit when metadata is unavailable and preserves builder validation errors", async () => {
+ const buildSql = vi.fn(async () => {
+ throw new Error("AUTO_INCREMENT must be a decimal integer");
+ });
+ const common = {
+ enabled: true,
+ databaseType: "mysql" as const,
+ driverProfile: "mysql",
+ schema: "sales",
+ tableName: "events",
+ buildSql,
+ };
+
+ await expect(buildMysqlAutoIncrementCounterStatement({ ...common, originalValue: undefined, value: undefined })).resolves.toBeUndefined();
+ await expect(buildMysqlAutoIncrementCounterStatement({ ...common, originalValue: "1", value: "1e3" })).rejects.toThrow("AUTO_INCREMENT must be a decimal integer");
+ });
+});
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 2efa2150e8..d0966feeb5 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -161,6 +161,7 @@ export const listSchemas = forward("listSchemas");
export const listSchemaInfos = forward("listSchemaInfos");
export const listTables = forward("listTables");
export const getTableComment = forward("getTableComment");
+export const getMysqlTableAutoIncrement = forward("getMysqlTableAutoIncrement");
export const listObjects = forward("listObjects");
export const listObjectStatistics = forward("listObjectStatistics");
export const listCompletionObjects = forward("listCompletionObjects");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 193ac546ae..a7ed8f6012 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -831,6 +831,10 @@ export async function getTableComment(_connectionId: string, _database: string,
throw new Error("Table comment lookup is not available in the web backend");
}
+export async function getMysqlTableAutoIncrement(_connectionId: string, _database: string, _table: string): Promise<string | null> {
+ throw new Error("MySQL AUTO_INCREMENT metadata is not available in the web backend");
+}
+
export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: TableNameFilter): Promise<ObjectInfo[]> {
return get(
`/api/schema/objects?${qs({
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 9ea3c95dfc..54bcb52e76 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1109,6 +1109,10 @@ export async function getTableComment(connectionId: string, database: string, sc
});
}
+export async function getMysqlTableAutoIncrement(connectionId: string, database: string, table: string): Promise<string | null> {
+ return invoke("get_mysql_table_auto_increment", { connectionId, database, table });
+}
+
export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string, tableNameFilter?: import("@/types/database").TableNameFilter): Promise<ObjectInfo[]> {
return invoke("list_objects", {
connectionId,
diff --git a/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts b/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts
new file mode 100644
index 0000000000..9f0b14611b
--- /dev/null
+++ b/apps/desktop/src/lib/table/mysqlAutoIncrementCounter.ts
@@ -0,0 +1,40 @@
+import type { ConnectionConfig, DatabaseType } from "@/types/database";
+import { supportsNativeMysqlAutoIncrement, type MysqlAutoIncrementSqlOptions } from "@/lib/database/dbAdminSql";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+
+export interface MysqlAutoIncrementCounterDraft {
+ value: string | undefined;
+ originalValue: string | undefined;
+}
+
+export function mysqlAutoIncrementCounterDraft(value: string | null): MysqlAutoIncrementCounterDraft {
+ const current = value ?? undefined;
+ return { value: current, originalValue: current };
+}
+
+export function refreshMysqlAutoIncrementCounterDraft(serverValue: string | null, current: MysqlAutoIncrementCounterDraft, preserveDraft: boolean): MysqlAutoIncrementCounterDraft {
+ const server = mysqlAutoIncrementCounterDraft(serverValue);
+ if (!preserveDraft || current.value === current.originalValue) return server;
+ return { 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;
+ return columns.some((column) => !!column.original && !column.markedForDrop && column.extra.autoIncrement === true);
+}
+
+export interface BuildMysqlAutoIncrementCounterStatementOptions extends Omit<MysqlAutoIncrementSqlOptions, "databaseType" | "value"> {
+ enabled: boolean;
+ databaseType: DatabaseType | undefined;
+ value: string | undefined;
+ originalValue: string | undefined;
+ buildSql: (options: MysqlAutoIncrementSqlOptions) => Promise<string>;
+}
+
+export async function buildMysqlAutoIncrementCounterStatement({ enabled, originalValue, buildSql, ...options }: BuildMysqlAutoIncrementCounterStatementOptions): Promise<string | undefined> {
+ const { databaseType, value } = options;
+ if (!enabled || databaseType === undefined || originalValue === undefined || value === undefined || value === originalValue) {
+ return undefined;
+ }
+ return buildSql({ ...options, databaseType, value });
+}
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 0e30558cdb..3d10b6e162 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1018,6 +1018,8 @@ export interface TableStructureEditorDraft {
newTableName: string;
tableComment: string;
originalTableComment: string;
+ mysqlAutoIncrementValue?: string;
+ originalMysqlAutoIncrementValue?: string;
tableOwner?: string;
originalTableOwner?: string;
columns: import("@/lib/table/tableStructureEditorSql").EditableStructureColumn[];
diff --git a/crates/dbx-core/src/db/mysql.rs b/crates/dbx-core/src/db/mysql.rs
index aaf0d9b25c..3451e59b85 100644
--- a/crates/dbx-core/src/db/mysql.rs
+++ b/crates/dbx-core/src/db/mysql.rs
@@ -320,6 +320,19 @@ fn get_opt_metadata_string(row: &mysql_async::Row, name: &str) -> Option<String>
.or_else(|| row_get::<NaiveTime, _>(row, name).map(|value| value.to_string()))
}
+fn get_opt_unsigned_metadata_string(row: &mysql_async::Row, name: &str) -> Option<String> {
+ row_get::<u64, _>(row, name)
+ .map(|value| value.to_string())
+ .or_else(|| {
+ row_get::<i64, _>(row, name).and_then(|value| u64::try_from(value).ok()).map(|value| value.to_string())
+ })
+ .or_else(|| {
+ get_opt_str(row, name)
+ .filter(|value| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()))
+ .and_then(|value| value.parse::<u64>().ok().map(|parsed| parsed.to_string()))
+ })
+}
+
fn numeric_metadata_u64_to_i32(value: Option<u64>) -> Option<i32> {
value.and_then(|v| i32::try_from(v).ok())
}
@@ -2842,8 +2855,11 @@ pub(super) struct TableStatusMeta {
comment: Option<String>,
created_at: Option<String>,
updated_at: Option<String>,
+ auto_increment: Option<String>,
}
+const MYSQL_FRESH_TABLE_STATUS_SESSION_SQL: &str = "/*!80000 SET SESSION information_schema_stats_expiry = 0 */";
+
async fn list_table_status_show(pool: &MySqlPool, database: &str) -> Result<HashMap<String, TableStatusMeta>, String> {
query_table_status_show(pool, database, None).await
}
@@ -2872,8 +2888,19 @@ async fn query_table_status_show(
filter: Option<&str>,
) -> Result<HashMap<String, TableStatusMeta>, String> {
let sql = show_table_status_sql(database, filter);
+ query_table_status_sql(pool, &sql).await
+}
+
+async fn query_table_status_sql(pool: &MySqlPool, sql: &str) -> Result<HashMap<String, TableStatusMeta>, String> {
let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
- let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;
+ query_table_status_sql_with_conn(&mut conn, sql).await
+}
+
+async fn query_table_status_sql_with_conn(
+ conn: &mut mysql_async::Conn,
+ sql: &str,
+) -> Result<HashMap<String, TableStatusMeta>, String> {
+ let result = conn.query_iter(sql).await.map_err(|e| e.to_string())?;
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
Ok(rows
.iter()
@@ -2886,6 +2913,7 @@ async fn query_table_status_show(
.filter(|s| !s.is_empty()),
created_at: get_opt_metadata_string(row, "Create_time"),
updated_at: get_opt_metadata_string(row, "Update_time"),
+ auto_increment: get_opt_unsigned_metadata_string(row, "Auto_increment"),
},
)
})
@@ -2893,6 +2921,17 @@ async fn query_table_status_show(
.collect())
}
+pub async fn get_table_auto_increment(pool: &MySqlPool, database: &str, table: &str) -> Result<Option<String>, String> {
+ let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
+ // MySQL 8 caches SHOW TABLE STATUS statistics by default, including the
+ // counter after ALTER TABLE. The version comment is a no-op on MySQL 5.7.
+ if let Err(error) = conn.query_drop(MYSQL_FRESH_TABLE_STATUS_SESSION_SQL).await {
+ log::debug!("Failed to disable cached MySQL table statistics before reading AUTO_INCREMENT: {error}");
+ }
+ let status = query_table_status_sql_with_conn(&mut conn, &show_table_status_exact_sql(database, table)).await?;
+ Ok(status.into_values().next().and_then(|meta| meta.auto_increment))
+}
+
fn filter_table_status_fallback(
status: HashMap<String, TableStatusMeta>,
filter: Option<&str>,
@@ -3067,6 +3106,15 @@ fn show_table_status_sql(database: &str, filter: Option<&str>) -> String {
sql
}
+fn show_table_status_exact_sql(database: &str, table: &str) -> String {
+ let prefix = if database.trim().is_empty() {
+ "SHOW TABLE STATUS".to_string()
+ } else {
+ format!("SHOW TABLE STATUS FROM {}", quote_identifier(database))
+ };
+ format!("{prefix} WHERE Name = {}", quote_value(table))
+}
+
fn show_tables_filter_conditions(database: &str, filter: Option<&str>, exact_names: &[String]) -> Vec<String> {
if database.trim().is_empty() {
// Catalogless services do not expose a stable Tables_in_<db> column name.
@@ -6506,6 +6554,33 @@ mod tests {
assert_eq!(filtered.keys().map(String::as_str).collect::<Vec<_>>(), vec!["orders"]);
}
+ #[test]
+ fn mysql_table_status_auto_increment_is_lossless_and_nullable() {
+ let auto_increment_column = Column::new(ColumnType::MYSQL_TYPE_LONGLONG).with_name(b"Auto_increment");
+ let maximum = mysql_test_row_with_columns(vec![Value::UInt(u64::MAX)], vec![auto_increment_column.clone()]);
+ let null = mysql_test_row_with_columns(vec![Value::NULL], vec![auto_increment_column]);
+
+ assert_eq!(
+ get_opt_unsigned_metadata_string(&maximum, "Auto_increment").as_deref(),
+ Some("18446744073709551615")
+ );
+ assert_eq!(get_opt_unsigned_metadata_string(&null, "Auto_increment"), None);
+ }
+
+ #[test]
+ fn mysql_exact_table_status_sql_quotes_identifiers_and_names() {
+ assert_eq!(
+ show_table_status_exact_sql("sales`archive", "order's"),
+ "SHOW TABLE STATUS FROM `sales``archive` WHERE Name = 'order\\'s'"
+ );
+ }
+
+ #[test]
+ fn mysql_table_status_refresh_directive_is_version_gated() {
+ assert!(MYSQL_FRESH_TABLE_STATUS_SESSION_SQL.starts_with("/*!80000 "));
+ assert!(MYSQL_FRESH_TABLE_STATUS_SESSION_SQL.contains("information_schema_stats_expiry = 0"));
+ }
+
#[test]
fn mysql_list_tables_sql_applies_table_name_filter_before_pagination() {
let filter = TableNameFilter {
diff --git a/crates/dbx-core/src/db_admin_sql.rs b/crates/dbx-core/src/db_admin_sql.rs
index eece852b1c..e211c2a904 100644
--- a/crates/dbx-core/src/db_admin_sql.rs
+++ b/crates/dbx-core/src/db_admin_sql.rs
@@ -1761,19 +1761,22 @@ mod tests {
#[test]
fn builds_mysql_auto_increment_sql_and_rejects_invalid_values() {
- let options = MysqlAutoIncrementSqlOptions {
- database_type: Some(DatabaseType::Mysql),
- driver_profile: Some("mysql".to_string()),
- schema: Some("sales`archive".to_string()),
- table_name: "order`items".to_string(),
- value: "18446744073709551615".to_string(),
- };
- assert_eq!(
- build_mysql_auto_increment_sql(options),
- Ok("ALTER TABLE `sales``archive`.`order``items` AUTO_INCREMENT = 18446744073709551615;".to_string())
- );
+ for value in ["1", "9007199254740993", "18446744073709551615"] {
+ assert_eq!(
+ build_mysql_auto_increment_sql(MysqlAutoIncrementSqlOptions {
+ database_type: Some(DatabaseType::Mysql),
+ driver_profile: Some("mysql".to_string()),
+ schema: Some("sales`archive".to_string()),
+ table_name: "order`items".to_string(),
+ value: value.to_string(),
+ }),
+ Ok(format!("ALTER TABLE `sales``archive`.`order``items` AUTO_INCREMENT = {value};"))
+ );
+ }
- for value in ["", "0", "01", " 1", "1 ", "+1", "-1", "1; DROP TABLE users", "18446744073709551616"] {
+ for value in
+ ["", "0", "01", " 1", "1 ", "+1", "-1", "1.0", "1e3", "1; DROP TABLE users", "18446744073709551616"]
+ {
assert!(
build_mysql_auto_increment_sql(MysqlAutoIncrementSqlOptions {
database_type: Some(DatabaseType::Mysql),
diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rs
index 9c45fd6dfa..b2fcdf829a 100644
--- a/crates/dbx-core/src/schema.rs
+++ b/crates/dbx-core/src/schema.rs
@@ -1162,6 +1162,38 @@ pub async fn get_table_comment_core(
result
}
+pub async fn get_mysql_table_auto_increment_core(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ table: &str,
+) -> Result<Option<String>, String> {
+ let db_config = connection_config(state, connection_id).await;
+ let native_mysql = db_config.as_ref().is_some_and(|config| {
+ config.db_type == DatabaseType::Mysql
+ && config
+ .driver_profile
+ .as_deref()
+ .map(str::trim)
+ .is_none_or(|profile| profile.is_empty() || profile.eq_ignore_ascii_case("mysql"))
+ });
+ if !native_mysql {
+ return Err("AUTO_INCREMENT metadata is supported only for native MySQL connections.".to_string());
+ }
+
+ retry_metadata_connection_for_session(state, connection_id, Some(database), None, || async {
+ let pool_key = state.get_or_create_metadata_pool_for_session(connection_id, Some(database), None).await?;
+ let pool = clone_metadata_pool(state, &pool_key).await.ok_or("Pool not found")?;
+ match &pool {
+ PoolKind::Mysql(pool, mode) if *mode != MysqlMode::OceanBaseOracle => {
+ db::mysql::get_table_auto_increment(pool, database, table).await
+ }
+ _ => Err("AUTO_INCREMENT metadata is supported only for native MySQL connections.".to_string()),
+ }
+ })
+ .await
+}
+
async fn get_table_comment_core_for_session(
state: &AppState,
connection_id: &str,
diff --git a/src-tauri/src/commands/schema.rs b/src-tauri/src/commands/schema.rs
index c5cd4f39df..239f9a2dee 100644
--- a/src-tauri/src/commands/schema.rs
+++ b/src-tauri/src/commands/schema.rs
@@ -210,6 +210,16 @@ pub async fn get_table_comment(
dbx_core::schema::get_table_comment_core(&state, &connection_id, &database, &schema, &table).await
}
+#[tauri::command]
+pub async fn get_mysql_table_auto_increment(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ database: String,
+ table: String,
+) -> Result<Option<String>, String> {
+ dbx_core::schema::get_mysql_table_auto_increment_core(&state, &connection_id, &database, &table).await
+}
+
#[tauri::command]
pub async fn list_objects(
state: State<'_, Arc<AppState>>,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c445150b06..871bae4387 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1906,6 +1906,7 @@ pub fn run() {
commands::schema::list_sqlserver_linked_server_tables,
commands::schema::list_tables,
commands::schema::get_table_comment,
+ commands::schema::get_mysql_table_auto_increment,
commands::schema::list_objects,
commands::schema::list_object_statistics,
commands::schema::list_completion_objects,