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
2 changes: 1 addition & 1 deletion crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ fn a_layer_without_a_declared_type_takes_its_first_geometrys() {
let layer = Dataset::new("points", GeometryType::None, points.fields.clone());
write_chunks_in(&Runs::new(&points, 2), &layer, &d.join("points.csv"), Crs::LonLat, 1).unwrap();
let text = std::fs::read_to_string(d.join("points.csv")).unwrap();
assert!(text.starts_with("n,longitude,latitude"), "{text}");
assert!(text.starts_with("longitude,latitude,n"), "{text}");
}

/// Rows a source couldn't read are counted, so an export can say how many it left out; a clean
Expand Down
141 changes: 120 additions & 21 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1438,8 +1438,10 @@ impl<W: std::io::Write> GeoJsonWriter<W> {
// ---------------------------------------------------------------------------------------------
// CSV

const LON_NAMES: &[&str] = &["lon", "lng", "long", "longitude", "x", "lon_dd", "longitude_dd"];
const LAT_NAMES: &[&str] = &["lat", "latitude", "y", "lat_dd", "latitude_dd"];
/// Longitude and latitude columns, recognised in any order; CSV export names its coordinate
/// columns with the first of each that no field has.
const LON_NAMES: &[&str] = &["longitude", "lon", "lng", "long", "x", "lon_dd", "longitude_dd"];
const LAT_NAMES: &[&str] = &["latitude", "lat", "y", "lat_dd", "latitude_dd"];

/// Projected coordinate columns, recognised as well as longitude/latitude ones.
const X_NAMES: &[&str] = &["easting", "point_x", "xcoord", "x_coord"];
Expand Down Expand Up @@ -1868,6 +1870,20 @@ fn csv_cell(v: &Value) -> String {
}
}

/// The names of a point layer's longitude and latitude columns in CSV: the first of the names
/// reading takes for each that no field has, ignoring case and the spaces around a name (reading
/// trims them).
/// A layer with a field of every such name gets `longitude_1` or `latitude_1`, and reading takes
/// that field instead ([`CsvLosses::coordinates_note`]).
fn csv_coordinate_names(fields: &[Field]) -> [String; 2] {
let taken = |name: &str| fields.iter().any(|f| f.name.trim().eq_ignore_ascii_case(name));
let pick = |base: &str, known: &[&str]| {
let name = known.iter().map(|n| n.to_string()).chain((1..).map(|i| format!("{base}_{i}"))).find(|n| !taken(n));
name.unwrap_or_default()
};
[pick("longitude", LON_NAMES), pick("latitude", LAT_NAMES)]
}

