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
159 changes: 141 additions & 18 deletions crates/analysis/src/attribute_join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,49 @@ fn written(v: &Value) -> String {
JoinKey::from_value(v).map(|k| k.display()).unwrap_or_default()
}

/// Validates windowed flags and key-field compatibility and returns the progress work units
/// (`source_len` + optional `NumberAsText` scan + `target_len`) that [`join_field`] will advance.
pub(crate) fn join_field_work(
target: &Dataset,
target_len: usize,
source: &Dataset,
source_len: usize,
target_field: &str,
join_field: &str,
) -> Result<usize, String> {
if target.windowed {
return Err("the target layer is streamed; load all features first".into());
}
if source.windowed {
return Err("the source layer is streamed; load all features first".into());
}
let target_key_idx = crate::tools::find_field_case_insensitive(target, target_field)?;
let source_key_idx = crate::tools::find_field_case_insensitive(source, join_field)?;
let target_key_field = target.fields.get(target_key_idx).ok_or_else(|| "target key field missing".to_string())?;
let source_key_field = source.fields.get(source_key_idx).ok_or_else(|| "source key field missing".to_string())?;
let comparison = key_comparison(target_key_field, source_key_field)?;
let extra_scan = if comparison == KeyComparison::NumberAsText { source_len } else { 0 };
Ok(source_len.saturating_add(extra_scan).saturating_add(target_len))
}

/// Executes a non-spatial attribute join from `source` onto `target`.
///
/// Preserves target order, IDs, geometry, existing attributes, and the record count of the
/// provided target dataset (when invoked through the tool, row selections are applied beforehand).
/// Appends selected attributes from `source` based on matching key values.
pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_>) -> Result<(Dataset, JoinFieldReport), String> {
join_field_with_progress(target, source, opts, false)
}

/// Executes [`join_field`], optionally continuing an active `control::begin` step started by the
/// caller (used by `joinField` when partial selections copy rows beforehand so progress climbs
/// monotonically across subsetting and joining).
pub(crate) fn join_field_with_progress(
target: &Dataset,
source: &Dataset,
opts: &JoinFieldOptions<'_>,
progress_started: bool,
Comment thread
ninhhaidang marked this conversation as resolved.
Resolved
) -> Result<(Dataset, JoinFieldReport), String> {
if target.windowed {
return Err("the target layer is streamed; load all features first".into());
}
Expand Down Expand Up @@ -278,45 +315,54 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_
}

// 5. Index source records: Map JoinKey -> source feature index
let extra_scan = if comparison == KeyComparison::NumberAsText { source.features.len() } else { 0 };
if !progress_started {
crate::control::begin(source.features.len().saturating_add(extra_scan).saturating_add(target.features.len()));
}
crate::control::check()?;
let mut source_index: HashMap<JoinKey, usize> = HashMap::with_capacity(source.features.len());
let mut duplicate_count = 0usize;

