Skip to content
Open
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
1 change: 0 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,6 @@ And alongside it:
- Traverse closure for `edit.traverse`: a misclosure report, an optional compass-rule adjustment,
curve legs and a form.
- Editor tracking fields (created/edited by and at).
- Attribute table columns: rename (hide and reorder are done) _(open)_.
- Attribute forms: widgets, constraints and conditional visibility, on top of domains and
subtypes.

Expand Down
23 changes: 23 additions & 0 deletions crates/data/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ impl Field {
pub fn display(&self) -> &str {
self.alias.as_deref().unwrap_or(&self.name)
}

/// Gives each of the `fresh` fields (a source read again) the alias its namesake in `was`
/// had, where it had one: a column renamed in RustGIS keeps its name for display when its data
/// is reloaded. A field without a namesake, or whose namesake had no alias, keeps its own.
pub fn keep_aliases(fresh: &mut [Field], was: &[Field]) {
for field in fresh {
if let Some(alias) = was.iter().find(|w| w.name == field.name).and_then(|w| w.alias.as_ref()) {
field.alias = Some(alias.clone());
}
}
}
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
Expand Down Expand Up @@ -757,6 +768,18 @@ pub fn sort_class_values(values: &mut Vec<String>) {
mod tests {
use super::*;

/// A reloaded source's fields take the aliases their namesakes had; a new field, and one
/// whose namesake had none, keep the source's own.
#[test]
fn reloaded_fields_keep_their_aliases() {
let aliased = |name: &str, alias: Option<&str>| Field { name: name.into(), ty: FieldType::Text, alias: alias.map(String::from) };
let was = [aliased("a", Some("Renamed")), aliased("b", None), aliased("gone", Some("Gone"))];
let mut fresh = [aliased("a", None), aliased("b", Some("From file")), aliased("new", None), aliased("A", None)];
Field::keep_aliases(&mut fresh, &was);
let shown: Vec<&str> = fresh.iter().map(Field::display).collect();
assert_eq!(shown, ["Renamed", "From file", "new", "A"]);
}

/// Whole numbers order exactly against whole numbers and against decimals, so values equal to
/// one another stay equal to the same things: a sort by this order never sees a contradiction.
#[test]
Expand Down
1 change: 1 addition & 0 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ edit.deleteField layer? table? field
edit.elevation mode z? units? surface?
edit.enable on?
edit.explode
edit.fieldAlias layer? table? field alias?
edit.flip
edit.groundToGrid on? scale? rotation?
edit.merge
Expand Down
100 changes: 100 additions & 0 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ pub fn commands() -> Vec<C> {
C::new("edit.deleteField", "Delete Field", "Data › Data Design › Fields", delete_field).roles(&[]).effects(crate::policy::Effects::NONE)
.when(need_layer_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused)}"#),
C::new("edit.fieldAlias", "Rename Column", "Attribute Table", field_alias).roles(&[]).effects(crate::policy::Effects::NONE)
.when(need_layer_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "alias"?: string|null (the column's display name, at most 255 characters; the field keeps its name; empty, null or left out shows the name again)}"#),
C::new("edit.convertField", "Convert Field to Dates", "Attribute Table", convert_field).roles(&[]).effects(crate::policy::Effects::NONE)
.when(need_layer_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "field": string (the exact name first; a name matching several fields only ignoring case is refused), "type": "date"|"datetime", "format"?: "iso" (default)|strftime numeric pattern|"excel1900"|"excel1904", "pivotYear"?: first year of the 100-year window for %y}"#),
Expand Down Expand Up @@ -1312,6 +1315,33 @@ fn to_dates(ds: &mut Dataset, fi: usize, ty: FieldType, reader: &rustgis_data::d
Ok(out)
}

/// The longest field alias `edit.fieldAlias` takes, in characters (GeoPackage's and the File
/// Geodatabase's alias columns hold 255).
const ALIAS_MAX: usize = 255;

/// `edit.fieldAlias`: names the field's column for display (the attribute table's header, layout
/// tables, search results) without renaming the field, so expressions, symbology, labels and the
/// file keep reading it by its name. An empty alias, null, or the field's own name shows the name
/// again. Only the field list changes, so a table's rows are never scanned and the edit runs on
/// the frame for every caller.
fn field_alias(s: &mut Session, p: &Json) -> CmdResult {
let t = target(s, p)?;
let fi = field_of(s, t, ps(p, "field").ok_or("field is required")?)?;
let alias = match p.get("alias") {
None | Some(Json::Null) => None,
Some(Json::String(a)) => Some(a.trim()),
Some(_) => return Err("alias is text, or null to show the field's name".into()),
};
if let Some(a) = alias
&& a.chars().count() > ALIAS_MAX
{
return Err(format!("an alias is at most {ALIAS_MAX} characters"));
}
let field = data_mut(s, t)?.fields.get_mut(fi).ok_or("no such field")?;
field.alias = alias.filter(|a| !a.is_empty() && *a != field.name).map(str::to_string);
Ok(json!({"field": field.name, "alias": field.alias}))
}

/// `edit.deleteField`: removes a field and the references to it (symbology and its expressions
/// by feature, labels and their expressions by feature, the data design, diagrams, the
/// extrusion's height and base, the marker rotation), or refuses while the definition query, a
Expand Down Expand Up @@ -2650,6 +2680,76 @@ mod tests {
}
}

/// A column renamed by `edit.fieldAlias` shows its alias while the field keeps its name, on a
/// layer and a standalone table; an empty alias, null or the field's own name shows the name
/// again; Undo and Redo take it back and forth; it is saved with the project; and a bad call
/// changes nothing.
#[test]
fn a_renamed_column_keeps_its_field_name() {
for table in [false, true] {
let mut s = Session::new(crate::Project::default());
let fields =
vec![Field::new("pop", FieldType::Integer), Field::new("Name", FieldType::Text), Field::new("name", FieldType::Text)];
let mut ds = Dataset::new("towns", GeometryType::None, fields);
ds.push(None, vec![Value::Int(5), Value::Text("a".into()), Value::Text("b".into())]);
let target = if table { json!({"table": s.project.add_table(ds)}) } else { json!({"layer": s.map_mut().add_dataset(ds)}) };
let t = super::target(&s, &target).unwrap();
let with = |extra: Json| {
let mut p = target.clone();
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
};
let shown = |s: &Session| -> Vec<String> { data(s, t).unwrap().fields.iter().map(|f| f.display().to_string()).collect() };
let names = |s: &Session| -> Vec<String> { data(s, t).unwrap().fields.iter().map(|f| f.name.clone()).collect() };

let answer = s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": " Population "}))).unwrap();
assert_eq!(answer, json!({"field": "pop", "alias": "Population"}), "table {table}");
assert_eq!(shown(&s), ["Population", "Name", "name"], "table {table}");
assert_eq!(names(&s), ["pop", "Name", "name"], "table {table}");

// Saved with the project, and read back.
let saved = crate::Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap();
let reopened = match t {
Target::Layer(id) => saved.maps[0].layer(id).map(|l| l.dataset.fields[0].display().to_string()),
Target::Table(i) => saved.tables.get(i).map(|t| t.dataset.fields[0].display().to_string()),
};
assert_eq!(reopened.as_deref(), Some("Population"), "table {table}");

// Undo shows the name again; Redo the alias.
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s), ["pop", "Name", "name"], "undo, table {table}");
s.run("edit.redo", &json!({})).unwrap();
assert_eq!(shown(&s), ["Population", "Name", "name"], "redo, table {table}");

// An empty alias, null, a missing alias or the field's own name clears it.
for clear in [json!({"alias": " "}), json!({"alias": null}), json!({}), json!({"alias": "pop"})] {
s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": "Population"}))).unwrap();
let mut p = with(clear.clone());
p["field"] = json!("pop");
s.run("edit.fieldAlias", &p).unwrap();
assert_eq!(data(&s, t).unwrap().fields[0].alias, None, "{clear}, table {table}");
}

// The exact case twin is renamed; one matching neither exactly, an unknown field, an
// alias that isn't text or one too long are refused, changing nothing.
s.run("edit.fieldAlias", &with(json!({"field": "name", "alias": "Second"}))).unwrap();
assert_eq!(shown(&s), ["pop", "Name", "Second"], "twin, table {table}");
for bad in [
json!({"field": "NAME", "alias": "X"}),
json!({"field": "nothing", "alias": "X"}),
json!({"field": "pop", "alias": 5}),
json!({"field": "pop", "alias": "x".repeat(ALIAS_MAX + 1)}),
json!({"alias": "X"}),
] {
assert!(s.run("edit.fieldAlias", &with(bad.clone())).is_err(), "{bad}, table {table}");
assert_eq!(shown(&s), ["pop", "Name", "Second"], "{bad}, table {table}");
}
s.run("edit.fieldAlias", &with(json!({"field": "pop", "alias": "é".repeat(ALIAS_MAX)}))).unwrap();
}
}

/// Converting and calculating geometry into a field named the same as another but for case
/// work on the field named; the design guard follows the field design applies to; and design
/// is refused on twins, which it couldn't tell apart (#1955).
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/repair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> {
l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(dataset.geometry_type, seed));
}
dataset.name.clone_from(&l.dataset.name);
rustgis_data::Field::keep_aliases(&mut dataset.fields, &l.dataset.fields);
l.dataset = dataset;
l.touch_replacement();
l.gpkg = Some(edit);
Expand Down
7 changes: 5 additions & 2 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,8 @@ impl Layer {
})
}

