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
28 changes: 26 additions & 2 deletions crates/data/src/filegdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,9 +324,27 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
// The attribute fields: every field but the geometry, and the object ID first.
let mut fields: Vec<Field> = Vec::new();
let mut columns: Vec<usize> = Vec::new();
// The table's own geometry is its first geometry field; the fields with no type of ours are
// left out, and said below.
let geometry_at = table.fields.iter().position(|f| f.kind == Kind::Geometry);
let mut left_out: Vec<(String, String)> = Vec::new();
for (i, f) in table.fields.iter().enumerate() {
let ty = match f.kind {
Kind::Geometry | Kind::Binary | Kind::Raster => continue,
Kind::Geometry if Some(i) == geometry_at => continue,
// A raster field is never read here (`Table::parse` refuses the table), but a kind that
// is left out is named whatever the parser does.
Kind::Geometry => {
left_out.push((f.name.clone(), "geometry".to_string()));
continue;
}
Kind::Binary => {
left_out.push((f.name.clone(), "binary".to_string()));
continue;
}
Kind::Raster => {
left_out.push((f.name.clone(), "raster".to_string()));
continue;
}
Kind::Int16 | Kind::Int32 | Kind::Int64 | Kind::ObjectId => FieldType::Integer,
Kind::Float32 | Kind::Float64 => FieldType::Double,
Kind::Date | Kind::DateTimeOffset => FieldType::DateTime,
Expand All @@ -337,6 +355,13 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
fields.push(Field { name: f.name.clone(), ty, alias });
columns.push(i);
}
// Said by the table's name, as another table with the same fields says it too.
if let Some(note) = crate::source::columns_note(
&left_out,
["of a type RustGIS has no field for was left out", "of types RustGIS has no field for were left out"],
) {
report.messages.push(format!("{name}: {note}"));

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.

The per-table naming is a reasonable way to keep two tables' notes apart, and the dedupe in read (line 183 onward) still works. But it means a geodatabase in which many feature classes each have a binary field gets one notice per table, up to 512 of them, each repeating the same kind of loss. The rule asks for one notice per kind with a count. Worth deciding before merge: either one note for the read that counts columns across tables and names the first 12 as table.field (kind), or keep one per table and say in the PR why the flood is acceptable. Not a data-loss issue, so it can wait for the quality pass if you prefer.

Category: quality

}
let patches = table.shape == Shape::Multipatch;
// A multipatch's lowest and highest Z, and the difference (what an extrusion stands it up by),
// in three fields after the table's own (named apart from them).
Expand Down Expand Up @@ -364,7 +389,6 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
ds.held_in = c;
}
let geometry_at = table.fields.iter().position(|f| f.kind == Kind::Geometry);
let (mut curves, mut wall_hulls, mut unmerged, mut unprojected, mut beyond) = (0usize, 0usize, 0usize, 0usize, 0usize);
// Multipatches with points but no footprint: too few, all on one line, or not finite numbers.
let mut no_footprint = 0usize;
Expand Down
124 changes: 96 additions & 28 deletions crates/data/src/filegdb/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ enum F {
Text(&'static str),
Int(&'static str),
Date(&'static str, u8),
Shape { z: bool, wkt: &'static str },
Shape {
z: bool,
wkt: &'static str,
},
/// A binary field.
Blob(&'static str),
/// A second geometry field, under its own name.
Shape2(&'static str),
}

/// One row's stored values (the object ID stores nothing): `None` is null.
Expand All @@ -59,6 +66,34 @@ fn table(layer_flags: u32, fields: &[F], rows: &[Vec<V>]) -> (Vec<u8>, Vec<u8>)
f.extend(utf16_bytes(n));
f.push(0);
};
let shape = |f: &mut Vec<u8>, field_name: &str, z: bool, wkt: &str| {
name(f, field_name);
f.extend([7, 0, 7]);
let w = utf16_bytes(wkt);
f.extend((w.len() as i16).to_le_bytes());
f.extend(w);
f.push(if z { 3 } else { 1 });
for v in [0.0f64, 0.0, 1000.0] {
f.extend(v.to_le_bytes());
}
if z {
f.extend(0.0f64.to_le_bytes());
f.extend(1000.0f64.to_le_bytes());
}
f.extend(0.001f64.to_le_bytes());
if z {
f.extend(0.001f64.to_le_bytes());
}
for v in [0.0f64, 0.0, 100.0, 100.0] {
f.extend(v.to_le_bytes());
}
if layer_flags & 0x8000_0000 != 0 {
f.extend([0.0f64, 100.0].iter().flat_map(|v| v.to_le_bytes()));
}
f.push(0);
f.extend(1u32.to_le_bytes());
f.extend(10.0f64.to_le_bytes());
};
for field in fields {
match field {
F::Oid => {
Expand All @@ -79,33 +114,11 @@ fn table(layer_flags: u32, fields: &[F], rows: &[Vec<V>]) -> (Vec<u8>, Vec<u8>)
name(&mut f, n);
f.extend([*kind, 8, 5, 0]);
}
F::Shape { z, wkt } => {
name(&mut f, "SHAPE");
f.extend([7, 0, 7]);
let w = utf16_bytes(wkt);
f.extend((w.len() as i16).to_le_bytes());
f.extend(w);
f.push(if *z { 3 } else { 1 });
for v in [0.0f64, 0.0, 1000.0] {
f.extend(v.to_le_bytes());
}
if *z {
f.extend(0.0f64.to_le_bytes());
f.extend(1000.0f64.to_le_bytes());
}
f.extend(0.001f64.to_le_bytes());
if *z {
f.extend(0.001f64.to_le_bytes());
}
for v in [0.0f64, 0.0, 100.0, 100.0] {
f.extend(v.to_le_bytes());
}
if layer_flags & 0x8000_0000 != 0 {
f.extend([0.0f64, 100.0].iter().flat_map(|v| v.to_le_bytes()));
}
f.push(0);
f.extend(1u32.to_le_bytes());
f.extend(10.0f64.to_le_bytes());
F::Shape { z, wkt } => shape(&mut f, "SHAPE", *z, wkt),
F::Shape2(n) => shape(&mut f, n, false, ""),
F::Blob(n) => {
name(&mut f, n);
f.extend([8, 0, 5]);
}
}
}
Expand Down Expand Up @@ -956,3 +969,58 @@ fn filegdb_temporal_fields_keep_days_offsets_and_null_notices() {
}
}
}

/// A binary field and a geometry field after the first are left out of the layer, and said, once
/// for the table and by its name; a table without them says nothing (#2916).
#[test]
fn binary_and_extra_geometry_fields_are_said_and_left_out() {
let square = || V::Blob(polygon(&square(0.0, 0.0, 10.0)));
let shape = F::Shape { z: false, wkt: LONLAT };
let said = |fields: &[F], row: Vec<V>, name: &'static str| {
let files = geodatabase(vec![(name, table(4, fields, &[row]))]);
let layers = read_files(&files).unwrap();
let (ds, report) = layers.into_iter().next().unwrap();
let names: Vec<String> = ds.fields.iter().map(|f| f.name.clone()).collect();
assert!(matches!(&ds.features[0].geometry, Some(Geometry::Polygon(_))), "{:?}", ds.features[0].geometry);
assert_eq!(report.skipped, 0, "{report:?}");
(names, report.messages.texts().map(str::to_string).collect::<Vec<_>>())
};
// One binary field: the values after it keep their place.
let (names, messages) =
said(&[F::Oid, shape, F::Blob("scan"), F::Text("name")], vec![square(), V::Blob(vec![1, 2, 3]), V::Text(Some("a"))], "photos");
assert_eq!(names, ["OBJECTID", "name"]);
assert_eq!(messages, ["photos: 1 column of a type RustGIS has no field for was left out: scan (binary)"]);
// A binary field and a second geometry field, each named with its kind.
let (names, messages) = said(
&[F::Oid, F::Shape { z: false, wkt: LONLAT }, F::Text("name"), F::Blob("scan"), F::Shape2("Shape_2")],
vec![square(), V::Text(Some("a")), V::Blob(vec![9]), square()],
"photos",
);
assert_eq!(names, ["OBJECTID", "name"]);
assert_eq!(messages, ["photos: 2 columns of types RustGIS has no field for were left out: scan (binary), Shape_2 (geometry)"]);
// Thirteen are counted and the first twelve named.
let blobs: Vec<&'static str> = ["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12", "b13"].into();
let mut fields = vec![F::Oid, F::Shape { z: false, wkt: LONLAT }];
fields.extend(blobs.iter().map(|n| F::Blob(n)));
let mut row = vec![square()];
row.extend(blobs.iter().map(|_| V::Blob(Vec::new())));
let (_, messages) = said(&fields, row, "many");
let named: Vec<String> = blobs.iter().take(12).map(|n| format!("{n} (binary)")).collect();
assert_eq!(messages, [format!("many: 13 columns of types RustGIS has no field for were left out: {} and 1 more", named.join(", "))]);
// Nothing left out: nothing said.
let (names, messages) =
said(&[F::Oid, F::Shape { z: false, wkt: LONLAT }, F::Text("name")], vec![square(), V::Text(Some("a"))], "clean");
assert_eq!(names, ["OBJECTID", "name"]);
assert!(messages.is_empty(), "{messages:?}");
// Two tables with the same field each say it: the table's name tells them apart.
let one = |name| (name, table(4, &[F::Oid, F::Shape { z: false, wkt: LONLAT }, F::Blob("scan")], &[vec![square(), V::Blob(vec![1])]]));
let layers = read_files(&geodatabase(vec![one("north"), one("south")])).unwrap();
let all: Vec<String> = layers.iter().flat_map(|(_, r)| r.messages.texts().map(str::to_string)).collect();
assert_eq!(
all,
[
"north: 1 column of a type RustGIS has no field for was left out: scan (binary)",
"south: 1 column of a type RustGIS has no field for was left out: scan (binary)"
]
);
}
13 changes: 10 additions & 3 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ impl GpkgSource {
// Columns: the primary key, the geometry and the attribute fields.
let mut pk = None;
let mut fields = Vec::new();
// The columns with no field type (BLOB), which reading leaves out.
let mut left_out = Vec::new();
{
let mut st = conn.prepare(&format!("PRAGMA table_info({})", quote(&table))).map_err(err)?;
let cols = st
Expand All @@ -294,8 +296,9 @@ impl GpkgSource {
pk = Some(name);
continue;
}
if let Some(ty) = field_type(&decl) {
fields.push(Field::new(name, ty));
match field_type(&decl) {
Some(ty) => fields.push(Field::new(name, ty)),
None => left_out.push((name, "binary".to_string())),

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.

The None arm labels every left-out column "binary". That is right today, because gpkg_blob::field_type returns None only for a BLOB declaration. But the label is now tied to that function's None meaning, and a later change that returns None for another reason would be reported as binary without anyone noticing. The same applies to gpkg_mem.rs:200. Small, optional fix: have field_type return the kind too, or add a comment at gpkg_blob::field_type saying that its None means "BLOB" and that the notes depend on it.

Category: quality

}
}
}
Expand Down Expand Up @@ -354,7 +357,7 @@ impl GpkgSource {
"POLYGON" | "MULTIPOLYGON" | "SURFACE" | "MULTISURFACE" => GeometryType::Polygon,
_ => GeometryType::None,
};
let info = SourceInfo {
let mut info = SourceInfo {
name: table.clone(),
format: "GeoPackage",
geometry_type,
Expand All @@ -368,6 +371,10 @@ impl GpkgSource {
notes,
zm_dropped: false,
};
info.note_columns(
&left_out,
["of a type RustGIS has no field for was left out", "of types RustGIS has no field for were left out"],
);
let file = Some((path.to_path_buf(), id));
let mut src = GpkgSource {
info,
Expand Down
17 changes: 13 additions & 4 deletions crates/data/src/source/gpkg_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,18 @@ impl GpkgMemSource {
.ok_or_else(|| DataError::Format(format!("GeoPackage: no column '{geom}' in {table_name}")))?;
let mut fields = Vec::new();
let mut field_cols = Vec::new();
// The columns with no field type (BLOB), which reading leaves out.
let mut left_out = Vec::new();
for (i, c) in table.columns.iter().enumerate() {
if i == geom_col || Some(i) == table.rowid_column {
continue;
}
if let Some(ty) = super::gpkg_blob::field_type(&c.decl) {
fields.push(Field::new(c.name.clone(), ty));
field_cols.push(i);
match super::gpkg_blob::field_type(&c.decl) {
Some(ty) => {
fields.push(Field::new(c.name.clone(), ty));
field_cols.push(i);
}
None => left_out.push((c.name.clone(), "binary".to_string())),
}
}
let contents = meta_rows(&db, &schema, "gpkg_contents").unwrap_or_default();
Expand All @@ -211,7 +216,7 @@ impl GpkgMemSource {
"POLYGON" | "MULTIPOLYGON" | "SURFACE" | "MULTISURFACE" => GeometryType::Polygon,
_ => GeometryType::None,
};
let info = SourceInfo {
let mut info = SourceInfo {
name: table_name,
format: "GeoPackage",
geometry_type,
Expand All @@ -225,6 +230,10 @@ impl GpkgMemSource {
notes,
zm_dropped: false,
};
info.note_columns(
&left_out,
["of a type RustGIS has no field for was left out", "of types RustGIS has no field for were left out"],
);
let mut src = GpkgMemSource { info, db, table, geom_col, field_cols, reproject };
// The extent the file declares, else the envelopes in the geometry headers.
let native = match declared.filter(|e| !e.is_empty()) {
Expand Down
36 changes: 22 additions & 14 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,21 +189,12 @@ impl SourceInfo {
}
}

/// Notes what happened to some columns in one note, counting them and naming the first 12
/// with their kind ("price (decimal)"): `what` says it for one column, then for several.
/// Nothing when there are none.
/// Notes what happened to some columns in one note ([`columns_note`]). Nothing when there are
/// none.
pub(crate) fn note_columns(&mut self, cols: &[(String, String)], what: [&str; 2]) {
const NAMED: usize = 12;
let [one, several] = what;
let n = cols.len();
let what = match n {
0 => return,
1 => one,
_ => several,
};
let named: Vec<String> = cols.iter().take(NAMED).map(|(name, kind)| format!("{name} ({kind})")).collect();
let more = if n > NAMED { format!(" and {} more", n - NAMED) } else { String::new() };
self.notes.push(format!("{n} column{} {what}: {}{more}", if n == 1 { "" } else { "s" }, named.join(", ")));
if let Some(note) = columns_note(cols, what) {
self.notes.push(note);
}
}

/// The source's coordinate system, when it isn't longitude/latitude: one known by its EPSG
Expand All @@ -213,6 +204,23 @@ impl SourceInfo {
}
}

/// The note of some columns a reader left out, counting them and naming the first 12 with their
/// kind ("photo (binary)"): `what` says it for one column, then for several. `None` when there
/// are none.
pub(crate) fn columns_note(cols: &[(String, String)], what: [&str; 2]) -> Option<String> {
const NAMED: usize = 12;
let [one, several] = what;
let n = cols.len();
let what = match n {
0 => return None,
1 => one,
_ => several,
};
let named: Vec<String> = cols.iter().take(NAMED).map(|(name, kind)| format!("{name} ({kind})")).collect();
let more = if n > NAMED { format!(" and {} more", n - NAMED) } else { String::new() };
Some(format!("{n} column{} {what}: {}{more}", if n == 1 { "" } else { "s" }, named.join(", ")))
}

/// A read: the features intersecting `extent` (longitude/latitude; `None` = all), at most `limit`.
/// A zero-limit count may be refused when matching would require a full geometry scan.
#[derive(Clone, Copy, Debug, PartialEq)]
Expand Down
46 changes: 46 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3935,6 +3935,52 @@ fn flatgeobuf_binary_columns_are_said_and_left_out() {
assert!(src.info().notes.is_empty(), "{:?}", src.info().notes);
}

/// A GeoPackage's BLOB columns, which RustGIS has no field type for, are said and left out by the
/// desktop reader and the browser's alike, the columns after them keeping their values; a table
/// without one says nothing (#2916).
#[test]
fn geopackage_blob_columns_are_said_and_left_out() {
let d = tempfile::tempdir().unwrap();
let blobs = |n: usize| {
let path = d.path().join(format!("blobs{n}.gpkg"));
write_gpkg(&path, false);
let c = rusqlite::Connection::open(&path).unwrap();
for i in 1..=n {
c.execute_batch(&format!(
"ALTER TABLE \"grid \"\"q\"\"\" ADD COLUMN b{i:02} BLOB; ALTER TABLE \"grid \"\"q\"\"\" ADD COLUMN after{i:02} TEXT;"
))
.unwrap();
}
path
};
let notes = |path: &Path| {
let bytes = Shared(Arc::new(std::fs::read(path).unwrap()));
let mem = gpkg_mem::GpkgMemSource::open_shared(bytes, None).unwrap();
let sql = open_path(path, None).unwrap();
let said = |s: &dyn FeatureSource| s.info().notes.texts().map(str::to_string).collect::<Vec<_>>();
assert_eq!(said(&mem), said(sql.as_ref()), "the browser's reader says what the desktop's does");
let fields: Vec<String> = sql.info().fields.iter().map(|f| f.name.clone()).collect();
assert_eq!(mem.info().fields, sql.info().fields);
// Read whole, the layer's name goes before it.
let (_, report) = materialize(sql.as_ref()).unwrap();
(said(sql.as_ref()), fields, report.messages.texts().map(str::to_string).collect::<Vec<_>>())
};
let one = notes(&blobs(1));
assert_eq!(one.0, ["1 column of a type RustGIS has no field for was left out: b01 (binary)"]);
assert_eq!(one.1, ["name", "value", "ok", "after01"]);
assert_eq!(one.2, [format!("grid \"q\": {}", one.0[0])]);
let two = notes(&blobs(2));
assert_eq!(two.0, ["2 columns of types RustGIS has no field for were left out: b01 (binary), b02 (binary)"]);
let many = notes(&blobs(13));
let named: Vec<String> = (1..=12).map(|i| format!("b{i:02} (binary)")).collect();
assert_eq!(many.0, [format!("13 columns of types RustGIS has no field for were left out: {} and 1 more", named.join(", "))]);
// The table as the fixture writes it: nothing is left out, nothing said.
let clean = d.path().join("clean.gpkg");
write_gpkg(&clean, false);
let none = notes(&clean);
assert!(none.0.is_empty() && none.2.is_empty(), "{none:?}");
}

/// The tables of a GeoPackage, by name.
fn gpkg_tables(path: &Path) -> Vec<String> {
let c = rusqlite::Connection::open(path).unwrap();
Expand Down
Loading
Loading