for (s_idx, s_feat) in source.features.iter().enumerate() {
crate::control::check()?;
let val = s_feat.attrs.get(source_key_idx).unwrap_or(&Value::Null);
let Some(key) = JoinKey::from_value_compared(val, comparison) else {
// Null or non-finite keys in source cannot match
continue;
};

match source_index.entry(key) {
std::collections::hash_map::Entry::Occupied(mut occ) => {
duplicate_count += 1;
match opts.duplicate_strategy {
DuplicateStrategy::Error => {
return Err(format!("duplicate key {} found in source table under Error duplicate strategy", occ.key().display()));
}
DuplicateStrategy::First => {}
DuplicateStrategy::Last => {
occ.insert(s_idx);
if let Some(key) = JoinKey::from_value_compared(val, comparison) {
match source_index.entry(key) {
std::collections::hash_map::Entry::Occupied(mut occ) => {
duplicate_count += 1;
match opts.duplicate_strategy {
DuplicateStrategy::Error => {
return Err(format!(
"duplicate key {} found in source table under Error duplicate strategy",
occ.key().display()
));
}
DuplicateStrategy::First => {}
DuplicateStrategy::Last => {
occ.insert(s_idx);
}
}
}
}
std::collections::hash_map::Entry::Vacant(vac) => {
vac.insert(s_idx);
std::collections::hash_map::Entry::Vacant(vac) => {
vac.insert(s_idx);
}
}
}
crate::control::advance(1);
}

// Source text keys with leading zeros, by their digits without them: a target number that
// lost its zeros (`1001` for `"01001"`) doesn't match, and the report says so.
let mut zero_padded_sources: HashMap<String, usize> = HashMap::new();
if comparison == KeyComparison::NumberAsText {
for (s_idx, s_feat) in source.features.iter().enumerate() {
crate::control::check()?;
if let Some(Value::Text(text)) = s_feat.attrs.get(source_key_idx)
&& let Some(digits) = without_leading_zeros(text)
{
zero_padded_sources.entry(digits.to_string()).or_insert(s_idx);
}
crate::control::advance(1);
}
}
let source_key_value = |s_idx: usize| source.features.get(s_idx).and_then(|f| f.attrs.get(source_key_idx)).unwrap_or(&Value::Null);
Expand All @@ -329,6 +375,7 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_
let mut out_features = Vec::with_capacity(target_len);

for t_feat in &target.features {
crate::control::check()?;
if t_feat.attrs.len() > target.fields.len() {
return Err(format!(
"target feature {} has {} attributes, exceeding schema field count {}",
Expand Down Expand Up @@ -376,6 +423,7 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_
}

out_features.push(rustgis_data::Feature { id: t_feat.id, geometry: t_feat.geometry.clone(), attrs: new_attrs });
crate::control::advance(1);
}

out.features = out_features.into();
Expand Down Expand Up @@ -1311,4 +1359,79 @@ mod tests {
assert_eq!(out_col.fields[2].alias, None);
assert_eq!(out_col.fields[2].display(), "cost_2");
}

#[test]
fn test_join_field_checks_cancel_and_reports_progress() {
use crate::control::Control;

// Case 1: Exact comparison (Integer vs Integer), 5 source rows (one Null key) + 5 target rows => total 10.
let target = make_table("target", vec![("id", FieldType::Integer)], (1..=5).map(|i| vec![Value::Int(i)]).collect());
let source = make_table(
"source",
vec![("id", FieldType::Integer), ("tag", FieldType::Text)],
vec![
vec![Value::Int(1), Value::Text("a".into())],
vec![Value::Int(2), Value::Text("b".into())],
vec![Value::Null, Value::Text("null".into())],
vec![Value::Int(4), Value::Text("d".into())],
vec![Value::Int(5), Value::Text("e".into())],
],
);
let opts = JoinFieldOptions {
target_field: "id",
join_field: "id",
fields_to_transfer: None,
prefix: "",
duplicate_strategy: DuplicateStrategy::First,
output_name: "joined".into(),
};

let counting = Control::cancelled_at_look(u64::MAX);
let (out, rep) = crate::run_under("Join Field", &counting, || join_field(&target, &source, &opts)).unwrap();
assert_eq!(rep.matched_records, 4);
assert_eq!(out.features.len(), 5);
assert_eq!(counting.progress(), Some((10, 10)));
assert_eq!(counting.looked(), 11);

let cancel_source = Control::cancelled_at_look(3);
let err = crate::run_under("Join Field", &cancel_source, || join_field(&target, &source, &opts)).unwrap_err();
assert!(err.contains("cancelled"), "{err}");
assert_eq!(cancel_source.looked(), 3);
assert_eq!(cancel_source.progress(), Some((1, 10)));

let cancel_target = Control::cancelled_at_look(8);
let err = crate::run_under("Join Field", &cancel_target, || join_field(&target, &source, &opts)).unwrap_err();
assert!(err.contains("cancelled"), "{err}");
assert_eq!(cancel_target.looked(), 8);
assert_eq!(cancel_target.progress(), Some((6, 10)));

// Case 2: NumberAsText comparison (Text target vs Integer source), 4 rows each => total 12.
let target_text =
make_table("target", vec![("GEOID", FieldType::Text)], (1..=4).map(|i| vec![Value::Text(i.to_string())]).collect());
let source_int = make_table(
"source",
vec![("GEOID", FieldType::Integer), ("tag", FieldType::Text)],
(1..=4).map(|i| vec![Value::Int(i), Value::Text(format!("v{i}"))]).collect(),
);
let opts_num = JoinFieldOptions {
target_field: "GEOID",
join_field: "GEOID",
fields_to_transfer: None,
prefix: "",
duplicate_strategy: DuplicateStrategy::First,
output_name: "joined_num".into(),
};

let counting_num = Control::cancelled_at_look(u64::MAX);
let (_, rep_num) = crate::run_under("Join Field", &counting_num, || join_field(&target_text, &source_int, &opts_num)).unwrap();
assert_eq!(rep_num.matched_records, 4);
assert_eq!(counting_num.progress(), Some((12, 12)));
assert_eq!(counting_num.looked(), 13);

let cancel_scan = Control::cancelled_at_look(7);
let err = crate::run_under("Join Field", &cancel_scan, || join_field(&target_text, &source_int, &opts_num)).unwrap_err();
assert!(err.contains("cancelled"), "{err}");
assert_eq!(cancel_scan.looked(), 7);
assert_eq!(cancel_scan.progress(), Some((5, 12)));
}
}
72 changes: 72 additions & 0 deletions crates/analysis/src/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,16 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result<ToolResult, Stri
n.checked_add(count).ok_or("Merge has too many features")
})?;
let no_memory = |e: TryReserveError| format!("Merge: not enough memory for {n} features: {e}");
crate::control::begin(n);
crate::control::check()?;
out.features.try_reserve_exact(n).map_err(no_memory)?;
for (i, ds) in layers.iter().enumerate() {
let mapping = mappings.get(i).ok_or("Merge field mapping is missing")?;
let selection = selected(i);
let all = 0..if selection.is_empty() { ds.features.len() } else { 0 };
for row in selection.iter().copied().chain(all) {
let Some(feature) = ds.features.get(row) else { continue };
crate::control::check()?;
if feature.geometry.as_ref().is_some_and(|g| g.kind() != first.geometry_type) {
return Err(format!("{}: a feature does not match the layer geometry type", ds.name));
}
Expand All @@ -69,6 +72,7 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result<ToolResult, Stri
}
let geometry = feature.geometry.as_ref().map(clone_geometry).transpose().map_err(no_memory)?;
out.push_next(geometry, attrs);
crate::control::advance(1);
}
}
Ok(ToolResult {
Expand Down Expand Up @@ -108,3 +112,71 @@ pub(crate) fn clone_geometry(g: &Geometry) -> Result<Geometry, TryReserveError>
}
})
}

