From 2cdffc628296f4681195207caf50f1f1bed591e3 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:45:35 -0500 Subject: [PATCH] XLSX: drop kept PivotTables that name a dropped cache by id; hash sets for style references --- crates/xlsx/src/passthrough/read.rs | 10 ++++++---- crates/xlsx/src/passthrough/rebase.rs | 13 +++++++++++-- crates/xlsx/src/passthrough/write.rs | 4 ++++ crates/xlsx/src/tests/passthrough_tests.rs | 21 ++++++++++++++++++++- 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/xlsx/src/passthrough/read.rs b/crates/xlsx/src/passthrough/read.rs index 1d65e0a04..36bfc7c5d 100644 --- a/crates/xlsx/src/passthrough/read.rs +++ b/crates/xlsx/src/passthrough/read.rs @@ -554,16 +554,18 @@ type StyleRefs = (Vec<(u32, gridcraft_model::Style)>, Vec<(u32, String)>); fn style_refs(cx: &Ctx<'_>, data: &[u8]) -> Option { let mut dxfs: Vec<(u32, gridcraft_model::Style)> = vec![]; let mut fmts: Vec<(u32, String)> = vec![]; + // Membership sets: a crafted part can name many distinct ids, so scanning the vectors would be quadratic. + let (mut seen_dxfs, mut seen_fmts) = (HashSet::new(), HashSet::new()); attr_values(data, &[b"dxfId", b"numFmtId"], |name, v| { let Ok(id) = v.trim().parse::() else { return }; if name == b"dxfId" { - if !dxfs.iter().any(|(i, _)| *i == id) - && let Some(s) = cx.dxfs.get(id as usize) + if let Some(s) = cx.dxfs.get(id as usize) + && seen_dxfs.insert(id) { dxfs.push((id, s.clone())); } - } else if !fmts.iter().any(|(i, _)| *i == id) - && let Some(code) = cx.num_fmts.get(&id) + } else if let Some(code) = cx.num_fmts.get(&id) + && seen_fmts.insert(id) { fmts.push((id, code.clone())); } diff --git a/crates/xlsx/src/passthrough/rebase.rs b/crates/xlsx/src/passthrough/rebase.rs index 9de3388a2..a80717d60 100644 --- a/crates/xlsx/src/passthrough/rebase.rs +++ b/crates/xlsx/src/passthrough/rebase.rs @@ -14,11 +14,20 @@ impl<'a> SheetKept<'a> { pub fn write(sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> SheetKept<'a> { let Some(p) = sheet.preserved.as_deref() else { return SheetKept { p: None, names: NameMap::new(), ids: HashMap::new() } }; // A kept PivotTable whose cache wasn't kept with the workbook is left out. - let wb_names = &out.kept.wb_names; + let (wb_names, cache_ids) = (&out.kept.wb_names, &out.kept.cache_ids); let orphan: HashSet = p .parts .iter() - .filter(|q| q.rels.iter().any(|r| !r.external && is_kind(r, &["pivotCacheDefinition"]) && !wb_names.contains_key(&normalize(&r.target)))) + .filter(|q| { + let direct = q.rels.iter().filter(|r| !r.external && is_kind(r, &["pivotCacheDefinition"])); + // A table with no relationship to its cache names it by `cacheId` instead. + let by_id = || { + q.content_type == CT_PIVOT_TABLE + && crate::xml::parse(&q.data).ok().and_then(|x| x.attr_u32("cacheId")).is_some_and(|id| !cache_ids.contains(&id)) + }; + let mut direct = direct.peekable(); + if direct.peek().is_some() { direct.any(|r| !wb_names.contains_key(&normalize(&r.target))) } else { by_id() } + }) .map(|q| normalize(&q.name)) .collect(); let (parts, sheet_rels): (Cow<'_, [PreservedPart]>, Cow<'_, [PreservedRel]>) = if orphan.is_empty() { diff --git a/crates/xlsx/src/passthrough/write.rs b/crates/xlsx/src/passthrough/write.rs index 0ebc997dc..189edd885 100644 --- a/crates/xlsx/src/passthrough/write.rs +++ b/crates/xlsx/src/passthrough/write.rs @@ -15,6 +15,9 @@ pub struct KeptOut { /// Names of the workbook's kept parts, which sheets' kept parts can refer to (the cache of a /// kept PivotTable). pub(super) wb_names: NameMap, + /// The `cacheId`s of the workbook's kept pivot caches: a kept PivotTable that names its cache + /// only by id is written only when its cache is among them. + pub(super) cache_ids: HashSet, patches: StylePatches, } @@ -416,6 +419,7 @@ pub fn write_workbook(wb: &Workbook, wb_rels: &mut Rels, out: &mut Out) -> Workb }) .collect(); out.kept.wb_names = names; + out.kept.cache_ids = pivot_caches.iter().map(|(id, _)| *id).collect(); WorkbookKept { pivot_caches, elements: p.elements.iter().filter(|e| e.slot == "externalReferences").filter_map(|e| remap(&e.xml, &ids)).collect(), diff --git a/crates/xlsx/src/tests/passthrough_tests.rs b/crates/xlsx/src/tests/passthrough_tests.rs index cc63bda78..2ac287d52 100644 --- a/crates/xlsx/src/tests/passthrough_tests.rs +++ b/crates/xlsx/src/tests/passthrough_tests.rs @@ -1210,9 +1210,12 @@ struct ConnPkg { connections_blocked: bool, /// The connection the Data Model cache names. model_connection: u32, + /// The PivotTables have relationships to their caches (otherwise they name them by `cacheId`). + table_rels: bool, } -const CONN_PKG: ConnPkg = ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1 }; +const CONN_PKG: ConnPkg = + ConnPkg { model_part: true, big_model: false, connections: true, connections_blocked: false, model_connection: 1, table_rels: true }; /// Sheet "Report" with a PivotTable on the Data Model (cache 3) and sheet "More" with one on the /// plain connection (cache 4, with records), plus the hidden name a worksheet connection uses. @@ -1281,6 +1284,9 @@ fn conn_pivot_package(o: ConnPkg) -> Vec { ("xl/pivotCache/_rels/pivotCacheDefinition2.xml.rels", c2_rels.as_bytes()), ("xl/pivotCache/pivotCacheRecords2.xml", CONN_RECORDS.as_bytes()), ]; + if !o.table_rels { + parts.retain(|(name, _)| !name.starts_with("xl/pivotTables/_rels/")); + } if o.connections { parts.push(("xl/connections.xml", MODEL_CONNECTIONS.as_bytes())); } @@ -1400,6 +1406,19 @@ fn data_model_pivot_tables_without_the_model_are_kept_as_plain_cells() { } } +#[test] +fn pivot_tables_naming_their_cache_by_id_go_with_a_dropped_cache() { + // No connections part: both caches are dropped, and the tables that name them only by + // `cacheId` must not stay behind with an id the workbook no longer lists. + let (wb, _) = read_xlsx(&conn_pivot_package(ConnPkg { connections: false, table_rels: false, ..CONN_PKG })).unwrap(); + let u = Unpacked::new(&write_xlsx(&wb).unwrap()); + u.assert_valid(); + for sheet in ["Report", "More"] { + assert!(written_pivot_tables(&u, sheet).is_empty(), "{sheet}"); + } + assert!(written_pivot_caches(&u).is_empty()); +} + #[test] fn connection_pivot_tables_need_their_connections() { // No connections part: the caches name connections that aren't there.