fix(sqlserver): restrict identity to compatible column types
Co-authored-by: staff <staff@qimaos-MacBook-Pro.local>
This commit is contained in:
1 parent
a224a6747c
commit
5d2ce9f189
13 files changed
+144
-12
No files matched your search
@@ -42,6 +42,7 @@ import {
|
|||||||
getDataTypeOptions,
|
getDataTypeOptions,
|
||||||
getDefaultLengthForType,
|
getDefaultLengthForType,
|
||||||
isDataTypeLengthDisabled,
|
isDataTypeLengthDisabled,
|
||||||
|
isSqlServerIdentityCompatibleDataType,
|
||||||
isProtectedManticoreIdColumn,
|
isProtectedManticoreIdColumn,
|
||||||
parseExtraToColumnExtra,
|
parseExtraToColumnExtra,
|
||||||
splitDataType,
|
splitDataType,
|
||||||
@@ -1017,7 +1018,19 @@ function isSqlServerIdentityChecked(column: EditableStructureColumn): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function canEditSqlServerIdentity(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) {
|
function ensureSqlServerIdentity(column: EditableStructureColumn) {
|
||||||
@@ -1034,8 +1047,7 @@ function setSqlServerIdentity(column: EditableStructureColumn, checked: boolean)
|
|||||||
ensureSqlServerIdentity(column);
|
ensureSqlServerIdentity(column);
|
||||||
column.isNullable = false;
|
column.isNullable = false;
|
||||||
} else {
|
} else {
|
||||||
column.extra.autoIncrement = false;
|
clearSqlServerIdentity(column);
|
||||||
column.extra.identity = undefined;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1059,6 +1071,16 @@ function updateSqlServerIdentityIncrement(column: EditableStructureColumn, value
|
|||||||
column.extra.identity!.increment = parseOptionalNumberInput(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) {
|
function moveColumnTo(index: number, insertionIndex: number) {
|
||||||
if (!canDropColumnAt(index, insertionIndex)) return;
|
if (!canDropColumnAt(index, insertionIndex)) return;
|
||||||
const nextColumns = [...columns.value];
|
const nextColumns = [...columns.value];
|
||||||
@@ -1797,17 +1819,12 @@ watch(activeTab, (tab) => {
|
|||||||
:loading-text="t('common.loading')"
|
:loading-text="t('common.loading')"
|
||||||
:allow-custom="true"
|
:allow-custom="true"
|
||||||
:trigger-class="[structureMonoControlClass, 'w-full']"
|
: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 />
|
<Input v-else :model-value="splitDataType(column.dataType).baseType" :class="[structureMonoControlClass, 'w-full']" disabled />
|
||||||
</td>
|
</td>
|
||||||
<td v-if="columnEditorControls.length" :class="structureCellClass">
|
<td v-if="columnEditorControls.length" :class="structureCellClass">
|
||||||
<Input
|
<Input :model-value="dataTypeLengthInputValue(databaseType, column.dataType)" :class="structureMonoControlClass" :disabled="isColumnLengthDisabled(column)" @update:model-value="updateColumnDataTypeLength(column, $event)" />
|
||||||
:model-value="dataTypeLengthInputValue(databaseType, column.dataType)"
|
|
||||||
:class="structureMonoControlClass"
|
|
||||||
:disabled="isColumnLengthDisabled(column)"
|
|
||||||
@update:model-value="column.dataType = combineDataTypeForDatabase(databaseType, splitDataType(column.dataType).baseType, String($event))"
|
|
||||||
/>
|
|
||||||
</td>
|
</td>
|
||||||
<td v-if="columnEditorControls.nullable" :class="structureCellClass">
|
<td v-if="columnEditorControls.nullable" :class="structureCellClass">
|
||||||
<label class="flex items-center gap-1.5">
|
<label class="flex items-center gap-1.5">
|
||||||
@@ -1967,7 +1984,7 @@ watch(activeTab, (tab) => {
|
|||||||
</template>
|
</template>
|
||||||
<!-- SQL Server: IDENTITY -->
|
<!-- SQL Server: IDENTITY -->
|
||||||
<template v-else-if="structureDialect === 'sqlserver'">
|
<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)" />
|
<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>
|
<span class="min-w-0 truncate">{{ t("structureEditor.autoIncrement") }}</span>
|
||||||
</label>
|
</label>
|
||||||
|
|||||||
@@ -1591,6 +1591,7 @@ export default {
|
|||||||
identityGeneration: "Generation",
|
identityGeneration: "Generation",
|
||||||
identitySeed: "Seed",
|
identitySeed: "Seed",
|
||||||
identityIncrement: "Increment",
|
identityIncrement: "Increment",
|
||||||
|
sqlServerIdentityTypeHint: "SQL Server identity only supports tinyint, smallint, int, bigint, and decimal/numeric with scale 0",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "Relationship Diagram",
|
title: "Relationship Diagram",
|
||||||
|
|||||||
@@ -1572,6 +1572,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "Generación",
|
identityGeneration: "Generación",
|
||||||
identitySeed: "Semilla",
|
identitySeed: "Semilla",
|
||||||
identityIncrement: "Incremento",
|
identityIncrement: "Incremento",
|
||||||
|
sqlServerIdentityTypeHint: "La identidad de SQL Server solo admite tinyint, smallint, int, bigint y decimal/numeric con escala 0",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "Diagrama de relaciones",
|
title: "Diagrama de relaciones",
|
||||||
|
|||||||
@@ -1592,6 +1592,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "Generazione",
|
identityGeneration: "Generazione",
|
||||||
identitySeed: "Seed",
|
identitySeed: "Seed",
|
||||||
identityIncrement: "Incremento",
|
identityIncrement: "Incremento",
|
||||||
|
sqlServerIdentityTypeHint: "Identity di SQL Server supporta solo tinyint, smallint, int, bigint e decimal/numeric con scala 0",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "Diagramma delle Relazioni",
|
title: "Diagramma delle Relazioni",
|
||||||
|
|||||||
@@ -1606,6 +1606,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "生成",
|
identityGeneration: "生成",
|
||||||
identitySeed: "開始値",
|
identitySeed: "開始値",
|
||||||
identityIncrement: "増分",
|
identityIncrement: "増分",
|
||||||
|
sqlServerIdentityTypeHint: "SQL Server の ID 列は tinyint、smallint、int、bigint、scale 0 の decimal/numeric のみ対応します",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "リレーション図",
|
title: "リレーション図",
|
||||||
|
|||||||
@@ -1584,6 +1584,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "Geração",
|
identityGeneration: "Geração",
|
||||||
identitySeed: "Valor inicial",
|
identitySeed: "Valor inicial",
|
||||||
identityIncrement: "Incremento",
|
identityIncrement: "Incremento",
|
||||||
|
sqlServerIdentityTypeHint: "A identidade do SQL Server só aceita tinyint, smallint, int, bigint e decimal/numeric com escala 0",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "Diagrama de relacionamentos",
|
title: "Diagrama de relacionamentos",
|
||||||
|
|||||||
@@ -1594,6 +1594,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "生成方式",
|
identityGeneration: "生成方式",
|
||||||
identitySeed: "起始值",
|
identitySeed: "起始值",
|
||||||
identityIncrement: "增量",
|
identityIncrement: "增量",
|
||||||
|
sqlServerIdentityTypeHint: "SQL Server 自增仅支持 tinyint、smallint、int、bigint、decimal/numeric(小数位为 0)",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "关系图",
|
title: "关系图",
|
||||||
|
|||||||
@@ -1528,6 +1528,7 @@ export default withEnglishFallback({
|
|||||||
identityGeneration: "產生方式",
|
identityGeneration: "產生方式",
|
||||||
identitySeed: "起始值",
|
identitySeed: "起始值",
|
||||||
identityIncrement: "增量",
|
identityIncrement: "增量",
|
||||||
|
sqlServerIdentityTypeHint: "SQL Server 自動遞增僅支援 tinyint、smallint、int、bigint、decimal/numeric(小數位為 0)",
|
||||||
},
|
},
|
||||||
diagram: {
|
diagram: {
|
||||||
title: "關係圖",
|
title: "關係圖",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
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", () => {
|
describe("tableStructureEditorState", () => {
|
||||||
it("keeps mysql unsigned attributes in the editable base type", () => {
|
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.defaultValue)).toEqual(["''", "1", "sysdatetime()", "'prefix (internal)'"]);
|
||||||
expect(drafts.map((draft) => draft.original?.column_default)).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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -725,6 +725,20 @@ export function splitDataType(raw: string): { baseType: string; params: string }
|
|||||||
return { baseType, params };
|
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 {
|
export function combineDataType(baseType: string, params: string): string {
|
||||||
const type = baseType.trim();
|
const type = baseType.trim();
|
||||||
const p = params.trim();
|
const p = params.trim();
|
||||||
|
|||||||
@@ -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."));
|
warnings.push(format!("Adding columns is not supported for {database_label} from this editor."));
|
||||||
continue;
|
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(
|
statements.extend(build_add_column_sql(
|
||||||
dialect,
|
dialect,
|
||||||
options.database_type,
|
options.database_type,
|
||||||
@@ -199,6 +209,38 @@ pub(super) fn build_primary_key_sql(
|
|||||||
statements
|
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(
|
pub(super) fn build_add_column_sql(
|
||||||
dialect: StructureDialect,
|
dialect: StructureDialect,
|
||||||
database_type: Option<crate::models::connection::DatabaseType>,
|
database_type: Option<crate::models::connection::DatabaseType>,
|
||||||
|
|||||||
@@ -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);"]);
|
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]
|
#[test]
|
||||||
fn sqlserver_changed_foreign_key_still_warns_as_unsupported() {
|
fn sqlserver_changed_foreign_key_still_warns_as_unsupported() {
|
||||||
let mut user_fk = foreign_key("fk_orders_user_id", "user_id", "accounts", "id");
|
let mut user_fk = foreign_key("fk_orders_user_id", "user_id", "accounts", "id");
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
getColumnEditorControls,
|
getColumnEditorControls,
|
||||||
getDataTypeOptions,
|
getDataTypeOptions,
|
||||||
isProtectedManticoreIdColumn,
|
isProtectedManticoreIdColumn,
|
||||||
|
isSqlServerIdentityCompatibleDataType,
|
||||||
normalizeDataTypeParams,
|
normalizeDataTypeParams,
|
||||||
parseExtraToColumnExtra,
|
parseExtraToColumnExtra,
|
||||||
toColumnNames,
|
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", () => {
|
test("parses Manticore Search text properties to ColumnExtra", () => {
|
||||||
assert.deepEqual(parseExtraToColumnExtra("stored indexed", "manticoresearch"), {
|
assert.deepEqual(parseExtraToColumnExtra("stored indexed", "manticoresearch"), {
|
||||||
manticoreStored: true,
|
manticoreStored: true,
|
||||||
|
|||||||
Reference in new issue
Block a user