#[cfg(test)]
mod tests {
use super::*;
use crate::control::Control;
use rustgis_data::FieldType;
use std::collections::HashMap;

#[derive(Default)]
struct MergeInputs {
data: HashMap<String, Dataset>,
selected: HashMap<String, Vec<usize>>,
}

impl Inputs for MergeInputs {
fn dataset(&self, layer: &str) -> Option<&Dataset> {
self.data.get(layer)
}

fn selection(&self, layer: &str) -> &[usize] {
self.selected.get(layer).map(Vec::as_slice).unwrap_or(&[])
}
}

fn point_layer(name: &str, count: usize) -> Dataset {
let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("n", FieldType::Integer)]);
for i in 0..count {
ds.push_next(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Int(i as i64)]);
}
ds
}

#[test]
fn merge_checks_cancel_and_reports_progress() {
let mut inputs = MergeInputs {
data: HashMap::from([("A".to_string(), point_layer("A", 3)), ("B".to_string(), point_layer("B", 4))]),
..Default::default()
};
let params = serde_json::json!({"inputs": ["A", "B"], "attributes": true});

let counting = Control::cancelled_at_look(u64::MAX);
let res = crate::run_with("merge", &inputs, &params, &counting).unwrap();
let Output::Layer(out) = res.output else { panic!("expected layer") };
assert_eq!(out.features.len(), 7);
assert_eq!(counting.progress(), Some((7, 7)));
assert_eq!(counting.looked(), 8);

let cancel_pre_reserve = Control::cancelled_at_look(1);
let err = crate::run_with("merge", &inputs, &params, &cancel_pre_reserve).unwrap_err();
assert!(err.contains("cancelled"), "{err}");
assert_eq!(cancel_pre_reserve.looked(), 1);
assert_eq!(cancel_pre_reserve.progress(), Some((0, 7)));

let cancel_mid = Control::cancelled_at_look(5);
let err = crate::run_with("merge", &inputs, &params, &cancel_mid).unwrap_err();
assert!(err.contains("cancelled"), "{err}");
assert_eq!(cancel_mid.looked(), 5);
assert_eq!(cancel_mid.progress(), Some((3, 7)));

// Stale selection indices in A must not inflate progress past valid count n = 1 + 4 = 5.
inputs.selected.insert("A".to_string(), vec![0, usize::MAX]);
let counting_sel = Control::cancelled_at_look(u64::MAX);
let res_sel = crate::run_with("merge", &inputs, &params, &counting_sel).unwrap();
let Output::Layer(out_sel) = res_sel.output else { panic!("expected layer") };
assert_eq!(out_sel.features.len(), 5);
assert_eq!(counting_sel.progress(), Some((5, 5)));
}
}
Loading
Loading