/// Installs a fresh source, retaining styling except an untouched no-geometry default.
/// Installs a fresh source, retaining styling except an untouched no-geometry default, and
/// the aliases of columns the new source still has ([`rustgis_data::Field::keep_aliases`]).
/// Clears feature-specific state whose ids may identify different features, returning the
/// number of saved label moves reset for a notice.
pub fn replace_source(&mut self, mut src: source::SourceLayer) -> usize {
Expand All @@ -603,7 +604,9 @@ impl Layer {
self.renderer = Renderer::Single(Symbol::default_for(info.geometry_type, seed));
}
self.dataset.geometry_type = info.geometry_type;
self.dataset.fields = info.fields.clone();
let mut fields = info.fields.clone();
rustgis_data::Field::keep_aliases(&mut fields, &self.dataset.fields);

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.

Two paths now decide which renamed columns survive a source replacement, and they disagree. refresh_replaced_source (just below, line 654) keeps an alias only when name and type match. keep_aliases matches by name alone, so a column whose type changed (say Text to Integer) keeps its alias here and loses it there. Both behaviours could be defensible, but the doc comments don't say why they differ. Either use one rule, or state the difference in keep_aliases' doc comment so the next reader doesn't pick one at random.

Category: quality

self.dataset.fields = fields;
self.dataset.crs = info.coordinate_system();
// The new source's Z and M, which reading it drops (see `Dataset::zm_dropped`).
self.dataset.zm_dropped = info.zm_dropped;
Expand Down
Loading