diff --git a/crates/engine/src/cmd/insert/table.rs b/crates/engine/src/cmd/insert/table.rs index 85d94b2bc..2a517766c 100644 --- a/crates/engine/src/cmd/insert/table.rs +++ b/crates/engine/src/cmd/insert/table.rs @@ -312,6 +312,19 @@ pub(super) fn table_rename(s: &mut Session, p: &Json) -> Result { }) }; cx.wb.rewrite_references(&|host, e| rename(host.sheet, e)); + // A bare PivotTable source binds to a table before a defined name (`pivot::resolve_source`), + // so a defined name with the old name doesn't shadow it: it follows the rename regardless. + for i in 0..cx.wb.sheets.len() { + let names_old = |src: &str| src.trim().trim_start_matches('=').trim().eq_ignore_ascii_case(&old); + if !cx.wb.sheet(i).is_some_and(|sh| sh.pivots.iter().any(|pt| names_old(&pt.source))) { + continue; + } + for pt in &mut cx.sheet_mut(i)?.pivots { + if names_old(&pt.source) { + pt.source = name.clone(); + } + } + } crate::cmd::edit::rewrite_python_refs(&mut cx.wb, &|host, e| rename(sheet_of.get(&host.to_ascii_lowercase()).copied(), e))?; cx.structural = true; Ok(Json::Null) diff --git a/crates/engine/src/cmd/pivot/tests.rs b/crates/engine/src/cmd/pivot/tests.rs index 03f2d7a5f..541b5a1f7 100644 --- a/crates/engine/src/cmd/pivot/tests.rs +++ b/crates/engine/src/cmd/pivot/tests.rs @@ -1428,3 +1428,20 @@ fn legacy_count_numbers_caption_follows_the_function() { assert_eq!(text(&s, "E3"), after, "{legacy}"); } } + +/// A defined name with a table's name doesn't stop a PivotTable's table source following a rename +/// of the table: a bare source binds to the table first. +#[test] +fn a_table_rename_moves_a_pivot_source_a_defined_name_shadows() { + let mut s = sales(); + s.execute("insert.table", json!({"range": "A1:E13"})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + s.execute("table.summarizePivot", json!({"rows": ["Product"], "values": ["Units"]})).unwrap(); + assert_eq!(pt(&s).source, "Table1"); + s.execute("formulas.defineName", json!({"name": "Table1", "refersTo": "=Sheet1!$A$1:$B$3"})).unwrap(); + s.execute("table.rename", json!({"table": "Table1", "name": "Data"})).unwrap(); + assert_eq!(pt(&s).source, "Data"); + s.execute("pivot.refresh", json!({})).unwrap(); + let gt = find_row(&s, "Grand Total").unwrap(); + assert_eq!(val(&s, &CellRef::new(gt, 1).a1()), Value::Number(72.0)); +}