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。

fix(mysql): edit table charset without rebuilding table

Xsyl.way338c2202ae5d
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
index 307681e5b1..a76394ee00 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
@@ -186,7 +186,7 @@ vi.mock("@/components/ui/searchable-select", async () => {
"data-model-value": props.modelValue,
"data-options": JSON.stringify(props.options),
"data-allow-custom": String(props.allowCustom),
- onClick: () => emit("update:modelValue", "custom_domain"),
+ onClick: () => emit("update:modelValue", "data-mysql-table-charset-select" in attrs ? "utf8mb4" : "data-mysql-table-collation-select" in attrs ? "utf8mb4_bin" : "custom_domain"),
}),
}),
};
@@ -316,6 +316,10 @@ function searchableSelectInColumn(root: HTMLElement, header: string): HTMLButton
return select;
}
+function queryResult(columns: string[], rows: unknown[][]): { columns: string[]; rows: unknown[][]; affected_rows: number; execution_time_ms: number } {
+ return { columns, rows, affected_rows: 0, execution_time_ms: 1 };
+}
+
beforeEach(() => {
vi.clearAllMocks();
mocks.connection.db_type = "mysql";
@@ -367,6 +371,60 @@ describe("TableStructureEditor charset/collation column width", () => {
});
});
+describe("TableStructureEditor MySQL table charset and collation", () => {
+ it("loads the table defaults and previews only the selected table-default change", async () => {
+ mocks.executeQuery.mockImplementation(async (_connectionId, _database, sql: string) => {
+ if (sql === "SHOW CHARACTER SET") {
+ return queryResult(
+ ["Charset", "Default collation"],
+ [
+ ["utf8mb4", "utf8mb4_0900_ai_ci"],
+ ["utf8mb3", "utf8mb3_general_ci"],
+ ],
+ );
+ }
+ if (sql === "SHOW COLLATION") {
+ return queryResult(
+ ["Collation", "Charset", "Default"],
+ [
+ ["utf8mb4_0900_ai_ci", "utf8mb4", "Yes"],
+ ["utf8mb4_bin", "utf8mb4", ""],
+ ["utf8mb3_general_ci", "utf8mb3", "Yes"],
+ ],
+ );
+ }
+ if (sql.includes("information_schema.TABLES")) return queryResult(["TABLE_COLLATION"], [["utf8mb3_general_ci"]]);
+ return queryResult([], []);
+ });
+
+ const root = await mountEditor();
+ const charsetSelect = await vi.waitFor(() => {
+ const select = root.querySelector<HTMLButtonElement>("[data-mysql-table-charset-select]");
+ expect(select).not.toBeNull();
+ return select!;
+ });
+ await vi.waitFor(() => expect(charsetSelect.dataset.modelValue).toBe("utf8mb3"));
+ expect(root.querySelector<HTMLButtonElement>("[data-mysql-table-collation-select]")?.dataset.modelValue).toBe("utf8mb3_general_ci");
+ expect(JSON.parse(charsetSelect.dataset.options ?? "[]")).toContain("utf8mb4");
+
+ charsetSelect.click();
+ await vi.waitFor(() =>
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenLastCalledWith(expect.objectContaining({ tableName: "users" }), undefined, {
+ charset: "utf8mb4",
+ collation: "utf8mb4_0900_ai_ci",
+ }),
+ );
+
+ root.querySelector<HTMLButtonElement>("[data-mysql-table-collation-select]")!.click();
+ await vi.waitFor(() =>
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenLastCalledWith(expect.objectContaining({ tableName: "users" }), undefined, {
+ charset: "utf8mb4",
+ collation: "utf8mb4_bin",
+ }),
+ );
+ });
+});
+
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);
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index da3312ff4c..6f5e55dac6 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -107,6 +107,7 @@ import {
type EditableStructureForeignKey,
type EditableStructureIndex,
type EditableStructureTrigger,
+ type MysqlTableCharsetChange,
type OracleConstraintChange,
type OracleConstraintDefinition,
type TablePartitionBoundDraft,
@@ -115,7 +116,7 @@ import {
type TablePartitionSqlOptions,
} from "@/lib/table/tableStructureEditorSql";
import { buildMysqlAutoIncrementCounterStatement, canEditMysqlAutoIncrementCounter, refreshMysqlAutoIncrementCounterDraft, translateMysqlAutoIncrementWarning } from "@/lib/table/mysqlAutoIncrementCounter";
-import { mysqlTableCollationSql, parseMysqlTableCollation } from "@/lib/table/mysqlTableCollation";
+import { mysqlTableCollationSql, parseMysqlTableCharset } 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";
import { PRESET_FIELDS_TEMPLATE_ID, createTableColumnTemplateDrafts } from "@/lib/table/tableColumnTemplates";
@@ -1629,6 +1630,22 @@ const charsetMetadataLoading = ref(false);
// The table's own default collation, used only to keep inherited charsets out of the
// generated DDL. Columns keep the real values MySQL reports so the pickers stay filled.
const mysqlTableDefaultCollation = ref("");
+const mysqlTableCharset = ref("");
+const originalMysqlTableCharset = ref("");
+const mysqlTableCollation = ref("");
+const originalMysqlTableCollation = ref("");
+const mysqlTableCharsetChanged = computed(() => mysqlTableCharset.value.trim().toLowerCase() !== originalMysqlTableCharset.value.trim().toLowerCase() || mysqlTableCollation.value.trim().toLowerCase() !== originalMysqlTableCollation.value.trim().toLowerCase());
+
+const mysqlTableCharsetChange = computed<MysqlTableCharsetChange | undefined>(() => {
+ const profile = connection.value?.driver_profile?.trim().toLowerCase();
+ if (isCreateMode.value || databaseType.value !== "mysql" || connection.value?.db_type !== "mysql" || (profile && profile !== "mysql") || !mysqlTableCharsetChanged.value) return undefined;
+ const charset = mysqlTableCharset.value.trim();
+ if (!charset) return undefined;
+ return {
+ charset,
+ collation: mysqlTableCollation.value.trim() || undefined,
+ };
+});
const mysqlCharsetOptions = computed<string[]>(() => {
const meta = serverCharsetMetadata.value;
@@ -1660,12 +1677,24 @@ async function loadCharsetMetadata() {
async function loadMysqlTableDefaultCollation() {
if (!showCharacterSet.value || isCreateMode.value || !props.connectionId || !props.database || !props.tableName) {
mysqlTableDefaultCollation.value = "";
+ mysqlTableCharset.value = "";
+ originalMysqlTableCharset.value = "";
+ mysqlTableCollation.value = "";
+ originalMysqlTableCollation.value = "";
return;
}
+ const preserveEditedValues = mysqlTableCharsetChanged.value;
try {
await store.ensureConnected(props.connectionId);
const result = await api.executeQuery(props.connectionId, props.database, mysqlTableCollationSql(props.database, props.tableName), undefined, undefined, { maxRows: 1 });
- mysqlTableDefaultCollation.value = parseMysqlTableCollation(result);
+ const metadata = parseMysqlTableCharset(result);
+ mysqlTableDefaultCollation.value = metadata.collation;
+ originalMysqlTableCharset.value = metadata.charset;
+ originalMysqlTableCollation.value = metadata.collation;
+ if (!preserveEditedValues) {
+ mysqlTableCharset.value = metadata.charset;
+ mysqlTableCollation.value = metadata.collation;
+ }
} catch {
// Optional metadata: without it the DDL just spells out the charset the column
// already has, which is equivalent SQL — never block the editor on this lookup.
@@ -1673,6 +1702,14 @@ async function loadMysqlTableDefaultCollation() {
}
}
+function onMysqlTableCharsetChange(value: string) {
+ mysqlTableCharset.value = value;
+ const collationCharset = mysqlTableCollation.value.split("_", 1)[0]?.toLowerCase();
+ if (mysqlTableCollation.value && collationCharset !== value.trim().toLowerCase()) {
+ mysqlTableCollation.value = collationOptionsForCharset(value)[0] ?? "";
+ }
+}
+
function onCharsetChange(column: EditableStructureColumn, charset: string) {
column.characterSet = charset;
// If the collation is no longer valid for the new charset, clear it so the
@@ -2733,6 +2770,10 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {
originalMysqlAutoIncrementValue: originalMysqlAutoIncrementValue.value,
mysqlTableEngine: mysqlTableEngine.value,
originalMysqlTableEngine: originalMysqlTableEngine.value,
+ mysqlTableCharset: mysqlTableCharset.value,
+ originalMysqlTableCharset: originalMysqlTableCharset.value,
+ mysqlTableCollation: mysqlTableCollation.value,
+ originalMysqlTableCollation: originalMysqlTableCollation.value,
physicalOptions: cloneDraftValue(physicalOptions.value),
starrocksPhysicalOptions: cloneDraftValue(starrocksPhysicalOptions.value),
starrocksSortColumns: starrocksSortColumns.value ? [...starrocksSortColumns.value] : undefined,
@@ -2814,6 +2855,10 @@ function restoreDraft(draft: TableStructureEditorDraft) {
originalMysqlAutoIncrementValue.value = draft.originalMysqlAutoIncrementValue;
mysqlTableEngine.value = draft.mysqlTableEngine || "";
originalMysqlTableEngine.value = draft.originalMysqlTableEngine || "";
+ mysqlTableCharset.value = draft.mysqlTableCharset || "";
+ originalMysqlTableCharset.value = draft.originalMysqlTableCharset || "";
+ mysqlTableCollation.value = draft.mysqlTableCollation || "";
+ originalMysqlTableCollation.value = draft.originalMysqlTableCollation || "";
tableOwner.value = draft.tableOwner || "";
originalTableOwner.value = draft.originalTableOwner || "";
columns.value = cloneDraftValue(draft.columns || []);
@@ -2948,6 +2993,7 @@ function hasPendingStructureChanges(includeExistingPrimaryKey = true, includeOra
scope.foreignKeys ||
scope.triggers ||
scope.tableComment ||
+ mysqlTableCharsetChanged.value ||
partitionOperations.value.length > 0 ||
mysqlTableEngine.value.toLowerCase() !== originalMysqlTableEngine.value.toLowerCase() ||
(canBuildMysqlAutoIncrement.value && mysqlAutoIncrementValue.value !== originalMysqlAutoIncrementValue.value) ||
@@ -3386,6 +3432,7 @@ async function refreshSqlPreview() {
}
sqlPreviewLoading.value = true;
const options = structureChangeOptions();
+ const tableCharsetChange = mysqlTableCharsetChange.value;
const partitionResultPromise = partitionOperations.value.length > 0 ? api.buildTablePartitionOperationSql(partitionSqlOptions()) : Promise.resolve({ statements: [], warnings: [] });
try {
const [result, ownerResult, mysqlAutoIncrementStatement, partitionResult] = await Promise.all([
@@ -3397,7 +3444,9 @@ async function refreshSqlPreview() {
? api.previewSqliteTableStructureChange(props.connectionId, props.database, options)
: databaseType.value === "starrocks"
? api.buildTableStructureChangeSql(options, { ...starrocksAlterContext.value!, reorderColumns: false, positionColumnOrder: structureCapabilities.value.reorderColumn, sortColumnNames: pendingStarRocksSort.value })
- : api.buildTableStructureChangeSql(options),
+ : tableCharsetChange
+ ? api.buildTableStructureChangeSql(options, undefined, tableCharsetChange)
+ : api.buildTableStructureChangeSql(options),
supportsTableOwner.value
? api.buildTableOwnerChangeSql({
databaseType: databaseType.value,
@@ -3528,6 +3577,10 @@ function resetState() {
mysqlAutoIncrementLoadError.value = "";
mysqlTableEngine.value = "";
originalMysqlTableEngine.value = "";
+ mysqlTableCharset.value = "";
+ originalMysqlTableCharset.value = "";
+ mysqlTableCollation.value = "";
+ originalMysqlTableCollation.value = "";
physicalOptions.value = emptyTablePhysicalOptions();
starrocksPhysicalOptions.value = emptyStarRocksPhysicalOptions();
starrocksAlterContext.value = undefined;
@@ -6765,6 +6818,7 @@ async function applyChanges() {
// structure draft it was applied from is clean, so the change-derived scope
// would be empty: reload every facet instead of leaving the tabs stale.
const refreshScope = ddlDirty.value ? { columns: true, indexes: true, foreignKeys: true, constraints: true, triggers: true, partitions: true, tableComment: true } : captureStructureRefreshScope();
+ if (!ddlDirty.value && mysqlTableCharsetChanged.value) refreshScope.columns = true;
const starrocksPhysicalOrderChanged = !ddlDirty.value && databaseType.value === "starrocks" && structureCapabilities.value.reorderColumn && columns.value.some((column, index) => column.original && column.originalPosition !== index);
// Plan A guard: concurrent builds only run with a long-enough query timeout
// (a cancelled build leaves an INVALID index behind), and are blocked
@@ -7059,6 +7113,12 @@ onMounted(() => {
void loadTableOwner(false, props.draft?.tableOwner !== undefined);
void loadTableOwnerRoles();
void loadMysqlTableEngine(props.draft?.mysqlTableEngine !== undefined);
+ if (props.draft && props.draft.mysqlTableCollation === undefined && !isCreateMode.value) {
+ // Drafts written before table-level charset support already mark the columns
+ // facet as loaded, so the normal structure load would skip this lookup.
+ void loadCharsetMetadata();
+ void loadMysqlTableDefaultCollation();
+ }
if (props.draft?.initialized) {
// A clean persisted editor snapshot is not a live schema cache. After an
// MCP DDL, restoring its loaded-facet flags would otherwise bypass the
@@ -7271,6 +7331,10 @@ watch(
mysqlTableEngineLoading,
mysqlTableEngineLoadError,
mysqlTableDefaultCollation,
+ mysqlTableCharset,
+ originalMysqlTableCharset,
+ mysqlTableCollation,
+ originalMysqlTableCollation,
tableOwner,
ddlDraft,
existingPrimaryKeyDraft,
@@ -7500,6 +7564,39 @@ watch(
</Tooltip>
</div>
+ <div v-if="supportsMysqlEngine && !isCreateMode" class="flex shrink-0 items-center gap-2">
+ <label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.characterSet") }}</label>
+ <SearchableSelect
+ :model-value="mysqlTableCharset"
+ :options="mysqlCharsetOptions"
+ :placeholder="t('structureEditor.charsetPlaceholder')"
+ :search-placeholder="t('structureEditor.charsetPlaceholder')"
+ :empty-text="t('structureEditor.noMatchingType')"
+ :allow-custom="true"
+ :loading="charsetMetadataLoading"
+ :loading-text="t('common.loading')"
+ :disabled="charsetMetadataLoading || saving"
+ :trigger-class="[structureMonoControlClass, 'w-[180px] max-w-[180px]']"
+ data-mysql-table-charset-select
+ @update:model-value="onMysqlTableCharsetChange"
+ />
+ </div>
+
+ <div v-if="supportsMysqlEngine && !isCreateMode" class="flex shrink-0 items-center gap-2">
+ <label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.collation") }}</label>
+ <SearchableSelect
+ v-model="mysqlTableCollation"
+ :options="collationOptionsForCharset(mysqlTableCharset)"
+ :placeholder="t('structureEditor.collationPlaceholder')"
+ :search-placeholder="t('structureEditor.collationPlaceholder')"
+ :empty-text="t('structureEditor.noMatchingType')"
+ :allow-custom="true"
+ :disabled="charsetMetadataLoading || saving"
+ :trigger-class="[structureMonoControlClass, 'w-[220px] max-w-[220px]']"
+ data-mysql-table-collation-select
+ />
+ </div>
+
<TablePhysicalOptionsEditor v-if="isCreateMode && databaseType === 'transwarp'" v-model="physicalOptions" :config="INCEPTOR_PHYSICAL_OPTIONS" :columns="columns.filter((column) => !column.markedForDrop && !!column.name.trim())" :disabled="saving" />
<div v-if="supportsTableOwner" class="flex shrink-0 items-center gap-2">
diff --git a/apps/desktop/src/lib/__tests__/table/mysqlTableCollation.spec.ts b/apps/desktop/src/lib/__tests__/table/mysqlTableCollation.spec.ts
index bf931b0c93..b6cb76af09 100644
--- a/apps/desktop/src/lib/__tests__/table/mysqlTableCollation.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/mysqlTableCollation.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { QueryResult } from "@/types/database";
-import { mysqlTableCollationSql, parseMysqlTableCollation } from "@/lib/table/mysqlTableCollation";
+import { mysqlTableCollationSql, parseMysqlTableCharset, parseMysqlTableCollation } from "@/lib/table/mysqlTableCollation";
function result(columns: string[], rows: QueryResult["rows"]): QueryResult {
return { columns, rows, affected_rows: 0, execution_time_ms: 1 };
@@ -27,4 +27,15 @@ describe("mysqlTableCollation", () => {
expect(parseMysqlTableCollation(result(["engine"], [["InnoDB"]]))).toBe("");
expect(parseMysqlTableCollation(undefined)).toBe("");
});
+
+ it("derives the table charset and collation from the same metadata row", () => {
+ expect(parseMysqlTableCharset(result(["TABLE_COLLATION"], [[" utf8mb4_0900_ai_ci "]]))).toEqual({
+ charset: "utf8mb4",
+ collation: "utf8mb4_0900_ai_ci",
+ });
+ expect(parseMysqlTableCharset(result(["table_collation"], [[null]]))).toEqual({
+ charset: "",
+ collation: "",
+ });
+ });
});
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 2c6616744d..a0b13a9c0e 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -238,7 +238,16 @@ import type {
} from "@/lib/dataGrid/dataGridSql";
import type { DmlChangePreviewSqlOptions, DmlChangePreviewSqlResult } from "@/lib/sql/dmlChangePreview";
import type { DataGridExtractRequest, DataGridExtractResult } from "@/lib/dataGrid/dataGridCopyExtractor";
-import type { BuildCreatePartitionedTableSqlOptions, BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TablePartitionSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
+import type {
+ BuildCreatePartitionedTableSqlOptions,
+ BuildTableOwnerChangeSqlOptions,
+ BuildTableStructureChangeSqlOptions,
+ BuildSingleColumnAlterSqlOptions,
+ MysqlTableCharsetChange,
+ SqliteTableStructureChangePreview,
+ TablePartitionSqlOptions,
+ TableStructureChangeSql,
+} from "@/lib/table/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
import type { DatabaseStructureSearchSql, DatabaseStructureSearchSqlOptions } from "@/lib/database/databaseStructureSearch";
@@ -2062,8 +2071,8 @@ export async function reviewOracleViewRenameSource(input: OracleViewRenameSource
return post("/api/query/review-oracle-view-rename-source", { input });
}
-export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions): Promise<TableStructureChangeSql> {
- return post("/api/query/build-table-structure-change-sql", { options, starrocks });
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions, mysqlTableCharset?: MysqlTableCharsetChange): Promise<TableStructureChangeSql> {
+ return post("/api/query/build-table-structure-change-sql", { options, starrocks, mysqlTableCharset });
}
export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSqlOptions): Promise<TableStructureChangeSql> {
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index e580ae33ce..6d3b72f1ff 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -161,7 +161,16 @@ import type { DmlChangePreviewSqlOptions, DmlChangePreviewSqlResult } from "@/li
import type { DataGridExtractRequest, DataGridExtractResult } from "@/lib/dataGrid/dataGridCopyExtractor";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, SchemaSyncSqlPlan, SelectedSchemaDiffInput, GenerateSchemaSyncPlanOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
-import type { BuildCreatePartitionedTableSqlOptions, BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TablePartitionSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
+import type {
+ BuildCreatePartitionedTableSqlOptions,
+ BuildTableOwnerChangeSqlOptions,
+ BuildTableStructureChangeSqlOptions,
+ BuildSingleColumnAlterSqlOptions,
+ MysqlTableCharsetChange,
+ SqliteTableStructureChangePreview,
+ TablePartitionSqlOptions,
+ TableStructureChangeSql,
+} from "@/lib/table/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
import type { DatabaseStructureSearchSql, DatabaseStructureSearchSqlOptions } from "@/lib/database/databaseStructureSearch";
@@ -2482,8 +2491,8 @@ export async function reviewOracleViewRenameSource(input: OracleViewRenameSource
return invoke("review_oracle_view_rename_source", { input });
}
-export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions): Promise<TableStructureChangeSql> {
- return invoke("build_table_structure_change_sql", { options, starrocks });
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions, mysqlTableCharset?: MysqlTableCharsetChange): Promise<TableStructureChangeSql> {
+ return invoke("build_table_structure_change_sql", { options, starrocks, mysqlTableCharset });
}
export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSqlOptions): Promise<TableStructureChangeSql> {
diff --git a/apps/desktop/src/lib/table/mysqlTableCollation.ts b/apps/desktop/src/lib/table/mysqlTableCollation.ts
index 6b73bb72d9..208d89b679 100644
--- a/apps/desktop/src/lib/table/mysqlTableCollation.ts
+++ b/apps/desktop/src/lib/table/mysqlTableCollation.ts
@@ -1,6 +1,11 @@
import type { QueryResult } from "@/types/database";
import { mysqlUtf8Literal } from "@/lib/table/mysqlTableEngine";
+export interface MysqlTableCharsetMetadata {
+ charset: string;
+ collation: string;
+}
+
/**
* Reads the table's default collation. MySQL reports the *effective* collation on every
* character column and never records whether it was written out explicitly, so a column
@@ -21,3 +26,17 @@ export function parseMysqlTableCollation(result: QueryResult | undefined): strin
const value = result.rows[0]?.[index];
return value === null || value === undefined ? "" : String(value).trim();
}
+
+/**
+ * MySQL does not expose a separate table character-set column in
+ * information_schema.TABLES. The default collation implies the character set
+ * (for example, utf8mb4_0900_ai_ci belongs to utf8mb4).
+ */
+export function parseMysqlTableCharset(result: QueryResult | undefined): MysqlTableCharsetMetadata {
+ const collation = parseMysqlTableCollation(result);
+ const separator = collation.indexOf("_");
+ return {
+ charset: separator > 0 ? collation.slice(0, separator) : "",
+ collation,
+ };
+}
diff --git a/apps/desktop/src/lib/table/tableStructureEditorSql.ts b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
index 762d37b4eb..d1e2742c1d 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorSql.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorSql.ts
@@ -206,6 +206,12 @@ export interface BuildTableStructureChangeSqlOptions {
};
}
+/** Change only an existing MySQL table's defaults; existing columns are left untouched. */
+export interface MysqlTableCharsetChange {
+ charset: string;
+ collation?: string;
+}
+
export interface TranswarpCreateTableOptions {
partitionColumns: string[];
bucketColumns: string[];
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index eab1be56ab..195ce4711f 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -2034,6 +2034,10 @@ export interface TableStructureEditorDraft {
originalMysqlAutoIncrementValue?: string;
mysqlTableEngine?: string;
originalMysqlTableEngine?: string;
+ mysqlTableCharset?: string;
+ originalMysqlTableCharset?: string;
+ mysqlTableCollation?: string;
+ originalMysqlTableCollation?: string;
physicalOptions?: import("@/lib/table/tablePhysicalOptions").TablePhysicalOptionsDraft;
starrocksLayoutDraft?: import("@/lib/table/starrocksAlterOptions").StarRocksLayoutDraft;
starrocksSortColumns?: string[];
diff --git a/crates/dbx-sql-schema/src/table_structure_sql.rs b/crates/dbx-sql-schema/src/table_structure_sql.rs
index d0ebfa2ee2..c57be5d3e7 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql.rs
@@ -12,6 +12,7 @@ mod existing_primary_key;
mod foreign_keys;
mod indexes;
mod mysql_engine;
+mod mysql_table_charset;
mod oracle_constraints;
mod oracle_foreign_keys;
mod owner;
@@ -32,6 +33,7 @@ pub use create_options::*;
pub use create_table::{
build_create_table_sql, build_create_table_sql_for_version, build_create_table_sql_with_dialect_options,
};
+pub use mysql_table_charset::{build_mysql_table_charset_change_sql, MysqlTableCharsetChange};
pub use owner::build_table_owner_change_sql;
pub use partitions::{build_create_partitioned_table_sql, build_table_partition_operation_sql};
pub use types::*;
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/mysql_table_charset.rs b/crates/dbx-sql-schema/src/table_structure_sql/mysql_table_charset.rs
new file mode 100644
index 0000000000..16a9e64c1a
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/mysql_table_charset.rs
@@ -0,0 +1,69 @@
+use serde::{Deserialize, Serialize};
+
+use super::dialect::StructureDialect;
+use super::types::{TableStructureSqlOptions, TableStructureSqlResult};
+use super::util::qualified_table;
+use crate::models::connection::DatabaseType;
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MysqlTableCharsetChange {
+ pub charset: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub collation: Option<String>,
+}
+
+fn valid_mysql_charset_identifier(value: &str) -> bool {
+ !value.is_empty()
+ && value.len() <= 64
+ && value.chars().all(|character| character.is_ascii_alphanumeric() || character == '_')
+}
+
+pub fn build_mysql_table_charset_change_sql(
+ options: &TableStructureSqlOptions,
+ change: MysqlTableCharsetChange,
+) -> TableStructureSqlResult {
+ if options.database_type != Some(DatabaseType::Mysql) || options.is_gaussdb_m_mode {
+ return TableStructureSqlResult {
+ statements: Vec::new(),
+ warnings: vec![
+ "Changing the table character set is supported only for native MySQL connections.".to_string()
+ ],
+ };
+ }
+
+ let charset = change.charset.trim();
+ if !valid_mysql_charset_identifier(charset) {
+ return TableStructureSqlResult {
+ statements: Vec::new(),
+ warnings: vec!["MySQL table character set contains invalid characters.".to_string()],
+ };
+ }
+
+ let collation = change.collation.as_deref().map(str::trim).filter(|value| !value.is_empty());
+ if let Some(collation) = collation {
+ if !valid_mysql_charset_identifier(collation) {
+ return TableStructureSqlResult {
+ statements: Vec::new(),
+ warnings: vec!["MySQL table collation contains invalid characters.".to_string()],
+ };
+ }
+ let charset_prefix = collation.split_once('_').map(|(prefix, _)| prefix);
+ if charset_prefix.is_some_and(|prefix| !prefix.eq_ignore_ascii_case(charset)) {
+ return TableStructureSqlResult {
+ statements: Vec::new(),
+ warnings: vec![format!("MySQL collation {collation} does not belong to character set {charset}.")],
+ };
+ }
+ }
+
+ let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
+ let mut statement = format!("ALTER TABLE {table} DEFAULT CHARACTER SET {charset}");
+ if let Some(collation) = collation {
+ statement.push_str(" COLLATE ");
+ statement.push_str(collation);
+ }
+ statement.push(';');
+
+ TableStructureSqlResult { statements: vec![statement], warnings: Vec::new() }
+}
diff --git a/crates/dbx-sql-schema/tests/mysql_table_charset.rs b/crates/dbx-sql-schema/tests/mysql_table_charset.rs
new file mode 100644
index 0000000000..0dea2ce241
--- /dev/null
+++ b/crates/dbx-sql-schema/tests/mysql_table_charset.rs
@@ -0,0 +1,46 @@
+use dbx_sql_schema::table_structure_sql::{
+ build_mysql_table_charset_change_sql, MysqlTableCharsetChange, TableStructureSqlOptions,
+};
+
+fn mysql_options() -> TableStructureSqlOptions {
+ serde_json::from_value(serde_json::json!({
+ "databaseType": "mysql",
+ "schema": "app",
+ "tableName": "users",
+ "columns": []
+ }))
+ .expect("valid MySQL table options")
+}
+
+#[test]
+fn mysql_table_charset_change_alters_defaults_without_rebuilding_the_table() {
+ let result = build_mysql_table_charset_change_sql(
+ &mysql_options(),
+ MysqlTableCharsetChange { charset: "utf8mb4".to_string(), collation: Some("utf8mb4_0900_ai_ci".to_string()) },
+ );
+
+ assert!(result.warnings.is_empty());
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE `users` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"]
+ );
+ assert!(!result.statements.iter().any(|sql| sql.contains("CREATE TABLE")));
+ assert!(!result.statements.iter().any(|sql| sql.contains("CONVERT TO")));
+}
+
+#[test]
+fn mysql_table_charset_change_requires_native_mysql() {
+ let mut options = mysql_options();
+ options.database_type = Some(dbx_sql_schema::models::connection::DatabaseType::Postgres);
+
+ let result = build_mysql_table_charset_change_sql(
+ &options,
+ MysqlTableCharsetChange { charset: "utf8mb4".to_string(), collation: None },
+ );
+
+ assert!(result.statements.is_empty());
+ assert_eq!(
+ result.warnings,
+ vec!["Changing the table character set is supported only for native MySQL connections."]
+ );
+}
diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rs
index bfc945197d..3856234023 100644
--- a/crates/dbx-web/src/routes/query.rs
+++ b/crates/dbx-web/src/routes/query.rs
@@ -331,6 +331,8 @@ pub struct BuildTableStructureSqlRequest {
pub starrocks: Option<dbx_core::table_structure_sql::StarRocksAlterOptions>,
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
#[serde(default)]
+ pub mysql_table_charset: Option<dbx_core::table_structure_sql::MysqlTableCharsetChange>,
+ #[serde(default)]
pub server_version: Option<String>,
#[serde(default)]
pub dialect_options: Option<dbx_core::table_structure_sql::CreateTableDialectOptions>,
@@ -1362,7 +1364,16 @@ pub async fn review_oracle_view_rename_source(
pub async fn build_table_structure_change_sql(
Json(req): Json<BuildTableStructureSqlRequest>,
) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {
- Json(dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(req.options, req.starrocks))
+ let mysql_table_charset = req
+ .mysql_table_charset
+ .map(|change| dbx_core::table_structure_sql::build_mysql_table_charset_change_sql(&req.options, change));
+ let mut result =
+ dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(req.options, req.starrocks);
+ if let Some(extra) = mysql_table_charset {
+ result.statements.extend(extra.statements);
+ result.warnings.extend(extra.warnings);
+ }
+ Json(result)
}
pub async fn build_table_owner_change_sql(
diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rs
index abd0f5aa85..372ad308ef 100644
--- a/src-tauri/src/commands/query.rs
+++ b/src-tauri/src/commands/query.rs
@@ -936,8 +936,16 @@ pub fn review_oracle_view_rename_source(
pub fn build_table_structure_change_sql(
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
starrocks: Option<dbx_core::table_structure_sql::StarRocksAlterOptions>,
+ mysql_table_charset: Option<dbx_core::table_structure_sql::MysqlTableCharsetChange>,
) -> Result<dbx_core::table_structure_sql::TableStructureSqlResult, String> {
- Ok(dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(options, starrocks))
+ let table_charset = mysql_table_charset
+ .map(|change| dbx_core::table_structure_sql::build_mysql_table_charset_change_sql(&options, change));
+ let mut result = dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(options, starrocks);
+ if let Some(extra) = table_charset {
+ result.statements.extend(extra.statements);
+ result.warnings.extend(extra.warnings);
+ }
+ Ok(result)
}
#[tauri::command]