From a55466f578cc5a54a2ecc5462331b14596b0a4fa Mon Sep 17 00:00:00 2001 From: YingNing <59612604+dxqlovestudy@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:24:01 +0800 Subject: [PATCH] fix(sqlserver): support primary key edits in structure editor --- .../TableStructureEditor.primaryKey.spec.ts | 20 +++++++ .../table/tableStructureCapabilities.spec.ts | 4 ++ .../lib/table/tableStructureCapabilities.ts | 3 + .../src/table_structure_sql/columns.rs | 52 +++++++++------- .../src/table_structure_sql/dialect.rs | 5 ++ .../src/table_structure_sql/tests.rs | 60 ++++++++++++++++++- 6 files changed, 121 insertions(+), 23 deletions(-) diff --git a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts index 7198a4b1eb..e75d3d2810 100644 --- a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts +++ b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts @@ -604,6 +604,26 @@ describe("TableStructureEditor primary key editing", () => { ); }); + it("allows an existing SQL Server primary key to be cleared", async () => { + const root = await mountEditor("sqlserver", true); + const primaryKey = columnCheckbox(root, "structureEditor.primaryKey"); + + expect(primaryKey.disabled).toBe(false); + expect(primaryKey.checked).toBe(true); + + primaryKey.checked = false; + primaryKey.dispatchEvent(new Event("change", { bubbles: true })); + await nextTick(); + + expect(primaryKey.checked).toBe(false); + await vi.waitFor(() => expect(mocks.buildTableStructureChangeSql).toHaveBeenCalled()); + expect(mocks.buildTableStructureChangeSql).toHaveBeenLastCalledWith( + expect.objectContaining({ + columns: [expect.objectContaining({ isPrimaryKey: false })], + }), + ); + }); + it("keeps the current SQL preview visible while a newer preview is loading", async () => { const root = await mountEditor("dameng", true); const primaryKey = columnCheckbox(root, "structureEditor.primaryKey"); diff --git a/apps/desktop/src/lib/__tests__/table/tableStructureCapabilities.spec.ts b/apps/desktop/src/lib/__tests__/table/tableStructureCapabilities.spec.ts index 408fd915c6..dabb769f61 100644 --- a/apps/desktop/src/lib/__tests__/table/tableStructureCapabilities.spec.ts +++ b/apps/desktop/src/lib/__tests__/table/tableStructureCapabilities.spec.ts @@ -102,6 +102,10 @@ describe("tableStructureCapabilities", () => { addPrimaryKey: true, alterPrimaryKey: false, }); + expect(getTableStructureCapabilities("sqlserver", "sqlserver")).toMatchObject({ + addPrimaryKey: true, + alterPrimaryKey: true, + }); for (const databaseType of ["oceanbase-oracle", "iris"] as const) { expect(getTableStructureCapabilities(databaseType, databaseType)).toMatchObject({ addPrimaryKey: false, diff --git a/apps/desktop/src/lib/table/tableStructureCapabilities.ts b/apps/desktop/src/lib/table/tableStructureCapabilities.ts index 1bf725ec09..46c4d02184 100644 --- a/apps/desktop/src/lib/table/tableStructureCapabilities.ts +++ b/apps/desktop/src/lib/table/tableStructureCapabilities.ts @@ -186,6 +186,9 @@ const sqlserverCapabilities = capabilities({ indexInclude: true, indexFilter: true, indexComment: true, + // T-SQL: ALTER TABLE ... DROP CONSTRAINT / ADD [CONSTRAINT name] PRIMARY KEY (...); + // the backend drops the persisted constraint by its index-metadata name (issue #10758). + alterPrimaryKey: true, }); const oracleCompatibleCapabilities = capabilities({ diff --git a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs b/crates/dbx-sql-schema/src/table_structure_sql/columns.rs index 2b726c3c58..0c0853e337 100644 --- a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs +++ b/crates/dbx-sql-schema/src/table_structure_sql/columns.rs @@ -473,29 +473,35 @@ pub(super) fn build_primary_key_sql( return Vec::new(); } - let persisted_postgres_primary_key_name = if options.database_type == Some(DatabaseType::Postgres) - && !change.old_ids.is_empty() - { - let mut primary_indexes = - options.indexes.iter().filter_map(|index| index.original.as_ref().filter(|original| original.is_primary)); - match (primary_indexes.next(), primary_indexes.next()) { - (Some(primary_index), None) if !primary_index.name.is_empty() => Some(primary_index.name.as_str()), - _ => { - warnings.push( - "Could not determine the existing PostgreSQL primary key constraint name. Refresh the table structure and try again." - .to_string(), - ); - return Vec::new(); + // PostgreSQL and SQL Server replace the persisted primary key by constraint name (neither + // engine has a dependable default naming rule), so the name must come from index metadata. + let persisted_primary_key_name = match options.database_type { + Some(DatabaseType::Postgres) | Some(DatabaseType::SqlServer) if !change.old_ids.is_empty() => { + let mut primary_indexes = options + .indexes + .iter() + .filter_map(|index| index.original.as_ref().filter(|original| original.is_primary)); + match (primary_indexes.next(), primary_indexes.next()) { + (Some(primary_index), None) if !primary_index.name.is_empty() => Some(primary_index.name.as_str()), + _ => { + let engine = if options.database_type == Some(DatabaseType::SqlServer) { + "SQL Server" + } else { + "PostgreSQL" + }; + warnings.push(format!( + "Could not determine the existing {engine} primary key constraint name. Refresh the table structure and try again." + )); + return Vec::new(); + } } } - } else { - None + _ => None, }; let mut statements = Vec::new(); if !change.old_ids.is_empty() { - let Some(drop_sql) = drop_primary_key_statement(dialect, table, options, persisted_postgres_primary_key_name) - else { + let Some(drop_sql) = drop_primary_key_statement(dialect, table, options, persisted_primary_key_name) else { warnings.push(format!( "Changing primary keys is not supported for {} from this editor.", database_label(options.database_type) @@ -508,7 +514,7 @@ pub(super) fn build_primary_key_sql( if !change.new_names.is_empty() { let pk_list = change.new_names.iter().map(|name| quote_ident(dialect, name)).collect::>().join(", "); // DM8: ADD [CONSTRAINT name] PRIMARY KEY; anonymous form matches Navicat/DBeaver/MySQL editors. - let constraint = persisted_postgres_primary_key_name + let constraint = persisted_primary_key_name .map(|name| format!("CONSTRAINT {} ", quote_ident(dialect, name))) .unwrap_or_default(); statements.push(format!("ALTER TABLE {table} ADD {constraint}PRIMARY KEY ({pk_list});")); @@ -526,16 +532,18 @@ pub(super) fn build_primary_key_sql( /// Cluster primary keys cannot use this path (DM8 restriction) — left to the server. /// - Postgres: `DROP CONSTRAINT ` for PostgreSQL; /// other Postgres-compatible engines retain the existing default-name behavior. +/// - SQL Server: `DROP CONSTRAINT `; the caller resolves the name +/// from the index metadata (server-generated names like `PK__orders__3213E83F` have no rule). fn drop_primary_key_statement( dialect: StructureDialect, table: &str, options: &TableStructureSqlOptions, - persisted_postgres_primary_key_name: Option<&str>, + persisted_primary_key_name: Option<&str>, ) -> Option { match dialect { StructureDialect::Postgres => { let fallback_name; - let pk_name = if let Some(name) = persisted_postgres_primary_key_name { + let pk_name = if let Some(name) = persisted_primary_key_name { name } else { let raw_table = options.table_name.split('.').next_back().unwrap_or(&options.table_name); @@ -544,6 +552,10 @@ fn drop_primary_key_statement( }; Some(format!("ALTER TABLE {table} DROP CONSTRAINT {};", quote_ident(dialect, pk_name))) } + StructureDialect::SqlServer => { + let pk_name = persisted_primary_key_name?; + Some(format!("ALTER TABLE {table} DROP CONSTRAINT {};", quote_ident(dialect, pk_name))) + } // 神通 Oscar 实测支持 `ALTER TABLE ... DROP PRIMARY KEY`(与 Dameng/MySQL 一致)。 StructureDialect::Mysql | StructureDialect::Dameng | StructureDialect::Oscar => { Some(format!("ALTER TABLE {table} DROP PRIMARY KEY;")) diff --git a/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs b/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs index 9c1d4e7b84..a7f22f2081 100644 --- a/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs +++ b/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs @@ -262,6 +262,11 @@ pub(super) fn capabilities_for( index_include: true, index_filter: true, index_comment: true, + // T-SQL: `ALTER TABLE ... DROP CONSTRAINT ` for the persisted primary key and + // `ADD [CONSTRAINT name] PRIMARY KEY (...)` are supported; constraint names are read + // from the index metadata (issue #10758). + add_primary_key: true, + alter_primary_key: true, ..base }, Some(DatabaseType::Dameng) => TableStructureCapabilities { diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs index 56e934299f..0a4b67ff09 100644 --- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs +++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs @@ -4751,6 +4751,57 @@ fn builds_dameng_alter_table_change_primary_key() { ); } +#[test] +fn builds_sqlserver_alter_table_add_primary_key() { + // T-SQL accepts an anonymous `ADD PRIMARY KEY`; the server names the constraint. + let result = build_table_structure_change_sql(structure_change_options( + DatabaseType::SqlServer, + Some("dbo"), + "users", + vec![existing_pk_column("id", "INT", false, true)], + )); + + assert_eq!(result.warnings, Vec::::new()); + assert_eq!(result.statements, vec!["ALTER TABLE [dbo].[users] ADD PRIMARY KEY ([id]);"]); +} + +#[test] +fn sqlserver_replaces_primary_key_by_persisted_constraint_name() { + let mut old_pk = existing_pk_column("id", "INT", true, false); + old_pk.id = "old_id".to_string(); + let mut new_pk = existing_pk_column("code", "VARCHAR(50)", false, true); + new_pk.id = "new_code".to_string(); + let mut options = structure_change_options(DatabaseType::SqlServer, Some("dbo"), "users", vec![old_pk, new_pk]); + options.indexes = vec![existing_primary_index("PK_users", &["id"])]; + + let result = build_table_structure_change_sql(options); + + assert_eq!(result.warnings, Vec::::new()); + assert_eq!( + result.statements, + vec![ + "ALTER TABLE [dbo].[users] DROP CONSTRAINT [PK_users];", + "ALTER TABLE [dbo].[users] ADD CONSTRAINT [PK_users] PRIMARY KEY ([code]);", + ] + ); +} + +#[test] +fn builds_sqlserver_alter_table_drop_primary_key() { + let mut options = structure_change_options( + DatabaseType::SqlServer, + Some("dbo"), + "users", + vec![existing_pk_column("id", "INT", true, false)], + ); + options.indexes = vec![existing_primary_index("PK_users", &["id"])]; + + let result = build_table_structure_change_sql(options); + + assert_eq!(result.warnings, Vec::::new()); + assert_eq!(result.statements, vec!["ALTER TABLE [dbo].[users] DROP CONSTRAINT [PK_users];"]); +} + #[test] fn dameng_validates_new_primary_key_column_before_replacing_existing_key() { let mut old_pk = existing_pk_column("id", "INT", true, false); @@ -5431,8 +5482,10 @@ fn warns_sqlite_cannot_alter_primary_key() { } #[test] -fn warns_sqlserver_cannot_alter_primary_key_without_drop_strategy() { - // alter_primary_key is false for SQL Server; fail closed (no partial ADD-only SQL). +fn sqlserver_requires_persisted_constraint_name_and_fails_closed_without_it() { + // Dropping the persisted primary key needs its constraint name from the index metadata + // (server-generated names have no rule); without it, emit no partial SQL (no ADD-only) and + // ask the user to refresh the structure (issue #10758). let result = build_table_structure_change_sql(structure_change_options( DatabaseType::SqlServer, Some("dbo"), @@ -5442,7 +5495,8 @@ fn warns_sqlserver_cannot_alter_primary_key_without_drop_strategy() { assert_eq!(result.statements, Vec::::new()); assert_eq!(result.warnings.len(), 1); - assert!(result.warnings[0].contains("primary key")); + assert!(result.warnings[0].contains("SQL Server primary key constraint name")); + assert!(result.warnings[0].contains("Refresh")); } #[test]