Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions crates/data/src/interop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,33 @@ fn text(out: Vec<u8>) -> crate::Result<String> {
String::from_utf8(out).map_err(|e| crate::DataError::Format(e.to_string()))
}

/// The opaque text identifier written with explicit XML Schema string typing. Loss prediction
/// uses the same rule, because these values are neither trimmed nor inferred on re-import.
pub(crate) fn kml_typed_string(field: &crate::Field) -> bool {
field.name == "id" && field.ty == crate::FieldType::Text
}

/// [`to_kml`]'s document, written to `out` as it is made.
pub(crate) fn write_kml(ds: &Dataset, name_field: Option<usize>, out: &mut impl Write) -> crate::Result<()> {
write!(
out.write_all(b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"")?;
writeln!(
out,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document><name>{}</name>\n",
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><Document><name>{}</name>",
xml(&ds.name, "KML", || "layer name".to_string())?
)?;
// Declare columns independently of populated values, so all-null columns survive a read.
out.write_all(b"<Schema id=\"fields\">")?;
for field in &ds.fields {
crate::progress::check()?;
let name = xml(&field.name, "KML", || format!("{}, field name '{}'", ds.name, field.name.escape_debug()))?
.replace('\t', "&#9;")
.replace('\n', "&#10;");
// ExtendedData's Data/value entries are text. Keep their inferred-reader behavior;
// a 64-bit integer must not be mislabeled as KML's 32-bit int type.
let ty = "string";
write!(out, "<SimpleField name=\"{name}\" type=\"{ty}\"/>")?;
}
out.write_all(b"</Schema>\n")?;
// KML's description is text. Other types and differently-cased columns stay in
// ExtendedData, where the reader preserves their values and reports name collisions.
let description = ds.fields.iter().position(|f| f.name == "description" && f.ty == crate::FieldType::Text);
Expand Down Expand Up @@ -147,7 +167,10 @@ pub(crate) fn write_kml(ds: &Dataset, name_field: Option<usize>, out: &mut impl
let name = xml(&fd.name, "KML", || format!("{}, field name '{}'", ds.name, fd.name.escape_debug()))?
.replace('\t', "&#9;")
.replace('\n', "&#10;");
Ok(format!("<Data name=\"{name}\"><value>{value}</value></Data>"))
// An opaque source id can look numeric, including ids accepted from malformed
// XML ID attributes. Explicit string typing keeps its exact spelling on read.
let ty = if kml_typed_string(fd) { " xsi:type=\"xs:string\"" } else { "" };
Ok(format!("<Data name=\"{name}\"><value{ty}>{value}</value></Data>"))
})
.collect::<crate::Result<String>>()?;
write!(
Expand Down
84 changes: 65 additions & 19 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3603,8 +3603,14 @@ pub fn double_holds(v: &str) -> bool {
/// Types a dataset's Text columns from their values (see [`text_type`]), for readers whose
/// formats hold every value as text (KML, GPX); the columns named in `keep` stay text.
pub(crate) fn type_text_columns(ds: &mut Dataset, keep: &[&str]) {
type_text_columns_keeping(ds, |_, field| keep.iter().any(|k| field.name.eq_ignore_ascii_case(k)));
}

/// Infer text column types except those a reader identifies as explicitly textual. The index
/// lets readers distinguish renamed extended-data fields from their fixed text columns.
pub(crate) fn type_text_columns_keeping(ds: &mut Dataset, keep: impl Fn(usize, &Field) -> bool) {
for i in 0..ds.fields.len() {
if ds.fields.get(i).is_none_or(|f| f.ty != FieldType::Text || keep.iter().any(|k| f.name.eq_ignore_ascii_case(k))) {
if ds.fields.get(i).is_none_or(|f| f.ty != FieldType::Text || keep(i, f)) {
continue;
}
let ty = text_type(ds.features.iter().filter_map(|f| match f.attrs.get(i) {
Expand Down Expand Up @@ -5605,9 +5611,8 @@ impl std::ops::AddAssign for CsvLosses {
/// ([`read_dbf`]).
/// - KML and GPX trim each value; a blank name reads as null, and a blank KML extended data
/// value too in a column read as numbers ([`type_text_columns`], for each kind of geometry's
/// layer). A KML description is kept as it is. KML writes no null value, so a field without one
/// has no column, which [`export_losses_notes`] says; GPX writes only names, which
/// [`gpx_notes`] says.
/// layer). A KML description and an explicitly typed string id are kept as they are. KML
/// declares even all-null columns in its Schema; GPX writes only names, which [`gpx_notes`] says.
///
/// A streamed export adds up its chunks' (`+=`): whether reading takes a column as numbers, which
/// decides what its blanks become, is settled over all of them.
Expand Down Expand Up @@ -5698,8 +5703,12 @@ impl TextLosses {
reads.push(TextRead::Cell);
} else if shp && matches!(f.ty, FieldType::Text | FieldType::DateTime) {
reads.push(TextRead::Dbf);
} else if kml && f.name != "description" && !(named && f.name.eq_ignore_ascii_case("name")) {
// A KML description is text as it is.
} else if kml
&& f.name != "description"
&& !crate::interop::kml_typed_string(f)
&& !(named && f.name.eq_ignore_ascii_case("name"))
{
// A KML description and an explicitly typed string id keep their text.
reads.push(TextRead::Data);
}
reads
Expand Down Expand Up @@ -5904,7 +5913,7 @@ impl std::ops::AddAssign for TextLosses {
}

/// What a CSV, Shapefile, KML, KMZ or GPX file (extension `ext`) of the whole dataset `ds`
/// changes when written to `target`: [`CsvLosses`]' notices, KML's fields without a value,
/// changes when written to `target`: [`CsvLosses`]' notices, KML's unusable field names,
/// [`gpx_notes`] with each feature named from `name_field`, and [`TextLosses`]' (a Shapefile's
/// other values are [`shapefile_values_notes`]). A streamed export counts CSV's changes a chunk
/// at a time instead.
Expand Down Expand Up @@ -6016,8 +6025,8 @@ fn written_with_geometry(ds: &Dataset) -> Result<Vec<bool>> {
.collect()
}

/// KML writes ExtendedData only for non-null values of placemarks it writes. Report every
/// field absent from that output, even when an unwritten feature has a value for it.
/// KML declares all columns. Blank names and empty columns coalesced into fixed columns
/// still cannot retain their original definition; populated blank names are counted separately.
fn kml_empty_fields_note(ds: &Dataset, placed: &[bool], target: &str) -> Result<Option<crate::loss::Note>> {
let mut written = vec![false; ds.fields.len()];
for (f, placemark) in ds.features.iter().zip(placed) {
Expand All @@ -6032,7 +6041,13 @@ fn kml_empty_fields_note(ds: &Dataset, placed: &[bool], target: &str) -> Result<
.fields
.iter()
.zip(written)
.filter(|(_, written)| !written)
.filter(|(field, written)| {
let coalesced = ["name", "folder", "style"]
.iter()
.any(|name| field.name.eq_ignore_ascii_case(name) && (field.name != *name || field.ty != FieldType::Text))
|| field.name == "description" && field.ty != FieldType::Text;
!written && (field.name.trim().is_empty() || coalesced)
})
.map(|(field, _)| format!("'{}'", dbf_notice_name(&field.name)))
.collect();
let target: String = target.chars().map(dbf_notice_char).collect();
Expand Down Expand Up @@ -8573,6 +8588,30 @@ mod tests {
assert!(!notes.iter().any(|n| n.contains("blank name")), "{notes:?}");
}

/// Explicit string ids survive unchanged; the same untyped attributes still report
/// trimming or blank-to-null conversions according to the values read back.
#[test]
fn kml_text_id_notices_match_preserved_values() {
for (values, expected) in [
([" x ", ""], "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'note'"),
(["123", " "], "t: 1 blank text value reads back as empty (null), in 'note'"),
] {
let ds = text_layer(&["id", "note"], &[&[Some(values[0]), Some(values[0])], &[Some(values[1]), Some(values[1])]]);
for ext in ["kml", "kmz"] {
assert_eq!(text_notes(&ds, ext), [expected]);
let (bytes, _) = write_bytes(&ds, ext).unwrap();
let back = crate::kml::read(&format!("t.{ext}"), &bytes).unwrap().remove(0).dataset;
let id = back.field_index("id").unwrap();
assert_eq!(back.fields[id].ty, FieldType::Text);
for (row, text) in values.iter().enumerate() {
assert_eq!(back.value(row, id), &Value::Text((*text).into()));
}
}
}
let clean = text_layer(&["id"], &[&[Some(" x ")], &[Some("")], &[Some(" ")]]);
assert!(text_notes(&clean, "kml").is_empty());
}

#[test]
fn kml_says_trimmed_and_blank_text() {
let ds = text_layer(
Expand All @@ -8599,7 +8638,7 @@ mod tests {
assert_eq!(column("name"), Some(vec![text("a"), Value::Null, text("b")]));
assert_eq!(column("note"), Some(vec![text("padded"), text(""), text("")]));
assert_eq!(column("code"), Some(vec![Value::Int(1), Value::Null, Value::Int(2)]));
assert_eq!(column("gone"), None);
assert_eq!(column("gone"), Some(vec![Value::Null; 3]));
assert_eq!(column("description"), Some(vec![text(" kept "), text(""), Value::Null]));
let clean = text_layer(&["name", "note"], &[&[Some("a"), Some("")], &[None, Some("x")]]);
assert!(text_notes(&clean, "kml").is_empty());
Expand Down Expand Up @@ -8899,7 +8938,7 @@ mod tests {
}

#[test]
fn kml_and_kmz_name_fields_missing_from_exported_placemarks() {
fn kml_and_kmz_keep_fields_without_values_in_exported_placemarks() {
let mut ds =
Dataset::new("parcels", GeometryType::Point, vec![Field::new("a", FieldType::Integer), Field::new("empty", FieldType::Text)]);
ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Int(1), Value::Null]);
Expand All @@ -8909,10 +8948,18 @@ mod tests {
let (bytes, _) = write_bytes(&ds, ext).unwrap();
let back = &crate::kml::read(&target, &bytes).unwrap()[0].dataset;
assert!(back.field_index("a").is_some());
assert!(back.field_index("empty").is_none());
assert_eq!(
export_losses_notes(&ds, ext, None, &target).unwrap(),
[format!("{target}: KML omitted 1 field with no values in the placemarks written ('empty')")]
let empty = back.field_index("empty").unwrap();
assert_eq!(back.features.value(0, empty), &Value::Null);
assert!(export_losses_notes(&ds, ext, None, &target).unwrap().is_empty());
}
// An empty declaration that coalesces with a fixed KML column still needs its notice.
for name in ["NAME", "Folder", "STYLE", "folder", "description"] {
let mut reserved = Dataset::new("reserved", GeometryType::Point, vec![Field::new(name, FieldType::Integer)]);
reserved.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Null]);
let notes = export_losses_notes(&reserved, "kml", None, "reserved.kml").unwrap();
assert!(
notes.iter().any(|n| n.contains(&format!("KML omitted 1 field with no values in the placemarks written ('{name}')"))),
"{notes:?}"
);
}
ds.push(Some(Geometry::Point(Coord::new(3.0, 4.0))), vec![Value::Int(3), Value::Text("present".into())]);
Expand All @@ -8925,12 +8972,11 @@ mod tests {
let notes = export_losses_notes(&held, ext, None, &format!("parcels.{ext}")).unwrap();
assert!(notes.iter().all(|n| n.loss != Some(crate::loss::LossCode::DroppedFeature)), "{ext}: {notes:?}");
}
// A feature with no place in longitude/latitude is written without its geometry, so no
// placemark holds its value: 'empty' still has none in the placemarks written.
// Even when no placed feature has a value, its field declaration is retained.
held.push(Some(Geometry::Point(Coord::new(1e12, 0.0))), vec![Value::Int(4), Value::Text("lost".into())]);
held.features[2].attrs[1] = Value::Null;
let notes = export_losses_notes(&held, "kml", None, "parcels.kml").unwrap();
assert!(notes.iter().any(|n| n.contains("KML omitted 1 field with no values in the placemarks written ('empty')")), "{notes:?}");
assert!(notes.iter().all(|n| !n.contains("KML omitted")), "{notes:?}");
}

/// A point layer's fields named like coordinates keep their values when its CSV is read back:
Expand Down
Loading
Loading