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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sqlserver): support primary key edits in structure editor
YingNinga55466f578cc
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.tsindex 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.tsindex 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.tsindex 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 <name> / 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.rsindex 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::<Vec<_>>().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 <persisted primary index name>` for PostgreSQL;/// other Postgres-compatible engines retain the existing default-name behavior.+/// - SQL Server: `DROP CONSTRAINT <persisted primary index name>`; 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<String> {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.rsindex 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 <name>` 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.rsindex 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::<String>::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::<String>::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::<String>::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::<String>::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]