From aeb887bb8f7cc1453d708cdc9fc0cb575ebbc26c Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 07:06:55 -0600 Subject: [PATCH 1/2] fix(data): report column declaration changes on overwrite --- crates/data/src/dbf.rs | 164 ++++++- crates/data/src/export/tests.rs | 5 +- crates/data/src/io.rs | 222 ++++++++-- crates/data/src/source/gpkg.rs | 9 +- crates/data/src/source/gpkg/add.rs | 66 ++- crates/data/src/source/tests.rs | 34 +- crates/engine/src/cmd/share.rs | 109 ++++- crates/engine/src/cmd/share/table.rs | 13 +- crates/engine/src/tests/write_notices.rs | 534 +++++++++++++++++++++++ 9 files changed, 1062 insertions(+), 94 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 6d88b75efd..c2d4f53f16 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -368,14 +368,7 @@ pub(crate) fn raw_table(dbf: &[u8]) -> Option> { let le16 = |at: usize| Some(usize::from(u16::from_le_bytes([*dbf.get(at)?, *dbf.get(at + 1)?]))); let count = usize::try_from(u32::from_le_bytes(dbf.get(4..8)?.try_into().ok()?)).ok()?; let (header_len, record_len) = (le16(8)?, le16(10)?); - let mut columns = Vec::new(); - for start in (32..header_len.min(dbf.len())).step_by(32) { - let d = dbf.get(start..start + 32).filter(|d| d.first() != Some(&0x0D)); - let Some(d) = d else { break }; - let name = d.get(..11)?; - let name = name.get(..name.iter().position(|b| *b == 0).unwrap_or(11))?.to_vec(); - columns.push(Column { name, ty: *d.get(11)?, len: *d.get(16)?, decimals: *d.get(17)? }); - } + let columns = column_descriptors(dbf, header_len)?; let width: usize = 1 + columns.iter().map(|c| usize::from(c.len)).sum::(); if width != record_len || record_len == 0 { return None; @@ -405,6 +398,98 @@ pub(crate) fn raw_table(dbf: &[u8]) -> Option> { Some(RawTable { columns, records, deleted }) } +/// Reads the column descriptors for Publish without decoding field values. +#[cfg(not(target_arch = "wasm32"))] +fn column_descriptors(dbf: &[u8], header_len: usize) -> Option> { + let mut columns = Vec::new(); + for start in (32..header_len.min(dbf.len())).step_by(32) { + let d = dbf.get(start..start + 32).filter(|d| d.first() != Some(&0x0D)); + let Some(d) = d else { break }; + columns.push(column_descriptor(d)?); + } + Some(columns) +} + +fn column_descriptor(d: &[u8]) -> Option { + let name = d.get(..11)?.split(|b| *b == 0).next()?.to_vec(); + Some(Column { name, ty: *d.get(11)?, len: *d.get(16)?, decimals: *d.get(17)? }) +} + +/// The generated descriptors precede the first record even if the writer's header length wrapped. +pub(crate) fn written_declarations(dbf: &[u8], count: usize) -> Option> { + let end = count.checked_mul(32)?.checked_add(32)?; + dbf.get(32..end)?.as_chunks::<32>().0.iter().map(|d| column_descriptor(d)).collect() +} + +impl Column { + /// Compares on-disk types and widths. Legacy character widths use the decimals byte as + /// the high byte of their width. + pub(crate) fn same_declaration(&self, other: &Self) -> bool { + let width = |c: &Self| { + if c.ty.eq_ignore_ascii_case(&b'C') { (u16::from_le_bytes([c.len, c.decimals]), 0) } else { (u16::from(c.len), c.decimals) } + }; + self.ty.eq_ignore_ascii_case(&other.ty) && width(self) == width(other) + } +} + +/// Reads only the bounded header, stopping the descriptor scan at a terminator or the +/// declared end. Record width and padding after the descriptors do not affect comparison. +pub(crate) fn read_declarations(path: &std::path::Path) -> std::io::Result<(Vec, u8)> { + use std::io::{Error, ErrorKind, Read}; + let invalid = || Error::new(ErrorKind::InvalidData, "incomplete DBF descriptors"); + let (file, size) = open_declaration_file(path)?; + if size < 32 { + return Err(invalid()); + } + let mut file = file.take(size); + let mut first = [0; 32]; + file.read_exact(&mut first)?; + let header_len = u64::from(u16::from_le_bytes([first[8], first[9]])).checked_sub(32).ok_or_else(invalid)?; + let mut header = Vec::new(); + file.take(header_len).read_to_end(&mut header)?; + let mut columns = Vec::new(); + for start in (0..header_len as usize).step_by(32) { + if header.get(start) == Some(&0x0D) { + break; + } + if start + 32 > header_len as usize { + return Err(invalid()); + } + let descriptor = header.get(start..start + 32).and_then(column_descriptor).ok_or_else(invalid)?; + columns.push(descriptor); + } + Ok((columns, first[29])) +} + +/// Decodes only those names that need a code page. A metadata read error or an unknown +/// language driver leaves those names unresolved without affecting the ASCII descriptors. +pub(crate) fn declaration_names(path: &std::path::Path, columns: &[Column], ldid: u8) -> Vec> { + use shapefile::dbase::Encoding; + let mut encoding = None; + columns + .iter() + .map(|column| { + if column.name.is_ascii() { + return std::str::from_utf8(&column.name).ok().map(str::to_owned); + } + let (encoding, decoder) = encoding + .get_or_insert_with(|| { + let cpg = read_declaration_cpg(path).ok()?; + let encoding = cpg_encoding(cpg.as_deref()).or_else(|| { + if ldid == 0 { Some(DbfEncoding::Utf8) } else { ldid_code_page(ldid).and_then(DbfEncoding::from_number) } + })?; + let decoder = encoding.decoder(); + Some((encoding, decoder)) + }) + .as_ref()?; + if encoding.malformed(&column.name) { + return None; + } + decoder.decode(&column.name).ok().map(|name| name.into_owned()) + }) + .collect() +} + /// A date (`D`) field's value, `YYYYMMDD`: `Ok(None)` when it's blank or zeros, as writers leave /// a date empty, and `Err(())` when it isn't a date (`20260230`, `2026-3-5`). A year padded with /// spaces (` 10101`, year 1, as GDAL writes it with `%4d`) is read as the zeros it stands for. @@ -509,29 +594,68 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { Ok(None) } -/// Checks before and after opening. Unix nonblocking open covers a FIFO swapped in between; -/// regular-file leases retry with cancellation between attempts instead of blocking in the kernel. -pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result> { +/// Reads the first present code-page spelling without recording a provenance input. +fn read_declaration_cpg(path: &std::path::Path) -> std::io::Result>> { + use std::io::{Error, ErrorKind, Read}; + for ext in CPG_SPELLINGS { + let sidecar = path.with_extension(ext); + match open_declaration_file(&sidecar) { + Ok((file, size)) => { + let mut bytes = Vec::new(); + file.take(size.min(MAX_CPG_BYTES as u64 + 1)).read_to_end(&mut bytes)?; + return Ok(Some(bytes)); + } + Err(e) if e.kind() == ErrorKind::NotFound => { + if std::fs::symlink_metadata(sidecar).is_ok() { + return Err(Error::other("the .cpg has no readable target")); + } + } + Err(e) => return Err(e), + } + } + Ok(None) +} + +/// Checks the path and the opened handle. A FIFO swapped in after the first check, or a +/// write lease on Unix, cannot block the open. Reads are limited to the reported file size, +/// so size-zero pseudo-files such as `/proc/kmsg` and `trace_pipe` aren't read. +fn open_declaration_file(path: &std::path::Path) -> std::io::Result<(std::fs::File, u64)> { + let file = open_regular_file_now(path)?.ok_or_else(|| std::io::Error::other("not a regular file"))?; + let size = file.metadata()?.len(); + Ok((file, size)) +} + +/// Checks the path and opened descriptor, making one nonblocking attempt without provenance. +/// Comparisons use this directly: waiting on a lease would change the export's write behavior. +fn open_regular_file_now(path: &std::path::Path) -> std::io::Result> { if !std::fs::metadata(path)?.is_file() { return Ok(None); } #[cfg(unix)] - let file = loop { + let file = { use rustix::fs::{Mode, OFlags, open}; - match open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty()) { - Ok(fd) => break std::fs::File::from(fd), - Err(rustix::io::Errno::AGAIN) => { - crate::progress::check().map_err(std::io::Error::other)?; - std::thread::sleep(std::time::Duration::from_millis(20)); - } - Err(e) => return Err(e.into()), - } + std::fs::File::from(open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty())?) }; #[cfg(not(unix))] let file = std::fs::File::open(path)?; Ok(file.metadata()?.is_file().then_some(file)) } +/// Regular-file leases retain their cancellable wait for imports and Publish. Comparisons +/// use the one-attempt opener instead; neither opener records a destination as a source input. +pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result> { + loop { + match open_regular_file_now(path) { + #[cfg(unix)] + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + crate::progress::check().map_err(std::io::Error::other)?; + std::thread::sleep(std::time::Duration::from_millis(20)); + } + result => return result, + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 111d91bb38..b303f39eea 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -482,7 +482,10 @@ fn a_streamed_export_into_an_existing_geopackage_starts_again_inside_its_transac let src = Runs::new(&both, 4); let (e, table) = write_chunks_to(&src, &layer, &county, Crs::LonLat, &add, 1, None).unwrap(); assert_eq!(src.passes.load(std::sync::atomic::Ordering::Relaxed), 3, "written three times"); - assert_eq!((e.written, table), (20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![] }))); + assert_eq!( + (e.written, table), + (20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![], declaration_changes: Default::default() })) + ); let whole = d.join("whole.gpkg"); crate::io::write_path(&both, &whole).unwrap(); let read = |p: &Path, t: &str| { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d92e38ddd5..576afc4943 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1401,13 +1401,42 @@ pub struct GpkgWritten { pub table: String, pub replaced: bool, pub dependents: Vec, + pub declaration_changes: DeclarationChanges, +} + +/// The result of comparing the declarations of a file or table it replaced. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum DeclarationChanges { + /// No previous declarations to compare, or no changes among matching columns. + #[default] + Unchanged, + /// Matching columns whose declarations differ, in output column order. + Compared { columns: Vec, unresolved: usize }, + /// The comparison could not read the declarations. + Unavailable, +} + +impl DeclarationChanges { + /// An empty comparison needs no notice. + pub(crate) fn compared(columns: Vec, unresolved: usize) -> Self { + if columns.is_empty() && unresolved == 0 { Self::Unchanged } else { Self::Compared { columns, unresolved } } + } +} + +/// The result of a file export that can compare Shapefile declarations. +pub struct PathWritten { + pub left_out: usize, + pub table: Option, + pub notes: Vec, + /// Changes to the declarations of a Shapefile this export overwrote. + pub declaration_changes: DeclarationChanges, } /// As [`write_path`], in the coordinate system `crs` (a GeoPackage, Shapefile or FlatGeobuf; see /// [`write_bytes_in`]). Refused on a place `crs` can't hold, naming its feature, as it gives no /// notes to say it; [`write_path_to`] writes the feature without its geometry instead, and says so. pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result { - write_path_as(ds, path, crs, &GpkgTable::default(), false).map(|(left_out, _, _, _)| left_out) + write_path_as(ds, path, crs, &GpkgTable::default(), false, false).map(|(written, _)| written.left_out) } /// As [`write_path_in`], a GeoPackage's table placed as `gpkg` says (other formats ignore it): @@ -1421,20 +1450,20 @@ pub fn write_path_to( crs: Crs, gpkg: &GpkgTable, ) -> Result<(usize, Option, Vec)> { - write_path_as(ds, path, crs, gpkg, true).map(|(left_out, table, notes, _)| (left_out, table, notes)) + write_path_as(ds, path, crs, gpkg, true, false).map(|(written, _)| (written.left_out, written.table, written.notes)) } -/// [`write_path_to`], also giving the dataset's [`Dataset::lonlat_extent`]: taken from the +/// As [`write_path_to`], also reporting declaration changes when a Shapefile is overwritten. +pub fn write_path_compared(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result { + write_path_as(ds, path, crs, gpkg, true, true).map(|(written, _)| written) +} + +/// [`write_path_compared`], also giving the dataset's [`Dataset::lonlat_extent`]: taken from the /// places converted for the file when it is written in longitude/latitude from another system, /// so each is converted once, and otherwise from the dataset after the write. -pub fn write_path_placed( - ds: &Dataset, - path: &Path, - crs: Crs, - gpkg: &GpkgTable, -) -> Result<(usize, Option, Vec, rustgis_geom::Extent)> { - let (left_out, table, notes, placed) = write_path_as(ds, path, crs, gpkg, true)?; - Ok((left_out, table, notes, lonlat_extent_placed(ds, crs, placed))) +pub fn write_path_placed(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(PathWritten, rustgis_geom::Extent)> { + let (written, placed) = write_path_as(ds, path, crs, gpkg, true, true)?; + Ok((written, lonlat_extent_placed(ds, crs, placed))) } /// [`write_path_to`], leaving out a geometry `crs` can't hold (`leaving_out`, said in the notes) @@ -1446,7 +1475,8 @@ fn write_path_as( crs: Crs, gpkg: &GpkgTable, leaving_out: bool, -) -> Result<(usize, Option, Vec, Option)> { + compare: bool, +) -> Result<(PathWritten, Option)> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if crs != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()) { check_projected(&ext, crs)?; @@ -1472,7 +1502,15 @@ fn write_path_as( // Every feature is written: a layer of several kinds of geometry gets a GEOMETRY // column, and one that declares no type takes its geometry's. let table = crate::source::gpkg::write_table_in(ds, path, crs, gpkg)?; - Ok((0, Some(table), unplaced.into_iter().collect(), placed)) + Ok(( + PathWritten { + left_out: 0, + table: Some(table), + notes: unplaced.into_iter().collect(), + declaration_changes: DeclarationChanges::Unchanged, + }, + placed, + )) } #[cfg(target_arch = "wasm32")] { @@ -1484,18 +1522,114 @@ fn write_path_as( crate::progress::begin(ds.features.len()); let (parts, left_out) = shapefile_parts_in(ds, crs)?; let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (shapefile_part(path, e), bytes)).collect(); - let kept = place_shapefile(path, &stage_shapefile(&parts)?)?; - Ok((left_out, None, unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect(), placed)) + let staged = stage_shapefile(&parts)?; + let declaration_changes = + if compare { shapefile_declaration_changes(path, &parts, ds.fields.len()) } else { DeclarationChanges::Unchanged }; + let kept = place_shapefile(path, &staged)?; + let notes = unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect(); + Ok((PathWritten { left_out, table: None, notes, declaration_changes }, placed)) } _ if crs != Crs::LonLat && !holds_a_system(&ext) => { Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label()))) } _ => { let (bytes, left_out) = projected_bytes(ds, &ext, crs)?; + let declaration_changes = if compare && ext == "zip" && path.try_exists().unwrap_or(true) { + DeclarationChanges::Unavailable + } else { + DeclarationChanges::Unchanged + }; write_atomic(path, &bytes)?; - Ok((left_out, None, unplaced.into_iter().collect(), placed)) + Ok((PathWritten { left_out, table: None, notes: unplaced.into_iter().collect(), declaration_changes }, placed)) + } + } +} + +/// Compares the old attributes independently of the state of the geometry file. +fn shapefile_declaration_changes(path: &Path, parts: &[(std::path::PathBuf, Vec)], count: usize) -> DeclarationChanges { + let Some(after) = parts + .iter() + .find(|(part, _)| part.extension().is_some_and(|e| e == "dbf")) + .and_then(|(_, bytes)| crate::dbf::written_declarations(bytes, count)) + else { + return DeclarationChanges::Unavailable; + }; + match crate::dbf::read_declarations(&dbf_sidecar(path)) { + Ok((before, ldid)) => compare_dbf_declarations(&before, &after, crate::dbf::declaration_names(path, &before, ldid)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => DeclarationChanges::Unchanged, + Err(_) => DeclarationChanges::Unavailable, + } +} + +/// Prefers exact stored names. Remaining names can follow the writer's shortening and +/// numbering when the corresponding names identify the whole collision group. +fn compare_dbf_declarations( + before: &[crate::dbf::Column], + after: &[crate::dbf::Column], + decoded: Vec>, +) -> DeclarationChanges { + use std::collections::{HashMap, HashSet}; + + let mut unresolved = decoded.iter().filter(|name| name.is_none()).count(); + let mut exact = HashMap::new(); + for (i, name) in decoded.iter().enumerate() { + if let Some(name) = name { + exact.entry(name.to_ascii_lowercase()).or_insert(i); + } + } + let mut writer = DbfNames::default(); + // An undecodable name may reserve a writer collision number. Only exact matches remain + // trustworthy when the complete old numbering sequence cannot be reconstructed. + let generated: Vec<_> = if decoded.iter().any(Option::is_none) { + vec![None; decoded.len()] + } else { + decoded.iter().map(|name| name.as_deref().map(|name| writer.assign(name).to_ascii_lowercase())).collect() + }; + let names: Vec<_> = after.iter().map(|c| std::str::from_utf8(&c.name).ok()).collect(); + let keys: Vec<_> = names.iter().map(|name| name.map(str::to_ascii_lowercase)).collect(); + let mut written = HashMap::new(); + for key in keys.iter().flatten() { + *written.entry(key.as_str()).or_insert(0) += 1; + } + + let mut aliases = HashMap::new(); + let mut incomplete = HashSet::new(); + let mut used_by_exact_match = HashSet::new(); + for (i, (name, generated)) in decoded.iter().zip(&generated).enumerate() { + let (Some(name), Some(generated)) = (name, generated) else { continue }; + let key = name.to_ascii_lowercase(); + if exact.get(&key) == Some(&i) && written.get(key.as_str()) == Some(&1) { + // A generated alias cannot consume a descriptor already matched under its stored name. + used_by_exact_match.insert(generated.as_str()); + continue; + } + let group = dbf_name_base(name).to_ascii_lowercase(); + if written.get(generated.as_str()) != Some(&1) || exact.contains_key(generated) && generated != &key { + incomplete.insert(group.clone()); + } + aliases.insert(generated.as_str(), (i, group)); + } + + let mut changed = Vec::new(); + for ((column, name), key) in after.iter().zip(names).zip(&keys) { + let (Some(name), Some(key)) = (name, key) else { + unresolved += 1; + continue; + }; + let key = key.as_str(); + let old = exact.get(key).copied().or_else(|| { + let (i, group) = aliases.get(key)?; + (!incomplete.contains(group)).then_some(*i) + }); + if let Some(old) = old.and_then(|i| before.get(i)).filter(|_| written.get(key) == Some(&1)) { + if !column.same_declaration(old) { + changed.push(name.to_owned()); + } + } else if exact.contains_key(key) || aliases.contains_key(key) || used_by_exact_match.contains(key) { + unresolved += 1; } } + DeclarationChanges::compared(changed, unresolved) } /// The path of the part with extension `ext` of the Shapefile at `path`: the `.shp` keeps the @@ -5582,7 +5716,7 @@ pub fn dbf_notice_char(c: char) -> char { /// A field name as a notice shows it: cut after 40 bytes, with controls and directional marks /// flattened. [`notice_name_ends`] cuts in the middle instead. -pub(crate) fn dbf_notice_name(name: &str) -> String { +pub fn dbf_notice_name(name: &str) -> String { let mut out = String::new(); for c in name.chars().map(dbf_notice_char) { if out.len() + c.len_utf8() > 40 { @@ -5705,27 +5839,43 @@ pub(crate) fn shapefile_column_names(fields: &[Field]) -> Vec { dbf_names(fields) } +/// The part of a field name that fits the writer's dBase field name limit. +fn dbf_name_base(name: &str) -> &str { + let base = cut(name.trim(), 10); + if base.is_empty() { "FIELD" } else { base } +} + +#[derive(Default)] +struct DbfNames { + taken: std::collections::HashSet, + next_suffix: std::collections::HashMap, +} + +impl DbfNames { + /// Assigns the first available name, case-insensitively, in field order. + fn assign(&mut self, name: &str) -> String { + let base = dbf_name_base(name); + let key = base.to_ascii_lowercase(); + if self.taken.insert(key.clone()) { + return base.to_owned(); + } + let next = self.next_suffix.entry(key).or_insert(1); + for i in *next..100_000 { + let tag = format!("_{i}"); + let name = format!("{}{tag}", cut(base, 10 - tag.len())); + if self.taken.insert(name.to_ascii_lowercase()) { + *next = i + 1; + return name; + } + } + base.to_owned() + } +} + /// dBase field names (at most 10 bytes, unique without regard to case) for the fields. fn dbf_names(fields: &[Field]) -> Vec { - let mut out: Vec = Vec::with_capacity(fields.len()); - for f in fields { - let base = cut(f.name.trim(), 10); - let base = if base.is_empty() { "FIELD" } else { base }; - let taken = |n: &str, out: &[String]| out.iter().any(|o| o.eq_ignore_ascii_case(n)); - let name = if !taken(base, &out) { - base.to_string() - } else { - (1..100_000) - .map(|i| { - let tag = format!("_{i}"); - format!("{}{tag}", cut(base, 10 - tag.len())) - }) - .find(|n| !taken(n, &out)) - .unwrap_or_else(|| base.to_string()) - }; - out.push(name); - } - out + let mut names = DbfNames::default(); + fields.iter().map(|field| names.assign(&field.name)).collect() } /// Decimals of the `.dbf` field for Double field `k`: as many as fit dBase's 24 characters beside diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index b8a77305d0..10e7a4c922 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -837,7 +837,7 @@ pub fn write_table_in(ds: &crate::Dataset, path: &Path, crs: Crs, target: &GpkgT let conn = Connection::open(&tmp).map_err(err)?; let table = build(&conn, ds, name, crs, pinned)?; install(conn, tmp, path)?; - Ok(GpkgWritten { table, replaced: false, dependents: Vec::new() }) + Ok(GpkgWritten { table, replaced: false, dependents: Vec::new(), declaration_changes: Default::default() }) } /// The kind of geometry a GeoPackage table of `ds` is made for: its type or, for a layer that @@ -905,7 +905,12 @@ pub(crate) fn write_features_in( Ok((layout, extent)) => { finish(&conn, &layout, extent, pinned)?; install(conn, tmp, path)?; - return Ok(GpkgWritten { table: layout.table, replaced: false, dependents: Vec::new() }); + return Ok(GpkgWritten { + table: layout.table, + replaced: false, + dependents: Vec::new(), + declaration_changes: Default::default(), + }); } } } diff --git a/crates/data/src/source/gpkg/add.rs b/crates/data/src/source/gpkg/add.rs index e8e66f7932..8f52a5fedc 100644 --- a/crates/data/src/source/gpkg/add.rs +++ b/crates/data/src/source/gpkg/add.rs @@ -7,6 +7,7 @@ use crate::{DataError, Field, GeometryType, Result}; use rusqlite::config::DbConfig; use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use std::cell::Cell; +use std::collections::HashMap; use std::path::Path; use std::time::Duration; @@ -45,7 +46,7 @@ pub(super) fn write_features( check_geopackage(&tx, &file)?; // An attribute table has no spatial reference system. let srs_id = if geometry_type == GeometryType::None { 0 } else { srs_id(&tx, crs)? }; - // The views and triggers naming a replaced table, when one is. + // The dependent objects and declarations of a replaced table, when one is. let replaced = Cell::new(None); // The replaced table's `last_change`, which the new one's moves past. let replaced_stamp = Cell::new(None); @@ -74,12 +75,18 @@ pub(super) fn write_features( Err(Redo::Renumber) => keep_ids = false, Ok((layout, extent)) => { register(&tx, &layout, extent, pinned, replaced_stamp.take().as_deref())?; + let previous = replaced.take(); + let declaration_changes = previous.as_ref().map_or_else(Default::default, |previous| match &previous.declarations { + Some(before) => changed_declarations(&tx, &layout.table, before), + None => crate::io::DeclarationChanges::Unavailable, + }); // A cancel that came while it was written rolls it all back; the last look, as // committing writes the table, and a Cancel after it finds it written. crate::progress::check()?; tx.commit().map_err(err)?; - let dependents = replaced.take(); - return Ok(GpkgWritten { table: layout.table, replaced: dependents.is_some(), dependents: dependents.unwrap_or_default() }); + let replace = previous.is_some(); + let dependents = previous.map(|p| p.dependents).unwrap_or_default(); + return Ok(GpkgWritten { table: layout.table, replaced: replace, dependents, declaration_changes }); } } } @@ -166,12 +173,22 @@ fn srs_id(conn: &Connection, crs: Crs) -> Result { i32::try_from(id).map_err(|_| DataError::Format(format!("GeoPackage: spatial reference system id {id} is out of range"))) } +#[derive(Default)] +struct Declarations { + columns: Vec<(String, String)>, + unresolved: usize, +} + +struct ReplacedTable { + dependents: Vec, + declarations: Option, +} + /// Clears the way for table `table`: nothing of that name, or (with `replace`, which needs one) a /// feature or attribute table of it, dropped with its spatial index and its GeoPackage records. -/// For a table replaced, returns the views and other tables' triggers whose SQL names it (they -/// read the new table, and break if a column they use is gone); anything else of the name is -/// refused. -fn make_room(conn: &Connection, file: &str, table: &str, replace: bool) -> Result>> { +/// Returns the declarations and dependent views and triggers of a replaced table. Anything +/// else of the name is refused. +fn make_room(conn: &Connection, file: &str, table: &str, replace: bool) -> Result> { let registered: Option<(String, String)> = conn .query_row("SELECT table_name, data_type FROM gpkg_contents WHERE lower(table_name) = lower(?1)", [table], |r| { Ok((r.get(0)?, r.get(1)?)) @@ -207,8 +224,9 @@ fn make_room(conn: &Connection, file: &str, table: &str, replace: bool) -> Resul ))); } let dependents = dependents(conn, &old)?; + let declarations = declarations(conn, &old); drop_table(conn, &old)?; - Ok(Some(dependents)) + Ok(Some(ReplacedTable { dependents, declarations })) } (_, Some((old, data_type))) => Err(DataError::Format(format!( "{file}: {old} is a {data_type} table, which an export doesn't replace; choose another table name" @@ -220,6 +238,38 @@ fn make_room(conn: &Connection, file: &str, table: &str, replace: bool) -> Resul } } +/// Reads declarations, including sizes such as `TEXT(10)`, independently of one another. +fn declarations(conn: &Connection, table: &str) -> Option { + use rusqlite::types::ValueRef; + let mut st = conn.prepare(&format!("PRAGMA main.table_xinfo({})", quote(table))).ok()?; + let mut rows = st.query([]).ok()?; + let mut out = Declarations::default(); + while let Some(row) = rows.next().ok()? { + match (row.get_ref(1).ok()?, row.get_ref(2).ok()?) { + (ValueRef::Text(name), ValueRef::Text(ty)) => match (std::str::from_utf8(name), std::str::from_utf8(ty)) { + (Ok(name), Ok(ty)) => out.columns.push((name.to_owned(), ty.to_owned())), + _ => out.unresolved += 1, + }, + _ => out.unresolved += 1, + } + } + Some(out) +} + +/// Compares same-named columns in the replacement, ignoring case as SQLite does. +fn changed_declarations(conn: &Connection, table: &str, before: &Declarations) -> crate::io::DeclarationChanges { + use crate::io::DeclarationChanges; + let Some(after) = declarations(conn, table) else { return DeclarationChanges::Unavailable }; + let by_name: HashMap<_, _> = before.columns.iter().map(|(name, ty)| (name.to_ascii_lowercase(), ty)).collect(); + let changed = after + .columns + .into_iter() + .filter(|(name, ty)| by_name.get(&name.to_ascii_lowercase()).is_some_and(|old| !old.eq_ignore_ascii_case(ty))) + .map(|(name, _)| name) + .collect(); + DeclarationChanges::compared(changed, before.unresolved + after.unresolved) +} + /// The other tables with a foreign key to `table`. Dropping it would delete or empty their rows /// (SQLite enforces foreign keys here), or leave them pointing at rows that aren't the same. fn referencing(conn: &Connection, table: &str) -> Result> { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index d9b4cd2e0f..b3775c163d 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4515,7 +4515,14 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { } let to = |mode, name: Option<&str>| GpkgTable { mode, name: name.map(String::from) }; let written = write_path_to(&permits, &path, Crs::LonLat, &to(GpkgMode::AddTable, None)).unwrap(); - assert_eq!(written, (0, Some(GpkgWritten { table: "permits".into(), replaced: false, dependents: vec![] }), Vec::new())); + assert_eq!( + written, + ( + 0, + Some(GpkgWritten { table: "permits".into(), replaced: false, dependents: vec![], declaration_changes: Default::default() }), + Vec::new() + ) + ); rusqlite::Connection::open(&path).unwrap().execute_batch("INSERT INTO gpkg_ogr_contents VALUES ('permits', 3)").unwrap(); assert_eq!(gpkg_tables(&path), ["owners", "parcels", "permits"]); // The file's own trigger on its contents didn't run. @@ -4561,7 +4568,15 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { .execute("UPDATE gpkg_contents SET last_change = '2999-01-01T00:00:00.000Z' WHERE table_name = 'permits'", []) .unwrap(); let replaced = write_path_to(&fewer, &path, Crs::WebMercator, &to(GpkgMode::ReplaceTable, None)).unwrap(); - assert_eq!(replaced.1, Some(GpkgWritten { table: "permits".into(), replaced: true, dependents: vec!["recent_permits".into()] })); + assert_eq!( + replaced.1, + Some(GpkgWritten { + table: "permits".into(), + replaced: true, + dependents: vec!["recent_permits".into()], + declaration_changes: Default::default() + }) + ); assert_eq!(stamp(&path), "2999-01-01T00:00:00.001Z"); assert_eq!(gpkg_tables(&path), ["owners", "parcels", "permits"]); let s = open_path(&path, Some("permits")).unwrap(); @@ -4580,11 +4595,22 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { drop(c); // A second table in that system reuses its entry. let more = write_path_to(&fewer, &path, Crs::WebMercator, &to(GpkgMode::AddTable, Some("permits_2027"))).unwrap(); - assert_eq!(more.1, Some(GpkgWritten { table: "permits_2027".into(), replaced: false, dependents: vec![] })); + assert_eq!( + more.1, + Some(GpkgWritten { table: "permits_2027".into(), replaced: false, dependents: vec![], declaration_changes: Default::default() }) + ); // Its spatial index triggers mention `permits` within their own table's name, but don't use // it, so replacing `permits` again names only the view. let again = write_path_to(&fewer, &path, Crs::WebMercator, &to(GpkgMode::ReplaceTable, Some("permits"))).unwrap(); - assert_eq!(again.1, Some(GpkgWritten { table: "permits".into(), replaced: true, dependents: vec!["recent_permits".into()] })); + assert_eq!( + again.1, + Some(GpkgWritten { + table: "permits".into(), + replaced: true, + dependents: vec!["recent_permits".into()], + declaration_changes: Default::default() + }) + ); // Replacing a table not there (a misspelt name) is refused rather than adding one. let e = write_path_to(&fewer, &path, Crs::LonLat, &to(GpkgMode::ReplaceTable, Some("permit"))).unwrap_err().to_string(); assert!(e.contains("no table permit to replace"), "{e}"); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 37dc11e68a..9b471029bb 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -8,14 +8,14 @@ pub(super) use table::table_work; use std::path::Path; use rustgis_data::capped::Limit; -use rustgis_data::io::{GpkgMode, GpkgTable, GpkgWritten}; +use rustgis_data::io::{DeclarationChanges, GpkgMode, GpkgTable, GpkgWritten, PathWritten}; use rustgis_data::raster::Crs; use rustgis_render::View; use serde_json::{Value, json}; use super::exports::{Room, Work, Wrote}; use super::{f, need_layer, ps}; -use crate::{CommandSpec as C, Session}; +use crate::{CommandSpec as C, Session, notice_text::NoticeText}; /// The map export binds exactly the map and tile routes the worker will copy. fn map_inputs(s: &super::InputContext<'_>, _: &Value) -> Result { @@ -65,8 +65,66 @@ pub fn gpkg_table(p: &Value, ext: &str) -> Result { Ok(GpkgTable { mode, name }) } +/// A committed overwrite's declaration changes. File and column names stay literal when +/// the front end formats the notice. +fn declaration_change_note(path: &str, table: Option<&str>, changes: &DeclarationChanges) -> Option { + let clean = |name: &str| -> NoticeText { name.chars().map(rustgis_data::io::dbf_notice_char).collect::().into() }; + let target = match table { + Some(table) => { + NoticeText::format("{path} ({table})", [("path", clean(path)), ("table", rustgis_data::io::dbf_notice_name(table).into())]) + } + None => clean(path), + }; + let (columns, unresolved) = match changes { + DeclarationChanges::Unchanged => return None, + DeclarationChanges::Unavailable => { + return Some(NoticeText::format("{target}: could not compare the old column declarations", [("target", target)])); + } + DeclarationChanges::Compared { columns, unresolved } => (columns, *unresolved), + }; + if columns.is_empty() { + let key = if unresolved == 1 { + "{target}: could not compare {count} column declaration" + } else { + "{target}: could not compare {count} column declarations" + }; + return Some(NoticeText::format(key, [("target", target), ("count", unresolved.to_string().into())])); + } + let key = if columns.len() == 1 { + "{target}: changed {count} column declaration ({columns})" + } else { + "{target}: changed {count} column declarations ({columns})" + }; + const SHOWN: usize = 5; + let mut listed = NoticeText::list(columns.iter().take(SHOWN).map(|name| rustgis_data::io::dbf_notice_name(name).into())); + if columns.len() > SHOWN { + listed = + NoticeText::format("{columns} and {count} more", [("columns", listed), ("count", (columns.len() - SHOWN).to_string().into())]); + } + let changed = NoticeText::format(key, [("target", target), ("count", columns.len().to_string().into()), ("columns", listed)]); + if unresolved == 0 { + Some(changed) + } else { + let key = if unresolved == 1 { + "{changed}. Could not compare {count} declaration" + } else { + "{changed}. Could not compare {count} declarations" + }; + Some(NoticeText::format(key, [("changed", changed), ("count", unresolved.to_string().into())])) + } +} + +/// Keeps a committed write's declaration notice through later workflow rollback. +fn report_declaration_change(s: &mut Session, note: Option) { + if let Some(note) = note { + let mark = s.notice_mark(); + s.notify_text(note, false); + s.retain_written_notices(mark); + } +} + /// File-only GeoPackage diagnostics, available even if delivery cannot refresh live layers. -fn table_write_notes(path: &str, gpkg: &GpkgTable, default: &str, table: &GpkgWritten) -> Vec { +fn table_write_notes(path: &str, gpkg: &GpkgTable, default: &str, table: &GpkgWritten) -> Vec { let mut notes = Vec::new(); // A new file's table is said only when it isn't the name asked for, or by default the // layer's (a reserved name is prefixed, control characters and edge spaces dropped); one @@ -84,7 +142,7 @@ fn table_write_notes(path: &str, gpkg: &GpkgTable, default: &str, table: &GpkgWr table.table ) }; - notes.push(note); + notes.push(note.into()); } if gpkg.mode != GpkgMode::NewFile { let note = if table.replaced { @@ -95,26 +153,33 @@ fn table_write_notes(path: &str, gpkg: &GpkgTable, default: &str, table: &GpkgWr } else { format!("{path}: added the table {}", table.table) }; - notes.push(note); + notes.push(note.into()); if !table.dependents.is_empty() { let n = table.dependents.len(); - notes.push(format!( - "{path}: {n} view{} or trigger{} naming {} may no longer work if a column it uses is gone: {}", - if n == 1 { "" } else { "s" }, - if n == 1 { "" } else { "s" }, - table.table, - table.dependents.join(", ") - )); + notes.push( + format!( + "{path}: {n} view{} or trigger{} naming {} may no longer work if a column it uses is gone: {}", + if n == 1 { "" } else { "s" }, + if n == 1 { "" } else { "s" }, + table.table, + table.dependents.join(", ") + ) + .into(), + ); } } + notes.extend(declaration_change_note(path, Some(&table.table), &table.declaration_changes)); notes } +/// Reports the committed table and refreshes live sources that read a table it replaced. fn report_table(s: &mut Session, path: &str, gpkg: &GpkgTable, default: &str, table: Option, out: &mut Value) { let Some(table) = table else { return }; + let mark = s.notice_mark(); for note in table_write_notes(path, gpkg, default, &table) { - s.notify_written(note); + s.notify_text(note, false); } + s.retain_written_notices(mark); if gpkg.mode != GpkgMode::NewFile { let (reread, failed) = if table.replaced { super::gpkg::reset_sources(s, Path::new(path), &table.table, true) } else { (0, Vec::new()) }; @@ -771,6 +836,7 @@ fn write_layer( // first geometry's, which the chunks written say. let mut csv_points = ds.geometry_type == rustgis_data::GeometryType::Point; let mut lonlat_extent = None; + let mut declaration_changes = DeclarationChanges::Unchanged; let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks { Some((src, layer)) => { let (e, table) = rustgis_data::export::write_source_filtered(src.as_ref(), layer, Path::new(&path), crs, &gpkg, query) @@ -818,17 +884,19 @@ fn write_layer( .map_err(|e| e.to_string())?; // The layer's box in longitude/latitude comes back with the write, taken from the places // converted for the file when it is written there, so each is converted once. - let (left_out, table, placed, lonlat) = if let Some(room) = download { + let (written, lonlat) = if let Some(room) = download { let (bytes, left_out, notes, lonlat) = room.encode(path, |limit| rustgis_data::io::write_bytes_noted_within(ds, &ext, crs, path, limit))?; held = Some(std::sync::Arc::new(bytes)); - (left_out, None, notes, lonlat) + (PathWritten { left_out, table: None, notes, declaration_changes: DeclarationChanges::Unchanged }, lonlat) } else { rustgis_data::io::write_path_placed(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())? }; lonlat_extent = Some(lonlat); + let PathWritten { left_out, table, notes, declaration_changes: changes } = written; + declaration_changes = changes; // Old parts of a Shapefile written over that couldn't be removed. - format_notes.extend(placed); + format_notes.extend(notes); let unfit = if parquet { rustgis_data::source::parquet::values_note(ds, path) } else { None }; let null_numbers = rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, &ext); let mut dates = read_notes(path, &ds.name, &unreadable); @@ -884,7 +952,10 @@ fn write_layer( let written_path = Some(path.to_string()); let path = path.to_string(); let default = ds.name.clone(); - let mut refused_notes = table.as_ref().map(|t| table_write_notes(&path, &gpkg, &default, t)).unwrap_or_default(); + let mut refused_notes = + table.iter().flat_map(|t| table_write_notes(&path, &gpkg, &default, t)).map(|note| note.english()).collect::>(); + let declaration_note = declaration_change_note(&path, None, &declaration_changes); + refused_notes.extend(declaration_note.iter().map(NoticeText::english)); if let Some(note) = null_numbers_note(&path, null_numbers) { refused_notes.push(note.english()); } @@ -892,9 +963,10 @@ fn write_layer( if let Some(note) = &query_note { refused_notes.push(note.english()); } - let then: Option = if table.is_some() || null_numbers > 0 || query_note.is_some() { + let then: Option = if table.is_some() || null_numbers > 0 || query_note.is_some() || declaration_note.is_some() { Some(Box::new(move |s: &mut Session, out: &mut Value| { notify_written_query(s, query_note); + report_declaration_change(s, declaration_note); notify_null_numbers(s, &path, null_numbers); if let Some(t) = table { report_table(s, &path, &gpkg, &default, Some(t), out); @@ -939,7 +1011,6 @@ pub(crate) fn query_export_note( layer: &str, report: &rustgis_data::export::QueryReport, ) -> Option { - use crate::notice_text::NoticeText; if let Some(error) = &report.parse_error { return Some(NoticeText::format( "{path}: the definition query on {layer} could not be read ({error}) and was skipped during export", diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index 2b9c7ae300..b4ce7a1982 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -176,14 +176,15 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result notes.extend(rustgis_data::io::export_losses_notes(&ds, &ext, name_field, &path).map_err(|e| e.to_string())?); let crs = rustgis_data::raster::Crs::LonLat; let mut held = None; - let (left_out, table, placed) = if let Some(room) = download { + let written = if let Some(room) = download { let (bytes, left_out, notes, _) = room.encode(&path, |limit| rustgis_data::io::write_bytes_noted_within(&ds, &ext, crs, &path, limit))?; held = Some(std::sync::Arc::new(bytes)); - (left_out, None, notes) + super::PathWritten { left_out, table: None, notes, declaration_changes: super::DeclarationChanges::Unchanged } } else { - rustgis_data::io::write_path_to(&ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())? + rustgis_data::io::write_path_compared(&ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())? }; + let super::PathWritten { left_out, table, notes: placed, declaration_changes } = written; // Old parts of a Shapefile written over that couldn't be removed. notes.extend(placed); if let Some(note) = rustgis_data::io::left_out_note(&path, &ext, left_out) { @@ -195,7 +196,10 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result [("path", path.clone().into()), ("count", omitted.to_string().into())], ) }); - let mut refused_notes = table.as_ref().map(|t| super::table_write_notes(&path, &gpkg, &default, t)).unwrap_or_default(); + let mut refused_notes = + table.iter().flat_map(|t| super::table_write_notes(&path, &gpkg, &default, t)).map(|note| note.english()).collect::>(); + let declaration_note = super::declaration_change_note(&path, None, &declaration_changes); + refused_notes.extend(declaration_note.iter().map(super::NoticeText::english)); if let Some(note) = super::null_numbers_note(&path, null_numbers) { refused_notes.push(note.english()); } @@ -217,6 +221,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result s.notify_text(note, false); s.retain_written_notices(mark); } + super::report_declaration_change(s, declaration_note); super::notify_null_numbers(s, &path, null_numbers); super::report_table(s, &path, &gpkg, &default, table, out); Ok(()) diff --git a/crates/engine/src/tests/write_notices.rs b/crates/engine/src/tests/write_notices.rs index 695bdb591b..01783fe8f5 100644 --- a/crates/engine/src/tests/write_notices.rs +++ b/crates/engine/src/tests/write_notices.rs @@ -578,3 +578,537 @@ fn write_notices_keep_table_and_null_losses_in_refused_receipts() { } } } + +/// Replacing a Shapefile reports the columns with different physical declarations once. +#[test] +fn export_declarations_on_shapefile_overwrite() { + let dir = Files::new(); + let path = dir.path().join("places.shp"); + let params = json!({"layer": "Places", "path": path}); + let mut s = places(); + let layer = s.map_mut().layers.first_mut().unwrap(); + layer.dataset.fields[0].name = "café".into(); + let code = layer.dataset.ensure_field("code", FieldType::Integer); + layer.dataset.features[0].attrs[code] = Cell::Int(7); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("column declaration"))); + + // Make an existing target with narrower columns and a legacy encoding for the name. + let dbf = path.with_extension("dbf"); + let mut bytes = std::fs::read(&dbf).unwrap(); + let header = usize::from(u16::from_le_bytes(bytes[8..10].try_into().unwrap())); + assert_eq!((bytes[48], bytes[80]), (4, 18)); + bytes[80] = 5; + bytes[10..12].copy_from_slice(&8u16.to_le_bytes()); + bytes[48] = 2; + bytes[32..43].fill(0); + bytes[32..36].copy_from_slice(b"caf\xe9"); + bytes.truncate(header); + bytes.extend_from_slice(b" ke 7\x1a"); + std::fs::write(&dbf, bytes).unwrap(); + std::fs::write(path.with_extension("cpg"), "Windows-1252").unwrap(); + let (existing, _) = rustgis_data::io::read_path(&path).unwrap(); + assert_eq!(existing.fields[0].name, "café"); + assert_eq!(existing.value(0, 1), &Cell::Int(7)); + + s.log.set_on(true); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + let entry = s.log.entries().last().unwrap(); + assert_eq!(entry.command, "share.exportLayer"); + assert!(entry.inputs.is_empty(), "{entry:?}"); + let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("column declaration")).collect(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].text, format!("{}: changed 2 column declarations (café, code)", path.display())); + assert!(notes[0].translated(|key, _| key.to_string()).is_some()); + + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert!(declaration_notices(&s, mark).is_empty()); + + std::fs::write(&dbf, b"not a DBF header").unwrap(); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [unavailable_declarations(&path)]); + assert_eq!(rustgis_data::io::read_path(&path).unwrap().0.value(0, 1), &Cell::Int(7)); +} + +/// Existing ZIP members are not compared: the successful overwrite explicitly reports that gap. +#[test] +fn export_declarations_report_uncompared_zip_overwrite() { + let dir = Files::new(); + let path = dir.path().join("places.zip"); + let mut s = places(); + let params = json!({"layer":"Places", "path":path}); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert!(declaration_notices(&s, mark).is_empty()); + let original = std::fs::read(&path).unwrap(); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [unavailable_declarations(&path)]); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +/// Replacing a GeoPackage feature table compares the declared types of matching columns. +#[test] +fn export_declarations_on_geopackage_replace() { + let dir = Files::new(); + let path = dir.path().join("places.gpkg"); + let mut s = places(); + let layer = s.map_mut().layers.first_mut().unwrap(); + layer.dataset.fields[0].name = "label".into(); + let code = layer.dataset.ensure_field("code", FieldType::Integer); + layer.dataset.features[0].attrs[code] = Cell::Int(7); + s.run("share.exportLayer", &json!({"layer": "Places", "path": path})).unwrap(); + { + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch( + "ALTER TABLE Places DROP COLUMN label; + ALTER TABLE Places DROP COLUMN code; + ALTER TABLE Places ADD COLUMN label TEXT(10) DEFAULT 'kept'; + ALTER TABLE Places ADD COLUMN code MEDIUMINT DEFAULT 7;", + ) + .unwrap(); + } + + // Use a different GeoPackage as the streamed source so the command keeps chunked export. + let source = dir.path().join("source.gpkg"); + s.run("share.exportLayer", &json!({"layer": "Places", "path": source})).unwrap(); + s.run("layer.addData", &json!({"name": "Streamed", "path": source, "layer": "Places", "stream": true})).unwrap(); + assert!(s.map().layer_by_name("Streamed").unwrap().is_streamed()); + + let params = json!({"layer": "Streamed", "path": path, "mode": "replaceTable", "tableName": "Places"}); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("column declaration")).collect(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].text, format!("{} (Places): changed 2 column declarations (label, code)", path.display())); + assert!(notes[0].translated(|key, _| key.to_string()).is_some()); + + let mark = s.notice_mark(); + s.run("share.exportLayer", &json!({"layer": "Places", "path": path, "mode": "replaceTable"})).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("column declaration"))); +} + +fn declaration_notices(s: &Session, mark: u64) -> Vec<&str> { + s.notices_since(mark).iter().map(|n| n.text.as_str()).filter(|text| text.contains("column declaration")).collect() +} + +fn unavailable_declarations(path: &std::path::Path) -> String { + format!("{}: could not compare the old column declarations", path.display()) +} + +/// Each descriptor component is compared independently, including a type or decimals change +/// with the same width. A rejected delivery still says what the completed write changed. +#[test] +fn export_declarations_report_type_and_decimals_even_if_delivery_is_refused() { + use crate::{ + analysis::control::Control, + cmd::exports, + policy::{AgentAccess, Effects, Revocation, Scope}, + }; + + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + + for (offset, value, refused) in [(43, b'F', false), (49, 14, true)] { + let dir = Files::new(); + let path = dir.path().join("places.shp"); + let dbf = path.with_extension("dbf"); + let mut s = places(); + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields[0] = Field::new("label", FieldType::Double); + ds.features[0].attrs[0] = Cell::Float(1.25); + let params = json!({"layer":"Places","path":path}); + s.run("share.exportLayer", ¶ms).unwrap(); + let expected = std::fs::read(&dbf).unwrap(); + let mut old = expected.clone(); + assert_ne!(old[offset], value); + old[offset] = value; + std::fs::write(&dbf, old).unwrap(); + + let scope = Scope::agent(AgentAccess::Allow, false, "declaration-receipt", None, std::sync::Arc::new(Live)); + let run = s.with_scope(scope, |s| exports::export_start(s, "share.exportLayer", ¶ms)).unwrap().unwrap(); + let started = run.started(); + let wrote = run.run(&Control::stoppable()).unwrap(); + if refused { + s.run("project.new", &json!({})).unwrap(); + } + let mark = s.notice_mark(); + let result = exports::export_land(&mut s, started, Ok(wrote)); + let notice = format!("{}: changed 1 column declaration (label)", path.display()); + let seen = declaration_notices(&s, mark); + if refused { + let error = result.unwrap_err(); + assert!(error.contains("completion was refused"), "{error}"); + assert_eq!(error.matches(¬ice).count(), 1, "{error}"); + assert_eq!(seen.iter().filter(|text| text.contains(¬ice)).count(), 1, "{seen:?}"); + } else { + result.unwrap(); + assert_eq!(seen, [notice]); + } + assert_eq!(std::fs::read(&dbf).unwrap(), expected); + } +} + +#[test] +fn export_declarations_match_exact_names_before_unambiguous_shortened_names() { + let dir = Files::new(); + let path = dir.path().join("places.shp"); + let dbf = path.with_extension("dbf"); + let params = json!({"layer":"Places","path":path}); + let mut s = places(); + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields[0].name = "ABCDEFGHI".into(); + let padded = ds.ensure_field("ABCDEFGHI JK", FieldType::Text); + ds.features[0].attrs[padded] = Cell::Text("kept".into()); + let legacy = ds.ensure_field("ééééé", FieldType::Text); + ds.features[0].attrs[legacy] = Cell::Text("kept".into()); + s.run("share.exportLayer", ¶ms).unwrap(); + let mut old = std::fs::read(&dbf).unwrap(); + assert_eq!(&old[64..74], b"ABCDEFGHI "); + // Both new ASCII names have their own old column. Only the second one's type changed. + old[75] = b'N'; + // This name expands beyond 10 bytes when the writer switches from Windows-1252 to UTF-8. + old[96..107].copy_from_slice(b"\xe9\xe9\xe9\xe9\xe9\xe9\0\0\0\0\0"); + old[107] = b'N'; + std::fs::write(&dbf, old).unwrap(); + std::fs::write(path.with_extension("cpg"), "Windows-1252").unwrap(); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [format!("{}: changed 2 column declarations (ABCDEFGHI , ééééé)", path.display())]); + + let mut old = std::fs::read(&dbf).unwrap(); + // The second old descriptor now repeats the first name in lower case, with another type. + // The first descriptor still matches exactly. The new padded name has no old counterpart. + old[64..75].copy_from_slice(b"abcdefghi\0\0"); + old[75] = b'N'; + std::fs::write(&dbf, old).unwrap(); + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert!(declaration_notices(&s, mark).is_empty()); +} + +/// Covers independently readable declarations, legacy headers, and names the writer numbers. +/// Each row goes through the actual export command and checks the complete declaration notice. +#[test] +fn export_declarations_compare_old_metadata_independently() { + use std::fs; + + fn descriptor(name: &[u8], ty: u8, width: u16) -> [u8; 32] { + let mut descriptor = [0; 32]; + descriptor[..name.len()].copy_from_slice(name); + descriptor[11] = ty; + descriptor[16..18].copy_from_slice(&width.to_le_bytes()); + descriptor + } + + let dir = Files::new(); + let changed = "changed 1 column declaration (label)"; + let unavailable = "could not compare the old column declarations"; + let partial = "changed 1 column declaration (label). Could not compare 1 declaration"; + let long_twins: &[&[u8]] = &[b"ABCDEFGHIJK", b"ABCDEFGHIJL"]; + let case_twins: &[&[u8]] = &[b"name", b"NAME"]; + let cpg = Some(b"UTF-8".as_slice()); + let number = "changed 2 column declarations (ABCDEFGHIJ, ABCDEFGH_1)"; + let cases = [ + ("ASCII with unsupported LDID", None, 0xff, Some(changed)), + ("ASCII with junk CPG", Some(b"OEM".as_slice()), 0xff, Some(changed)), + ("unchanged ASCII with junk CPG", Some(b"OEM".as_slice()), 0xff, None), + ("absent DBF", cpg, 0, None), + ("uppercase DBF", cpg, 0, Some(changed)), + ("no terminator", cpg, 0, Some(changed)), + ("record width mismatch", cpg, 0, Some(changed)), + ("Clipper width with matching low byte", cpg, 0, Some(changed)), + ("truncated descriptor", cpg, 0, Some(unavailable)), + ("header ends within descriptor", cpg, 0, Some(unavailable)), + ("malformed UTF-8", cpg, 0, Some(partial)), + ("non-ASCII with unsupported LDID", None, 0xff, Some(partial)), + ("numbered after cutting", cpg, 0, Some(number)), + ("numbered case twins", cpg, 0, Some("changed 2 column declarations (name, NAME_1)")), + ("ambiguous cut", cpg, 0, Some(partial)), + ("alias already matched exactly", cpg, 0, Some("changed 1 column declaration (ABCDEFGHIJ). Could not compare 1 declaration")), + ("ambiguous written name", cpg, 0, Some("could not compare 2 column declarations")), + ("retained after rollback", cpg, 0, Some(changed)), + #[cfg(unix)] + ("dangling DBF", cpg, 0, None), + #[cfg(unix)] + ("dangling CPG", None, 3, Some(partial)), + #[cfg(unix)] + ("geometry symlink loop", cpg, 0, Some(changed)), + #[cfg(unix)] + ("unreadable CPG", None, 3, Some(partial)), + ]; + + for (i, (case, cpg, ldid, expected)) in cases.into_iter().enumerate() { + let path = dir.path().join(format!("p{i}.shp")); + let dbf = path.with_extension("dbf"); + let codepage = path.with_extension("cpg"); + let params = json!({"layer":"Places","path":path}); + let mut s = places(); + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields[0].name = "label".into(); + let (names, fields, width) = match case { + "numbered after cutting" => (long_twins, &["ABCDEFGHIJK", "ABCDEFGHIJL"][..], 4), + "numbered case twins" => (case_twins, &["name", "NAME"][..], 4), + "ambiguous cut" => (long_twins, &["ABCDEFGHIJ"][..], 20), + "alias already matched exactly" => { + (&[b"ABCDEFGHIJK".as_slice(), b"ABCDEFGHIJ".as_slice()][..], &["ABCDEFGHIJK", "ABCDEFGHIJ"][..], 4) + } + "ambiguous written name" => (&[b"name".as_slice()][..], &["name\0aa", "name\0bb"][..], 4), + "non-ASCII with unsupported LDID" => (&["café".as_bytes()][..], &["café"][..], 20), + "malformed UTF-8" | "dangling CPG" | "unreadable CPG" => (&[b"caf\xe9".as_slice()][..], &["café"][..], 20), + "Clipper width with matching low byte" => (&[][..], &[][..], 260), + "unchanged ASCII with junk CPG" => (&[][..], &[][..], 4), + _ => (&[][..], &[][..], 20), + }; + for name in fields { + let slot = ds.fields.len(); + ds.fields.push(Field::new(*name, FieldType::Text)); + ds.features[0].attrs.resize(slot + 1, Cell::Text("kept".into())); + } + s.run("share.exportLayer", ¶ms).unwrap(); + let mut old = fs::read(&dbf).unwrap()[..32].to_vec(); + old[29] = ldid; + old.extend_from_slice(&descriptor(b"label", b'C', width)); + for name in names { + old.extend_from_slice(&descriptor(name, b'C', 9)); + } + if case != "no terminator" { + old.push(0x0d); + } + let header_len = u16::try_from(old.len()).unwrap(); + old[8..10].copy_from_slice(&header_len.to_le_bytes()); + let record_len = 1 + width + 9 * names.len() as u16 + u16::from(case == "record width mismatch"); + old[10..12].copy_from_slice(&record_len.to_le_bytes()); + if case == "truncated descriptor" { + old.truncate(48); + } + if case == "header ends within descriptor" { + old[8..10].copy_from_slice(&48u16.to_le_bytes()); + } + fs::write(&dbf, old).unwrap(); + fs::remove_file(&codepage).unwrap(); + if let Some(cpg) = cpg { + fs::write(&codepage, cpg).unwrap(); + } + match case { + "uppercase DBF" => fs::rename(&dbf, path.with_extension("DBF")).unwrap(), + "absent DBF" => fs::remove_file(&dbf).unwrap(), + #[cfg(unix)] + "dangling DBF" => { + fs::remove_file(&dbf).unwrap(); + std::os::unix::fs::symlink("missing", &dbf).unwrap(); + } + #[cfg(unix)] + "dangling CPG" => std::os::unix::fs::symlink("missing", &codepage).unwrap(), + #[cfg(unix)] + "geometry symlink loop" => { + fs::remove_file(&path).unwrap(); + std::os::unix::fs::symlink(path.file_name().unwrap(), &path).unwrap(); + } + #[cfg(unix)] + "unreadable CPG" => { + use std::os::unix::fs::PermissionsExt; + fs::write(&codepage, b"1252").unwrap(); + fs::set_permissions(&codepage, fs::Permissions::from_mode(0o000)).unwrap(); + if fs::File::open(&codepage).is_ok() { + continue; // A privileged runner can read the sidecar. + } + } + _ => {} + } + let mark = s.notice_mark(); + if case == "retained after rollback" { + let script = format!("share.exportLayer {params}\nlayer.remove {{\"layer\":\"missing\"}}"); + assert!(s.run("script.run", &json!({"script":script})).is_err()); + } else { + s.run("share.exportLayer", ¶ms).unwrap(); + } + let expected: Vec<_> = expected.into_iter().map(|message| format!("{}: {message}", path.display())).collect(); + assert_eq!(declaration_notices(&s, mark), expected, "{case}"); + } +} + +/// Runs the export in a child process so a regression can be stopped and reaped even if it +/// blocks in open or read. +#[cfg(unix)] +#[test] +fn export_declarations_do_not_open_non_regular_sidecars_for_io() { + const SCENARIO: &str = "RUSTGIS_TEST_OVERWRITE_FIFO"; + let path = if let Some(path) = std::env::var_os(SCENARIO) { + std::path::PathBuf::from(path) + } else { + let dir = Files::new(); + let path = dir.path().join("places.shp"); + let name = concat!(module_path!(), "::export_declarations_do_not_open_non_regular_sidecars_for_io"); + let name = name.split_once("::").unwrap().1; + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--nocapture"]) + .env(SCENARIO, &path) + .spawn() + .unwrap(); + let start = std::time::Instant::now(); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success(), "FIFO export child: {status}"); + assert!(path.is_file(), "the child did not run the export"); + return; + } + if start.elapsed() >= std::time::Duration::from_secs(60) { + let _ = child.kill(); + child.wait().unwrap(); + panic!("export blocked on a FIFO"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); // test-wait: poll child exit until the blocked-export deadline + } + }; + for extension in ["CpG", "dbf"] { + let params = json!({"layer":"Places","path":path}); + let mut s = places(); + s.map_mut().layers.first_mut().unwrap().dataset.fields[0].name = "café".into(); + s.run("share.exportLayer", ¶ms).unwrap(); + std::fs::remove_file(path.with_extension(extension.to_ascii_lowercase())).unwrap(); + let sidecar = path.with_extension(extension); + assert!(std::process::Command::new("mkfifo").arg(&sidecar).status().unwrap().success()); + + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + let expected = if extension == "dbf" { + unavailable_declarations(&path) + } else { + format!("{}: could not compare 1 column declaration", path.display()) + }; + assert_eq!(declaration_notices(&s, mark), [expected]); + assert!(path.with_extension("dbf").is_file()); + assert!( + std::fs::read_dir(path.parent().unwrap()).unwrap().all(|entry| !entry.unwrap().file_name().to_string_lossy().starts_with('.')) + ); + } +} + +#[test] +fn export_declarations_are_quiet_on_failed_or_cancelled_overwrite() { + use crate::{analysis::control::Control, cmd::exports}; + + let dir = Files::new(); + let path = dir.path().join("places.shp"); + let params = json!({"layer":"Places","path":path}); + let mut s = places(); + s.run("share.exportLayer", ¶ms).unwrap(); + let dbf = path.with_extension("dbf"); + let mut old = std::fs::read(&dbf).unwrap(); + old[43] = b'N'; + + // Count the write's cancellation checks, then stop it at the last one during placement. + let control = Control::cancelled_at_look(u64::MAX); + exports::export_start(&mut s, "share.exportLayer", ¶ms).unwrap().run(&control).unwrap(); + assert!(control.looked() > 1); + std::fs::write(&dbf, &old).unwrap(); + let run = exports::export_start(&mut s, "share.exportLayer", ¶ms).unwrap(); + let started = run.started(); + let done = run.run(&Control::cancelled_at_look(control.looked())); + let mark = s.notice_mark(); + assert!(exports::export_land(&mut s, started, done).unwrap_err().contains("cancelled")); + assert!(declaration_notices(&s, mark).is_empty()); + assert_eq!(std::fs::read(&dbf).unwrap(), old); + + s.map_mut().layers.first_mut().unwrap().dataset = Dataset::new("Places", GeometryType::None, vec![]); + let mark = s.notice_mark(); + assert!(s.run("share.exportLayer", ¶ms).unwrap_err().contains("without geometry as a Shapefile")); + assert!(declaration_notices(&s, mark).is_empty()); + assert_eq!(std::fs::read(&dbf).unwrap(), old); +} + +#[test] +fn export_declarations_cover_table_replacements() { + let dir = Files::new(); + let mut s = places(); + // A project file can hold a table with geometry. Exercise that command entry point. + let dataset = s.map().layer_by_name("Places").unwrap().dataset.clone(); + let mut snapshot = serde_json::to_value(&s.project).unwrap(); + snapshot["tables"] = json!([{"id":1, "name":"spatial", "geometry_type":dataset.geometry_type, + "fields":dataset.fields, "features":dataset.features}]); + s.run("project.openText", &json!({"text":snapshot.to_string()})).unwrap(); + let path = dir.path().join("places.shp"); + let params = json!({"table":"spatial","path":path}); + s.run("share.exportTable", ¶ms).unwrap(); + let dbf = path.with_extension("dbf"); + let mut old = std::fs::read(&dbf).unwrap(); + old[43] = b'N'; + std::fs::write(&dbf, old).unwrap(); + let mark = s.notice_mark(); + s.run("share.exportTable", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [format!("{}: changed 1 column declaration (long_attri)", path.display())]); + + s.run("layer.addDataText", &json!({"fileName":"ranks.csv","text":"label\nfirst\nsecond\n"})).unwrap(); + let path = dir.path().join("ranks.gpkg"); + let mark = s.notice_mark(); + s.run("share.exportTable", &json!({"table":"ranks","path":path})).unwrap(); + s.run("share.exportTable", &json!({"table":"ranks","path":path,"mode":"addTable","tableName":"other"})).unwrap(); + assert!(declaration_notices(&s, mark).is_empty()); + { + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch("ALTER TABLE ranks DROP COLUMN label; ALTER TABLE ranks ADD COLUMN label TEXT(10);").unwrap(); + } + let params = json!({"table":"ranks","path":path,"mode":"replaceTable"}); + let mark = s.notice_mark(); + s.run("share.exportTable", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [format!("{} (ranks): changed 1 column declaration (label)", path.display())]); + for (declaration, expected) in [ + ("'\"label\" BLOB' || CAST(x'FF' AS TEXT)", "could not compare 1 column declaration"), + ( + "'\"label\" TEXT(10), \"bad' || CAST(x'FF' AS TEXT) || '\" TEXT, \"bad_type\" BLOB' || CAST(x'FF' AS TEXT)", + "changed 1 column declaration (label). Could not compare 2 declarations", + ), + ] { + // SQLite can read the schema and replace this table even when some text isn't UTF-8. + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch(&format!( + "PRAGMA writable_schema=ON; + UPDATE sqlite_schema SET sql=replace(sql, '\"label\" TEXT', {declaration}) WHERE name='ranks';" + )) + .unwrap(); + drop(db); + let mark = s.notice_mark(); + s.run("share.exportTable", ¶ms).unwrap(); + assert_eq!(declaration_notices(&s, mark), [format!("{} (ranks): {expected}", path.display())]); + } + let db = rusqlite::Connection::open(&path).unwrap(); + assert_eq!(db.query_row("SELECT label FROM ranks ORDER BY fid LIMIT 1", [], |r| r.get::<_, String>(0)).unwrap(), "first"); + assert_eq!(db.query_row("SELECT count(*) FROM other", [], |r| r.get::<_, u32>(0)).unwrap(), 2); +} + +#[test] +fn export_declarations_count_all_changed_columns_of_a_wide_table() { + let dir = Files::new(); + let path = dir.path().join("wide.gpkg"); + let mut s = places(); + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields[0].name = "label".into(); + for i in 0..240 { + ds.ensure_field(&format!("col_{i:03}_{}", "x".repeat(65)), FieldType::Text); + } + s.run("share.exportLayer", &json!({"layer":"Places","path":path})).unwrap(); + { + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch( + "PRAGMA writable_schema=ON; + UPDATE sqlite_schema SET sql=replace(sql,' TEXT',' TEXT(10)') WHERE name='Places';", + ) + .unwrap(); + } + let mark = s.notice_mark(); + s.run("share.exportLayer", &json!({"layer":"Places","path":path,"mode":"replaceTable"})).unwrap(); + let names = (0..4).map(|i| format!("col_{i:03}_{}…", "x".repeat(32))).collect::>().join(", "); + let expected = format!("{} (Places): changed 241 column declarations (label, {names} and 236 more)", path.display()); + assert_eq!(declaration_notices(&s, mark), [expected.as_str()]); + let notice = s.notices_since(mark).iter().find(|n| n.text == expected).unwrap(); + assert!(notice.translated(|key, _| key.to_owned()).is_some()); +} From 066291f0bb04d87634e02411be8250f9d7a995bc Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 08:31:13 -0600 Subject: [PATCH 2/2] fix(data): match original names before DBF export aliases --- crates/data/src/dbf.rs | 6 ++- crates/data/src/io.rs | 41 +++++++++++++----- crates/data/src/source/gpkg/add.rs | 4 +- crates/engine/src/tests/write_notices.rs | 53 ++++++++++++++++++++---- 4 files changed, 82 insertions(+), 22 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index c2d4f53f16..b8d05eb175 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -644,9 +644,13 @@ fn open_regular_file_now(path: &std::path::Path) -> std::io::Result std::io::Result> { + #[cfg(not(unix))] + { + open_regular_file_now(path) + } + #[cfg(unix)] loop { match open_regular_file_now(path) { - #[cfg(unix)] Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { crate::progress::check().map_err(std::io::Error::other)?; std::thread::sleep(std::time::Duration::from_millis(20)); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 576afc4943..3f6d5c160b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1524,7 +1524,7 @@ fn write_path_as( let parts: Vec<(std::path::PathBuf, Vec)> = parts.into_iter().map(|(e, bytes)| (shapefile_part(path, e), bytes)).collect(); let staged = stage_shapefile(&parts)?; let declaration_changes = - if compare { shapefile_declaration_changes(path, &parts, ds.fields.len()) } else { DeclarationChanges::Unchanged }; + if compare { shapefile_declaration_changes(path, &parts, &ds.fields) } else { DeclarationChanges::Unchanged }; let kept = place_shapefile(path, &staged)?; let notes = unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect(); Ok((PathWritten { left_out, table: None, notes, declaration_changes }, placed)) @@ -1546,37 +1546,49 @@ fn write_path_as( } /// Compares the old attributes independently of the state of the geometry file. -fn shapefile_declaration_changes(path: &Path, parts: &[(std::path::PathBuf, Vec)], count: usize) -> DeclarationChanges { +fn shapefile_declaration_changes(path: &Path, parts: &[(std::path::PathBuf, Vec)], fields: &[Field]) -> DeclarationChanges { let Some(after) = parts .iter() .find(|(part, _)| part.extension().is_some_and(|e| e == "dbf")) - .and_then(|(_, bytes)| crate::dbf::written_declarations(bytes, count)) + .and_then(|(_, bytes)| crate::dbf::written_declarations(bytes, fields.len())) else { return DeclarationChanges::Unavailable; }; match crate::dbf::read_declarations(&dbf_sidecar(path)) { - Ok((before, ldid)) => compare_dbf_declarations(&before, &after, crate::dbf::declaration_names(path, &before, ldid)), + Ok((before, ldid)) => compare_dbf_declarations(&before, &after, fields, crate::dbf::declaration_names(path, &before, ldid)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => DeclarationChanges::Unchanged, Err(_) => DeclarationChanges::Unavailable, } } -/// Prefers exact stored names. Remaining names can follow the writer's shortening and -/// numbering when the corresponding names identify the whole collision group. +/// Matches original export names first, then stored output names and unambiguous writer aliases. +/// Original names pair legacy eleven-byte descriptors correctly after field reordering. +/// Without those matches, `abcdefghijk` and `abcdefghijl` can match `abcdefghij` and `abcdefgh_1` +/// together; with just one output name present, that collision group stays unresolved. fn compare_dbf_declarations( before: &[crate::dbf::Column], after: &[crate::dbf::Column], + fields: &[Field], decoded: Vec>, ) -> DeclarationChanges { use std::collections::{HashMap, HashSet}; let mut unresolved = decoded.iter().filter(|name| name.is_none()).count(); let mut exact = HashMap::new(); + let mut stored = HashMap::new(); for (i, name) in decoded.iter().enumerate() { if let Some(name) = name { exact.entry(name.to_ascii_lowercase()).or_insert(i); + stored.entry(name.as_str()).or_insert(i); } } + // Original export names survive field reordering; numbered writer aliases do not. + let original: Vec<_> = + fields.iter().map(|f| stored.get(f.name.as_str()).or_else(|| exact.get(&f.name.to_ascii_lowercase())).copied()).collect(); + let mut claimed = HashMap::new(); + for &old in original.iter().flatten() { + *claimed.entry(old).or_insert(0) += 1; + } let mut writer = DbfNames::default(); // An undecodable name may reserve a writer collision number. Only exact matches remain // trustworthy when the complete old numbering sequence cannot be reconstructed. @@ -1611,21 +1623,28 @@ fn compare_dbf_declarations( } let mut changed = Vec::new(); - for ((column, name), key) in after.iter().zip(names).zip(&keys) { + for (at, ((column, name), key)) in after.iter().zip(names).zip(&keys).enumerate() { let (Some(name), Some(key)) = (name, key) else { unresolved += 1; continue; }; let key = key.as_str(); - let old = exact.get(key).copied().or_else(|| { - let (i, group) = aliases.get(key)?; - (!incomplete.contains(group)).then_some(*i) + let direct = original.get(at).copied().flatten(); + let old = direct.filter(|i| claimed.get(i) == Some(&1)).or_else(|| { + exact + .get(key) + .copied() + .or_else(|| { + let (i, group) = aliases.get(key)?; + (!incomplete.contains(group)).then_some(*i) + }) + .filter(|i| !claimed.contains_key(i)) }); if let Some(old) = old.and_then(|i| before.get(i)).filter(|_| written.get(key) == Some(&1)) { if !column.same_declaration(old) { changed.push(name.to_owned()); } - } else if exact.contains_key(key) || aliases.contains_key(key) || used_by_exact_match.contains(key) { + } else if direct.is_some() || exact.contains_key(key) || aliases.contains_key(key) || used_by_exact_match.contains(key) { unresolved += 1; } } diff --git a/crates/data/src/source/gpkg/add.rs b/crates/data/src/source/gpkg/add.rs index 8f52a5fedc..0450956c0e 100644 --- a/crates/data/src/source/gpkg/add.rs +++ b/crates/data/src/source/gpkg/add.rs @@ -224,9 +224,9 @@ fn make_room(conn: &Connection, file: &str, table: &str, replace: bool) -> Resul ))); } let dependents = dependents(conn, &old)?; - let declarations = declarations(conn, &old); + let old_declarations = declarations(conn, &old); drop_table(conn, &old)?; - Ok(Some(ReplacedTable { dependents, declarations })) + Ok(Some(ReplacedTable { dependents, declarations: old_declarations })) } (_, Some((old, data_type))) => Err(DataError::Format(format!( "{file}: {old} is a {data_type} table, which an export doesn't replace; choose another table name" diff --git a/crates/engine/src/tests/write_notices.rs b/crates/engine/src/tests/write_notices.rs index 01783fe8f5..18fdda722c 100644 --- a/crates/engine/src/tests/write_notices.rs +++ b/crates/engine/src/tests/write_notices.rs @@ -621,7 +621,7 @@ fn export_declarations_on_shapefile_overwrite() { let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("column declaration")).collect(); assert_eq!(notes.len(), 1); assert_eq!(notes[0].text, format!("{}: changed 2 column declarations (café, code)", path.display())); - assert!(notes[0].translated(|key, _| key.to_string()).is_some()); + assert_eq!(notes[0].translated(|key, _| key.to_string()), Some("{target}: changed {count} column declarations ({columns})".into())); let mark = s.notice_mark(); s.run("share.exportLayer", ¶ms).unwrap(); @@ -640,15 +640,27 @@ fn export_declarations_report_uncompared_zip_overwrite() { let dir = Files::new(); let path = dir.path().join("places.zip"); let mut s = places(); + let contents = || { + rustgis_data::zip::read(&std::fs::read(&path).unwrap()) + .unwrap() + .into_iter() + .map(|(name, mut bytes)| { + if name.ends_with(".dbf") { + bytes[1..4].fill(0); // The writer stamps its current day. + } + (name, bytes) + }) + .collect::>() + }; let params = json!({"layer":"Places", "path":path}); let mark = s.notice_mark(); s.run("share.exportLayer", ¶ms).unwrap(); assert!(declaration_notices(&s, mark).is_empty()); - let original = std::fs::read(&path).unwrap(); + let original = contents(); let mark = s.notice_mark(); s.run("share.exportLayer", ¶ms).unwrap(); assert_eq!(declaration_notices(&s, mark), [unavailable_declarations(&path)]); - assert_eq!(std::fs::read(&path).unwrap(), original); + assert_eq!(contents(), original); } /// Replacing a GeoPackage feature table compares the declared types of matching columns. @@ -685,7 +697,7 @@ fn export_declarations_on_geopackage_replace() { let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("column declaration")).collect(); assert_eq!(notes.len(), 1); assert_eq!(notes[0].text, format!("{} (Places): changed 2 column declarations (label, code)", path.display())); - assert!(notes[0].translated(|key, _| key.to_string()).is_some()); + assert_eq!(notes[0].translated(|key, _| key.to_string()), Some("{target}: changed {count} column declarations ({columns})".into())); let mark = s.notice_mark(); s.run("share.exportLayer", &json!({"layer": "Places", "path": path, "mode": "replaceTable"})).unwrap(); @@ -753,7 +765,8 @@ fn export_declarations_report_type_and_decimals_even_if_delivery_is_refused() { result.unwrap(); assert_eq!(seen, [notice]); } - assert_eq!(std::fs::read(&dbf).unwrap(), expected); + let actual = std::fs::read(&dbf).unwrap(); + assert_eq!((&actual[..1], &actual[4..]), (&expected[..1], &expected[4..])); } } @@ -793,6 +806,29 @@ fn export_declarations_match_exact_names_before_unambiguous_shortened_names() { let mark = s.notice_mark(); s.run("share.exportLayer", ¶ms).unwrap(); assert!(declaration_notices(&s, mark).is_empty()); + + // Legacy descriptors can hold eleven bytes without a NUL. Reordering the original + // fields changes the writer's shortened aliases, but neither field's declaration. + for reversed in [false, true] { + let mut s = places(); + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields[0].name = "ABCDEFGHIJK".into(); + let number = ds.ensure_field("ABCDEFGHIJL", FieldType::Integer); + ds.features[0].attrs[number] = Cell::Int(7); + s.run("share.exportLayer", ¶ms).unwrap(); + let mut old = std::fs::read(&dbf).unwrap(); + old[32..43].copy_from_slice(b"ABCDEFGHIJK"); + old[64..75].copy_from_slice(b"ABCDEFGHIJL"); + std::fs::write(&dbf, old).unwrap(); + if reversed { + let ds = &mut s.map_mut().layers.first_mut().unwrap().dataset; + ds.fields.swap(0, 1); + ds.features[0].attrs.swap(0, 1); + } + let mark = s.notice_mark(); + s.run("share.exportLayer", ¶ms).unwrap(); + assert!(declaration_notices(&s, mark).is_empty(), "reversed={reversed}: {:?}", declaration_notices(&s, mark)); + } } /// Covers independently readable declarations, legacy headers, and names the writer numbers. @@ -833,7 +869,7 @@ fn export_declarations_compare_old_metadata_independently() { ("numbered after cutting", cpg, 0, Some(number)), ("numbered case twins", cpg, 0, Some("changed 2 column declarations (name, NAME_1)")), ("ambiguous cut", cpg, 0, Some(partial)), - ("alias already matched exactly", cpg, 0, Some("changed 1 column declaration (ABCDEFGHIJ). Could not compare 1 declaration")), + ("alias already matched exactly", cpg, 0, Some("changed 2 column declarations (ABCDEFGHIJ, ABCDEFGH_1)")), ("ambiguous written name", cpg, 0, Some("could not compare 2 column declarations")), ("retained after rollback", cpg, 0, Some(changed)), #[cfg(unix)] @@ -919,7 +955,8 @@ fn export_declarations_compare_old_metadata_independently() { fs::write(&codepage, b"1252").unwrap(); fs::set_permissions(&codepage, fs::Permissions::from_mode(0o000)).unwrap(); if fs::File::open(&codepage).is_ok() { - continue; // A privileged runner can read the sidecar. + eprintln!("skipping unreadable CPG case: this runner can read a mode-000 file"); + continue; } } _ => {} @@ -1110,5 +1147,5 @@ fn export_declarations_count_all_changed_columns_of_a_wide_table() { let expected = format!("{} (Places): changed 241 column declarations (label, {names} and 236 more)", path.display()); assert_eq!(declaration_notices(&s, mark), [expected.as_str()]); let notice = s.notices_since(mark).iter().find(|n| n.text == expected).unwrap(); - assert!(notice.translated(|key, _| key.to_owned()).is_some()); + assert_eq!(notice.translated(|key, _| key.to_owned()), Some("{target}: changed {count} column declarations ({columns})".into())); }