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(sqlserver): restrict identity to compatible column types

zipg5d2ce9f18917
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index a4f2a3027c..c082ff8db9 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -42,6 +42,7 @@ import {
getDataTypeOptions,
getDefaultLengthForType,
isDataTypeLengthDisabled,
+ isSqlServerIdentityCompatibleDataType,
isProtectedManticoreIdColumn,
parseExtraToColumnExtra,
splitDataType,
@@ -1017,7 +1018,19 @@ function isSqlServerIdentityChecked(column: EditableStructureColumn): boolean {
}
function canEditSqlServerIdentity(column: EditableStructureColumn): boolean {
- return !column.original && !column.markedForDrop;
+ return !column.original && !column.markedForDrop && isSqlServerIdentityCompatibleDataType(column.dataType);
+}
+
+function clearSqlServerIdentity(column: EditableStructureColumn) {
+ column.extra.autoIncrement = false;
+ column.extra.identity = undefined;
+}
+
+function syncSqlServerIdentityForDataType(column: EditableStructureColumn) {
+ if (databaseType.value !== "sqlserver") return;
+ if (!isSqlServerIdentityChecked(column)) return;
+ if (isSqlServerIdentityCompatibleDataType(column.dataType)) return;
+ clearSqlServerIdentity(column);
}
function ensureSqlServerIdentity(column: EditableStructureColumn) {
@@ -1034,8 +1047,7 @@ function setSqlServerIdentity(column: EditableStructureColumn, checked: boolean)
ensureSqlServerIdentity(column);
column.isNullable = false;
} else {
- column.extra.autoIncrement = false;
- column.extra.identity = undefined;
+ clearSqlServerIdentity(column);
}
}
@@ -1059,6 +1071,16 @@ function updateSqlServerIdentityIncrement(column: EditableStructureColumn, value
column.extra.identity!.increment = parseOptionalNumberInput(value);
}
+function updateColumnDataType(column: EditableStructureColumn, baseType: string) {
+ column.dataType = combineDataTypeForDatabase(databaseType.value, baseType, getDefaultLengthForType(databaseType.value, baseType));
+ syncSqlServerIdentityForDataType(column);
+}
+
+function updateColumnDataTypeLength(column: EditableStructureColumn, value: string | number) {
+ column.dataType = combineDataTypeForDatabase(databaseType.value, splitDataType(column.dataType).baseType, String(value));
+ syncSqlServerIdentityForDataType(column);
+}
+
function moveColumnTo(index: number, insertionIndex: number) {
if (!canDropColumnAt(index, insertionIndex)) return;
const nextColumns = [...columns.value];
@@ -1797,17 +1819,12 @@ watch(activeTab, (tab) => {
:loading-text="t('common.loading')"
:allow-custom="true"
:trigger-class="[structureMonoControlClass, 'w-full']"
- @update:model-value="(v: string) => (column.dataType = combineDataTypeForDatabase(databaseType, v, getDefaultLengthForType(databaseType, v)))"
+ @update:model-value="(v: string) => updateColumnDataType(column, v)"
/>
<Input v-else :model-value="splitDataType(column.dataType).baseType" :class="[structureMonoControlClass, 'w-full']" disabled />
</td>
<td v-if="columnEditorControls.length" :class="structureCellClass">
- <Input
- :model-value="dataTypeLengthInputValue(databaseType, column.dataType)"
- :class="structureMonoControlClass"
- :disabled="isColumnLengthDisabled(column)"
- @update:model-value="column.dataType = combineDataTypeForDatabase(databaseType, splitDataType(column.dataType).baseType, String($event))"
- />
+ <Input :model-value="dataTypeLengthInputValue(databaseType, column.dataType)" :class="structureMonoControlClass" :disabled="isColumnLengthDisabled(column)" @update:model-value="updateColumnDataTypeLength(column, $event)" />
</td>
<td v-if="columnEditorControls.nullable" :class="structureCellClass">
<label class="flex items-center gap-1.5">
@@ -1967,7 +1984,7 @@ watch(activeTab, (tab) => {
</template>
<!-- SQL Server: IDENTITY -->
<template v-else-if="structureDialect === 'sqlserver'">
- <label :class="structurePropertyLabelClass" :title="t('structureEditor.identity')">
+ <label :class="structurePropertyLabelClass" :title="canEditSqlServerIdentity(column) || isSqlServerIdentityChecked(column) ? t('structureEditor.identity') : t('structureEditor.sqlServerIdentityTypeHint')">
<input :checked="isSqlServerIdentityChecked(column)" type="checkbox" :class="[structureCheckboxClass, 'shrink-0']" :disabled="!canEditSqlServerIdentity(column)" @change="setSqlServerIdentity(column, ($event.target as HTMLInputElement).checked)" />
<span class="min-w-0 truncate">{{ t("structureEditor.autoIncrement") }}</span>
</label>
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index dffe6de247..82e81df57e 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1591,6 +1591,7 @@ export default {
identityGeneration: "Generation",
identitySeed: "Seed",
identityIncrement: "Increment",
+ sqlServerIdentityTypeHint: "SQL Server identity only supports tinyint, smallint, int, bigint, and decimal/numeric with scale 0",
},
diagram: {
title: "Relationship Diagram",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 26135f3538..2942455432 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1572,6 +1572,7 @@ export default withEnglishFallback({
identityGeneration: "Generación",
identitySeed: "Semilla",
identityIncrement: "Incremento",
+ sqlServerIdentityTypeHint: "La identidad de SQL Server solo admite tinyint, smallint, int, bigint y decimal/numeric con escala 0",
},
diagram: {
title: "Diagrama de relaciones",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 676df509a0..5135cfd3ed 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1592,6 +1592,7 @@ export default withEnglishFallback({
identityGeneration: "Generazione",
identitySeed: "Seed",
identityIncrement: "Incremento",
+ sqlServerIdentityTypeHint: "Identity di SQL Server supporta solo tinyint, smallint, int, bigint e decimal/numeric con scala 0",
},
diagram: {
title: "Diagramma delle Relazioni",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index dc44bd2c62..d3f2b9648a 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1606,6 +1606,7 @@ export default withEnglishFallback({
identityGeneration: "生成",
identitySeed: "開始値",
identityIncrement: "増分",
+ sqlServerIdentityTypeHint: "SQL Server の ID 列は tinyint、smallint、int、bigint、scale 0 の decimal/numeric のみ対応します",
},
diagram: {
title: "リレーション図",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index e0e29821db..1a16be000b 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1584,6 +1584,7 @@ export default withEnglishFallback({
identityGeneration: "Geração",
identitySeed: "Valor inicial",
identityIncrement: "Incremento",
+ sqlServerIdentityTypeHint: "A identidade do SQL Server só aceita tinyint, smallint, int, bigint e decimal/numeric com escala 0",
},
diagram: {
title: "Diagrama de relacionamentos",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 92a2a5870f..d5285518e4 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1594,6 +1594,7 @@ export default withEnglishFallback({
identityGeneration: "生成方式",
identitySeed: "起始值",
identityIncrement: "增量",
+ sqlServerIdentityTypeHint: "SQL Server 自增仅支持 tinyint、smallint、int、bigint、decimal/numeric(小数位为 0)",
},
diagram: {
title: "关系图",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index c6dedbf82e..550f661faa 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1528,6 +1528,7 @@ export default withEnglishFallback({
identityGeneration: "產生方式",
identitySeed: "起始值",
identityIncrement: "增量",
+ sqlServerIdentityTypeHint: "SQL Server 自動遞增僅支援 tinyint、smallint、int、bigint、decimal/numeric(小數位為 0)",
},
diagram: {
title: "關係圖",
diff --git a/apps/desktop/src/lib/__tests__/tableStructureEditorState.spec.ts b/apps/desktop/src/lib/__tests__/tableStructureEditorState.spec.ts
index 3d0942a6ef..c4027dea1d 100644
--- a/apps/desktop/src/lib/__tests__/tableStructureEditorState.spec.ts
+++ b/apps/desktop/src/lib/__tests__/tableStructureEditorState.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { combineDataTypeForDatabase, createColumnDrafts, dataTypeLengthInputValue, isDataTypeLengthDisabled, splitDataType } from "../tableStructureEditorState";
+import { combineDataTypeForDatabase, createColumnDrafts, dataTypeLengthInputValue, isDataTypeLengthDisabled, isSqlServerIdentityCompatibleDataType, splitDataType } from "../tableStructureEditorState";
describe("tableStructureEditorState", () => {
it("keeps mysql unsigned attributes in the editable base type", () => {
@@ -70,4 +70,13 @@ describe("tableStructureEditorState", () => {
expect(drafts.map((draft) => draft.defaultValue)).toEqual(["''", "1", "sysdatetime()", "'prefix (internal)'"]);
expect(drafts.map((draft) => draft.original?.column_default)).toEqual(["''", "1", "sysdatetime()", "'prefix (internal)'"]);
});
+
+ it("limits SQL Server identity columns to supported data types", () => {
+ expect(isSqlServerIdentityCompatibleDataType("int")).toBe(true);
+ expect(isSqlServerIdentityCompatibleDataType("bigint")).toBe(true);
+ expect(isSqlServerIdentityCompatibleDataType("numeric(18, 0)")).toBe(true);
+ expect(isSqlServerIdentityCompatibleDataType("decimal(10)")).toBe(true);
+ expect(isSqlServerIdentityCompatibleDataType("varchar(255)")).toBe(false);
+ expect(isSqlServerIdentityCompatibleDataType("numeric(18, 2)")).toBe(false);
+ });
});
diff --git a/apps/desktop/src/lib/tableStructureEditorState.ts b/apps/desktop/src/lib/tableStructureEditorState.ts
index be8e182f1d..64579a3806 100644
--- a/apps/desktop/src/lib/tableStructureEditorState.ts
+++ b/apps/desktop/src/lib/tableStructureEditorState.ts
@@ -725,6 +725,20 @@ export function splitDataType(raw: string): { baseType: string; params: string }
return { baseType, params };
}
+export function isSqlServerIdentityCompatibleDataType(rawDataType: string): boolean {
+ const { baseType, params } = splitDataType(rawDataType);
+ const normalized = baseType.trim().replace(/\s+/g, " ").toLowerCase();
+ if (["tinyint", "smallint", "int", "integer", "bigint"].includes(normalized)) return true;
+ if (normalized !== "decimal" && normalized !== "numeric") return false;
+ const normalizedParams = params.replace(/\s+/g, "");
+ if (!normalizedParams) return true;
+ const parts = normalizedParams.split(",");
+ if (parts.length === 1) return /^\d+$/.test(parts[0] ?? "");
+ if (parts.length !== 2) return false;
+ const [precision, scale] = parts;
+ return /^\d+$/.test(precision ?? "") && scale === "0";
+}
+
export function combineDataType(baseType: string, params: string): string {
const type = baseType.trim();
const p = params.trim();
diff --git a/crates/dbx-core/src/table_structure_sql/columns.rs b/crates/dbx-core/src/table_structure_sql/columns.rs
index 7d964fbf23..49a8518bdf 100644
--- a/crates/dbx-core/src/table_structure_sql/columns.rs
+++ b/crates/dbx-core/src/table_structure_sql/columns.rs
@@ -63,6 +63,16 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
warnings.push(format!("Adding columns is not supported for {database_label} from this editor."));
continue;
}
+ if dialect == StructureDialect::SqlServer
+ && has_sqlserver_identity(column)
+ && !is_sqlserver_identity_compatible_type(&column.data_type)
+ {
+ warnings.push(format!(
+ "SQL Server identity column \"{}\" must use tinyint, smallint, int, bigint, or decimal/numeric with scale 0.",
+ column.name
+ ));
+ continue;
+ }
statements.extend(build_add_column_sql(
dialect,
options.database_type,
@@ -199,6 +209,38 @@ pub(super) fn build_primary_key_sql(
statements
}
+fn has_sqlserver_identity(column: &EditableStructureColumn) -> bool {
+ column.extra.as_ref().is_some_and(|extra| extra.auto_increment.unwrap_or(false) || extra.identity.is_some())
+}
+
+fn is_sqlserver_identity_compatible_type(data_type: &str) -> bool {
+ let trimmed = data_type.trim();
+ let (base_type, params) = match trimmed.find('(') {
+ Some(open_index) => {
+ let close_index = trimmed.rfind(')').unwrap_or(trimmed.len());
+ (&trimmed[..open_index], trimmed.get(open_index + 1..close_index).unwrap_or(""))
+ }
+ None => (trimmed, ""),
+ };
+ let normalized = base_type.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_lowercase();
+ if matches!(normalized.as_str(), "tinyint" | "smallint" | "int" | "integer" | "bigint") {
+ return true;
+ }
+ if !matches!(normalized.as_str(), "decimal" | "numeric") {
+ return false;
+ }
+ let normalized_params = params.split_whitespace().collect::<String>();
+ if normalized_params.is_empty() {
+ return true;
+ }
+ let parts = normalized_params.split(',').collect::<Vec<_>>();
+ match parts.as_slice() {
+ [precision] => precision.parse::<u32>().is_ok(),
+ [precision, scale] => precision.parse::<u32>().is_ok() && *scale == "0",
+ _ => false,
+ }
+}
+
pub(super) fn build_add_column_sql(
dialect: StructureDialect,
database_type: Option<crate::models::connection::DatabaseType>,
diff --git a/crates/dbx-core/src/table_structure_sql/tests.rs b/crates/dbx-core/src/table_structure_sql/tests.rs
index afb461f365..e7085c12ed 100644
--- a/crates/dbx-core/src/table_structure_sql/tests.rs
+++ b/crates/dbx-core/src/table_structure_sql/tests.rs
@@ -1208,6 +1208,36 @@ fn sqlserver_add_column_with_identity() {
assert_eq!(result.statements, vec!["ALTER TABLE [dbo].[orders] ADD [id] int NOT NULL IDENTITY(10, 2);"]);
}
+#[test]
+fn sqlserver_rejects_identity_on_incompatible_type() {
+ let mut column = column("test");
+ column.data_type = "varchar(255)".to_string();
+ column.is_nullable = false;
+ column.extra = Some(ColumnExtra {
+ auto_increment: Some(true),
+ identity: Some(ColumnIdentity { generation: None, seed: Some(1), increment: Some(1) }),
+ ..Default::default()
+ });
+
+ let result = build_table_structure_change_sql(TableStructureSqlOptions {
+ database_type: Some(DatabaseType::SqlServer),
+ schema: Some("core".to_string()),
+ table_name: "products".to_string(),
+ columns: vec![column],
+ indexes: Vec::new(),
+ foreign_keys: Vec::new(),
+ triggers: Vec::new(),
+ table_comment: None,
+ original_table_comment: None,
+ });
+
+ assert_eq!(result.statements, Vec::<String>::new());
+ assert_eq!(
+ result.warnings,
+ vec!["SQL Server identity column \"test\" must use tinyint, smallint, int, bigint, or decimal/numeric with scale 0."]
+ );
+}
+
#[test]
fn sqlserver_changed_foreign_key_still_warns_as_unsupported() {
let mut user_fk = foreign_key("fk_orders_user_id", "user_id", "accounts", "id");
diff --git a/packages/app-tests/tableStructureEditorState.test.ts b/packages/app-tests/tableStructureEditorState.test.ts
index ec907fbefa..cbd7f4ae20 100644
--- a/packages/app-tests/tableStructureEditorState.test.ts
+++ b/packages/app-tests/tableStructureEditorState.test.ts
@@ -12,6 +12,7 @@ import {
getColumnEditorControls,
getDataTypeOptions,
isProtectedManticoreIdColumn,
+ isSqlServerIdentityCompatibleDataType,
normalizeDataTypeParams,
parseExtraToColumnExtra,
toColumnNames,
@@ -200,6 +201,18 @@ test("parses SQL Server identity extra string to ColumnExtra", () => {
});
});
+test("recognizes SQL Server identity-compatible data types", () => {
+ assert.equal(isSqlServerIdentityCompatibleDataType("tinyint"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("smallint"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("int"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("integer"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("bigint"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("decimal(18,0)"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("numeric(10)"), true);
+ assert.equal(isSqlServerIdentityCompatibleDataType("varchar(255)"), false);
+ assert.equal(isSqlServerIdentityCompatibleDataType("numeric(18,2)"), false);
+});
+
test("parses Manticore Search text properties to ColumnExtra", () => {
assert.deepEqual(parseExtraToColumnExtra("stored indexed", "manticoresearch"), {
manticoreStored: true,