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
13 changes: 13 additions & 0 deletions crates/data/src/source/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,19 @@ impl GeoJsonSource {
Self::open_with(path, name, crate::io::BYTES_FLOOR)
}

/// Opens a linked collection with known property names first, in saved layer order.
/// Other properties keep their inferred order. Missing names and changed types remain
/// visible in the fresh schema for the caller to reject. Every read decodes by property
/// name in this same order.
pub(super) fn open_path_for_fields(path: &Path, name: &str, saved: &[crate::Field]) -> Result<Self> {
let mut source = Self::open_path(path, name)?;
if !saved.is_empty() {
let positions: std::collections::HashMap<_, _> = saved.iter().enumerate().map(|(i, field)| (field.name.as_str(), i)).collect();
source.info.fields.sort_by_cached_key(|field| positions.get(field.name.as_str()).copied().unwrap_or(usize::MAX));
}
Ok(source)
}

/// [`open_path`](Self::open_path), reading a file of at most `in_memory` bytes into memory to
/// scan it, and a larger one through a buffer.
pub(crate) fn open_with(path: &Path, name: &str, in_memory: u64) -> Result<GeoJsonSource> {
Expand Down
10 changes: 8 additions & 2 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,12 @@ pub trait FeatureSource: Send + Sync {

/// Opens a file through its provider. `layer` names a table in a GeoPackage (default: the first).
pub fn open_path(path: &Path, layer: Option<&str>) -> Result<Box<dyn FeatureSource>> {
open_path_for_fields(path, layer, &[])
}

/// Opens a linked file. GeoJSON reads properties by name and presents the saved names first.
/// Formats with a declared column order retain that order.
pub fn open_path_for_fields(path: &Path, layer: Option<&str>, saved: &[crate::Field]) -> Result<Box<dyn FeatureSource>> {
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string();
match ext(path).as_str() {
"parquet" | "geoparquet" => Ok(Box::new(parquet::ParquetSource::open_path(path, &name)?)),
Expand All @@ -730,12 +736,12 @@ pub fn open_path(path: &Path, layer: Option<&str>) -> Result<Box<dyn FeatureSour
// Only large GeoJSON files are read in place (see `geojson`); `is_source_name` leaves
// them out.
#[cfg(not(target_arch = "wasm32"))]
"geojson" | "json" => Ok(Box::new(geojson::GeoJsonSource::open_path(path, &name)?)),
"geojson" | "json" => Ok(Box::new(geojson::GeoJsonSource::open_path_for_fields(path, &name, saved)?)),
// Only large Shapefiles are read in place (see `shp`); `is_source_name` leaves them out.
#[cfg(not(target_arch = "wasm32"))]
"shp" => Ok(Box::new(shp::ShpSource::open_path(path, &name)?)),
other => {
let _ = layer;
let _ = (layer, saved);
Err(DataError::Unsupported(other.to_string()))
}
}
Expand Down
4 changes: 3 additions & 1 deletion crates/engine/src/cmd/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,12 +437,14 @@ fn discard_edits(s: &mut Session, p: &Value) -> CmdResult {
{
let (id, name, edit) = gpkg_layer(s, p)?;
let old = s.map().layer(id).ok_or("no such layer")?;
let Candidate { dataset, edit: baseline, notes, matched } = read_candidate(&old.dataset.name, &edit)?;
let Candidate { mut dataset, edit: baseline, mut notes, matched } = read_candidate(&old.dataset.name, &edit)?;
let n = dataset.features.len();
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
if l.dataset.geometry_type != dataset.geometry_type {
l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(dataset.geometry_type, id));
}
notes.extend(l.removed_source_fields_note(&dataset.fields).map(rustgis_data::loss::Note::plain));
l.keep_aliases(&mut dataset.fields);
l.dataset = dataset;
l.gpkg = Some(baseline);
l.selection.clear();
Expand Down
28 changes: 21 additions & 7 deletions crates/engine/src/cmd/repair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ struct Input {

#[cfg(not(target_arch = "wasm32"))]
enum Snapshot {
Vector(Box<rustgis_map::source::SourceLayer>),
Vector {
source: Box<rustgis_map::source::SourceLayer>,
fields: Vec<rustgis_data::Field>,
},
Raster(Box<rustgis_map::RasterLayer>),
Editable {
name: String,
Expand Down Expand Up @@ -170,7 +173,7 @@ fn reload_input(s: &Session, p: &Value) -> Result<Input, String> {
capture(s, id, path, table, discard)
}

/// Capture only what reading and stale validation consume, never vector presentation.
/// Capture the source and schema needed to prepare and validate a replacement.
#[cfg(not(target_arch = "wasm32"))]
fn capture(s: &Session, id: u32, path: String, table: Option<String>, discard: bool) -> Result<Input, String> {
let l = s.map().layer(id).ok_or("the layer no longer exists")?;
Expand All @@ -185,7 +188,10 @@ fn capture(s: &Session, id: u32, path: String, table: Option<String>, discard: b
} else if let Some(raster) = &l.raster {
Snapshot::Raster(Box::new(raster.clone()))
} else {
Snapshot::Vector(Box::new(l.source.as_ref().ok_or("the layer has no linked source")?.clone()))
Snapshot::Vector {
source: Box::new(l.source.as_ref().ok_or("the layer has no linked source")?.clone()),
fields: l.dataset.fields.clone(),
}
};
Ok(Input {
id,
Expand Down Expand Up @@ -242,7 +248,9 @@ fn prepare(input: Input) -> Result<Prepared, String> {
};
Candidate::Raster(Box::new(new))
}
Snapshot::Vector(source) => Candidate::Vector(Box::new(source.relinked(&input.path, input.table.as_deref())?)),
Snapshot::Vector { source, fields } => {
Candidate::Vector(Box::new(source.relinked_for_fields(&input.path, input.table.as_deref(), fields)?))
}
};
Ok(Prepared { input, candidate })
}
Expand Down Expand Up @@ -342,7 +350,7 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> {
l.touch_geometry();
}
Candidate::Vector(new) => {
let (Some(current), Snapshot::Vector(prior)) = (&l.source, &input.source) else { return Err(stale()) };
let (Some(current), Snapshot::Vector { source: prior, fields }) = (&l.source, &input.source) else { return Err(stale()) };
if l.gpkg.is_some()
|| !current.same_opening(prior)
|| current.path != prior.path
Expand All @@ -359,8 +367,12 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> {
return Err(stale());
}
let info = new.info().ok_or_else(|| format!("{}: the source did not open", input.path))?;
if info.format == "GeoJSON" && l.dataset.fields != *fields {
return Err(stale());
}
compatible(l, info.geometry_type, &info.fields, &input.path)?;
let notes = info.notes.clone();
let mut notes = info.notes.clone();
notes.extend(l.removed_source_fields_note(&info.fields).map(rustgis_data::loss::Note::plain));
let moved = s.map_mut().layer_mut(id).ok_or("the layer no longer exists")?.replace_source(*new);
reset_labels(s, id, moved);
let name = s.map().layer(id).map_or_else(|| "Layer".to_string(), |l| l.name.clone());
Expand All @@ -369,7 +381,7 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> {
}
}
Candidate::Editable(new) => {
let super::gpkg::Candidate { mut dataset, edit, notes, .. } = *new;
let super::gpkg::Candidate { mut dataset, edit, mut notes, .. } = *new;
let (Some(current), Snapshot::Editable { edit: prior, features, fields, geometry, .. }) = (&l.gpkg, &input.source) else {
return Err(stale());
};
Expand All @@ -383,6 +395,8 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> {
}
compatible(l, dataset.geometry_type, &dataset.fields, &input.path)?;
let l = s.map_mut().layer_mut(id).ok_or("the layer no longer exists")?;
notes.extend(l.removed_source_fields_note(&dataset.fields).map(rustgis_data::loss::Note::plain));
l.keep_aliases(&mut dataset.fields);
let moved = l.labels.in_order().map(|class| class.moved.len()).sum();
l.labels.default.moved.clear();
l.labels.classes.iter_mut().for_each(|class| class.moved.clear());
Expand Down
35 changes: 34 additions & 1 deletion crates/engine/src/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ fn reopen(p: &mut Project, at: &At) -> Vec<(&'static str, String)> {
| rustgis_map::LayerRole::GdalPath => {
if let Some(source) = &mut layer.source {
source.allow_reconnect();
if let Err(e) = source.reopen() {
if let Err(e) = source.reopen(&layer.dataset.fields) {
source.error = Some(rustgis_data::diagnostics::Redacted::new(&e).into_string());
}
return crate::cmd::connections::layer_keys(source);
Expand Down Expand Up @@ -544,6 +544,39 @@ fn text(p: &Project) -> Result<String, String> {
mod tests {
use super::*;

/// Local files open during peer normalization. The retained-source helper also has to
/// respect the owning layer's current schema when explicitly asked to reopen that reader.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn peer_geojson_replacement_uses_current_layer_fields() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schema/fixtures/linked_geojson_order.rgis");
let mut s = Session::new(Project::load(&fixture).unwrap());
let (public, _) = s.peer_text(Peer::Bridge).unwrap();
let raw = Project::from_peer_raw(&public).unwrap();
assert!(s.exchange.as_ref().unwrap().incoming(&raw).is_empty());
s.open_peer_text(Peer::Bridge, &public).unwrap();
let check = |p: &Project, order: &[&str], stage: &str| {
let ds = p.map().layers[0].load_all().unwrap_or_else(|error| panic!("{stage}: {error}"));
assert_eq!(ds.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), order, "{stage}");
for (name, value) in [("a", 10), ("b", 20), ("c", 30)] {
assert_eq!(ds.value(0, ds.field_index(name).unwrap()), &rustgis_data::Value::Int(value), "{stage}: {name}");
}
};
check(&s.project, &["b", "a", "c"], "peer round trip");

let at = At {
owners: vec![Owner::Map(0)],
leaf: Leaf::Map(rustgis_map::SlotPos::Layer { layer: 0, role: rustgis_map::LayerRole::Streamed }),
};
let mut copy = s.project.clone();
reopen(&mut copy, &at);
check(&copy, &["b", "a", "c"], "source reopened");

copy.map_mut().layers[0].dataset.fields.swap(0, 2);
reopen(&mut copy, &at);
check(&copy, &["c", "a", "b"], "cloned source reopened after schema order changed");
}

/// Table/family/CRS are part of a retained reader, even before normalization opens it.
#[test]
fn bridge_census_binds_the_full_source_choice_before_normalization() {
Expand Down
20 changes: 14 additions & 6 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,7 @@ impl Project {
repairs.push((l.name.clone(), r));
}
}
let mut added_fields: Vec<String> = Vec::new();
let mut notices: Vec<(ReadPart, NoticeText)> =
layout_notices(&self.name, when, layouts_dropped, &repairs).into_iter().map(|n| (ReadPart::Layouts, n.into())).collect();
let mut done = Repaired::default();
Expand Down Expand Up @@ -1853,12 +1854,12 @@ impl Project {
// before): reading a project fetches nothing with another session's keys.
if let Some(src) = &mut l.source {
l.dataset.windowed = true;
if !src.is_open()
&& src.error.is_none()
&& !src.path.as_deref().is_some_and(crate::s3_connections::is_s3_backed)
&& let Err(e) = src.open()
{
log::warn!("{}: {e}", l.name);
if !src.is_open() && src.error.is_none() && !src.path.as_deref().is_some_and(crate::s3_connections::is_s3_backed) {
match l.open_saved_source() {
Ok(Some(note)) => added_fields.push(note.prefixed(&l.name).text.to_string()),
Ok(None) => {}
Err(e) => log::warn!("{}: {e}", l.name),
}
}
}
l.normalize_selection();
Expand All @@ -1872,6 +1873,13 @@ impl Project {
}
read_in_place(m);
}
// One notice, however many layers gained fields: the first few of them by name.
if !added_fields.is_empty() {
let more = added_fields.len().saturating_sub(5);
added_fields.truncate(5);
let more = if more > 0 { format!("; and {more} more layer(s)") } else { String::new() };
notices.push((ReadPart::Maps, format!("{}{more}", added_fields.join("; ")).into()));
}
notices.extend(done.notices(&self.name, when));
notices
}
Expand Down
5 changes: 3 additions & 2 deletions crates/engine/src/s3_connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,11 @@ pub(crate) struct Counts {
fn reopen_where(s: &mut Session, which: impl Fn(&str) -> bool) -> Counts {
let mut n = Counts::default();
let wait = s.in_place_wait;
for src in s.project.maps.iter_mut().flat_map(|m| m.layers.iter_mut()).filter_map(|l| l.source.as_mut()) {
for layer in s.project.maps.iter_mut().flat_map(|m| &mut m.layers) {
let Some(src) = &mut layer.source else { continue };
let Some(path) = src.path.clone() else { continue };
if (!src.is_open() || src.error.is_some()) && which(&path) {
match src.reopen() {
match src.reopen(&layer.dataset.fields) {
Ok(()) => n.opened += 1,
Err(_) => n.failed += 1,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/service_logins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ fn rebind_connection(s: &mut Session, c: &Connection) -> usize {
// is); one not open yet, or whose open failed, opens on the next sync.
if changed {
if source.is_open() {
let _ = source.reopen();
let _ = source.reopen(&l.dataset.fields);
} else {
source.clear_error();
}
Expand Down
13 changes: 9 additions & 4 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2450,7 +2450,8 @@ fn a_streamed_layer_says_its_view_reads_notes_once() {
assert_eq!(notes(&s, mark), expected, "{name}: view reads");
// Opened anew (the file may have changed), the source says it again, once.
let mark = s.notice_mark();
s.map_mut().layer_mut(id).unwrap().source.as_mut().unwrap().reopen().unwrap();
let layer = s.map_mut().layer_mut(id).unwrap();
layer.source.as_mut().unwrap().reopen(&layer.dataset.fields).unwrap();
reads(&mut s);
assert_eq!(notes(&s, mark), expected, "{name}: reopened");
// Undo and redo bring back the same opening, not what it had said then: a snapshot taken
Expand Down Expand Up @@ -26233,7 +26234,7 @@ fn any_command_editing_a_streamed_layer_is_undone() {
let l = &mut s.map_mut().layers[0];
let reads = l.source.as_ref().unwrap().reads;
let mut reopened = l.source.as_ref().unwrap().clone();
reopened.reopen()?;
reopened.reopen(&l.dataset.fields)?;
reopened.reads = reads;
l.source = Some(reopened);
l.dataset.features[0].attrs[0] = rustgis_data::Value::Int(-1);
Expand Down Expand Up @@ -59237,7 +59238,8 @@ fn reads_made_ahead_are_taken_by_the_command() {
// An opening replaced at the same path cannot trigger a new read under old authority.
let id = s.run("layer.addData", &json!({"path": path.display().to_string(), "stream": true})).unwrap()["layer"].as_u64().unwrap();
let read = crate::cmd::reads::read_ahead(&mut s, "layer.loadAll", &json!({"layer": id})).unwrap().run(&Control::new()).unwrap();
s.map_mut().layer_mut(id as u32).unwrap().source.as_mut().unwrap().reopen().unwrap();
let layer = s.map_mut().layer_mut(id as u32).unwrap();
layer.source.as_mut().unwrap().reopen(&layer.dataset.fields).unwrap();
assert!(crate::cmd::reads::read_land(&mut s, read).unwrap_err().contains("source changed"));
assert!(s.map().layer(id as u32).unwrap().is_streamed() && s.read_ahead.is_none());

Expand Down Expand Up @@ -59763,7 +59765,10 @@ fn prepared_reload_validates_live_presentation_and_refuses_stale_source_without_
l.dataset.fields.push(rustgis_data::Field::new("new_field", rustgis_data::FieldType::Integer));
l.labels.default.field = "new_field".into();
}
"reopen" => s.map_mut().layer_mut(id).unwrap().source.as_mut().unwrap().reopen().unwrap(),
"reopen" => {
let layer = s.map_mut().layer_mut(id).unwrap();
layer.source.as_mut().unwrap().reopen(&layer.dataset.fields).unwrap();
}
"path" => s.map_mut().layer_mut(id).unwrap().source.as_mut().unwrap().path = Some("missing.fgb".into()),
"second reload" => {
s.run("layer.reloadData", &p).unwrap();
Expand Down
Loading
Loading