/// A dataset as CSV text: its fields, and a point layer's longitude and latitude ([`CsvWriter`]).
pub fn to_csv(ds: &Dataset) -> Result<String> {
let mut w = CsvWriter::new(Vec::new(), &ds.fields, ds.geometry_type)?;
Expand All @@ -1876,7 +1892,7 @@ pub fn to_csv(ds: &Dataset) -> Result<String> {
}

/// Writes CSV a run of features at a time: a header of the fields, and for a point layer
/// longitude and latitude columns after them.
/// longitude and latitude columns before them.
pub(crate) struct CsvWriter<W: std::io::Write> {
w: csv::Writer<W>,
point: bool,
Expand All @@ -1887,19 +1903,13 @@ impl<W: std::io::Write> CsvWriter<W> {
pub(crate) fn new(out: W, fields: &[Field], geometry_type: GeometryType) -> Result<Self> {
let mut w = csv::Writer::from_writer(out);
let point = geometry_type == GeometryType::Point;
let mut head: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
let mut head = Vec::new();
if point {
// Coordinate columns get names that don't collide with existing fields.
for base in ["longitude", "latitude"] {
let mut name = base.to_string();
let mut i = 1;
while head.iter().any(|h| h.eq_ignore_ascii_case(&name)) {
name = format!("{base}_{i}");
i += 1;
}
head.push(name);
}
// The coordinate columns come first, so reading takes them rather than a field
// named `lat` or `x`.
head.extend(csv_coordinate_names(fields));
}
head.extend(fields.iter().map(|f| f.name.clone()));
w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?;
Ok(CsvWriter { w, point })
}
Expand All @@ -1908,12 +1918,13 @@ impl<W: std::io::Write> CsvWriter<W> {
pub(crate) fn write(&mut self, features: &[crate::Feature]) -> Result<()> {
for f in features {
crate::progress::step(1)?;
let mut row: Vec<String> = f.attrs.iter().map(csv_cell).collect();
let mut row = Vec::with_capacity(f.attrs.len() + 2);
if self.point {
let c = f.geometry.as_ref().and_then(|g| g.label_point());
row.push(c.map(|c| c.x.to_string()).unwrap_or_default());
row.push(c.map(|c| c.y.to_string()).unwrap_or_default());
}
row.extend(f.attrs.iter().map(csv_cell));
self.w.write_record(&row).map_err(|e| DataError::Format(e.to_string()))?;
}
Ok(())
Expand Down Expand Up @@ -2696,12 +2707,15 @@ pub struct CsvLosses {
/// Features whose geometry isn't written: in a line or polygon layer (or one that declares
/// no type), and in a point layer those with no point to write (an empty multipoint).
pub unwritten: usize,
/// Written with coordinate columns, as a point layer: a streamed export knows this from its
/// chunks when the layer declares no type ([`CsvLosses::coordinates_note`]).
pub points: bool,
}

impl CsvLosses {
/// The losses of `features` in a layer of type `gt`; a streamed export adds up its chunks'.
pub fn of(features: &[crate::Feature], gt: GeometryType) -> Self {
let mut out = Self::default();
let mut out = Self { points: gt == GeometryType::Point, ..Self::default() };
for g in features.iter().filter_map(|f| f.geometry.as_ref()) {
match (gt, g) {
(GeometryType::Point, Geometry::Point(_)) => {}
Expand Down Expand Up @@ -2732,13 +2746,39 @@ impl CsvLosses {
}
notes
}

/// What a CSV export with these losses says when reading the file back wouldn't take its
/// coordinate columns: its `fields` have every name reading takes for a longitude or a
/// latitude, and reading takes those fields instead. `None` otherwise.
pub fn coordinates_note(self, fields: &[Field], target: &str) -> Option<String> {
if !self.points {
return None;
}
let header: Vec<String> = csv_coordinate_names(fields).into_iter().chain(fields.iter().map(|f| f.name.clone())).collect();
let found = found_xy(&header);
if found == Some((0, 1)) {
return None;
}
let name = |i: usize| dbf_notice_name(header.get(i).map_or("", String::as_str));
let read = match found {
Some((x, y)) => format!("reads columns '{}' and '{}' as the coordinates, which moves the points", name(x), name(y)),
None => "reads no coordinates".to_string(),
};
let target: String = target.chars().map(dbf_notice_char).collect();
Comment on lines +2764 to +2767

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dead branch (Quality, confidence ~85%). coordinates_note only gets past the early return when found != Some((0, 1)), and found_xy can't return None here. Header 0 is either a LON_NAMES/LAT_NAMES name, or longitude_1/latitude_1, which is only picked when every such name is already a field. Either way find(LON_NAMES) and find(LAT_NAMES) both match, so the None arm ("reads no coordinates") is unreachable and its wording would be wrong if it ever ran. Suggest stating the invariant instead:

Suggested change
Some((x, y)) => format!("reads columns '{}' and '{}' as the coordinates, which moves the points", name(x), name(y)),
None => "reads no coordinates".to_string(),
};
let target: String = target.chars().map(dbf_notice_char).collect();
// A coordinate column is always found here: either it has a recognised name, or every such name is a field.
let (x, y) = found?;
let read = format!("reads columns '{}' and '{}' as the coordinates, which moves the points", name(x), name(y));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: the arm is unreachable today, and it keeps the note honest if the reader's fallback names change.

Some(format!(
"{target}: the fields have every name read as a longitude or latitude, so the coordinates are in columns '{}' and '{}'; adding the file back {read} unless those columns are picked",
name(0),
name(1)
))
}
}

impl std::ops::AddAssign for CsvLosses {
/// Adds a chunk's losses.
fn add_assign(&mut self, other: Self) {
self.as_one_point += other.as_one_point;
self.unwritten += other.unwritten;
self.points |= other.points;
}
}

Expand All @@ -2747,7 +2787,12 @@ impl std::ops::AddAssign for CsvLosses {
/// none for another format. A streamed export counts CSV's a chunk at a time instead.
pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option<usize>, target: &str) -> Vec<String> {
match ext {
"csv" => CsvLosses::of(&ds.features, ds.geometry_type).notes(target),
"csv" => {
let losses = CsvLosses::of(&ds.features, ds.geometry_type);
let mut notes = losses.notes(target);
notes.extend(losses.coordinates_note(&ds.fields, target));
notes
}
"gpx" => gpx_notes(ds, name_field, target),
_ => Vec::new(),
}
Expand Down Expand Up @@ -4107,14 +4152,14 @@ mod tests {
ds.push(Some(square), vec![]);
ds.push(None, vec![]);
let losses = CsvLosses::of(&ds.features, ds.geometry_type);
assert_eq!(losses, CsvLosses { as_one_point: 0, unwritten: 1 });
assert_eq!(losses, CsvLosses { as_one_point: 0, unwritten: 1, points: false });
assert!(losses.notes("t.csv")[0].contains("the geometry of 1 feature wasn't written"));
assert!(!to_csv(&ds).unwrap().contains("longitude"));
let points = [crate::Feature { id: 0, geometry: Some(Geometry::Point(Coord::new(1.0, 2.0))), attrs: vec![] }];
assert_eq!(CsvLosses::of(&points, GeometryType::Point), CsvLosses::default());
assert_eq!(CsvLosses::of(&points, GeometryType::Point), CsvLosses { points: true, ..CsvLosses::default() });
// A multipoint without a point in a point layer gets empty coordinate cells.
let empty = [crate::Feature { id: 1, geometry: Some(Geometry::MultiPoint(vec![])), attrs: vec![] }];
assert_eq!(CsvLosses::of(&empty, GeometryType::Point), CsvLosses { as_one_point: 0, unwritten: 1 });
assert_eq!(CsvLosses::of(&empty, GeometryType::Point), CsvLosses { as_one_point: 0, unwritten: 1, points: true });
}

/// GPX leaves out a feature without geometry and a multipoint without a point (no waypoint
Expand All @@ -4129,6 +4174,60 @@ mod tests {
assert_eq!(write_bytes(&ds, "gpx").unwrap().1, 2);
}

/// A point layer's fields named like coordinates keep their values when its CSV is read back:
/// the coordinate columns come first, so reading takes them, not the fields. (Reading keeps the
/// coordinate columns as fields too.)
#[test]
fn csv_fields_named_like_coordinates_stay_fields() {
let names = ["lat", "x", "longitude"];
let fields: Vec<Field> = names.iter().map(|n| Field::new(*n, FieldType::Double)).collect();
let mut ds = Dataset::new("t", GeometryType::Point, fields);
ds.push(Some(Geometry::Point(Coord::new(20.0, 10.0))), vec![Value::Float(1.5), Value::Float(2.5), Value::Float(3.5)]);
let out = to_csv(&ds).unwrap();
assert_eq!(out.lines().next(), Some("lon,latitude,lat,x,longitude"), "{out}");
let (back, _) = read_csv(&out, "t").unwrap();
assert_eq!(back.features[0].geometry, Some(Geometry::Point(Coord::new(20.0, 10.0))));
for (name, v) in names.iter().zip([1.5, 2.5, 3.5]) {
let i = back.field_index(name).unwrap();
assert_eq!(back.value(0, i), &Value::Float(v), "{name}");
}
// A name with spaces around it is the name reading gives it.
let mut padded = Dataset::new("t", GeometryType::Point, vec![Field::new(" longitude ", FieldType::Double)]);
padded.push(Some(Geometry::Point(Coord::new(20.0, 10.0))), vec![Value::Float(1.5)]);
let out = to_csv(&padded).unwrap();
assert_eq!(out.lines().next(), Some("lon,latitude, longitude "), "{out}");
let (back, _) = read_csv(&out, "t").unwrap();
assert_eq!(back.features[0].geometry, Some(Geometry::Point(Coord::new(20.0, 10.0))));
assert_eq!(back.value(0, back.field_index("longitude").unwrap()), &Value::Float(1.5));
}

/// A point layer with a field of every longitude name has its longitudes in a column reading
/// doesn't take, and its export says so; one with a name left says nothing.
#[test]
fn csv_coordinates_in_columns_reading_doesnt_take_are_said() {
let layer = |names: &[&str]| {
let fields: Vec<Field> = names.iter().map(|n| Field::new(*n, FieldType::Integer)).collect();
let mut ds = Dataset::new("t", GeometryType::Point, fields);
ds.push(Some(Geometry::Point(Coord::new(20.0, 10.0))), names.iter().map(|_| Value::Int(1)).collect());
ds
};
let every = layer(LON_NAMES);
let out = to_csv(&every).unwrap();
assert!(out.starts_with("longitude_1,latitude,"), "{out}");
let notes = export_losses_notes(&every, "csv", None, "t.csv");
assert_eq!(notes.len(), 1, "{notes:?}");
assert_eq!(
notes[0],
"t.csv: the fields have every name read as a longitude or latitude, so the coordinates are in columns 'longitude_1' and 'latitude'; adding the file back reads columns 'longitude' and 'latitude' as the coordinates, which moves the points unless those columns are picked"
);
// As said: reading takes the field `longitude` (1) for the longitude.
let (back, _) = read_csv(&out, "t").unwrap();
assert_eq!(back.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 10.0))));
// A name left, or a layer that isn't of points: nothing to say.
assert!(export_losses_notes(&layer(&LON_NAMES[1..]), "csv", None, "t.csv").is_empty());
assert_eq!(CsvLosses::of(&[], GeometryType::Polyline).coordinates_note(&every.fields, "t.csv"), None);
}

#[test]
fn csv_leading_zeros_and_guard_roundtrip() {
let (ds, _) = read_csv("zip,n,note\n02134,0,-abc\n10001,0.5,=x\n", "t").unwrap();
Expand Down Expand Up @@ -4156,7 +4255,7 @@ mod tests {
assert_eq!(ds.geometry_type, GeometryType::Point, "BOM must not hide the lon header");
let out = to_csv(&ds).unwrap();
assert!(out.contains("'=SUM(A1)"), "{out}");
assert!(out.lines().next().unwrap().contains("longitude_1"), "{out}");
assert_eq!(out.lines().next(), Some("lng,latitude,lon,lat,longitude,note"), "{out}");
let (ds, _) = read_csv("a\nNaN\nx\n", "t").unwrap();
assert_eq!(ds.fields[0].ty, FieldType::Text);
}
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option<Crs>, gpkg: Gpk
// CSV holds a point a row, GPX a name for each feature and no areas.
if ext == "csv" {
said.extend(csv.notes(path));
said.extend(csv.coordinates_note(&ds.fields, path));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test coverage (Quality, confidence ~70%). This call is the only place the app/CLI export path adds the coordinate-column notice for a streamed or in-memory layer; the other path (export_losses_notes) is wired separately. The new tests in crates/data/src/io.rs (csv_coordinates_in_columns_reading_doesnt_take_are_said) call coordinates_note/export_losses_notes directly, so removing this line would not fail any test. AGENTS.md's "test both ways" rule covers the notice at the layer that emits it. Suggest an engine test that exports a point layer whose fields include every longitude name to CSV through share.exportLayer and asserts the notice reaches the session, plus a clean layer that gets none.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: the data-level test pins the note, and adding an engine test means another engine build for a one-line call.

}
if ext == "gpx" {
said.extend(rustgis_data::io::gpx_notes(ds, rustgis_data::io::name_field(ds), path));
Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34550,13 +34550,13 @@ fn geopackage_past_the_count_limit_streams_exports_and_reads_whole() {
let output = fixture.dir.join("whole.csv");
let exported = s.run("share.exportLayer", &json!({"layer": id, "path": output})).unwrap();
assert_eq!(exported["features"].as_u64(), Some(count as u64));
// A header, then every row once and in order (the first column is the road's name).
// A header, then every row once and in order (the road's name after its coordinates).
let mut lines = std::io::BufRead::lines(std::io::BufReader::new(std::fs::File::open(&output).unwrap()));
assert!(lines.next().unwrap().unwrap().starts_with("name,"));
assert!(lines.next().unwrap().unwrap().starts_with("longitude,latitude,name"));
let mut rows = 0;
for (k, line) in lines.enumerate() {
let line = line.unwrap();
assert!(line.starts_with(&format!("road {},", k + 1)), "row {k}: {line}");
assert_eq!(line.split(',').nth(2), Some(format!("road {}", k + 1).as_str()), "row {k}: {line}");
rows += 1;
}
assert_eq!(rows, count, "every row");
Expand Down
Loading