diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 76802e85c7..f260faf359 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -110,13 +110,33 @@ fn text(out: Vec) -> crate::Result { 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, out: &mut impl Write) -> crate::Result<()> { - write!( + out.write_all(b"\n\n{}\n", + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{}", 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"")?; + 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', " ") + .replace('\n', " "); + // 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, "")?; + } + out.write_all(b"\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); @@ -147,7 +167,10 @@ pub(crate) fn write_kml(ds: &Dataset, name_field: Option, out: &mut impl let name = xml(&fd.name, "KML", || format!("{}, field name '{}'", ds.name, fd.name.escape_debug()))? .replace('\t', " ") .replace('\n', " "); - Ok(format!("{value}")) + // 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!("{value}")) }) .collect::>()?; write!( diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 3d840583c7..7fbb44134a 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -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) { @@ -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. @@ -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 @@ -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. @@ -6016,8 +6025,8 @@ fn written_with_geometry(ds: &Dataset) -> Result> { .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> { let mut written = vec![false; ds.fields.len()]; for (f, placemark) in ds.features.iter().zip(placed) { @@ -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(); @@ -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( @@ -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()); @@ -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]); @@ -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())]); @@ -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: diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 9dc269e6b9..1a5030c4eb 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -83,11 +83,13 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> { duplicate_placemarks: 0, rows: Vec::new(), keys: Vec::new(), + string_keys: Default::default(), skipped: 0, geometry_losses: GeometryLosses::default(), }; r.collect_styles(doc.root()); r.walk(doc.root(), &mut Vec::new(), 0); + r.collect_fields(doc.root()); Ok(r.layers(&name)) } @@ -192,6 +194,7 @@ fn ground_overlays_within(file_name: &str, bytes: &[u8], budget: usize) -> Resul /// One placemark, before it's put in a layer. struct Row { geometry: Geometry, + id: Option, name: Option, description: Option, folder: String, @@ -211,6 +214,8 @@ struct Reader { rows: Vec, /// Extended data keys, in the order first seen. keys: Vec, + /// Explicit string keys from retained points, lines and polygons, each bounded by MAX_KEYS. + string_keys: [HashSet; 3], /// Extended data entries past the column cap. dropped_keys: usize, duplicate_entries: usize, @@ -219,6 +224,15 @@ struct Reader { geometry_losses: GeometryLosses, } +/// Resolve an explicit XML Schema string type by namespace, independent of the chosen prefix. +/// KML's value element is already a schema string; the explicit annotation preserves an opaque +/// identifier through readers that would otherwise infer numbers from ExtendedData values. +fn explicit_string(n: &Node) -> bool { + let Some(ty) = n.attribute(("http://www.w3.org/2001/XMLSchema-instance", "type")) else { return false }; + let (prefix, name) = ty.trim().split_once(':').map_or((None, ty.trim()), |(prefix, name)| (Some(prefix), name)); + name == "string" && n.lookup_namespace_uri(prefix) == Some("http://www.w3.org/2001/XMLSchema") +} + fn local<'a>(n: &Node<'a, '_>) -> &'a str { n.tag_name().name() } @@ -528,6 +542,23 @@ impl Reader { } } + /// Adds declared headers after populated keys, so empty declarations cannot displace + /// fields with values at the column cap. It retains only the existing bounded key list. + fn collect_fields(&mut self, root: Node) { + for schema in root.descendants().filter(|n| n.is_element() && local(n) == "Schema") { + for field in schema.children().filter(|f| f.is_element() && local(f) == "SimpleField") { + let Some(name) = field.attribute("name").filter(|n| !n.trim().is_empty()) else { continue }; + if !self.keys.iter().any(|k| k == name) { + if self.keys.len() >= MAX_KEYS { + self.dropped_keys += 1; + } else { + self.keys.push(name.to_string()); + } + } + } + } + } + /// The style id a placemark draws with: its inline style, else its styleUrl (through a style /// map). Only ids defined in this document count. fn style_for(&mut self, pm: &Node) -> Option { @@ -590,18 +621,22 @@ impl Reader { // geometry's loss. let losses = std::mem::take(&mut parts.losses); let mut data = Vec::new(); + let mut string_indices = Vec::new(); let mut seen = HashSet::new(); let mut duplicates = 0usize; if let Some(ext) = child(pm, "ExtendedData") { for d in ext.descendants().filter(|d| d.is_element()) { let pair = match local(&d) { - "Data" => { - d.attribute("name").map(|k| (k.to_string(), child(&d, "value").map(|v| data_text(&v, k)).unwrap_or_default())) - } - "SimpleData" => d.attribute("name").map(|k| (k.to_string(), data_text(&d, k))), + "Data" => d.attribute("name").map(|k| { + let value = child(&d, "value"); + let string = value.as_ref().is_some_and(explicit_string); + let text = value.map(|v| if string { raw_text_of(&v) } else { data_text(&v, k) }).unwrap_or_default(); + (k.to_string(), text, string) + }), + "SimpleData" => d.attribute("name").map(|k| (k.to_string(), data_text(&d, k), false)), _ => None, }; - if let Some((k, v)) = pair.filter(|(k, _)| !k.trim().is_empty()) { + if let Some((k, v, string)) = pair.filter(|(k, _, _)| !k.trim().is_empty()) { // The attribute reader uses the first entry for a key. Count and discard // later entries here, including duplicates across Data and SimpleData and // names past the column cap. @@ -617,6 +652,9 @@ impl Reader { } self.keys.push(k.clone()); } + if string { + string_indices.push(data.len()); + } data.push((k, v)); } } @@ -628,10 +666,20 @@ impl Reader { // A placemark mixing kinds (a MultiGeometry of a point and a line) gives one feature per // kind, each in its layer. let mut any = false; - let mut push = |geometry: Geometry, zm: &Cell, rows: &mut Vec| { + let mut push = |geometry: Geometry, zm: &Cell, rows: &mut Vec, typed: &mut HashSet| { any = true; + // Only retained rows affect inference, and each geometry layer is typed separately. + // The temporary indices avoid another string copy for each placemark's annotation. + for index in &string_indices { + if let Some((key, _)) = data.get(*index) + && !typed.contains(key) + { + typed.insert(key.clone()); + } + } rows.push(Row { geometry, + id: pm.attribute("id").map(str::to_string), name: name.clone(), description: description.clone(), folder: folder.clone(), @@ -642,14 +690,14 @@ impl Reader { }; match parts.points.as_slice() { [] => {} - [p] => push(Geometry::Point(*p), &parts.zm[0], &mut self.rows), - _ => push(Geometry::MultiPoint(parts.points), &parts.zm[0], &mut self.rows), + [p] => push(Geometry::Point(*p), &parts.zm[0], &mut self.rows, &mut self.string_keys[0]), + _ => push(Geometry::MultiPoint(parts.points), &parts.zm[0], &mut self.rows, &mut self.string_keys[0]), } if !parts.lines.is_empty() { - push(Geometry::Line(parts.lines), &parts.zm[1], &mut self.rows); + push(Geometry::Line(parts.lines), &parts.zm[1], &mut self.rows, &mut self.string_keys[1]); } if !parts.polygons.is_empty() { - push(Geometry::Polygon(parts.polygons), &parts.zm[2], &mut self.rows); + push(Geometry::Polygon(parts.polygons), &parts.zm[2], &mut self.rows, &mut self.string_keys[2]); } if any { self.geometry_losses.add(&losses); @@ -672,6 +720,11 @@ impl Reader { Field::new("folder", FieldType::Text), Field::new("style", FieldType::Text), ]; + let has_ids = self.rows.iter().any(|r| r.id.is_some()); + if has_ids { + fields.push(Field::new("id", FieldType::Text)); + } + let fixed_fields = fields.len(); // Each extended data key's column, as (key, column name). A key named like one of those, // ignoring case, is left out when it only repeats that column (an exported name field // does), else kept under a free name. @@ -689,9 +742,14 @@ impl Reader { 0 => r.name.as_deref(), 1 => r.description.as_deref(), 2 => Some(r.folder.as_str()), - _ => r.style.as_deref(), + 3 => r.style.as_deref(), + _ => r.id.as_deref(), }; - r.data.iter().find(|(dk, _)| dk == k).is_none_or(|(_, v)| v == fixed.unwrap_or_default()) + r.data.iter().find(|(dk, _)| dk == k).is_none_or(|(_, v)| match fixed { + Some(fixed) => v == fixed, + // An explicit empty Data id differs from an absent source identifier. + None => i != 4 && v.is_empty(), + }) }; if (i != 1 || k == "description") && self.rows.iter().all(repeats) { continue; @@ -715,6 +773,9 @@ impl Reader { if r.folder.is_empty() { Value::Null } else { Value::Text(r.folder.clone()) }, r.style.clone().map(Value::Text).unwrap_or_default(), ]; + if has_ids { + attrs.push(r.id.clone().map(Value::Text).unwrap_or_default()); + } attrs.extend( keys.iter() .map(|(k, _)| r.data.iter().find(|(dk, _)| dk == k).map(|(_, v)| Value::Text(v.clone())).unwrap_or_default()), @@ -727,8 +788,16 @@ impl Reader { ds.push_next(Some(r.geometry.clone()), attrs); zm_rows += usize::from(r.zm); } - // Extended data is typed; names, descriptions, folders and style ids stay text. - crate::io::type_text_columns(&mut ds, &["name", "description", "folder", "style"]); + // Fixed columns and this layer's explicitly typed strings stay text; other data + // is inferred from its own retained rows, even when only one kind is present. + let string_keys = match *kind { + GeometryType::Point => &self.string_keys[0], + GeometryType::Polyline => &self.string_keys[1], + _ => &self.string_keys[2], + }; + crate::io::type_text_columns_keeping(&mut ds, |column, _| { + column < fixed_fields || keys.get(column - fixed_fields).is_some_and(|(key, _)| string_keys.contains(key)) + }); let mut report = ReadReport::default(); // The notes go with the first layer only. if i == 0 { @@ -767,8 +836,9 @@ impl Reader { } else { format!("{} extended data names were", renamed.len()) }; + let columns = if has_ids { "name, description, folder, style and id" } else { "name, description, folder and style" }; report.messages.push(format!( - "{name}: {count} renamed, as RustGIS gives every placemark a name, description, folder and style column: {}{more}", + "{name}: {count} renamed, as RustGIS gives every placemark a {columns} column: {}{more}", listed.join(", ") )); } @@ -1019,6 +1089,21 @@ mod tests { assert!(messages.iter().any(|m| m.contains("distinct names")), "{messages:?}"); } + /// Schema-only headers fill remaining capacity after populated data, regardless of their + /// earlier position in the document; the omitted headers are still reported. + #[test] + fn declared_empty_headers_do_not_displace_populated_kml_keys() { + let fields = (0..=MAX_KEYS).map(|i| format!("")).collect::(); + let xml = format!( + "{fields}71,2" + ); + let layer = read("capped.kml", xml.as_bytes()).unwrap().remove(0); + let column = layer.dataset.field_index("important").unwrap(); + assert_eq!(layer.dataset.value(0, column), &Value::Int(7)); + assert_eq!(layer.dataset.fields.len(), 4 + MAX_KEYS); + assert!(layer.report.messages.iter().any(|n| n.contains("distinct names")), "{:?}", layer.report.messages); + } + #[test] fn distinct_extended_data_keys_across_placemarks_are_clean() { let xml = r#"0 @@ -1040,6 +1125,130 @@ mod tests { assert_eq!(ds.value(0, id), &Value::Text("12345678901234567891".into())); } + #[test] + fn source_ids_and_declared_empty_columns_survive_kml_round_trips() { + let xml = r##" + 1,2 + 3,4"##; + let layer = read("permits.kml", xml.as_bytes()).unwrap().remove(0); + let ds = &layer.dataset; + let id = ds.field_index("id").expect("keep the original opaque identifier"); + assert_eq!(ds.fields[id].ty, FieldType::Text); + assert_eq!(ds.value(0, id), &Value::Text("Permits.001".into())); + assert_eq!(ds.value(1, id), &Value::Text("Permits.002".into())); + let empty = ds.field_index("empty").expect("keep a declared field with no populated values"); + assert_eq!(ds.value(0, empty), &Value::Null); + assert_eq!(ds.value(1, empty), &Value::Null); + assert!(layer.report.messages.is_empty()); + let exported = crate::interop::to_kml(ds, None).unwrap(); + let back = read("again.kml", exported.as_bytes()).unwrap().remove(0); + assert!(back.dataset.field_index("id_1").is_none()); + assert_eq!(back.dataset.value(0, back.dataset.field_index("id").unwrap()), &Value::Text("Permits.001".into())); + assert!(back.dataset.field_index("empty").is_some()); + } + + /// Numeric-looking source identifiers are opaque text even when an accepted input id is + /// not an XML ID; exporting it as ordinary untyped Data must not change its spelling. + #[test] + fn numeric_source_identifiers_stay_text_in_kml_and_kmz_round_trips() { + let ids = ["123", "1e3", "-7", " 1e3 "]; + let placemarks = ids + .iter() + .map(|id| format!("1,2")) + .collect::(); + let source = format!("{placemarks}"); + let layer = read("source.kml", source.as_bytes()).unwrap().remove(0); + let xml = crate::interop::to_kml(&layer.dataset, None).unwrap(); + for ext in ["kml", "kmz"] { + let bytes = if ext == "kmz" { + crate::zip::write(&[("doc.kml".into(), xml.as_bytes().to_vec())]).unwrap() + } else { + xml.as_bytes().to_vec() + }; + let back = read(&format!("again.{ext}"), &bytes).unwrap().remove(0); + let id = back.dataset.field_index("id").unwrap(); + assert_eq!(back.dataset.fields[id].ty, FieldType::Text); + for (row, value) in ids.iter().enumerate() { + assert_eq!(back.dataset.value(row, id), &Value::Text((*value).into())); + } + } + let untyped = br#"1231,2"#; + let plain = read("plain.kml", untyped).unwrap().remove(0); + assert_eq!(plain.dataset.value(0, plain.dataset.field_index("id").unwrap()), &Value::Int(123)); + } + + /// Type annotations use namespace identities, and apply to their exact data key rather + /// than every column sharing a case-insensitive spelling. + #[test] + fn explicit_kml_strings_resolve_namespaces_without_typing_other_keys() { + let xml = + br#" + + 1e3 + 7 + 9 + 1,2"#; + let layer = read("typed.kml", xml).unwrap().remove(0); + assert_eq!(layer.dataset.value(0, layer.dataset.field_index("id").unwrap()), &Value::Text(" 1e3 ".into())); + assert_eq!(layer.dataset.value(0, layer.dataset.fields.iter().position(|f| f.name == "ID").unwrap()), &Value::Int(7)); + assert_eq!(layer.dataset.value(0, layer.dataset.field_index("other").unwrap()), &Value::Int(9)); + } + + /// Skipped placemarks and other geometry layers cannot determine a retained column's type. + #[test] + fn explicit_kml_string_types_follow_retained_geometry_layers() { + let point = "1,2"; + let line = "1,2 2,3"; + let polygon = + "0,0 1,0 0,1 0,0"; + for (typed_geometry, plain_geometry, plain_kind) in [ + ("", point, GeometryType::Point), + ("", line, GeometryType::Polyline), + ("", polygon, GeometryType::Polygon), + (point, line, GeometryType::Polyline), + (line, polygon, GeometryType::Polygon), + ] { + let xml = format!( + r#" + 1e3 {typed_geometry} + 7{plain_geometry}"# + ); + let layers = read("kinds.kml", xml.as_bytes()).unwrap(); + let plain = &layers.iter().find(|layer| layer.dataset.geometry_type == plain_kind).unwrap().dataset; + assert_eq!(plain.value(0, plain.field_index("code").unwrap()), &Value::Int(7)); + if !typed_geometry.is_empty() { + let typed = &layers.iter().find(|layer| layer.dataset.geometry_type != plain_kind).unwrap().dataset; + assert_eq!(typed.value(0, typed.field_index("code").unwrap()), &Value::Text(" 1e3 ".into())); + } + } + } + + /// A missing XML id is null, while explicitly empty extended data is present text. Only + /// present, equal identifiers coalesce; retaining both columns reports the collision. + #[test] + fn empty_kml_data_identifier_does_not_repeat_an_absent_xml_identifier() { + let xml = br#" + A1,2 + 3,4"#; + let layer = read("ids.kml", xml).unwrap().remove(0); + let ds = &layer.dataset; + assert_eq!(ds.value(1, ds.field_index("id").unwrap()), &Value::Null); + let data = ds.field_index("id_1").expect("empty data differs from an absent source id"); + assert_eq!(ds.value(0, data), &Value::Text("A".into())); + assert_eq!(ds.value(1, data), &Value::Text(String::new())); + assert_eq!(layer.report.messages.iter().filter(|n| n.contains("'id' → 'id_1'")).count(), 1); + } + + #[test] + fn source_id_collision_keeps_both_distinct_values_and_names_the_rename() { + let xml = br#"different1,2"#; + let layer = read("permits.kml", xml).unwrap().remove(0); + assert_eq!(layer.dataset.value(0, layer.dataset.field_index("id").unwrap()), &Value::Text("Permits.001".into())); + assert_eq!(layer.dataset.value(0, layer.dataset.field_index("id_1").unwrap()), &Value::Text("different".into())); + assert_eq!(layer.report.messages.len(), 1); + assert!(layer.report.messages[0].contains("'id' → 'id_1'")); + } + #[test] fn reads_placemarks_folders_data_and_styles() { let layers = read("trip.kml", DOC.as_bytes()).unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3bf757cc87..ae35a99ffc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -31296,17 +31296,17 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("tracks")), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "csv"})); assert!(n.iter().any(|t| t.contains("wasn't written, only the attributes")), "{n:?}"); - // Both formats count the row without geometry and name the omitted null field. + // Both formats count the row without geometry; KML also declares the all-null field. let mut rows = layer("Rows", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]); rows.push(None, vec![V::Text("no place".into()), V::Null]); s.map_mut().add_dataset(rows); for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); assert!(n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); - assert_eq!(n.len(), 2, "{format}: {n:?}"); if format == "kml" { - assert!(n.iter().any(|t| t.contains("KML omitted 1 field with no values in the placemarks written ('height')")), "{n:?}"); + assert_eq!(n.len(), 1, "{n:?}"); } else { + assert_eq!(n.len(), 2, "{n:?}"); assert!(n.iter().any(|t| t.contains("1 field wasn't written: 'height'")), "{n:?}"); } } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index f658417c16..04344f7b15 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -22,7 +22,7 @@ export names its feature. | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, in English or another language such as `經度`/`緯度`, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within the size read into memory of expanded text (256 MiB in the web app); decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | | Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. `"x"`, `"y"` and `"wkt"` given to Add Data apply to a zip's delimited members and to the first sheet of its workbooks, as to the file by itself, and `"delimiter"` to its delimited members only, so a zip of several tables with the same columns gives points together. A member that lacks a column given is read without them; one notice says how many members took the columns and names those that didn't, with the column each lacks. Other members ignore all of them. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry when the whole layer is read, in place too, and is counted in a notice; a view of an area, which holds no feature without geometry, leaves it out. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | | dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | -| KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder` or `style` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | +| KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder`, `style` or source `id` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). A placemark's XML `id`, when present, is kept in a text `id` column; a distinct extended-data `id` is renamed with a notice. Declared Schema fields are kept even when every value is null. Extended-data values explicitly typed as XML Schema strings keep their exact text, including surrounding spaces. For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | | GPX | `.gpx` | Add Data, drop the file, or upload it in the web app | Waypoints, routes, tracks (one line per track, its segments as parts) and track points (with elevation and time) as separate layers. | | Spreadsheets | `.xlsx`, `.xlsm`, `.xlsb`, `.xls`, `.ods` | Add Data (or Delimited Text… to choose the columns), drop the file, or upload it in the web app | One sheet at a time, read like delimited text: the first non-empty row names the columns, and x/y or WKT columns (found, or given with `"x"`, `"y"`, `"wkt"` and `"crs"`) make the geometry; a sheet without them is a table. The first sheet is added and the others named in a notice; `"layer"` picks one, and `info.fileLayers` lists them. Dates read as ISO 8601. ZIP-based workbooks share a 1 GiB expanded-member budget (256 MiB in the browser), including relationships and metadata, with or without a preamble. Workbooks with ambiguous ZIP directories are refused. A sheet's dense grid is limited to 20 million cells (4 million in the browser); ODS sheets load together and share that cell allowance, with repetition checked before loading. Repeated ODS text shares the expanded-byte allowance; row/column counts beyond the reader's 1,048,576 × 16,384 dimensions are refused, not truncated. Repeated blank margins that need no dense grid remain supported within those dimensions. | | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | @@ -733,7 +733,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | GeoParquet (`.parquet`, `.geoparquet`) | Data › Export | GeoParquet 1.1: WKB geometry in the layer's coordinate system when it has an EPSG code (given as PROJJSON in the file), else WGS 84, Zstd level 9 compression, row groups of up to 65,536 features and a `bbox` covering column with byte-stream-split encoding. The covering keeps spatial range reads available; compression favours smaller files over export speed. Reading the file needs Zstd support, and reading its `bbox` column needs byte-stream-split support, which current GDAL, PyArrow and DuckDB have and some older readers lack (some of those refuse the file). A standalone table without geometry writes plain Parquet. | | Shapefile | Data › Export to `.shp` (or `.zip` for the files zipped) | Writes `.shp`, `.shx`, `.dbf`, `.prj` (the coordinate system, see below) and `.cpg` (UTF-8). Field names are cut to 10 bytes (made unique ignoring case, and reported), text to at most 254 bytes, and numbers that do not fit their dBase field are left empty. Date fields are written as dBase dates; date-time fields as ISO 8601 text, since dBase has no date-time field other programs read (said in a notice). Export notices count shortened text, non-null values left empty (including incompatible types), and numbers rounded to the field's precision, and name the affected source fields; features without geometry, and lines of a single point, are left out (and reported). An export in longitude/latitude leaves out vertices with a missing (NaN) or infinite coordinate; an export in a projected system refuses any coordinate that doesn't project to a finite one, naming its feature. In either, line parts and polygon rings too short to draw (fewer than 2 or 3 drawable vertices, whether written so or left so) and the holes of a polygon whose outer ring goes are left out. The export counts the vertices, and the parts or rings, in the features it writes; a feature with nothing drawable left is counted with the features left out. | | FlatGeobuf | Data › Export to `.fgb` | In the layer's coordinate system (see below), with a spatial index. Features are written in spatial-index order, so record order can change; keep an attribute key to match records after export. Features without geometry are left out (and reported). Desktop only: the writer needs a temporary file, which the browser doesn't have. | -| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. The export reports fields omitted because they have no non-null values in the placemarks written. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept, and the export names them. Features without geometry are left out. | +| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. A text field named exactly `id` is explicitly typed as a string, preserving numeric-looking identifiers and whitespace on re-import. KML/KMZ declare field names in a Schema, including columns with no non-null values. Blank field names and empty declarations coalesced into fixed KML columns cannot retain their original definition and are reported. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept, and the export names them. Features without geometry are left out. | | GeoJSON, KML, GPX, CSV, CSV with WKT | Analyze › Workflows › Data Interop (`data.convert`; `"format": "geojson"`, `"kml"`, `"gpx"`, `"csv"` or `"wkt"`) | Returns text when `"path"` is omitted; a streamed layer requires a path to avoid returning only its loaded view. Desktop conversion asks for a file first, then reads the whole source in the background with progress and Cancel. GeoJSON and CSV read a chunk at a time where supported; KML, GPX and WKT need the whole layer within the memory limit. | | GeoTIFF / Cloud-optimised GeoTIFF | Data › Export Raster (`share.exportRaster`) | Untiled GeoTIFF by default; `"cog": true` writes 512-pixel tiles, Deflate compression and overviews. Writes the loaded raster's resolution (an overview when that is what was opened), the selected band or its colour bands. A WMS, WMTS or XYZ tile layer (`"tiles"`) is written as its tiles at one zoom, RGBA in Web Mercator (see [Sharing](sharing.md#exporting)). The web app's Export Raster downloads an ordinary GeoTIFF. | | PNG | Publish › Export Map (`share.exportMap`) | Configurable DPI, with labels, scale bar and tile credits. |