fix(sqlserver): support primary key edits in structure editor
This commit is contained in:
1 parent
c9e8ee53f7
commit
a55466f578
6 files changed
+121
-23
No files matched your search
+20
@@ -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 () => {
|
it("keeps the current SQL preview visible while a newer preview is loading", async () => {
|
||||||
const root = await mountEditor("dameng", true);
|
const root = await mountEditor("dameng", true);
|
||||||
const primaryKey = columnCheckbox(root, "structureEditor.primaryKey");
|
const primaryKey = columnCheckbox(root, "structureEditor.primaryKey");
|
||||||
|
|||||||
@@ -102,6 +102,10 @@ describe("tableStructureCapabilities", () => {
|
|||||||
addPrimaryKey: true,
|
addPrimaryKey: true,
|
||||||
alterPrimaryKey: false,
|
alterPrimaryKey: false,
|
||||||
});
|
});
|
||||||
|
expect(getTableStructureCapabilities("sqlserver", "sqlserver")).toMatchObject({
|
||||||
|
addPrimaryKey: true,
|
||||||
|
alterPrimaryKey: true,
|
||||||
|
});
|
||||||
for (const databaseType of ["oceanbase-oracle", "iris"] as const) {
|
for (const databaseType of ["oceanbase-oracle", "iris"] as const) {
|
||||||
expect(getTableStructureCapabilities(databaseType, databaseType)).toMatchObject({
|
expect(getTableStructureCapabilities(databaseType, databaseType)).toMatchObject({
|
||||||
addPrimaryKey: false,
|
addPrimaryKey: false,
|
||||||
|
|||||||
@@ -186,6 +186,9 @@ const sqlserverCapabilities = capabilities({
|
|||||||
indexInclude: true,
|
indexInclude: true,
|
||||||
indexFilter: true,
|
indexFilter: true,
|
||||||
indexComment: 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({
|
const oracleCompatibleCapabilities = capabilities({
|
||||||
|
|||||||
@@ -473,29 +473,35 @@ pub(super) fn build_primary_key_sql(
|
|||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
let persisted_postgres_primary_key_name = if options.database_type == Some(DatabaseType::Postgres)
|
// PostgreSQL and SQL Server replace the persisted primary key by constraint name (neither
|
||||||
&& !change.old_ids.is_empty()
|
// engine has a dependable default naming rule), so the name must come from index metadata.
|
||||||
{
|
let persisted_primary_key_name = match options.database_type {
|
||||||
let mut primary_indexes =
|
Some(DatabaseType::Postgres) | Some(DatabaseType::SqlServer) if !change.old_ids.is_empty() => {
|
||||||
options.indexes.iter().filter_map(|index| index.original.as_ref().filter(|original| original.is_primary));
|
let mut primary_indexes = options
|
||||||
match (primary_indexes.next(), primary_indexes.next()) {
|
.indexes
|
||||||
(Some(primary_index), None) if !primary_index.name.is_empty() => Some(primary_index.name.as_str()),
|
.iter()
|
||||||
_ => {
|
.filter_map(|index| index.original.as_ref().filter(|original| original.is_primary));
|
||||||
warnings.push(
|
match (primary_indexes.next(), primary_indexes.next()) {
|
||||||
"Could not determine the existing PostgreSQL primary key constraint name. Refresh the table structure and try again."
|
(Some(primary_index), None) if !primary_index.name.is_empty() => Some(primary_index.name.as_str()),
|
||||||
.to_string(),
|
_ => {
|
||||||
);
|
let engine = if options.database_type == Some(DatabaseType::SqlServer) {
|
||||||
return Vec::new();
|
"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();
|
let mut statements = Vec::new();
|
||||||
if !change.old_ids.is_empty() {
|
if !change.old_ids.is_empty() {
|
||||||
let Some(drop_sql) = drop_primary_key_statement(dialect, table, options, persisted_postgres_primary_key_name)
|
let Some(drop_sql) = drop_primary_key_statement(dialect, table, options, persisted_primary_key_name) else {
|
||||||
else {
|
|
||||||
warnings.push(format!(
|
warnings.push(format!(
|
||||||
"Changing primary keys is not supported for {} from this editor.",
|
"Changing primary keys is not supported for {} from this editor.",
|
||||||
database_label(options.database_type)
|
database_label(options.database_type)
|
||||||
@@ -508,7 +514,7 @@ pub(super) fn build_primary_key_sql(
|
|||||||
if !change.new_names.is_empty() {
|
if !change.new_names.is_empty() {
|
||||||
let pk_list = change.new_names.iter().map(|name| quote_ident(dialect, name)).collect::<Vec<_>>().join(", ");
|
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.
|
// 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)))
|
.map(|name| format!("CONSTRAINT {} ", quote_ident(dialect, name)))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
statements.push(format!("ALTER TABLE {table} ADD {constraint}PRIMARY KEY ({pk_list});"));
|
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.
|
/// Cluster primary keys cannot use this path (DM8 restriction) — left to the server.
|
||||||
/// - Postgres: `DROP CONSTRAINT <persisted primary index name>` for PostgreSQL;
|
/// - Postgres: `DROP CONSTRAINT <persisted primary index name>` for PostgreSQL;
|
||||||
/// other Postgres-compatible engines retain the existing default-name behavior.
|
/// 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(
|
fn drop_primary_key_statement(
|
||||||
dialect: StructureDialect,
|
dialect: StructureDialect,
|
||||||
table: &str,
|
table: &str,
|
||||||
options: &TableStructureSqlOptions,
|
options: &TableStructureSqlOptions,
|
||||||
persisted_postgres_primary_key_name: Option<&str>,
|
persisted_primary_key_name: Option<&str>,
|
||||||
) -> Option<String> {
|
) -> Option<String> {
|
||||||
match dialect {
|
match dialect {
|
||||||
StructureDialect::Postgres => {
|
StructureDialect::Postgres => {
|
||||||
let fallback_name;
|
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
|
name
|
||||||
} else {
|
} else {
|
||||||
let raw_table = options.table_name.split('.').next_back().unwrap_or(&options.table_name);
|
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)))
|
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 一致)。
|
// 神通 Oscar 实测支持 `ALTER TABLE ... DROP PRIMARY KEY`(与 Dameng/MySQL 一致)。
|
||||||
StructureDialect::Mysql | StructureDialect::Dameng | StructureDialect::Oscar => {
|
StructureDialect::Mysql | StructureDialect::Dameng | StructureDialect::Oscar => {
|
||||||
Some(format!("ALTER TABLE {table} DROP PRIMARY KEY;"))
|
Some(format!("ALTER TABLE {table} DROP PRIMARY KEY;"))
|
||||||
|
|||||||
@@ -262,6 +262,11 @@ pub(super) fn capabilities_for(
|
|||||||
index_include: true,
|
index_include: true,
|
||||||
index_filter: true,
|
index_filter: true,
|
||||||
index_comment: 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
|
..base
|
||||||
},
|
},
|
||||||
Some(DatabaseType::Dameng) => TableStructureCapabilities {
|
Some(DatabaseType::Dameng) => TableStructureCapabilities {
|
||||||
|
|||||||
@@ -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]
|
#[test]
|
||||||
fn dameng_validates_new_primary_key_column_before_replacing_existing_key() {
|
fn dameng_validates_new_primary_key_column_before_replacing_existing_key() {
|
||||||
let mut old_pk = existing_pk_column("id", "INT", true, false);
|
let mut old_pk = existing_pk_column("id", "INT", true, false);
|
||||||
@@ -5431,8 +5482,10 @@ fn warns_sqlite_cannot_alter_primary_key() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn warns_sqlserver_cannot_alter_primary_key_without_drop_strategy() {
|
fn sqlserver_requires_persisted_constraint_name_and_fails_closed_without_it() {
|
||||||
// alter_primary_key is false for SQL Server; fail closed (no partial ADD-only SQL).
|
// 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(
|
let result = build_table_structure_change_sql(structure_change_options(
|
||||||
DatabaseType::SqlServer,
|
DatabaseType::SqlServer,
|
||||||
Some("dbo"),
|
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.statements, Vec::<String>::new());
|
||||||
assert_eq!(result.warnings.len(), 1);
|
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]
|
#[test]
|
||||||
|
|||||||
Reference in new issue
Block a user