From e5d2af7943af1287a1f717169a9e93e68123c90c Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 17 Nov 2026 11:45:31 +0100 Subject: [PATCH 01/37] add grammar --- doc/ggsql.xml | 63 ++++++++++++++++ tree-sitter-ggsql/grammar.js | 19 +++++ tree-sitter-ggsql/queries/highlights.scm | 4 ++ tree-sitter-ggsql/test/corpus/basic.txt | 91 ++++++++++++++++++++++++ 4 files changed, 177 insertions(+) diff --git a/doc/ggsql.xml b/doc/ggsql.xml index b7376fe7b..0aa88b0a3 100644 --- a/doc/ggsql.xml +++ b/doc/ggsql.xml @@ -391,6 +391,8 @@ + + @@ -439,6 +441,8 @@ + + @@ -480,6 +484,8 @@ + + @@ -520,6 +526,8 @@ + + @@ -567,6 +575,8 @@ + + @@ -611,6 +621,8 @@ + + @@ -654,6 +666,8 @@ + + @@ -689,6 +703,8 @@ + + @@ -727,6 +743,8 @@ + + @@ -768,6 +786,8 @@ + + @@ -804,6 +824,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -820,6 +881,8 @@ + + diff --git a/tree-sitter-ggsql/grammar.js b/tree-sitter-ggsql/grammar.js index fb2947c9d..d97d17249 100644 --- a/tree-sitter-ggsql/grammar.js +++ b/tree-sitter-ggsql/grammar.js @@ -694,6 +694,7 @@ module.exports = grammar({ $.span_clause, $.format_clause, $.facet_clause, + $.summarise_clause, ), // FORMAT — configures cell formatting for a group of columns. Multiple @@ -718,6 +719,24 @@ module.exports = grammar({ caseInsensitive('STUB') // row-label column(s) ), + // SUMMARISE — adds aggregate rows to the table. One clause per operation; + // clauses repeat like FORMAT, each contributing its own summary row(s). + // GROUP (default) summarises within each facet group, GRAND over all rows. + // The operation is a plain identifier; validity is checked downstream. + summarise_clause: $ => seq( + choice(caseInsensitive('SUMMARISE'), caseInsensitive('SUMMARIZE')), + optional(field('scope', $.summarise_scope)), + field('operation', $.identifier), + caseInsensitive('OF'), + $.column_list, + optional($.setting_clause) + ), + + summarise_scope: $ => choice( + caseInsensitive('GROUP'), + caseInsensitive('GRAND') + ), + // SPAN — groups columns under one spanner cell. Multiple spanners repeat // the whole clause (SPAN ... SPAN ...), the same model DRAW/SCALE use for // more than one instance — not a comma list inside one SPAN. Two forms, diff --git a/tree-sitter-ggsql/queries/highlights.scm b/tree-sitter-ggsql/queries/highlights.scm index e8319356d..2b5a5c96d 100644 --- a/tree-sitter-ggsql/queries/highlights.scm +++ b/tree-sitter-ggsql/queries/highlights.scm @@ -109,6 +109,10 @@ (project_property_name) @property (label_type) @property +; SUMMARISE clause: operation name and GROUP/GRAND scope +(summarise_clause operation: (identifier) @function.builtin) +(summarise_scope) @keyword + ; Operators "=" @operator "!=" @operator diff --git a/tree-sitter-ggsql/test/corpus/basic.txt b/tree-sitter-ggsql/test/corpus/basic.txt index f0c6f62f1..4e6941e86 100644 --- a/tree-sitter-ggsql/test/corpus/basic.txt +++ b/tree-sitter-ggsql/test/corpus/basic.txt @@ -5094,3 +5094,94 @@ TABULATE * FROM sales FORMAT `body`, x (quoted_identifier)) (identifier (bare_identifier))))))) + +================================================================================ +TABULATE SUMMARISE clause +================================================================================ + +TABULATE * FROM sales SUMMARISE mean OF foo, bar + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier)) + (identifier + (bare_identifier))))))) + +================================================================================ +TABULATE SUMMARISE clause with GRAND scope and SETTING +================================================================================ + +TABULATE * FROM sales SUMMARISE GRAND sdev OF foo SETTING place => 'top' + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + scope: (summarise_scope) + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier))) + (setting_clause + (parameter_assignment + name: (parameter_name + (identifier + (bare_identifier))) + value: (parameter_value + (string)))))))) + +================================================================================ +TABULATE SUMMARIZE spelling alias +================================================================================ + +TABULATE * FROM sales SUMMARIZE median OF foo + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (identifier + (bare_identifier)) + (column_list + (identifier + (bare_identifier))))))) From 94801f2e837e642a8237280411c3deb87751564f Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 17 Nov 2026 12:16:40 +0100 Subject: [PATCH 02/37] parsing + build AST --- src/lib.rs | 2 +- src/parser/builder.rs | 129 +++++++++++++++++++++++++++++++++++++++++- src/table/mod.rs | 117 +++++++++++++++++++++++++++++++++++++- 3 files changed, 244 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c859f9bf5..7fe6c63ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,7 +75,7 @@ pub use plot::{ // Re-export the parse-time Plot/Table result and the Table stub pub use spec::Spec; -pub use table::{ColumnSection, Format, SelectionItem, Spanner, Table}; +pub use table::{ColumnSection, Format, SelectionItem, Spanner, Summary, SummaryScope, Table}; // Re-export aesthetic classification utilities pub use plot::aesthetic::{ diff --git a/src/parser/builder.rs b/src/parser/builder.rs index 2d8290d5f..4a1bc6db6 100644 --- a/src/parser/builder.rs +++ b/src/parser/builder.rs @@ -8,7 +8,10 @@ use crate::plot::layer::geom::Geom; use crate::plot::projection::resolve_coord; use crate::plot::scale::{color_to_hex, is_color_aesthetic, is_user_facet_aesthetic, Transform}; use crate::plot::*; -use crate::{ColumnSection, Format, GgsqlError, Result, SelectionItem, Spanner, Spec, Table}; +use crate::{ + ColumnSection, Format, GgsqlError, Result, SelectionItem, Spanner, Spec, Summary, SummaryScope, + Table, +}; use std::collections::HashMap; use tree_sitter::Node; @@ -452,6 +455,11 @@ fn process_tab_clause(node: &Node, source: &SourceTree, table: &mut Table) -> Re "format_clause" => { table.formats.push(build_format_clause(&child, source)?); } + "summarise_clause" => { + table + .summaries + .push(build_summarise_clause(&child, source)?); + } "facet_clause" => { let facet = build_facet(&child, source)?; if facet.is_grid() { @@ -515,6 +523,62 @@ fn build_span_clause(node: &Node, source: &SourceTree, span_idx: usize) -> Resul }) } +/// Build a Summary from a summarise_clause node: +/// SUMMARISE [GROUP|GRAND] OF col, ... [SETTING ...] +fn build_summarise_clause(node: &Node, source: &SourceTree) -> Result { + let operation_node = node.child_by_field_name("operation").ok_or_else(|| { + GgsqlError::ParseError("Missing operation in SUMMARISE clause".to_string()) + })?; + let operation = naming::unquote_ident(&source.get_text(&operation_node)); + + let scope = match node.child_by_field_name("scope") { + Some(scope_node) => match source.get_text(&scope_node).to_lowercase().as_str() { + "group" => SummaryScope::Group, + "grand" => SummaryScope::Grand, + text => { + return Err(GgsqlError::ParseError(format!( + "Unknown SUMMARISE scope: '{}'. Valid scopes: group, grand", + text + ))) + } + }, + None => SummaryScope::Group, + }; + + let columns_node = source + .find_node(node, "(column_list) @cols") + .ok_or_else(|| GgsqlError::ParseError("Missing columns in SUMMARISE clause".to_string()))?; + let columns = parse_column_list(&columns_node, source)?; + + // A repeated column would aggregate twice into the same cell — meaningless + // rather than redundant, so reject it. + let mut seen = std::collections::HashSet::new(); + let mut duplicates: Vec<&str> = Vec::new(); + for column in &columns { + if !seen.insert(column) && !duplicates.contains(&column.as_str()) { + duplicates.push(column); + } + } + if !duplicates.is_empty() { + return Err(GgsqlError::ParseError(format!( + "Duplicate columns in SUMMARISE clause: {}", + crate::and_list_quoted(&duplicates, '\'') + ))); + } + + let settings = match source.find_node(node, "(setting_clause) @s") { + Some(setting_node) => parse_setting_clause(&setting_node, source)?, + None => Parameters::new(), + }; + + Ok(Summary { + operation, + scope, + columns, + settings, + }) +} + /// Build a Format from a format_clause node: FORMAT [ANY|BODY|STUB] (*|col, ...) [SETTING ...] [RENAMING ...] fn build_format_clause(node: &Node, source: &SourceTree) -> Result { let target = parse_format_target_identifier(node, source)?; @@ -1796,6 +1860,69 @@ mod tests { assert_eq!(table.formats[1].columns, vec!["bar"]); } + #[test] + fn test_tabulate_summarise_basic() { + let specs = parse_test_specs("TABULATE * FROM sales SUMMARISE mean OF foo, bar").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries.len(), 1); + assert_eq!(table.summaries[0].operation, "mean"); + assert_eq!(table.summaries[0].scope, SummaryScope::Group); + assert_eq!(table.summaries[0].columns, vec!["foo", "bar"]); + assert!(table.summaries[0].settings.is_empty()); + } + + #[test] + fn test_tabulate_summarise_grand_scope_and_setting() { + let specs = parse_test_specs( + "TABULATE * FROM sales SUMMARISE GRAND sdev OF foo SETTING place => 'top'", + ) + .unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries[0].scope, SummaryScope::Grand); + assert_eq!( + table.summaries[0].settings.get("place"), + Some(&ParameterValue::String("top".to_string())) + ); + } + + #[test] + fn test_tabulate_summarise_operation_is_verbatim() { + let specs = parse_test_specs("TABULATE * FROM sales SUMMARIZE MEAN OF foo").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries[0].operation, "MEAN"); + } + + #[test] + fn test_tabulate_repeated_summarise_clauses_produce_separate_summaries() { + let specs = parse_test_specs( + "TABULATE * FROM sales FACET region SUMMARISE mean OF foo SUMMARISE GRAND max OF foo, bar", + ) + .unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!(table.summaries.len(), 2); + assert_eq!(table.summaries[0].operation, "mean"); + assert_eq!(table.summaries[0].scope, SummaryScope::Group); + assert_eq!(table.summaries[1].operation, "max"); + assert_eq!(table.summaries[1].scope, SummaryScope::Grand); + assert_eq!(table.summaries[1].columns, vec!["foo", "bar"]); + } + + #[test] + fn test_tabulate_summarise_reports_all_duplicate_columns() { + let result = parse_test_specs("TABULATE * FROM sales SUMMARISE mean OF foo, bar, foo, bar"); + let error = result.unwrap_err().to_string(); + + assert!( + error.contains("Duplicate columns in SUMMARISE clause: 'foo' and 'bar'"), + "got: {}", + error + ); + } + // ======================================== // PROJECT Property Validation Tests // ======================================== diff --git a/src/table/mod.rs b/src/table/mod.rs index 075c7245b..4934cc7f8 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -4,8 +4,9 @@ //! statements, parallel to how `plot` defines `Plot` for `VISUALISE` //! statements: `source` (from `TABULATE FROM`), `selection` (from //! `TABULATE`'s own column list), `labels` (from `TABULATE LABEL`), `spans` -//! (from `TABULATE SPAN`), `formats` (from `TABULATE FORMAT`), and `facet` -//! (from `TABULATE FACET`) are populated so far. +//! (from `TABULATE SPAN`), `formats` (from `TABULATE FORMAT`), `facet` +//! (from `TABULATE FACET`), and `summaries` (from `TABULATE SUMMARISE`) are +//! populated so far. mod facet; mod layout; @@ -60,6 +61,9 @@ pub struct Table { /// Row grouping (from `TABULATE FACET`). Only the wrap form is /// meaningful for tables; the builder rejects `BY`. pub facet: Option, + /// Row summaries (from `TABULATE SUMMARISE`), one per `SUMMARISE` clause + /// written — same one-clause-per-row model as `formats`. + pub summaries: Vec, } /// One item in a TABULATE column selection. @@ -97,6 +101,7 @@ impl Table { spans: Vec::new(), formats: Vec::new(), facet: None, + summaries: Vec::new(), } } } @@ -265,6 +270,71 @@ impl ColumnSection { } } +/// One `SUMMARISE` clause: an aggregate operation producing one summary row +/// per group — or a single row over all rows for `GRAND`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Summary { + /// The aggregate operation (e.g. `mean`), verbatim as written — it doubles + /// as the default row label. Matching against the operation vocabulary is + /// case-insensitive at execution time. + pub operation: String, + /// Which rows the operation aggregates over. + pub scope: SummaryScope, + /// The columns to summarise, in the order written. + pub columns: Vec, + /// `SETTING` parameters for this SUMMARISE (e.g. `place => 'top'`, + /// `rowlabel => 'Average'`). + pub settings: Parameters, +} + +/// Which rows a `SUMMARISE` clause aggregates over. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SummaryScope { + /// One summary row per facet group. Without a `FACET`, all rows form a + /// single group. + #[default] + Group, + /// A single summary row over all rows. + Grand, +} + +/// `SETTING` parameters `SUMMARISE` accepts. +const SUMMARY_PARAMS: &[ParamDefinition] = &[ + ParamDefinition { + name: "place", + // No default: an unset place resolves at execution time. + default: DefaultParamValue::Null, + constraint: ParamConstraint::string_option(&["top", "bottom"]), + }, + ParamDefinition { + name: "rowlabel", + // No default: an unset rowlabel falls back to the operation verbatim. + default: DefaultParamValue::Null, + constraint: ParamConstraint::string(), + }, +]; + +impl Summary { + /// Validate `settings` against `SUMMARY_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + let valid: Vec<&str> = SUMMARY_PARAMS.iter().map(|p| p.name).collect(); + + for (name, value) in &self.settings { + let Some(param) = SUMMARY_PARAMS.iter().find(|p| p.name == name.as_str()) else { + return Err(format!( + "SUMMARISE setting should be {}, not '{}'", + crate::or_list_quoted(&valid, '\''), + name + )); + }; + validate_parameter(name, value, ¶m.constraint)?; + } + + Ok(()) + } +} + /// One `FORMAT` clause: cell formatting for a group of columns. /// /// `settings` is validated against `FORMAT_PARAMS` and resolved into each @@ -472,6 +542,49 @@ mod tests { assert!(format_with_settings(settings).validate_settings().is_ok()); } + fn summary_with_settings(settings: Parameters) -> Summary { + Summary { + operation: "mean".to_string(), + scope: SummaryScope::Group, + columns: vec!["a".to_string()], + settings, + } + } + + #[test] + fn summary_validate_settings_accepts_place_and_rowlabel() { + let mut settings = Parameters::new(); + settings.insert( + "place".to_string(), + ParameterValue::String("top".to_string()), + ); + settings.insert( + "rowlabel".to_string(), + ParameterValue::String("Average".to_string()), + ); + + assert!(summary_with_settings(settings).validate_settings().is_ok()); + } + + #[test] + fn summary_validate_settings_rejects_a_non_string_rowlabel() { + let mut settings = Parameters::new(); + settings.insert("rowlabel".to_string(), ParameterValue::Number(1.0)); + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_validate_settings_rejects_an_unknown_setting() { + let mut settings = Parameters::new(); + settings.insert( + "colour".to_string(), + ParameterValue::String("red".to_string()), + ); + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + #[test] fn validate_boundaries_rejects_a_span_over_a_stub_column() { let table = Table { From 121b202d63f0d5e859e6ee0d8b1a20bda54e6160 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 17 Nov 2026 13:53:34 +0100 Subject: [PATCH 03/37] write validation steps --- src/table/mod.rs | 110 +---------------------------- src/table/summary.rs | 164 +++++++++++++++++++++++++++++++++++++++++++ src/validate.rs | 46 ++++++++++++ 3 files changed, 212 insertions(+), 108 deletions(-) create mode 100644 src/table/summary.rs diff --git a/src/table/mod.rs b/src/table/mod.rs index 4934cc7f8..6d0e0575c 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -11,6 +11,7 @@ mod facet; mod layout; mod spanner; +mod summary; pub(crate) use facet::{groups_are_woven, setup_facet}; pub(crate) use layout::{ @@ -20,6 +21,7 @@ pub(crate) use layout::{ pub use layout::{TableCell, TableCellKind, TableClass, TableColumn, TableLayout, TableRow}; pub use spanner::Spanner; pub(crate) use spanner::{create_spanners, reorder_table_columns}; +pub use summary::{Summary, SummaryScope, SUMMARY_OPERATIONS}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -270,71 +272,6 @@ impl ColumnSection { } } -/// One `SUMMARISE` clause: an aggregate operation producing one summary row -/// per group — or a single row over all rows for `GRAND`. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Summary { - /// The aggregate operation (e.g. `mean`), verbatim as written — it doubles - /// as the default row label. Matching against the operation vocabulary is - /// case-insensitive at execution time. - pub operation: String, - /// Which rows the operation aggregates over. - pub scope: SummaryScope, - /// The columns to summarise, in the order written. - pub columns: Vec, - /// `SETTING` parameters for this SUMMARISE (e.g. `place => 'top'`, - /// `rowlabel => 'Average'`). - pub settings: Parameters, -} - -/// Which rows a `SUMMARISE` clause aggregates over. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum SummaryScope { - /// One summary row per facet group. Without a `FACET`, all rows form a - /// single group. - #[default] - Group, - /// A single summary row over all rows. - Grand, -} - -/// `SETTING` parameters `SUMMARISE` accepts. -const SUMMARY_PARAMS: &[ParamDefinition] = &[ - ParamDefinition { - name: "place", - // No default: an unset place resolves at execution time. - default: DefaultParamValue::Null, - constraint: ParamConstraint::string_option(&["top", "bottom"]), - }, - ParamDefinition { - name: "rowlabel", - // No default: an unset rowlabel falls back to the operation verbatim. - default: DefaultParamValue::Null, - constraint: ParamConstraint::string(), - }, -]; - -impl Summary { - /// Validate `settings` against `SUMMARY_PARAMS`. - pub fn validate_settings(&self) -> Result<(), String> { - let valid: Vec<&str> = SUMMARY_PARAMS.iter().map(|p| p.name).collect(); - - for (name, value) in &self.settings { - let Some(param) = SUMMARY_PARAMS.iter().find(|p| p.name == name.as_str()) else { - return Err(format!( - "SUMMARISE setting should be {}, not '{}'", - crate::or_list_quoted(&valid, '\''), - name - )); - }; - validate_parameter(name, value, ¶m.constraint)?; - } - - Ok(()) - } -} - /// One `FORMAT` clause: cell formatting for a group of columns. /// /// `settings` is validated against `FORMAT_PARAMS` and resolved into each @@ -542,49 +479,6 @@ mod tests { assert!(format_with_settings(settings).validate_settings().is_ok()); } - fn summary_with_settings(settings: Parameters) -> Summary { - Summary { - operation: "mean".to_string(), - scope: SummaryScope::Group, - columns: vec!["a".to_string()], - settings, - } - } - - #[test] - fn summary_validate_settings_accepts_place_and_rowlabel() { - let mut settings = Parameters::new(); - settings.insert( - "place".to_string(), - ParameterValue::String("top".to_string()), - ); - settings.insert( - "rowlabel".to_string(), - ParameterValue::String("Average".to_string()), - ); - - assert!(summary_with_settings(settings).validate_settings().is_ok()); - } - - #[test] - fn summary_validate_settings_rejects_a_non_string_rowlabel() { - let mut settings = Parameters::new(); - settings.insert("rowlabel".to_string(), ParameterValue::Number(1.0)); - - assert!(summary_with_settings(settings).validate_settings().is_err()); - } - - #[test] - fn summary_validate_settings_rejects_an_unknown_setting() { - let mut settings = Parameters::new(); - settings.insert( - "colour".to_string(), - ParameterValue::String("red".to_string()), - ); - - assert!(summary_with_settings(settings).validate_settings().is_err()); - } - #[test] fn validate_boundaries_rejects_a_span_over_a_stub_column() { let table = Table { diff --git a/src/table/summary.rs b/src/table/summary.rs new file mode 100644 index 000000000..4dab58464 --- /dev/null +++ b/src/table/summary.rs @@ -0,0 +1,164 @@ +//! Row summaries: the AST for `TABULATE SUMMARISE` clauses. + +use serde::{Deserialize, Serialize}; + +use crate::params::{ + validate_parameter, DefaultParamValue, ParamConstraint, ParamDefinition, Parameters, +}; + +/// One `SUMMARISE` clause: an aggregate operation producing one summary row +/// per group — or a single row over all rows for `GRAND`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Summary { + /// The aggregate operation (e.g. `mean`), verbatim as written — it doubles + /// as the default row label. Matching against the operation vocabulary is + /// case-insensitive at execution time. + pub operation: String, + /// Which rows the operation aggregates over. + pub scope: SummaryScope, + /// The columns to summarise, in the order written. + pub columns: Vec, + /// `SETTING` parameters for this SUMMARISE (e.g. `place => 'top'`, + /// `rowlabel => 'Average'`). + pub settings: Parameters, +} + +/// Which rows a `SUMMARISE` clause aggregates over. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SummaryScope { + /// One summary row per facet group. Without a `FACET`, all rows form a + /// single group. + #[default] + Group, + /// A single summary row over all rows. + Grand, +} + +/// Operations a `SUMMARISE` clause accepts: the plot aggregate vocabulary +/// (`AGG_NAMES`) minus the order-dependent positional ones (`first`, `last`, +/// `diff`), which need row-order machinery tables don't have. +pub const SUMMARY_OPERATIONS: &[&str] = &[ + "count", "sum", "prod", "min", "max", "range", "mid", "mean", "geomean", "harmean", "rms", + "median", "sdev", "var", "iqr", "p05", "p10", "p25", "p50", "p75", "p90", "p95", +]; + +/// `SETTING` parameters `SUMMARISE` accepts. +const SUMMARY_PARAMS: &[ParamDefinition] = &[ + ParamDefinition { + name: "place", + // No default: an unset place resolves at execution time. + default: DefaultParamValue::Null, + constraint: ParamConstraint::string_option(&["top", "bottom"]), + }, + ParamDefinition { + name: "rowlabel", + // No default: an unset rowlabel falls back to the operation verbatim. + default: DefaultParamValue::Null, + constraint: ParamConstraint::string(), + }, +]; + +impl Summary { + /// Validate `operation` against `SUMMARY_OPERATIONS`, case-insensitively. + pub fn validate_operation(&self) -> Result<(), String> { + if SUMMARY_OPERATIONS + .iter() + .any(|op| self.operation.eq_ignore_ascii_case(op)) + { + Ok(()) + } else { + Err(format!( + "Unknown operation '{}'. Valid operations: {}", + self.operation, + crate::or_list_quoted(SUMMARY_OPERATIONS, '\'') + )) + } + } + + /// Validate `settings` against `SUMMARY_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + let valid: Vec<&str> = SUMMARY_PARAMS.iter().map(|p| p.name).collect(); + + for (name, value) in &self.settings { + let Some(param) = SUMMARY_PARAMS.iter().find(|p| p.name == name.as_str()) else { + return Err(format!( + "SUMMARISE setting should be {}, not '{}'", + crate::or_list_quoted(&valid, '\''), + name + )); + }; + validate_parameter(name, value, ¶m.constraint)?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plot::ParameterValue; + + fn summary_with_settings(settings: Parameters) -> Summary { + Summary { + operation: "mean".to_string(), + scope: SummaryScope::Group, + columns: vec!["a".to_string()], + settings, + } + } + + #[test] + fn summary_validate_settings_accepts_place_and_rowlabel() { + let mut settings = Parameters::new(); + settings.insert( + "place".to_string(), + ParameterValue::String("top".to_string()), + ); + settings.insert( + "rowlabel".to_string(), + ParameterValue::String("Average".to_string()), + ); + + assert!(summary_with_settings(settings).validate_settings().is_ok()); + } + + #[test] + fn summary_validate_settings_rejects_a_non_string_rowlabel() { + let mut settings = Parameters::new(); + settings.insert("rowlabel".to_string(), ParameterValue::Number(1.0)); + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_validate_settings_rejects_an_unknown_setting() { + let mut settings = Parameters::new(); + settings.insert( + "colour".to_string(), + ParameterValue::String("red".to_string()), + ); + + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + + #[test] + fn summary_validate_operation_accepts_case_insensitively() { + assert!(summary_with_settings(Parameters::new()) + .validate_operation() + .is_ok()); + let mut summary = summary_with_settings(Parameters::new()); + summary.operation = "MEAN".to_string(); + assert!(summary.validate_operation().is_ok()); + } + + #[test] + fn summary_validate_operation_rejects_unknown_and_positional() { + let mut summary = summary_with_settings(Parameters::new()); + summary.operation = "meen".to_string(); + assert!(summary.validate_operation().is_err()); + summary.operation = "first".to_string(); + assert!(summary.validate_operation().is_err()); + } +} diff --git a/src/validate.rs b/src/validate.rs index 0c21c1045..2055d1438 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -349,6 +349,22 @@ pub fn validate(query: &str) -> Result { }); } } + + // And each SUMMARISE's operation and SETTING parameters. + for (idx, summary) in table.summaries.iter().enumerate() { + if let Err(e) = summary.validate_operation() { + errors.push(ValidationError { + message: format!("SUMMARISE {}: {}", idx + 1, e), + location: None, + }); + } + if let Err(e) = summary.validate_settings() { + errors.push(ValidationError { + message: format!("SUMMARISE {}: {}", idx + 1, e), + location: None, + }); + } + } } Ok(Validated { @@ -425,6 +441,36 @@ mod tests { assert!(!validated.valid()); } + #[test] + fn test_validate_summarise_rejects_an_unknown_operation() { + let validated = validate("TABULATE * FROM sales SUMMARISE meen OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0] + .message + .contains("SUMMARISE 1: Unknown operation 'meen'")); + } + + #[test] + fn test_validate_summarise_accepts_operations_case_insensitively() { + let validated = validate("TABULATE * FROM sales SUMMARISE MEAN OF foo").unwrap(); + assert!(validated.valid()); + } + + #[test] + fn test_validate_summarise_rejects_positional_operations() { + let validated = validate("TABULATE * FROM sales SUMMARISE first OF foo").unwrap(); + assert!(!validated.valid()); + } + + #[test] + fn test_validate_summarise_rejects_a_bad_setting() { + let validated = + validate("TABULATE * FROM sales SUMMARISE mean OF foo SETTING place => 'middle'") + .unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.contains("SUMMARISE 1:")); + } + #[test] fn test_validate_tabulate_from_is_valid() { // A TABULATE FROM has a data source (extract_sql injects From 2d8c092c18cc0e5e8929eabba9a9ee41289234a7 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 18 Nov 2026 11:45:23 +0100 Subject: [PATCH 04/37] initial set of summary computation --- src/execute/table/mod.rs | 1 + src/execute/table/summary.rs | 116 +++++++++++++++++++++++++++++++++++ src/table/summary.rs | 25 ++++++++ 3 files changed, 142 insertions(+) create mode 100644 src/execute/table/summary.rs diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 5fcb20db2..03b12fb87 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -11,6 +11,7 @@ mod facet; mod format; mod layout; mod stub; +mod summary; use facet::collapse_group_columns; use format::{apply_formats, setup_formats}; diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs new file mode 100644 index 000000000..11f9a2140 --- /dev/null +++ b/src/execute/table/summary.rs @@ -0,0 +1,116 @@ +//! Statistics kernel for `SUMMARISE` clauses: aggregate operations computed +//! directly on the materialised table data. +//! +//! Only `mean` and `median` exist so far; the rest of `SUMMARY_OPERATIONS` +//! lands once the execution pipeline is wired end-to-end. + +use arrow::array::{Array, ArrayRef}; +use arrow::datatypes::DataType; + +use crate::array_util::{as_f64, cast_array}; +use crate::{GgsqlError, Result}; + +/// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls +/// are ignored; otherwise a single null makes the result `None` (NULL), as +/// does an empty input. Matching on `operation` is case-insensitive. +// Unused until summary execution calls it. +#[allow(dead_code)] +pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { + let values = numeric_values(array, operation, drop_nulls)?; + let Some(values) = values else { + return Ok(None); + }; + match operation.to_ascii_lowercase().as_str() { + "mean" => Ok(Some(values.iter().sum::() / values.len() as f64)), + "median" => Ok(Some(quantile(values, 0.5))), + _ => Err(GgsqlError::InternalError(format!( + "SUMMARISE operation '{operation}' is not implemented" + ))), + } +} + +/// Extract a column's values as f64. Returns `None` when the result should be +/// NULL: the input is empty, all-null, or holds nulls without `drop_nulls`. +fn numeric_values(array: &ArrayRef, operation: &str, drop_nulls: bool) -> Result>> { + if !array.data_type().is_numeric() { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {operation} requires a numeric column, not {}", + array.data_type() + ))); + } + let f64s: ArrayRef = if array.data_type() == &DataType::Float64 { + array.clone() + } else { + cast_array(array, &DataType::Float64)? + }; + let array = as_f64(&f64s)?; + if array.is_empty() || (array.logical_null_count() > 0 && !drop_nulls) { + return Ok(None); + } + let values: Vec = array.iter().flatten().collect(); + Ok((!values.is_empty()).then_some(values)) +} + +/// Linear-interpolated quantile. +/// Uses the `quantile_cont` convention, R's default `quantile(type = 7)`. +fn quantile(mut values: Vec, q: f64) -> f64 { + values.sort_by(f64::total_cmp); + let pos = q * (values.len() - 1) as f64; + let lower = values[pos.floor() as usize]; + let upper = values[pos.ceil() as usize]; + lower + (upper - lower) * pos.fract() +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow::array::{Float64Array, Int64Array, StringArray}; + use std::sync::Arc; + + #[test] + fn nulls_propagate_by_default() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(summary_stat("mean", &array, false).unwrap(), None); + assert_eq!(summary_stat("median", &array, false).unwrap(), None); + } + + #[test] + fn drop_nulls_ignores_them() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(summary_stat("mean", &array, true).unwrap(), Some(2.0)); + assert_eq!(summary_stat("median", &array, true).unwrap(), Some(2.0)); + } + + #[test] + fn mean_accepts_integer_columns() { + let array: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3])); + assert_eq!(summary_stat("MEAN", &array, false).unwrap(), Some(2.0)); + } + + #[test] + fn median_interpolates_even_counts() { + let odd: ArrayRef = Arc::new(Float64Array::from(vec![3.0, 1.0, 2.0])); + assert_eq!(summary_stat("median", &odd, false).unwrap(), Some(2.0)); + + let even: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])); + assert_eq!(summary_stat("median", &even, false).unwrap(), Some(2.5)); + } + + #[test] + fn all_null_input_is_none() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![None::, None])); + assert_eq!(summary_stat("mean", &array, true).unwrap(), None); + } + + #[test] + fn non_numeric_column_is_rejected() { + let array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"])); + assert!(summary_stat("mean", &array, true).is_err()); + } + + #[test] + fn unimplemented_operation_is_rejected() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0])); + assert!(summary_stat("geomean", &array, false).is_err()); + } +} diff --git a/src/table/summary.rs b/src/table/summary.rs index 4dab58464..1f60582b3 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -57,6 +57,13 @@ const SUMMARY_PARAMS: &[ParamDefinition] = &[ default: DefaultParamValue::Null, constraint: ParamConstraint::string(), }, + ParamDefinition { + // Whether nulls make the summary null ('propagate') or are ignored + // ('drop'). + name: "missing", + default: DefaultParamValue::String("propagate"), + constraint: ParamConstraint::string_option(&["propagate", "drop"]), + }, ]; impl Summary { @@ -124,6 +131,24 @@ mod tests { assert!(summary_with_settings(settings).validate_settings().is_ok()); } + #[test] + fn summary_validate_settings_accepts_missing_options() { + for value in ["propagate", "drop"] { + let mut settings = Parameters::new(); + settings.insert( + "missing".to_string(), + ParameterValue::String(value.to_string()), + ); + assert!(summary_with_settings(settings).validate_settings().is_ok()); + } + let mut settings = Parameters::new(); + settings.insert( + "missing".to_string(), + ParameterValue::String("ignore".to_string()), + ); + assert!(summary_with_settings(settings).validate_settings().is_err()); + } + #[test] fn summary_validate_settings_rejects_a_non_string_rowlabel() { let mut settings = Parameters::new(); From 24d2477afd662781706093ba9eae88be3a2d9cc8 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 18 Nov 2026 14:27:03 +0100 Subject: [PATCH 05/37] summarising data --- src/execute/table/summary.rs | 233 ++++++++++++++++++++++++++++++++++- src/naming.rs | 13 ++ 2 files changed, 242 insertions(+), 4 deletions(-) diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 11f9a2140..896fe4247 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -4,17 +4,122 @@ //! Only `mean` and `median` exist so far; the rest of `SUMMARY_OPERATIONS` //! lands once the execution pipeline is wired end-to-end. -use arrow::array::{Array, ArrayRef}; +use std::sync::Arc; + +use std::ops::Range; + +use arrow::array::{Array, ArrayRef, Float64Array, StringArray}; use arrow::datatypes::DataType; use crate::array_util::{as_f64, cast_array}; -use crate::{GgsqlError, Result}; +use crate::naming; +use crate::params::{ParameterValue, Parameters}; +use crate::table::{Summary, SummaryScope, TableRow}; +use crate::{DataFrame, GgsqlError, Result}; + +/// Compute every `SUMMARISE` clause against the (unformatted) data, one +/// DataFrame per clause, parallel to `summaries`. Every frame leads with a +/// `SUMMARY_GROUP_COLUMN` of ';'-joined group ranks, then one nullable-f64 +/// column per summarised column, raw (before `FORMAT`). A `GROUP` frame +/// holds one row per group — in display order, since `setup_rows` leaves +/// rows group-contiguous; a `GRAND` frame a single row keyed by the empty +/// key (a grand total has no group). The clause itself carries the row's +/// label and placement, so nothing here duplicates them. +// Unused until the table pipeline calls it. +#[allow(dead_code)] +pub(super) fn setup_summaries( + df: &DataFrame, + rows: &[TableRow], + summaries: &[Summary], +) -> Result> { + // Rows are group-contiguous after setup_rows, so each group's membership + // is a contiguous range; a GRAND clause's single "group" is all of them. + let mut start = 0; + let mut ranges: Vec> = Vec::new(); + let mut key_strings: Vec = Vec::new(); + for chunk in rows.chunk_by(|a, b| a.group == b.group) { + ranges.push(start..start + chunk.len()); + start += chunk.len(); + key_strings.push(naming::summary_group_key(&chunk[0].group)); + } + + // A grand total has no group; the empty key matches the facet-less one. + let grand_key = [String::new()]; + summaries + .iter() + .map(|summary| { + let (groups, keys) = match summary.scope { + SummaryScope::Grand => (None, grand_key.as_slice()), + SummaryScope::Group => (Some(ranges.as_slice()), key_strings.as_slice()), + }; + summary_frame(df, summary, groups, keys) + }) + .collect() +} + +/// Compute one clause's frame: the key column followed by one nullable-f64 +/// column per summarised column. `groups` is `None` for a GRAND clause — a +/// single row over all rows. +fn summary_frame( + df: &DataFrame, + summary: &Summary, + groups: Option<&[Range]>, + keys: &[String], +) -> Result { + let drop_nulls = setting_string(&summary.settings, "missing").as_deref() == Some("drop"); + + let mut columns: Vec<(String, ArrayRef)> = Vec::new(); + columns.push(( + naming::SUMMARY_GROUP_COLUMN.to_string(), + Arc::new(StringArray::from(keys.to_vec())), + )); + for column in &summary.columns { + let values = summary_column(df, column, summary, groups, drop_nulls)?; + columns.push((column.clone(), Arc::new(Float64Array::from(values)))); + } + DataFrame::new(columns) +} + +/// Compute a clause's operation on one column, one value per group — or a +/// single value over the whole column when `groups` is `None` (GRAND). +fn summary_column( + df: &DataFrame, + column: &str, + summary: &Summary, + groups: Option<&[Range]>, + drop_nulls: bool, +) -> Result>> { + let array = df.column(column).map_err(|_| { + GgsqlError::ValidationError(format!( + "SUMMARISE {}: no column '{column}' in the query result", + summary.operation + )) + })?; + match groups { + Some(groups) => groups + .iter() + .map(|range| { + summary_stat( + &summary.operation, + &array.slice(range.start, range.len()), + drop_nulls, + ) + }) + .collect(), + None => summary_stat(&summary.operation, array, drop_nulls).map(|value| vec![value]), + } +} + +fn setting_string(settings: &Parameters, name: &str) -> Option { + match settings.get(name) { + Some(ParameterValue::String(value)) => Some(value.clone()), + _ => None, + } +} /// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. -// Unused until summary execution calls it. -#[allow(dead_code)] pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { let values = numeric_values(array, operation, drop_nulls)?; let Some(values) = values else { @@ -113,4 +218,124 @@ mod tests { let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0])); assert!(summary_stat("geomean", &array, false).is_err()); } + + fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { + Summary { + operation: operation.to_string(), + scope, + columns: columns.iter().map(|c| c.to_string()).collect(), + settings: Parameters::new(), + } + } + + fn body_rows(keys: &[&[usize]]) -> Vec { + keys.iter() + .map(|key| TableRow { + group: key.to_vec(), + ..TableRow::body() + }) + .collect() + } + + fn column_values(frame: &DataFrame, column: &str) -> Vec> { + as_f64(frame.column(column).unwrap()) + .unwrap() + .iter() + .collect() + } + + fn group_keys(frame: &DataFrame) -> Vec { + crate::array_util::as_str(frame.column(naming::SUMMARY_GROUP_COLUMN).unwrap()) + .unwrap() + .iter() + .map(|key| key.unwrap().to_string()) + .collect() + } + + #[test] + fn grand_summary_is_a_single_row_keyed_by_the_empty_key() { + let df = crate::df! { + "x" => vec![1.0, 2.0, 3.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let frames = + setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["x"])]).unwrap(); + + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].height(), 1); + assert_eq!(group_keys(&frames[0]), vec![""]); + assert_eq!(column_values(&frames[0], "x"), vec![Some(2.0)]); + } + + #[test] + fn group_summary_emits_one_row_per_group_in_display_order() { + let df = crate::df! { + "x" => vec![1.0, 3.0, 10.0, 20.0], + } + .unwrap(); + // Two nested-facet groups, contiguous after setup_rows' reorder. + let rows = body_rows(&[&[2, 0], &[2, 0], &[2, 1], &[2, 1]]); + + let frames = + setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + + assert_eq!(frames[0].height(), 2); + assert_eq!(group_keys(&frames[0]), vec!["2;0", "2;1"]); + assert_eq!(column_values(&frames[0], "x"), vec![Some(2.0), Some(15.0)]); + } + + #[test] + fn no_facet_means_one_group_with_an_empty_key() { + let df = crate::df! { + "x" => vec![2.0, 4.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + + let frames = + setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + + assert_eq!(frames[0].height(), 1); + assert_eq!(group_keys(&frames[0]), vec![""]); + assert_eq!(column_values(&frames[0], "x"), vec![Some(3.0)]); + } + + #[test] + fn the_missing_setting_drives_null_handling() { + let df = crate::df! { + "x" => vec![Some(1.0), None, Some(3.0)], + } + .unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let mut drop = summary("mean", SummaryScope::Grand, &["x"]); + drop.settings.insert( + "missing".to_string(), + ParameterValue::String("drop".to_string()), + ); + + let frames = setup_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"]), drop], + ) + .unwrap(); + + assert_eq!(column_values(&frames[0], "x"), vec![None]); + assert_eq!(column_values(&frames[1], "x"), vec![Some(2.0)]); + } + + #[test] + fn summarising_a_missing_column_errors() { + let df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + let rows = body_rows(&[&[]]); + + let result = setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["y"])]); + assert!(result.is_err()); + } } diff --git a/src/naming.rs b/src/naming.rs index acc716b64..f203acdc2 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -94,6 +94,10 @@ pub const SCHEMA_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "schema", GGSQL_SUFFIX); /// Alias for the derived table a TABULATE selection wraps its source in pub const TABLE_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "table", GGSQL_SUFFIX); +/// Key column of a `SUMMARISE` result frame: the row's group key as +/// ';'-joined facet ranks. A `GRAND` frame's single row uses the empty key. +pub const SUMMARY_GROUP_COLUMN: &str = concatcp!(GGSQL_PREFIX, "group", GGSQL_SUFFIX); + /// Column name for densification group ID. /// Used by geoms that expand geometry (tile, segment, ribbon, rule) to group /// densified vertices back into their original feature. @@ -315,6 +319,15 @@ pub fn anonymous_span_id(span_idx: usize) -> String { format!("{}span_{}{}", GGSQL_PREFIX, span_idx, GGSQL_SUFFIX) } +/// Encode a row's group key (one facet rank per level) for +/// `SUMMARY_GROUP_COLUMN`. +pub fn summary_group_key(key: &[usize]) -> String { + key.iter() + .map(usize::to_string) + .collect::>() + .join(";") +} + // ============================================================================ // SQL Quoting // ============================================================================ From 6374d31b428f7836e1011bcf18c5569d743c0e8d Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 19 Nov 2026 10:20:52 +0100 Subject: [PATCH 06/37] insert label stub column if it doesn't exist --- src/execute/table/layout.rs | 18 +++-- src/execute/table/mod.rs | 4 +- src/execute/table/summary.rs | 138 ++++++++++++++++++++++++++++++++--- src/naming.rs | 5 ++ 4 files changed, 146 insertions(+), 19 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index abf6bc137..fc06603bb 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -8,6 +8,7 @@ use std::collections::HashMap; use super::format::resolve_column_properties; use super::stub::{create_row_labels, create_stubhead}; use crate::array_util::{column_to_strings, value_to_string}; +use crate::naming; use crate::plot::facet::Facet; use crate::plot::Labels; use crate::table::{ @@ -160,12 +161,17 @@ fn create_table_columns( .data_type(); let format = formats.get(&name); let properties = resolve_column_properties(dtype, format); - // Group stubs record nesting order - let target = group_stub_variables - .iter() - .position(|v| *v == name) - .map(ColumnSection::GroupStub) - .unwrap_or_else(|| format.and_then(|f| f.target).unwrap_or_default()); + // the synthetic summary-label column is always a stub. + let target = if name == naming::SUMMARY_LABEL_COLUMN { + ColumnSection::Stub + } else { + // Group stubs record nesting order + group_stub_variables + .iter() + .position(|v| *v == name) + .map(ColumnSection::GroupStub) + .unwrap_or_else(|| format.and_then(|f| f.target).unwrap_or_default()) + }; let label = match labels.labels.get(&name) { // A stub head is a row-label header, not a data column header — // default it blank rather than to the column's own name. diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 03b12fb87..5cde859ff 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -16,6 +16,7 @@ mod summary; use facet::collapse_group_columns; use format::{apply_formats, setup_formats}; use layout::{build_cells, setup_columns, setup_rows}; +use summary::setup_summaries; use crate::table::extract_table_titles; @@ -67,7 +68,7 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Result 'left'` facet keeps its columns as group stubs, so check // for body columns rather than emptiness. diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 896fe4247..dc4fbdea7 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -1,12 +1,13 @@ -//! Statistics kernel for `SUMMARISE` clauses: aggregate operations computed -//! directly on the materialised table data. +//! `SUMMARISE` execution: `setup_summaries` validates the clauses against the +//! data and prepares the frame for summary rows, `compute_summaries` runs +//! the aggregate operations on it. //! //! Only `mean` and `median` exist so far; the rest of `SUMMARY_OPERATIONS` //! lands once the execution pipeline is wired end-to-end. -use std::sync::Arc; - +use std::collections::HashMap; use std::ops::Range; +use std::sync::Arc; use arrow::array::{Array, ArrayRef, Float64Array, StringArray}; use arrow::datatypes::DataType; @@ -14,8 +15,42 @@ use arrow::datatypes::DataType; use crate::array_util::{as_f64, cast_array}; use crate::naming; use crate::params::{ParameterValue, Parameters}; -use crate::table::{Summary, SummaryScope, TableRow}; -use crate::{DataFrame, GgsqlError, Result}; +use crate::table::{Format, Summary, SummaryScope, TableRow}; +use crate::{ColumnSection, DataFrame, GgsqlError, Result}; + +/// Validate `summaries` against the data and prepare the frame for summary +/// rows. Every summarised column must exist. Summary row labels need a stub +/// column to live in, so a table with summaries but no `STUB` column gets a +/// synthetic, empty one ([`naming::SUMMARY_LABEL_COLUMN`]). +pub(super) fn setup_summaries( + df: &mut DataFrame, + formats: &HashMap, + summaries: &[Summary], +) -> Result<()> { + if summaries.is_empty() { + return Ok(()); + } + for summary in summaries { + for column in &summary.columns { + if df.column(column).is_err() { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {}: no column '{column}' in the query result", + summary.operation + ))); + } + } + } + if !formats + .values() + .any(|f| f.target == Some(ColumnSection::Stub)) + { + *df = df.with_column( + naming::SUMMARY_LABEL_COLUMN, + Arc::new(StringArray::from(vec![""; df.height()])), + )?; + } + Ok(()) +} /// Compute every `SUMMARISE` clause against the (unformatted) data, one /// DataFrame per clause, parallel to `summaries`. Every frame leads with a @@ -27,7 +62,7 @@ use crate::{DataFrame, GgsqlError, Result}; /// label and placement, so nothing here duplicates them. // Unused until the table pipeline calls it. #[allow(dead_code)] -pub(super) fn setup_summaries( +pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], summaries: &[Summary], @@ -261,7 +296,7 @@ mod tests { let rows = body_rows(&[&[], &[], &[]]); let frames = - setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["x"])]).unwrap(); + compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["x"])]).unwrap(); assert_eq!(frames.len(), 1); assert_eq!(frames[0].height(), 1); @@ -279,7 +314,7 @@ mod tests { let rows = body_rows(&[&[2, 0], &[2, 0], &[2, 1], &[2, 1]]); let frames = - setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); assert_eq!(frames[0].height(), 2); assert_eq!(group_keys(&frames[0]), vec!["2;0", "2;1"]); @@ -295,7 +330,7 @@ mod tests { let rows = body_rows(&[&[], &[]]); let frames = - setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); assert_eq!(frames[0].height(), 1); assert_eq!(group_keys(&frames[0]), vec![""]); @@ -316,7 +351,7 @@ mod tests { ParameterValue::String("drop".to_string()), ); - let frames = setup_summaries( + let frames = compute_summaries( &df, &rows, &[summary("mean", SummaryScope::Grand, &["x"]), drop], @@ -327,6 +362,85 @@ mod tests { assert_eq!(column_values(&frames[1], "x"), vec![Some(2.0)]); } + fn stub_format() -> Format { + Format { + columns: vec!["x".to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + settings: Parameters::new(), + value_mapping: None, + value_template: None, + } + } + + #[test] + fn setup_adds_an_empty_label_column_when_no_stub_exists() { + let mut df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + + setup_summaries( + &mut df, + &HashMap::new(), + &[summary("mean", SummaryScope::Group, &["x"])], + ) + .unwrap(); + + let labels = + crate::array_util::as_str(df.column(naming::SUMMARY_LABEL_COLUMN).unwrap()).unwrap(); + assert_eq!(labels.iter().collect::>(), vec![Some(""), Some("")]); + } + + #[test] + fn setup_leaves_the_frame_alone_when_a_stub_exists() { + let mut df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + let formats = HashMap::from([("x".to_string(), stub_format())]); + + setup_summaries( + &mut df, + &formats, + &[summary("mean", SummaryScope::Group, &["x"])], + ) + .unwrap(); + + assert!(df.column(naming::SUMMARY_LABEL_COLUMN).is_err()); + } + + #[test] + fn setup_without_summaries_is_a_no_op() { + let mut df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + + setup_summaries(&mut df, &HashMap::new(), &[]).unwrap(); + + assert_eq!(df.width(), 1); + } + + #[test] + fn setup_rejects_a_summarised_column_the_data_lacks() { + let mut df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + + let result = setup_summaries( + &mut df, + &HashMap::new(), + &[summary("mean", SummaryScope::Group, &["y"])], + ); + + assert_eq!( + result.unwrap_err().to_string(), + "Validation error: SUMMARISE mean: no column 'y' in the query result" + ); + } + #[test] fn summarising_a_missing_column_errors() { let df = crate::df! { @@ -335,7 +449,7 @@ mod tests { .unwrap(); let rows = body_rows(&[&[]]); - let result = setup_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["y"])]); + let result = compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["y"])]); assert!(result.is_err()); } } diff --git a/src/naming.rs b/src/naming.rs index f203acdc2..8f4b3a9d8 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -98,6 +98,11 @@ pub const TABLE_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "table", GGSQL_SUFFIX); /// ';'-joined facet ranks. A `GRAND` frame's single row uses the empty key. pub const SUMMARY_GROUP_COLUMN: &str = concatcp!(GGSQL_PREFIX, "group", GGSQL_SUFFIX); +/// Synthetic stub column holding `SUMMARISE` row labels, inserted when a +/// table has summaries but no `STUB` column to put them in. Never names a +/// `DataFrame` column. +pub const SUMMARY_LABEL_COLUMN: &str = concatcp!(GGSQL_PREFIX, "summary_label", GGSQL_SUFFIX); + /// Column name for densification group ID. /// Used by geoms that expand geometry (tile, segment, ribbon, rule) to group /// densified vertices back into their original feature. From 95250407e1f2e2061805cb70e90aff6e50b75626 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 19 Nov 2026 16:55:02 +0100 Subject: [PATCH 07/37] layout weaving --- src/execute/table/layout.rs | 414 ++++++++++++++++++++++++++++++++--- src/execute/table/mod.rs | 3 +- src/execute/table/summary.rs | 338 +++++++++++++++++++--------- src/naming.rs | 13 -- src/table/layout.rs | 16 ++ src/writer/html.rs | 1 + 6 files changed, 644 insertions(+), 141 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index fc06603bb..e7f46d0df 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -7,6 +7,7 @@ use std::collections::HashMap; use super::format::resolve_column_properties; use super::stub::{create_row_labels, create_stubhead}; +use super::summary::SummaryChunk; use crate::array_util::{column_to_strings, value_to_string}; use crate::naming; use crate::plot::facet::Facet; @@ -77,8 +78,9 @@ pub(super) fn setup_rows( } /// Build the resolved `TableLayout` for a table from its already-resolved -/// `columns`, already-`FORMAT`-applied `df`, and `setup_rows` body rows — -/// spanner rows, column labels, and body, composed together and validated. +/// `columns`, already-`FORMAT`-applied `df`, `setup_rows` body rows and +/// computed `summaries` — spanner rows, column labels, and body, composed +/// together and validated. pub(super) fn build_cells( df: &DataFrame, columns: Vec, @@ -86,6 +88,7 @@ pub(super) fn build_cells( spans: &[Spanner], titles: &TableTitles, facet: Option<&Facet>, + summaries: &[SummaryChunk], ) -> Result { let spanners = create_spanners(&columns, spans); // Every label empty means `LABEL col => NULL` (or `=> ''`) on every @@ -114,6 +117,10 @@ pub(super) fn build_cells( let header = heading.rowbind(header); let mut body_cells = create_row_labels(df, &columns); body_cells.extend(create_body(df, &columns)); + // Group summaries weave in before the facet passes, so group-stub + // merging and group-heading offsets cover them for free; grand rows sit + // outside every group, so they weave in last. + let (rows, body_cells) = weave_group_summaries(rows, body_cells, &columns, summaries); let (body_rows, body_cells) = match facet { None => (rows, body_cells), Some(facet) => { @@ -125,6 +132,7 @@ pub(super) fn build_cells( } } }; + let (body_rows, body_cells) = weave_grand_summaries(body_rows, body_cells, &columns, summaries); let table_body = TableLayout::new(columns.clone(), body_rows, body_cells); let layout = header.rowbind(table_body); let caption_layout = create_caption(titles.caption.as_deref(), &columns); @@ -220,11 +228,102 @@ fn create_body(df: &DataFrame, columns: &[TableColumn]) -> Vec { cells } +/// Interleave the `GROUP` chunks' rows into the body, in data space: each +/// chunk's `top` rows, then the chunk itself, then its bottom rows. Runs +/// before the facet passes — summary rows carry their group's key, so the +/// row-driven group-stub merge spans them and group-heading offsets cover +/// them like data rows. +fn weave_group_summaries( + rows: Vec, + cells: Vec, + columns: &[TableColumn], + summaries: &[SummaryChunk], +) -> (Vec, Vec) { + let summaries: Vec<&SummaryChunk> = summaries.iter().filter(|(key, _)| key.is_some()).collect(); + if summaries.is_empty() { + return (rows, cells); + } + debug_assert_eq!( + rows.chunk_by(|a, b| a.group == b.group).count(), + summaries.len(), + "one summary chunk per group" + ); + + let inserted: usize = summaries.iter().map(|(_, rows)| rows.len()).sum(); + let mut new_rows = Vec::with_capacity(rows.len() + inserted); + let mut summary_cells = Vec::new(); + // row_map[old data-row index] = its grid row after the weave. + let mut row_map = vec![0usize; rows.len()]; + let mut old_index = 0usize; + for (chunk, (key, chunk_summaries)) in rows + .chunk_by(|a, b| a.group == b.group) + .zip(summaries.iter()) + { + let key = key.as_ref().expect("filtered to group chunks"); + debug_assert_eq!(chunk[0].group, *key, "summary chunks in group order"); + for summary in chunk_summaries.iter().filter(|s| s.top) { + summary_cells.extend(summary.cells(new_rows.len(), columns, false)); + new_rows.push(TableRow::summary(key.clone())); + } + for row in chunk.iter() { + row_map[old_index] = new_rows.len(); + new_rows.push(row.clone()); + old_index += 1; + } + for summary in chunk_summaries.iter().filter(|s| !s.top) { + summary_cells.extend(summary.cells(new_rows.len(), columns, false)); + new_rows.push(TableRow::summary(key.clone())); + } + } + + let mut cells = cells; + for cell in &mut cells { + cell.top = row_map[cell.top]; + cell.bottom = row_map[cell.bottom]; + } + summary_cells.extend(cells); + (new_rows, summary_cells) +} + +/// Place the `GRAND` chunk's rows: `top` rows above the whole body, bottom +/// rows below it. Runs after the facet passes — a grand row belongs to no +/// group, so nothing about it should merge or shift with group machinery. +fn weave_grand_summaries( + rows: Vec, + cells: Vec, + columns: &[TableColumn], + summaries: &[SummaryChunk], +) -> (Vec, Vec) { + let Some((_, grand)) = summaries.iter().find(|(key, _)| key.is_none()) else { + return (rows, cells); + }; + let tops = grand.iter().filter(|s| s.top).count(); + + let mut cells = cells; + for cell in &mut cells { + cell.offset_rows(tops); + } + let mut new_rows = Vec::with_capacity(rows.len() + grand.len()); + let mut summary_cells = Vec::new(); + for summary in grand.iter().filter(|s| s.top) { + summary_cells.extend(summary.cells(new_rows.len(), columns, true)); + new_rows.push(TableRow::summary(Vec::new())); + } + new_rows.extend(rows); + for summary in grand.iter().filter(|s| !s.top) { + summary_cells.extend(summary.cells(new_rows.len(), columns, true)); + new_rows.push(TableRow::summary(Vec::new())); + } + summary_cells.extend(cells); + (new_rows, summary_cells) +} + /// Interleave group-label rows into the body. At each group boundary, emit /// one `GroupHeading` row per facet-variable level that changed, labels read -/// from the group's first row (so an unchanged outer variable isn't +/// from the group's first data row (so an unchanged outer variable isn't /// restated). Body cells keep their data-row numbering, shifted down by -/// the label rows before them. +/// the label rows before them. Summary rows interleave with the data rows +/// but have no row in `df`, so only data rows advance the label lookup. fn weave_group_labels( df: &DataFrame, columns: &[TableColumn], @@ -246,17 +345,18 @@ fn weave_group_labels( let mut out_rows = Vec::new(); let mut label_cells = Vec::new(); - // body_offset[data row] = how many label rows precede it in the grid. - let mut body_offset = vec![0usize; df.height()]; + // body_offset[body row] = how many label rows precede it in the grid. + let mut body_offset = vec![0usize; rows.len()]; // None until the first group's key is read: it emits every level. let mut previous_key: Option<&[usize]> = None; + let mut df_row = 0usize; let mut row = 0usize; for group_rows in rows.chunk_by(|a, b| a.group == b.group) { let key = group_rows[0].group.as_slice(); let labels: Vec = facet_arrays .iter() - .map(|array| value_to_string(array, row)) + .map(|array| value_to_string(array, df_row)) .collect(); // When multiple labels exist, we have a nesting pattern. // We don't need to repeat every level label at every group, @@ -281,6 +381,9 @@ fn weave_group_labels( for table_row in group_rows.iter() { body_offset[row] = out_rows.len() - row; + if !table_row.classes.contains(&TableClass::SummaryRow) { + df_row += 1; + } out_rows.push(table_row.clone()); row += 1; } @@ -295,10 +398,13 @@ fn weave_group_labels( Ok((out_rows, label_cells)) } -/// Merge each group stub column's row labels into rowspanned cells. A cell -/// at depth `d` spans rows while the `d + 1` outermost ranks of the rows' -/// group keys are equal, so a group never merges into a cell opened under -/// a different outer level even when its label repeats. +/// Merge each group-stub column's per-row labels into rowspanned cells. +/// Runs are read off `rows`, not cells: a cell at depth `d` spans rows while +/// the `d + 1` outermost ranks of the rows' group keys are equal, so a group +/// never merges into a cell opened under a different outer level even when +/// its label repeats. A summary row carries its chunk's key but has no stub +/// cell of its own, so it joins its group's run by construction; the run's +/// content comes from its first data row's cell. fn merge_group_stub_cells( cells: Vec, columns: &[TableColumn], @@ -308,23 +414,39 @@ fn merge_group_stub_cells( return cells; } - // Column index of a group stub column -> position of its open cell in - // `out`, for the column whose cells are currently being walked. - let mut open: HashMap = HashMap::new(); + // Each group-stub column's per-row cells, by row — replaced by merged + // cells below. + let mut stub_cells: HashMap<(usize, usize), TableCell> = HashMap::new(); let mut out: Vec = Vec::with_capacity(cells.len()); for cell in cells { - if let ColumnSection::GroupStub(depth) = columns[cell.left].target { - if let Some(&index) = open.get(&cell.left) { - let current_key = &rows[cell.top].group[..=depth]; - let previous_key = &rows[cell.top - 1].group[..=depth]; - if current_key == previous_key { - out[index].bottom = cell.bottom; - continue; - } + if columns[cell.left].is_group_stub() { + stub_cells.insert((cell.left, cell.top), cell); + } else { + out.push(cell); + } + } + + for (left, column) in columns.iter().enumerate() { + let ColumnSection::GroupStub(depth) = column.target else { + continue; + }; + let mut start = 0; + while start < rows.len() { + let mut end = start; + while end + 1 < rows.len() + && rows[end + 1].group[..=depth] == rows[start].group[..=depth] + { + end += 1; } - open.insert(cell.left, out.len()); + let source = (start..=end) + .find_map(|row| stub_cells.get(&(left, row))) + .expect("every group-stub run holds a data row"); + let mut merged = TableCell::new_stub_row_group(start, left, source.content.clone()); + merged.bottom = end; + merged.properties = source.properties.clone(); + out.push(merged); + start = end + 1; } - out.push(cell); } out } @@ -332,10 +454,11 @@ fn merge_group_stub_cells( #[cfg(test)] mod tests { use super::super::format::{apply_formats, setup_formats}; + use super::super::summary::{compute_summaries, setup_summaries}; use super::*; use crate::df; use crate::plot::{ParameterValue, Parameters}; - use crate::table::{extract_table_titles, TableCellKind}; + use crate::table::{extract_table_titles, Summary, SummaryScope, TableCellKind}; use crate::{ColumnSection, GgsqlError, Spanner, Table}; /// Runs the same steps `resolve_table_with_reader` does, minus the @@ -352,7 +475,7 @@ mod tests { let columns = setup_columns(df, &spans, &labels, &formats, None); let df = apply_formats(df, &formats)?; let rows = vec![TableRow::body(); df.height()]; - build_cells(&df, columns, rows, &spans, &titles, None) + build_cells(&df, columns, rows, &spans, &titles, None, &[]) } /// `resolve_layout`, for the (common) tests that only care about cells. @@ -360,6 +483,245 @@ mod tests { resolve_layout(df, table).map(|layout| layout.cells) } + /// `resolve_layout`, plus the `SUMMARISE` steps and a facet. + fn resolve_layout_with_summaries( + df: &DataFrame, + table: &Table, + facet: Option<&Facet>, + ) -> Result { + let mut labels = table.labels.clone(); + let titles = extract_table_titles(&mut labels); + let (mut df, rows) = setup_rows(df.clone(), facet)?; + let column_names = df.get_column_names(); + let spans = table + .resolve_spanners(&labels, Some(&column_names)) + .map_err(GgsqlError::ValidationError)?; + let formats = setup_formats(&df, &table.formats, &spans)?; + setup_summaries(&mut df, &formats, &table.summaries)?; + let columns = setup_columns(&df, &spans, &labels, &formats, facet); + let computed = compute_summaries(&df, &rows, &table.summaries)?; + let df = apply_formats(&df, &formats)?; + build_cells(&df, columns, rows, &spans, &titles, facet, &computed) + } + + fn summary_clause(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { + Summary { + operation: operation.to_string(), + scope, + columns: columns.iter().map(|c| c.to_string()).collect(), + settings: Parameters::new(), + } + } + + fn top_facet(variables: &[&str]) -> Facet { + let mut facet = left_facet(variables); + facet.properties.insert( + "place".to_string(), + ParameterValue::String("top".to_string()), + ); + facet + } + + /// Body rows (header excluded) whose classes contain `class`, as grid rows. + fn rows_with_class(layout: &TableLayout, class: TableClass) -> Vec { + layout + .rows + .iter() + .enumerate() + .filter(|(_, row)| !row.is_header && row.classes.contains(&class)) + .map(|(index, _)| index) + .collect() + } + + /// The cell at exactly `row` whose content is `content`. + fn find_cell<'a>(layout: &'a TableLayout, row: usize, content: &str) -> &'a TableCell { + layout + .cells + .iter() + .find(|cell| cell.top == row && cell.content == content) + .unwrap_or_else(|| panic!("no cell at row {row} with content {content:?}")) + } + + #[test] + fn group_summary_without_a_facet_weaves_below_the_single_group() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Group, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Column-label row, two data rows, then the summary row. + assert_eq!(layout.rows.len(), 4); + let summary_row = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_row, vec![3]); + assert_eq!( + find_cell(&layout, 3, "mean").kind, + TableCellKind::StubRowLabel + ); + assert_eq!(find_cell(&layout, 3, "2.5").kind, TableCellKind::Body); + } + + #[test] + fn grand_summaries_sit_outside_the_body() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + let mut top = summary_clause("median", SummaryScope::Grand, &["x"]); + top.settings.insert( + "place".to_string(), + ParameterValue::String("top".to_string()), + ); + // Written bottom-clause first: placement, not clause order, decides. + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"]), top]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + assert_eq!(layout.rows.len(), 5); + assert_eq!(rows_with_class(&layout, TableClass::SummaryRow), vec![1, 4]); + assert_eq!( + find_cell(&layout, 1, "median").kind, + TableCellKind::StubRowLabel + ); + assert_eq!( + find_cell(&layout, 4, "mean").kind, + TableCellKind::StubRowLabel + ); + } + + #[test] + fn group_summary_weaves_after_its_groups_heading_rows() { + let frame = df! { + "region" => vec!["n".to_string(), "n".to_string(), "s".to_string()], + "x" => vec![1.5, 3.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Group, &["x"])]; + let facet = top_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + // Col labels; heading n; 2 data; summary; heading s; data; summary. + let summary_rows = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_rows, vec![4, 7]); + assert_eq!(layout.rows[summary_rows[0]].group, vec![0]); + assert_eq!(layout.rows[summary_rows[1]].group, vec![1]); + assert_eq!(find_cell(&layout, 4, "2.5").kind, TableCellKind::Body); + assert_eq!(find_cell(&layout, 7, "10.5").kind, TableCellKind::Body); + } + + #[test] + fn group_stub_cells_grow_over_a_groups_summary_rows() { + let frame = df! { + "region" => vec!["n".to_string(), "n".to_string(), "s".to_string()], + "x" => vec![1.5, 3.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![ + summary_clause("mean", SummaryScope::Group, &["x"]), + summary_clause("mean", SummaryScope::Grand, &["x"]), + ]; + let facet = left_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + // Body: 2 data + summary (n), data + summary (s), grand summary. + let summary_rows = rows_with_class(&layout, TableClass::SummaryRow); + assert_eq!(summary_rows, vec![3, 5, 6]); + // The group stub cell for "n" spans its data rows and its summary. + let north = find_cell(&layout, 1, "n"); + assert_eq!(north.kind, TableCellKind::GroupHeading); + assert_eq!(north.bottom, 3); + // A group summary row emits no cell in the group stub column... + assert!(layout + .cells + .iter() + .all(|cell| cell.top != 3 || cell.left != north.left)); + // ...and the grand row's label spans the group stub column instead. + let grand_label = layout + .cells + .iter() + .find(|cell| cell.top == 6 && cell.left == north.left) + .expect("grand row's label spans the group stub column"); + assert_eq!(grand_label.kind, TableCellKind::StubRowLabel); + assert_eq!(grand_label.content, "mean"); + } + + #[test] + fn a_grand_summary_label_spans_the_group_stub_columns() { + let frame = df! { + "region" => vec!["n".to_string(), "s".to_string()], + "x" => vec![1.5, 10.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + let facet = left_facet(&["region"]); + + let layout = resolve_layout_with_summaries(&frame, &table, Some(&facet)).unwrap(); + + let grand_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; + let label = find_cell(&layout, grand_row, "mean"); + assert_eq!(label.kind, TableCellKind::StubRowLabel); + assert_eq!(label.left, 0); + assert!( + label.right > label.left, + "the label colspans the group stub column" + ); + // No group-stub filler cell on the grand row, and no grid gaps. + assert!(layout + .cells + .iter() + .all(|cell| cell.top != grand_row || cell.kind != TableCellKind::GroupHeading)); + layout.slots_by_row(); + } + + #[test] + fn a_summary_label_spans_all_stub_columns() { + let frame = df! { + "a" => vec!["p".to_string(), "q".to_string()], + "b" => vec!["u".to_string(), "v".to_string()], + "x" => vec![1.5, 3.5], + } + .unwrap(); + let stub = |column: &str| crate::Format { + columns: vec![column.to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + settings: Parameters::new(), + value_mapping: None, + value_template: None, + }; + let mut table = Table::new(); + table.formats = vec![stub("a"), stub("b")]; + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + let summary_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; + let label = find_cell(&layout, summary_row, "mean"); + assert_eq!(label.kind, TableCellKind::StubRowLabel); + assert_eq!(label.left, 0); + assert_eq!(label.right, 1); + // The second stub column emits no cell of its own on the summary row. + assert_eq!( + layout + .cells + .iter() + .filter(|cell| cell.top == summary_row && cell.kind == TableCellKind::StubRowLabel) + .count(), + 1 + ); + assert_eq!(find_cell(&layout, summary_row, "2.5").left, 2); + layout.slots_by_row(); + } + fn column(name: &str, label: &str) -> TableColumn { TableColumn { name: name.to_string(), diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 5cde859ff..3d88aa7da 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -92,7 +92,8 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Vec { + let mut cells = vec![self.label_cell(row, columns, span_group_stubs)]; + cells.extend( + columns + .iter() + .enumerate() + .filter(|(_, column)| column.target == ColumnSection::Body) + .map(|(index, column)| { + let content = self + .frame + .column(&column.name) + .map(|array| column_to_strings(array).remove(0)) + .unwrap_or_default(); + TableCell::new_body(row, index, content) + .with_properties(column.properties.clone()) + }), + ); + cells + } + + /// The row's label cell, spanning every stub column — leftward over the + /// group-stub columns too for a `GRAND` row (`span_group_stubs`). + /// `setup_summaries` adds a stub column when summaries exist without one; + /// `move_stub_columns` puts every stub-section column in one contiguous + /// run, so the span covers only stub columns. + fn label_cell(&self, row: usize, columns: &[TableColumn], span_group_stubs: bool) -> TableCell { + let label_column = columns + .iter() + .position(|c| c.target == ColumnSection::Stub) + .expect("setup_summaries guarantees a stub column"); + let left = if span_group_stubs && columns.first().is_some_and(|c| c.is_group_stub()) { + 0 + } else { + label_column + }; + let right = columns + .iter() + .rposition(|c| c.target == ColumnSection::Stub) + .unwrap_or(label_column); + debug_assert!( + columns[left..=right].iter().all(|c| c.is_stub()), + "the label's colspan covers only stub columns" + ); + + let mut cell = TableCell::new_stub_row_label(row, label_column, self.label.clone()); + cell.left = left; + cell.right = right; + cell.with_properties(columns[label_column].properties.clone()) + } +} + +/// One chunk of summary rows: the chunk's group key (`None` for the `GRAND` +/// chunk) and the clause rows computed over it, in clause order. +pub(super) type SummaryChunk = (Option>, Vec); + +/// Compute every `SUMMARISE` clause against the (unformatted) data: one +/// chunk per group, in display order (`setup_rows` leaves rows +/// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. +/// Chunks with no matching clauses are omitted. Placement within a chunk is +/// the weavers' concern; they read each row's `top`. // Unused until the table pipeline calls it. #[allow(dead_code)] pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], summaries: &[Summary], -) -> Result> { - // Rows are group-contiguous after setup_rows, so each group's membership - // is a contiguous range; a GRAND clause's single "group" is all of them. +) -> Result> { + if summaries.is_empty() { + return Ok(Vec::new()); + } + // Chunks the clauses emit into: one contiguous range per group, then one + // range over all rows for the GRAND clauses. + let mut chunks: Vec<(Option>, Range)> = Vec::new(); let mut start = 0; - let mut ranges: Vec> = Vec::new(); - let mut key_strings: Vec = Vec::new(); for chunk in rows.chunk_by(|a, b| a.group == b.group) { - ranges.push(start..start + chunk.len()); + chunks.push((Some(chunk[0].group.clone()), start..start + chunk.len())); start += chunk.len(); - key_strings.push(naming::summary_group_key(&chunk[0].group)); } + chunks.push((None, 0..rows.len())); + + let mut out = Vec::new(); + for (key, range) in chunks { + let scope = match key { + Some(_) => SummaryScope::Group, + None => SummaryScope::Grand, + }; + let rows = summaries + .iter() + .filter(|s| s.scope == scope) + .map(|summary| summary.new_row(df, &range)) + .collect::>>()?; + if !rows.is_empty() { + out.push((key, rows)); + } + } + Ok(out) +} - // A grand total has no group; the empty key matches the facet-less one. - let grand_key = [String::new()]; - summaries - .iter() - .map(|summary| { - let (groups, keys) = match summary.scope { - SummaryScope::Grand => (None, grand_key.as_slice()), - SummaryScope::Group => (Some(ranges.as_slice()), key_strings.as_slice()), - }; - summary_frame(df, summary, groups, keys) +impl Summary { + /// Build this clause's row over `range`: placement, label and computed + /// values. + pub(super) fn new_row(&self, df: &DataFrame, range: &Range) -> Result { + Ok(SummaryRow { + top: is_top(self), + label: label(self), + frame: summary_frame(df, self, range)?, }) - .collect() + } } -/// Compute one clause's frame: the key column followed by one nullable-f64 -/// column per summarised column. `groups` is `None` for a GRAND clause — a -/// single row over all rows. -fn summary_frame( - df: &DataFrame, - summary: &Summary, - groups: Option<&[Range]>, - keys: &[String], -) -> Result { - let drop_nulls = setting_string(&summary.settings, "missing").as_deref() == Some("drop"); +fn is_top(summary: &Summary) -> bool { + setting_string(&summary.settings, "place").as_deref() == Some("top") +} - let mut columns: Vec<(String, ArrayRef)> = Vec::new(); - columns.push(( - naming::SUMMARY_GROUP_COLUMN.to_string(), - Arc::new(StringArray::from(keys.to_vec())), - )); - for column in &summary.columns { - let values = summary_column(df, column, summary, groups, drop_nulls)?; - columns.push((column.clone(), Arc::new(Float64Array::from(values)))); - } - DataFrame::new(columns) +fn label(summary: &Summary) -> String { + setting_string(&summary.settings, "rowlabel").unwrap_or_else(|| summary.operation.clone()) } -/// Compute a clause's operation on one column, one value per group — or a -/// single value over the whole column when `groups` is `None` (GRAND). -fn summary_column( - df: &DataFrame, - column: &str, - summary: &Summary, - groups: Option<&[Range]>, - drop_nulls: bool, -) -> Result>> { - let array = df.column(column).map_err(|_| { - GgsqlError::ValidationError(format!( - "SUMMARISE {}: no column '{column}' in the query result", - summary.operation - )) - })?; - match groups { - Some(groups) => groups - .iter() - .map(|range| { - summary_stat( - &summary.operation, - &array.slice(range.start, range.len()), - drop_nulls, - ) - }) - .collect(), - None => summary_stat(&summary.operation, array, drop_nulls).map(|value| vec![value]), - } +/// Compute one clause's frame over the rows in `range`: one row, one +/// nullable-f64 column per summarised column. +fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Result { + let drop_nulls = setting_string(&summary.settings, "missing").as_deref() == Some("drop"); + + let columns = summary + .columns + .iter() + .map(|column| { + let array = df.column(column).map_err(|_| { + GgsqlError::ValidationError(format!( + "SUMMARISE {}: no column '{column}' in the query result", + summary.operation + )) + })?; + let value = summary_stat( + &summary.operation, + &array.slice(range.start, range.len()), + drop_nulls, + )?; + Ok(( + column.clone(), + Arc::new(Float64Array::from(vec![value])) as ArrayRef, + )) + }) + .collect::>>()?; + DataFrame::new(columns) } fn setting_string(settings: &Parameters, name: &str) -> Option { @@ -279,29 +358,24 @@ mod tests { .collect() } - fn group_keys(frame: &DataFrame) -> Vec { - crate::array_util::as_str(frame.column(naming::SUMMARY_GROUP_COLUMN).unwrap()) - .unwrap() - .iter() - .map(|key| key.unwrap().to_string()) - .collect() - } - #[test] - fn grand_summary_is_a_single_row_keyed_by_the_empty_key() { + fn grand_summary_is_a_single_ungrouped_row() { let df = crate::df! { "x" => vec![1.0, 2.0, 3.0], } .unwrap(); let rows = body_rows(&[&[], &[], &[]]); - let frames = + let computed = compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["x"])]).unwrap(); - assert_eq!(frames.len(), 1); - assert_eq!(frames[0].height(), 1); - assert_eq!(group_keys(&frames[0]), vec![""]); - assert_eq!(column_values(&frames[0], "x"), vec![Some(2.0)]); + assert_eq!(computed.len(), 1); + let (key, rows) = &computed[0]; + assert_eq!(*key, None); + assert_eq!(rows.len(), 1); + assert!(!rows[0].top); + assert_eq!(rows[0].label, "mean"); + assert_eq!(column_values(&rows[0].frame, "x"), vec![Some(2.0)]); } #[test] @@ -313,12 +387,72 @@ mod tests { // Two nested-facet groups, contiguous after setup_rows' reorder. let rows = body_rows(&[&[2, 0], &[2, 0], &[2, 1], &[2, 1]]); - let frames = + let computed = compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); - assert_eq!(frames[0].height(), 2); - assert_eq!(group_keys(&frames[0]), vec!["2;0", "2;1"]); - assert_eq!(column_values(&frames[0], "x"), vec![Some(2.0), Some(15.0)]); + assert_eq!(computed.len(), 2); + assert_eq!(computed[0].0, Some(vec![2, 0])); + assert_eq!(computed[1].0, Some(vec![2, 1])); + assert_eq!(column_values(&computed[0].1[0].frame, "x"), vec![Some(2.0)]); + assert_eq!( + column_values(&computed[1].1[0].frame, "x"), + vec![Some(15.0)] + ); + } + + #[test] + fn rows_come_chunk_major_in_clause_order() { + let df = crate::df! { + "x" => vec![1.0, 10.0], + } + .unwrap(); + let rows = body_rows(&[&[0], &[1]]); + let mut above = summary("mean", SummaryScope::Group, &["x"]); + above.settings.insert( + "place".to_string(), + ParameterValue::String("top".to_string()), + ); + let below = summary("median", SummaryScope::Group, &["x"]); + + let computed = compute_summaries(&df, &rows, &[below, above]).unwrap(); + + let order: Vec<(Vec, &str, bool)> = computed + .iter() + .flat_map(|(key, rows)| { + let key = key.clone().expect("GROUP chunks are keyed"); + rows.iter() + .map(move |row| (key.clone(), row.label.as_str(), row.top)) + }) + .collect(); + // Chunk-major, clause order within a chunk; placement is the + // weavers' concern. + assert_eq!( + order, + vec![ + (vec![0], "median", false), + (vec![0], "mean", true), + (vec![1], "median", false), + (vec![1], "mean", true), + ] + ); + } + + #[test] + fn rowlabel_overrides_the_operation_as_label() { + let df = crate::df! { + "x" => vec![1.0], + } + .unwrap(); + let rows = body_rows(&[&[]]); + let mut labelled = summary("mean", SummaryScope::Grand, &["x"]); + labelled.settings.insert( + "rowlabel".to_string(), + ParameterValue::String("Average".to_string()), + ); + + let computed = compute_summaries(&df, &rows, &[labelled]).unwrap(); + + assert_eq!(computed[0].1[0].label, "Average"); } #[test] @@ -329,12 +463,12 @@ mod tests { .unwrap(); let rows = body_rows(&[&[], &[]]); - let frames = + let computed = compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); - assert_eq!(frames[0].height(), 1); - assert_eq!(group_keys(&frames[0]), vec![""]); - assert_eq!(column_values(&frames[0], "x"), vec![Some(3.0)]); + assert_eq!(computed.len(), 1); + assert_eq!(computed[0].0, Some(vec![])); + assert_eq!(column_values(&computed[0].1[0].frame, "x"), vec![Some(3.0)]); } #[test] @@ -351,15 +485,17 @@ mod tests { ParameterValue::String("drop".to_string()), ); - let frames = compute_summaries( + let computed = compute_summaries( &df, &rows, &[summary("mean", SummaryScope::Grand, &["x"]), drop], ) .unwrap(); - assert_eq!(column_values(&frames[0], "x"), vec![None]); - assert_eq!(column_values(&frames[1], "x"), vec![Some(2.0)]); + let (key, rows) = &computed[0]; + assert_eq!(*key, None); + assert_eq!(column_values(&rows[0].frame, "x"), vec![None]); + assert_eq!(column_values(&rows[1].frame, "x"), vec![Some(2.0)]); } fn stub_format() -> Format { diff --git a/src/naming.rs b/src/naming.rs index 8f4b3a9d8..e588cb834 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -94,10 +94,6 @@ pub const SCHEMA_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "schema", GGSQL_SUFFIX); /// Alias for the derived table a TABULATE selection wraps its source in pub const TABLE_ALIAS: &str = concatcp!(GGSQL_SUFFIX, "table", GGSQL_SUFFIX); -/// Key column of a `SUMMARISE` result frame: the row's group key as -/// ';'-joined facet ranks. A `GRAND` frame's single row uses the empty key. -pub const SUMMARY_GROUP_COLUMN: &str = concatcp!(GGSQL_PREFIX, "group", GGSQL_SUFFIX); - /// Synthetic stub column holding `SUMMARISE` row labels, inserted when a /// table has summaries but no `STUB` column to put them in. Never names a /// `DataFrame` column. @@ -324,15 +320,6 @@ pub fn anonymous_span_id(span_idx: usize) -> String { format!("{}span_{}{}", GGSQL_PREFIX, span_idx, GGSQL_SUFFIX) } -/// Encode a row's group key (one facet rank per level) for -/// `SUMMARY_GROUP_COLUMN`. -pub fn summary_group_key(key: &[usize]) -> String { - key.iter() - .map(usize::to_string) - .collect::>() - .join(";") -} - // ============================================================================ // SQL Quoting // ============================================================================ diff --git a/src/table/layout.rs b/src/table/layout.rs index d29bde4b3..7a3e1b37f 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -127,6 +127,8 @@ pub enum TableClass { /// The first body row of a facet group (gt's `gt_row_group_first`) — /// carries the thick border separating a group from what precedes it. RowGroupFirst, + /// A `SUMMARISE` row (gt's `gt_summary_row`). + SummaryRow, // -------------------------- Cell-scoped ------------------------- // Recorded on `TableCell::classes`, rendered on the ``/``. @@ -190,6 +192,7 @@ impl TableClass { TableClass::GroupHeading, TableClass::GroupHeadingRow, TableClass::RowGroupFirst, + TableClass::SummaryRow, TableClass::AlignLeft, TableClass::AlignCenter, TableClass::AlignRight, @@ -219,6 +222,7 @@ impl std::fmt::Display for TableClass { TableClass::Subtitle => "subtitle", TableClass::Caption => "caption", TableClass::Heading => "heading", + TableClass::SummaryRow => "summary_row", TableClass::GroupHeading => "group_heading", TableClass::GroupHeadingRow => "group_heading_row", TableClass::RowGroupFirst => "row_group_first", @@ -519,6 +523,18 @@ impl TableRow { ..Self::body() } } + + /// A summary row (`TableClass::SummaryRow`) keyed by its chunk's `group` + /// — empty for a `GRAND` row. The key marks the row as having no data + /// row behind it, so later passes (group-stub merge, group-label weave) + /// treat it accordingly. + pub fn summary(group: Vec) -> Self { + Self { + classes: vec![TableClass::SummaryRow], + group, + ..Self::body() + } + } } /// The row extent a set of cells implies — the highest `bottom` plus one, diff --git a/src/writer/html.rs b/src/writer/html.rs index d6e4f62cb..357505f35 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -389,6 +389,7 @@ fn class_declarations(class: TableClass) -> &'static [(&'static str, &'static st ("border-top-width", "2px"), ("border-top-color", "#D3D3D3"), ], + TableClass::SummaryRow => &[], TableClass::AlignLeft => &[("text-align", "left")], TableClass::AlignCenter => &[("text-align", "center")], TableClass::AlignRight => &[ From 6085a9beb415036a9c78b6bf54f19536f649670a Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 19 Nov 2026 17:11:26 +0100 Subject: [PATCH 08/37] Adopt new parameter infra --- src/execute/table/layout.rs | 17 ++------ src/execute/table/summary.rs | 56 ++++++++++--------------- src/table/summary.rs | 79 ++++++++++-------------------------- src/validate.rs | 2 +- 4 files changed, 48 insertions(+), 106 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 3e508027b..072e77715 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -515,10 +515,7 @@ mod tests { fn top_facet(variables: &[&str]) -> Facet { let mut facet = left_facet(variables); - facet.properties.insert( - "place".to_string(), - ParameterValue::String("top".to_string()), - ); + facet.properties = crate::params! { "place" => "top" }; facet } @@ -572,10 +569,7 @@ mod tests { .unwrap(); let mut table = Table::new(); let mut top = summary_clause("median", SummaryScope::Grand, &["x"]); - top.settings.insert( - "place".to_string(), - ParameterValue::String("top".to_string()), - ); + top.settings = crate::params! { "place" => "top" }; // Written bottom-clause first: placement, not clause order, decides. table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"]), top]; @@ -815,16 +809,11 @@ mod tests { } fn left_facet(variables: &[&str]) -> Facet { - let mut properties = Parameters::new(); - properties.insert( - "place".to_string(), - ParameterValue::String("left".to_string()), - ); Facet { layout: crate::plot::facet::FacetLayout::Wrap { variables: variables.iter().map(|s| s.to_string()).collect(), }, - properties, + properties: crate::params! { "place" => "left" }, resolved: true, } } diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 852b7abdf..1d0e1eeee 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -14,7 +14,7 @@ use arrow::datatypes::DataType; use crate::array_util::{as_f64, cast_array, column_to_strings}; use crate::naming; -use crate::params::{ParameterValue, Parameters}; +use crate::params::ParameterValue; use crate::table::{Format, Summary, SummaryScope, TableCell, TableColumn, TableRow}; use crate::{ColumnSection, DataFrame, GgsqlError, Result}; @@ -179,26 +179,23 @@ impl Summary { /// Build this clause's row over `range`: placement, label and computed /// values. pub(super) fn new_row(&self, df: &DataFrame, range: &Range) -> Result { + let label = self + .settings + .get("rowlabel") + .and_then(ParameterValue::as_str) + .map_or_else(|| self.operation.clone(), str::to_string); Ok(SummaryRow { - top: is_top(self), - label: label(self), + top: ParameterValue::is_str(self.settings.get("place"), "top"), + label, frame: summary_frame(df, self, range)?, }) } } -fn is_top(summary: &Summary) -> bool { - setting_string(&summary.settings, "place").as_deref() == Some("top") -} - -fn label(summary: &Summary) -> String { - setting_string(&summary.settings, "rowlabel").unwrap_or_else(|| summary.operation.clone()) -} - /// Compute one clause's frame over the rows in `range`: one row, one /// nullable-f64 column per summarised column. fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Result { - let drop_nulls = setting_string(&summary.settings, "missing").as_deref() == Some("drop"); + let drop_nulls = ParameterValue::is_str(summary.settings.get("missing"), "drop"); let columns = summary .columns @@ -224,13 +221,6 @@ fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Res DataFrame::new(columns) } -fn setting_string(settings: &Parameters, name: &str) -> Option { - match settings.get(name) { - Some(ParameterValue::String(value)) => Some(value.clone()), - _ => None, - } -} - /// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. @@ -283,6 +273,7 @@ fn quantile(mut values: Vec, q: f64) -> f64 { #[cfg(test)] mod tests { use super::*; + use crate::params::Parameters; use arrow::array::{Float64Array, Int64Array, StringArray}; use std::sync::Arc; @@ -407,11 +398,10 @@ mod tests { } .unwrap(); let rows = body_rows(&[&[0], &[1]]); - let mut above = summary("mean", SummaryScope::Group, &["x"]); - above.settings.insert( - "place".to_string(), - ParameterValue::String("top".to_string()), - ); + let above = Summary { + settings: crate::params! { "place" => "top" }, + ..summary("mean", SummaryScope::Group, &["x"]) + }; let below = summary("median", SummaryScope::Group, &["x"]); let computed = compute_summaries(&df, &rows, &[below, above]).unwrap(); @@ -444,11 +434,10 @@ mod tests { } .unwrap(); let rows = body_rows(&[&[]]); - let mut labelled = summary("mean", SummaryScope::Grand, &["x"]); - labelled.settings.insert( - "rowlabel".to_string(), - ParameterValue::String("Average".to_string()), - ); + let labelled = Summary { + settings: crate::params! { "rowlabel" => "Average" }, + ..summary("mean", SummaryScope::Grand, &["x"]) + }; let computed = compute_summaries(&df, &rows, &[labelled]).unwrap(); @@ -479,11 +468,10 @@ mod tests { .unwrap(); let rows = body_rows(&[&[], &[], &[]]); - let mut drop = summary("mean", SummaryScope::Grand, &["x"]); - drop.settings.insert( - "missing".to_string(), - ParameterValue::String("drop".to_string()), - ); + let drop = Summary { + settings: crate::params! { "missing" => "drop" }, + ..summary("mean", SummaryScope::Grand, &["x"]) + }; let computed = compute_summaries( &df, diff --git a/src/table/summary.rs b/src/table/summary.rs index 1f60582b3..dc6c68e2b 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -2,9 +2,7 @@ use serde::{Deserialize, Serialize}; -use crate::params::{ - validate_parameter, DefaultParamValue, ParamConstraint, ParamDefinition, Parameters, -}; +use crate::params::{DefaultParamValue, ParamConstraint, ParamDefinition, Parameters}; /// One `SUMMARISE` clause: an aggregate operation producing one summary row /// per group — or a single row over all rows for `GRAND`. @@ -83,29 +81,17 @@ impl Summary { } } - /// Validate `settings` against `SUMMARY_PARAMS`. - pub fn validate_settings(&self) -> Result<(), String> { - let valid: Vec<&str> = SUMMARY_PARAMS.iter().map(|p| p.name).collect(); - - for (name, value) in &self.settings { - let Some(param) = SUMMARY_PARAMS.iter().find(|p| p.name == name.as_str()) else { - return Err(format!( - "SUMMARISE setting should be {}, not '{}'", - crate::or_list_quoted(&valid, '\''), - name - )); - }; - validate_parameter(name, value, ¶m.constraint)?; - } - - Ok(()) + /// Validate `settings` against `SUMMARY_PARAMS` and resolve each to its + /// effective value: the user's value if present, otherwise the + /// definition's default. + pub fn resolve_settings(&self) -> Result { + crate::params::resolve_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") } } #[cfg(test)] mod tests { use super::*; - use crate::plot::ParameterValue; fn summary_with_settings(settings: Parameters) -> Summary { Summary { @@ -117,55 +103,34 @@ mod tests { } #[test] - fn summary_validate_settings_accepts_place_and_rowlabel() { - let mut settings = Parameters::new(); - settings.insert( - "place".to_string(), - ParameterValue::String("top".to_string()), - ); - settings.insert( - "rowlabel".to_string(), - ParameterValue::String("Average".to_string()), - ); - - assert!(summary_with_settings(settings).validate_settings().is_ok()); + fn summary_resolve_settings_accepts_place_and_rowlabel() { + let settings = crate::params! { "place" => "top", "rowlabel" => "Average" }; + + assert!(summary_with_settings(settings).resolve_settings().is_ok()); } #[test] - fn summary_validate_settings_accepts_missing_options() { + fn summary_resolve_settings_accepts_missing_options() { for value in ["propagate", "drop"] { - let mut settings = Parameters::new(); - settings.insert( - "missing".to_string(), - ParameterValue::String(value.to_string()), - ); - assert!(summary_with_settings(settings).validate_settings().is_ok()); + let settings = crate::params! { "missing" => value }; + assert!(summary_with_settings(settings).resolve_settings().is_ok()); } - let mut settings = Parameters::new(); - settings.insert( - "missing".to_string(), - ParameterValue::String("ignore".to_string()), - ); - assert!(summary_with_settings(settings).validate_settings().is_err()); + let settings = crate::params! { "missing" => "ignore" }; + assert!(summary_with_settings(settings).resolve_settings().is_err()); } #[test] - fn summary_validate_settings_rejects_a_non_string_rowlabel() { - let mut settings = Parameters::new(); - settings.insert("rowlabel".to_string(), ParameterValue::Number(1.0)); + fn summary_resolve_settings_rejects_a_non_string_rowlabel() { + let settings = crate::params! { "rowlabel" => 1.0 }; - assert!(summary_with_settings(settings).validate_settings().is_err()); + assert!(summary_with_settings(settings).resolve_settings().is_err()); } #[test] - fn summary_validate_settings_rejects_an_unknown_setting() { - let mut settings = Parameters::new(); - settings.insert( - "colour".to_string(), - ParameterValue::String("red".to_string()), - ); - - assert!(summary_with_settings(settings).validate_settings().is_err()); + fn summary_resolve_settings_rejects_an_unknown_setting() { + let settings = crate::params! { "colour" => "red" }; + + assert!(summary_with_settings(settings).resolve_settings().is_err()); } #[test] diff --git a/src/validate.rs b/src/validate.rs index 5a922e071..33b3797a7 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -358,7 +358,7 @@ pub fn validate(query: &str) -> Result { location: None, }); } - if let Err(e) = summary.validate_settings() { + if let Err(e) = summary.resolve_settings() { errors.push(ValidationError { message: format!("SUMMARISE {}: {}", idx + 1, e), location: None, From a53ba094679ca43da935f642637e70c1b4620f6e Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 24 Nov 2026 10:37:49 +0100 Subject: [PATCH 09/37] Renumber collapsed facet group keys at birth setup_rows renumbers a separated facet's multi-rank group keys to single ids right after the reorder, so nothing downstream ever sees the multi-rank keys the sort needed. collapse_group_columns sheds its rows parameter and renumbering pass; the shared collapses() predicate decides both sides. --- src/execute/table/facet.rs | 52 +++++++++++++++---------------------- src/execute/table/layout.rs | 13 ++++++++++ src/execute/table/mod.rs | 4 +-- 3 files changed, 36 insertions(+), 33 deletions(-) diff --git a/src/execute/table/facet.rs b/src/execute/table/facet.rs index 90f55f5ec..0bb9c2791 100644 --- a/src/execute/table/facet.rs +++ b/src/execute/table/facet.rs @@ -9,7 +9,7 @@ use crate::array_util::value_to_string; use crate::dataframe::into_array_ref; use crate::plot::facet::{distinct_levels, level_keys, order_levels, Facet, FacetLayout, LevelKey}; use crate::plot::ParameterValue; -use crate::table::{TableColumn, TableRow}; +use crate::table::TableColumn; use crate::{ColumnSection, DataFrame}; /// Assign each `df` row its group key: one rank per facet variable (see @@ -56,36 +56,37 @@ fn facet_columns<'a>(facet: &Facet, df: &'a DataFrame) -> Result bool { + matches!( + facet.properties.get("separator"), + Some(ParameterValue::String(_)) + ) && facet.get_variables().len() > 1 +} + /// Collapse a separated facet into one variable: join the facet variables' /// (formatted) values per row into a column named for the first variable, -/// drop the originals, renumber the rows' group keys to single ids, and -/// reduce the facet to that variable. Group stub columns in `columns` are -/// replaced by one, keeping the first's label and properties. Passes -/// everything through unchanged when the facet sets no `separator` or has a -/// single variable. -/// The table pieces `collapse_group_columns` rewrites for a separated facet. -type Collapsed = (DataFrame, Vec, Vec, Option); - +/// drop the originals, and reduce the facet to that variable. Group stub +/// columns in `columns` are replaced by one, keeping the first's label and +/// properties. The rows' group keys are already single ids — `setup_rows` +/// renumbers them at birth. Passes everything through unchanged unless +/// [`collapses`] applies. pub(super) fn collapse_group_columns( df: DataFrame, mut columns: Vec, - mut rows: Vec, facet: Option<&Facet>, -) -> Result { - let Some(facet) = facet else { - return Ok((df, columns, rows, None)); +) -> Result<(DataFrame, Vec, Option), String> { + let Some(facet) = facet.filter(|f| collapses(f)) else { + return Ok((df, columns, facet.cloned())); }; let separator = match facet.properties.get("separator") { Some(ParameterValue::String(separator)) => separator.clone(), - _ => return Ok((df, columns, rows, Some(facet.clone()))), + _ => unreachable!("collapses gates on a separator"), }; - // One variable has nothing to join. - let variables = facet.get_variables(); - if variables.len() == 1 { - return Ok((df, columns, rows, Some(facet.clone()))); - } // The joined column takes the first variable's name. + let variables = facet.get_variables(); let name = variables[0].clone(); let arrays: Vec<&ArrayRef> = variables @@ -106,17 +107,6 @@ pub(super) fn collapse_group_columns( .and_then(|df| df.with_column(&name, into_array_ref(joined))) .map_err(|e| e.to_string())?; - // Single-id keys: rows are group-sorted, so the id is the chunk index. - let mut id = 0; - let mut previous: Option> = None; - for row in &mut rows { - if previous.as_ref().is_some_and(|key| *key != row.group) { - id += 1; - } - previous = Some(std::mem::take(&mut row.group)); - row.group = vec![id]; - } - // Replace the group stub columns with one, at the first's position. if let Some(position) = columns.iter().position(|c| c.is_group_stub()) { let mut joined_column = columns[position].clone(); @@ -135,7 +125,7 @@ pub(super) fn collapse_group_columns( resolved: facet.resolved, }; - Ok((df, columns, rows, Some(facet))) + Ok((df, columns, Some(facet))) } /// Rank one facet variable's rows: non-null levels in the scale-free facet diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 072e77715..8ad300e8f 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -62,6 +62,19 @@ pub(super) fn setup_rows( let df = super::facet::drop_null_rows(facet, &df).map_err(GgsqlError::ValidationError)?; let keys = super::facet::setup_groups(facet, &df).map_err(GgsqlError::ValidationError)?; let (df, keys) = super::facet::reorder_rows(&df, keys).map_err(GgsqlError::ValidationError)?; + // A separated facet collapses to a single grouping level: renumber the + // keys to single ids (rows are group-contiguous after the reorder, so + // the id is the chunk index) and nothing downstream sees the multi-rank + // keys the sort needed. + let keys = if super::facet::collapses(facet) { + let mut ids = Vec::with_capacity(keys.len()); + for (id, chunk) in keys.chunk_by(|a, b| a == b).enumerate() { + ids.extend(std::iter::repeat_n(vec![id], chunk.len())); + } + ids + } else { + keys + }; let mut rows = Vec::with_capacity(keys.len()); for key in keys { let first_in_group = rows.last().is_none_or(|row: &TableRow| row.group != key); diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 3d88aa7da..b9015b657 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -90,8 +90,8 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Date: Tue, 24 Nov 2026 10:38:25 +0100 Subject: [PATCH 10/37] Wire SUMMARISE into the table pipeline compute_summaries runs between setup_columns and apply_formats, on the raw numeric values, and its chunks flow to build_cells. End-to-end tests cover grand and group placement, rowlabel, clause order, separated-facet re-keying, and the error paths. --- src/execute/table/mod.rs | 232 ++++++++++++++++++++++++++++++++++- src/execute/table/summary.rs | 2 - 2 files changed, 229 insertions(+), 5 deletions(-) diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index b9015b657..fa00534cf 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -16,7 +16,7 @@ mod summary; use facet::collapse_group_columns; use format::{apply_formats, setup_formats}; use layout::{build_cells, setup_columns, setup_rows}; -use summary::setup_summaries; +use summary::{compute_summaries, setup_summaries}; use crate::table::extract_table_titles; @@ -87,13 +87,22 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result panic!("expected a ValidationError, got {e:?}"), } } + + fn reader_with_region_sales() -> DuckDBReader { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES \ + ('north', 'q1', 1), ('north', 'q2', 2), ('south', 'q1', 3)) \ + AS t(region, quarter, sales)", + ) + .unwrap(); + reader + } + + fn summary_row_indices(resolved: &ResolvedTable) -> Vec { + resolved + .rows() + .iter() + .enumerate() + .filter(|(_, row)| row.classes.contains(&TableClass::SummaryRow)) + .map(|(index, _)| index) + .collect() + } + + #[test] + fn test_tabulate_summarise_grand_without_facet_appends_one_row() { + let reader = reader_with_sales(); + let resolved = + resolve_table_with_reader("TABULATE * FROM sales SUMMARISE mean OF id", &reader) + .unwrap(); + + // Header row + 3 body rows + 1 summary row. + assert_eq!(resolved.rows().len(), 5); + // The summary row gets a synthetic stub column for its label. + assert_eq!( + resolved.columns()[0].name, + crate::naming::SUMMARY_LABEL_COLUMN + ); + assert_eq!(resolved.columns()[0].target, crate::ColumnSection::Stub); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::StubRowLabel && c.top == 4) + .unwrap(); + assert_eq!(label.content, "mean"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::Body && c.top == 4 && c.left == 1) + .unwrap(); + assert_eq!(value.content, "2"); + // The non-summarised column's cell is blank. + let blank = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::Body && c.top == 4 && c.left == 2) + .unwrap(); + assert_eq!(blank.content, ""); + } + + #[test] + fn test_tabulate_summarise_group_rows_follow_their_group() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header; per group: heading, data rows, summary row. + assert_eq!(summary_row_indices(&resolved), [4, 7]); + + let last = resolved.columns().len() - 1; + let values: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::Body && c.left == last && [4, 7].contains(&c.top)) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(values, ["1.5", "3"]); + } + + #[test] + fn test_tabulate_summarise_place_top_sits_before_the_group_rows() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' \ + SUMMARISE mean OF sales SETTING place => 'top'", + &reader, + ) + .unwrap(); + + // Header at 0, north's heading at 1, then north's summary row. + assert_eq!(summary_row_indices(&resolved), [2, 6]); + } + + #[test] + fn test_tabulate_summarise_grand_with_facet_uses_all_rows_and_rowlabel() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region SETTING place => 'top' \ + SUMMARISE GRAND mean OF sales SETTING rowlabel => 'Average'", + &reader, + ) + .unwrap(); + + let summary_row = summary_row_indices(&resolved); + // One grand row, after every body row. + assert_eq!(summary_row, [resolved.rows().len() - 1]); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::StubRowLabel && c.top == summary_row[0]) + .unwrap(); + assert_eq!(label.content, "Average"); + let value = resolved + .cells() + .iter() + .find(|c| { + c.kind == TableCellKind::Body + && c.top == summary_row[0] + && resolved.columns()[c.left].name == "sales" + }) + .unwrap(); + assert_eq!(value.content, "2"); + } + + #[test] + fn test_tabulate_summarise_separated_facet_rekeys_the_summary_chunks() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET region, quarter SETTING place => 'top', separator => ' - ' \ + SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header; per collapsed group (north-q1, north-q2, south-q1): + // heading, data row, summary row. + let summary_rows = summary_row_indices(&resolved); + assert_eq!(summary_rows, [3, 6, 9]); + + let last = resolved.columns().len() - 1; + let values: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| { + c.kind == TableCellKind::Body && c.left == last && summary_rows.contains(&c.top) + }) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(values, ["1", "2", "3"]); + } + + #[test] + fn test_tabulate_summarise_rejects_a_non_numeric_column_for_numeric_ops() { + let reader = reader_with_sales(); + match resolve_table_with_reader("TABULATE * FROM sales SUMMARISE mean OF name", &reader) { + Ok(_) => panic!("expected mean OF a text column to error"), + Err(GgsqlError::ValidationError(msg)) => assert!(msg.contains("numeric")), + Err(e) => panic!("expected a ValidationError, got {e:?}"), + } + } + + #[test] + fn test_tabulate_summarise_rejects_a_column_outside_the_selection() { + let reader = reader_with_sales(); + match resolve_table_with_reader("TABULATE id FROM sales SUMMARISE mean OF name", &reader) { + Ok(_) => panic!("expected a non-selection column to error"), + Err(GgsqlError::ValidationError(msg)) => { + assert!(msg.contains("no column 'name'")) + } + Err(e) => panic!("expected a ValidationError, got {e:?}"), + } + } + + #[test] + fn test_tabulate_summarise_skips_the_null_group_under_missing_drop() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES ('a', 1), (NULL, 2), ('b', 3)) \ + AS t(name, sales)", + ) + .unwrap(); + + let resolved = resolve_table_with_reader( + "TABULATE * FROM t FACET name SETTING place => 'top', missing => 'drop' \ + SUMMARISE mean OF sales", + &reader, + ) + .unwrap(); + + // Header + per surviving group (heading, data row, summary row). + assert_eq!(resolved.rows().len(), 7); + assert_eq!(summary_row_indices(&resolved).len(), 2); + } + + #[test] + fn test_tabulate_summarise_clauses_stay_in_clause_order() { + let reader = reader_with_region_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE mean OF sales SUMMARISE median OF sales", + &reader, + ) + .unwrap(); + + let labels: Vec<(usize, &str)> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::StubRowLabel && !c.content.is_empty()) + .map(|c| (c.top, c.content.as_str())) + .collect(); + // Anti-alphabetical: clause order, not any other ordering, decides. + assert_eq!(labels, [(4, "mean"), (5, "median")]); + } } diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 1d0e1eeee..4f7e81d9e 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -137,8 +137,6 @@ pub(super) type SummaryChunk = (Option>, Vec); /// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. /// Chunks with no matching clauses are omitted. Placement within a chunk is /// the weavers' concern; they read each row's `top`. -// Unused until the table pipeline calls it. -#[allow(dead_code)] pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], From cc4d6768109f3239d8292356d5fc3a84dee99ec0 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 24 Nov 2026 12:59:00 +0100 Subject: [PATCH 11/37] Set new TableCellKinds --- src/execute/table/layout.rs | 29 +++++++++++++++++++---------- src/execute/table/mod.rs | 20 ++++++++++++-------- src/execute/table/summary.rs | 4 ++-- src/table/layout.rs | 20 ++++++++++++++++++++ src/writer/html.rs | 3 ++- 5 files changed, 55 insertions(+), 21 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 8ad300e8f..ce05eab57 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -569,9 +569,12 @@ mod tests { assert_eq!(summary_row, vec![3]); assert_eq!( find_cell(&layout, 3, "mean").kind, - TableCellKind::StubRowLabel + TableCellKind::SummaryLabel + ); + assert_eq!( + find_cell(&layout, 3, "2.5").kind, + TableCellKind::SummaryValue ); - assert_eq!(find_cell(&layout, 3, "2.5").kind, TableCellKind::Body); } #[test] @@ -592,11 +595,11 @@ mod tests { assert_eq!(rows_with_class(&layout, TableClass::SummaryRow), vec![1, 4]); assert_eq!( find_cell(&layout, 1, "median").kind, - TableCellKind::StubRowLabel + TableCellKind::SummaryLabel ); assert_eq!( find_cell(&layout, 4, "mean").kind, - TableCellKind::StubRowLabel + TableCellKind::SummaryLabel ); } @@ -618,8 +621,14 @@ mod tests { assert_eq!(summary_rows, vec![4, 7]); assert_eq!(layout.rows[summary_rows[0]].group, vec![0]); assert_eq!(layout.rows[summary_rows[1]].group, vec![1]); - assert_eq!(find_cell(&layout, 4, "2.5").kind, TableCellKind::Body); - assert_eq!(find_cell(&layout, 7, "10.5").kind, TableCellKind::Body); + assert_eq!( + find_cell(&layout, 4, "2.5").kind, + TableCellKind::SummaryValue + ); + assert_eq!( + find_cell(&layout, 7, "10.5").kind, + TableCellKind::SummaryValue + ); } #[test] @@ -656,7 +665,7 @@ mod tests { .iter() .find(|cell| cell.top == 6 && cell.left == north.left) .expect("grand row's label spans the group stub column"); - assert_eq!(grand_label.kind, TableCellKind::StubRowLabel); + assert_eq!(grand_label.kind, TableCellKind::SummaryLabel); assert_eq!(grand_label.content, "mean"); } @@ -675,7 +684,7 @@ mod tests { let grand_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; let label = find_cell(&layout, grand_row, "mean"); - assert_eq!(label.kind, TableCellKind::StubRowLabel); + assert_eq!(label.kind, TableCellKind::SummaryLabel); assert_eq!(label.left, 0); assert!( label.right > label.left, @@ -713,7 +722,7 @@ mod tests { let summary_row = rows_with_class(&layout, TableClass::SummaryRow)[0]; let label = find_cell(&layout, summary_row, "mean"); - assert_eq!(label.kind, TableCellKind::StubRowLabel); + assert_eq!(label.kind, TableCellKind::SummaryLabel); assert_eq!(label.left, 0); assert_eq!(label.right, 1); // The second stub column emits no cell of its own on the summary row. @@ -721,7 +730,7 @@ mod tests { layout .cells .iter() - .filter(|cell| cell.top == summary_row && cell.kind == TableCellKind::StubRowLabel) + .filter(|cell| cell.top == summary_row && cell.kind == TableCellKind::SummaryLabel) .count(), 1 ); diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index fa00534cf..1f49a0f6d 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -867,20 +867,20 @@ mod integration_tests { let label = resolved .cells() .iter() - .find(|c| c.kind == TableCellKind::StubRowLabel && c.top == 4) + .find(|c| c.kind == TableCellKind::SummaryLabel && c.top == 4) .unwrap(); assert_eq!(label.content, "mean"); let value = resolved .cells() .iter() - .find(|c| c.kind == TableCellKind::Body && c.top == 4 && c.left == 1) + .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 1) .unwrap(); assert_eq!(value.content, "2"); // The non-summarised column's cell is blank. let blank = resolved .cells() .iter() - .find(|c| c.kind == TableCellKind::Body && c.top == 4 && c.left == 2) + .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 2) .unwrap(); assert_eq!(blank.content, ""); } @@ -901,7 +901,9 @@ mod integration_tests { let values: Vec<&str> = resolved .cells() .iter() - .filter(|c| c.kind == TableCellKind::Body && c.left == last && [4, 7].contains(&c.top)) + .filter(|c| { + c.kind == TableCellKind::SummaryValue && c.left == last && [4, 7].contains(&c.top) + }) .map(|c| c.content.as_str()) .collect(); assert_eq!(values, ["1.5", "3"]); @@ -938,14 +940,14 @@ mod integration_tests { let label = resolved .cells() .iter() - .find(|c| c.kind == TableCellKind::StubRowLabel && c.top == summary_row[0]) + .find(|c| c.kind == TableCellKind::SummaryLabel && c.top == summary_row[0]) .unwrap(); assert_eq!(label.content, "Average"); let value = resolved .cells() .iter() .find(|c| { - c.kind == TableCellKind::Body + c.kind == TableCellKind::SummaryValue && c.top == summary_row[0] && resolved.columns()[c.left].name == "sales" }) @@ -973,7 +975,9 @@ mod integration_tests { .cells() .iter() .filter(|c| { - c.kind == TableCellKind::Body && c.left == last && summary_rows.contains(&c.top) + c.kind == TableCellKind::SummaryValue + && c.left == last + && summary_rows.contains(&c.top) }) .map(|c| c.content.as_str()) .collect(); @@ -1036,7 +1040,7 @@ mod integration_tests { let labels: Vec<(usize, &str)> = resolved .cells() .iter() - .filter(|c| c.kind == TableCellKind::StubRowLabel && !c.content.is_empty()) + .filter(|c| c.kind == TableCellKind::SummaryLabel && !c.content.is_empty()) .map(|c| (c.top, c.content.as_str())) .collect(); // Anti-alphabetical: clause order, not any other ordering, decides. diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 4f7e81d9e..39f745d0a 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -90,7 +90,7 @@ impl SummaryRow { .column(&column.name) .map(|array| column_to_strings(array).remove(0)) .unwrap_or_default(); - TableCell::new_body(row, index, content) + TableCell::new_summary_value(row, index, content) .with_properties(column.properties.clone()) }), ); @@ -121,7 +121,7 @@ impl SummaryRow { "the label's colspan covers only stub columns" ); - let mut cell = TableCell::new_stub_row_label(row, label_column, self.label.clone()); + let mut cell = TableCell::new_summary_label(row, label_column, self.label.clone()); cell.left = left; cell.right = right; cell.with_properties(columns[label_column].properties.clone()) diff --git a/src/table/layout.rs b/src/table/layout.rs index fe260c740..53a661885 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -27,8 +27,13 @@ pub enum TableCellKind { StubHead, /// A data value (gt's `body`). Body, + /// A computed value in a `SUMMARISE` row. + SummaryValue, /// A row-label value in the stub (`TABULATE FORMAT STUB`, gt's `stub`). StubRowLabel, + /// A summary row's label cell in the stub (`SUMMARISE`'s `rowlabel` or + /// the operation name). + SummaryLabel, /// A spanner cell, grouping several columns under one label (`TABULATE /// SPAN`). Spanner, @@ -63,6 +68,7 @@ impl TableCellKind { | TableCellKind::Subtitle | TableCellKind::Filler // every current case is header-shaped | TableCellKind::StubRowLabel + | TableCellKind::SummaryLabel ) } } @@ -73,7 +79,9 @@ impl std::fmt::Display for TableCellKind { TableCellKind::ColumnLabel => "column label", TableCellKind::StubHead => "stub head", TableCellKind::Body => "body", + TableCellKind::SummaryValue => "summary value", TableCellKind::StubRowLabel => "stub row label", + TableCellKind::SummaryLabel => "summary label", TableCellKind::Spanner => "spanner", TableCellKind::Title => "title", TableCellKind::Subtitle => "subtitle", @@ -309,6 +317,18 @@ impl TableCell { .with_classes(vec![TableClass::Stub]) } + /// A summary value cell (`TableClass::Row`). + pub(crate) fn new_summary_value(row: usize, col: usize, content: String) -> Self { + Self::new(TableCellKind::SummaryValue, row, row, col, col, content) + .with_classes(vec![TableClass::Row]) + } + + /// A summary row's stub label cell (`TableClass::Stub`). + pub(crate) fn new_summary_label(row: usize, index: usize, content: String) -> Self { + Self::new(TableCellKind::SummaryLabel, row, row, index, index, content) + .with_classes(vec![TableClass::Stub]) + } + /// A group-stub group-label cell (`TableClass::StubRowGroup`). pub(crate) fn new_stub_row_group(row: usize, index: usize, content: String) -> Self { Self::new(TableCellKind::GroupHeading, row, row, index, index, content) diff --git a/src/writer/html.rs b/src/writer/html.rs index 27a4ca163..eee032b6d 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -539,9 +539,10 @@ fn header_scope(kind: TableCellKind) -> Option<&'static str> { match kind { TableCellKind::ColumnLabel | TableCellKind::StubHead => Some("col"), TableCellKind::Spanner => Some("colgroup"), - TableCellKind::StubRowLabel => Some("row"), + TableCellKind::StubRowLabel | TableCellKind::SummaryLabel => Some("row"), TableCellKind::GroupHeading => Some("rowgroup"), TableCellKind::Body + | TableCellKind::SummaryValue | TableCellKind::Title | TableCellKind::Subtitle | TableCellKind::Caption From 18d4daede427aa88ba3aa7a11569e9d3e0582fd1 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 24 Nov 2026 13:42:25 +0100 Subject: [PATCH 12/37] Store scope on SummaryRow --- src/execute/table/layout.rs | 8 ++++---- src/execute/table/summary.rs | 28 ++++++++++++++-------------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index ce05eab57..32b1233f0 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -275,7 +275,7 @@ fn weave_group_summaries( let key = key.as_ref().expect("filtered to group chunks"); debug_assert_eq!(chunk[0].group, *key, "summary chunks in group order"); for summary in chunk_summaries.iter().filter(|s| s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns, false)); + summary_cells.extend(summary.cells(new_rows.len(), columns)); new_rows.push(TableRow::summary(key.clone())); } for row in chunk.iter() { @@ -284,7 +284,7 @@ fn weave_group_summaries( old_index += 1; } for summary in chunk_summaries.iter().filter(|s| !s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns, false)); + summary_cells.extend(summary.cells(new_rows.len(), columns)); new_rows.push(TableRow::summary(key.clone())); } } @@ -319,12 +319,12 @@ fn weave_grand_summaries( let mut new_rows = Vec::with_capacity(rows.len() + grand.len()); let mut summary_cells = Vec::new(); for summary in grand.iter().filter(|s| s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns, true)); + summary_cells.extend(summary.cells(new_rows.len(), columns)); new_rows.push(TableRow::summary(Vec::new())); } new_rows.extend(rows); for summary in grand.iter().filter(|s| !s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns, true)); + summary_cells.extend(summary.cells(new_rows.len(), columns)); new_rows.push(TableRow::summary(Vec::new())); } summary_cells.extend(cells); diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 39f745d0a..594e46a58 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -57,6 +57,9 @@ pub(super) fn setup_summaries( /// clause itself. #[derive(Debug)] pub(super) struct SummaryRow { + /// Whether the row summarises its group (`GROUP`) or the whole table + /// (`GRAND`). + pub scope: SummaryScope, /// Whether the row sits above (`true`) or below its group's rows. pub top: bool, /// The row's stub label: `rowlabel`, else the operation name. @@ -70,15 +73,10 @@ impl SummaryRow { /// This row's cells at grid row `row`: the label spanning the stub /// columns, then the computed values in their body columns. No cells in /// group-stub columns: a `GROUP` row's are covered by the merged stub - /// cell; a `GRAND` row (`span_group_stubs`) owns them by extending its - /// label's colspan leftward. - pub(super) fn cells( - &self, - row: usize, - columns: &[TableColumn], - span_group_stubs: bool, - ) -> Vec { - let mut cells = vec![self.label_cell(row, columns, span_group_stubs)]; + /// cell; a `GRAND` row owns them by extending its label's colspan + /// leftward. + pub(super) fn cells(&self, row: usize, columns: &[TableColumn]) -> Vec { + let mut cells = vec![self.label_cell(row, columns)]; cells.extend( columns .iter() @@ -98,15 +96,16 @@ impl SummaryRow { } /// The row's label cell, spanning every stub column — leftward over the - /// group-stub columns too for a `GRAND` row (`span_group_stubs`). - /// `setup_summaries` adds a stub column when summaries exist without one; - /// `move_stub_columns` puts every stub-section column in one contiguous - /// run, so the span covers only stub columns. - fn label_cell(&self, row: usize, columns: &[TableColumn], span_group_stubs: bool) -> TableCell { + /// group-stub columns too for a `GRAND` row. `setup_summaries` adds a + /// stub column when summaries exist without one; `move_stub_columns` + /// puts every stub-section column in one contiguous run, so the span + /// covers only stub columns. + fn label_cell(&self, row: usize, columns: &[TableColumn]) -> TableCell { let label_column = columns .iter() .position(|c| c.target == ColumnSection::Stub) .expect("setup_summaries guarantees a stub column"); + let span_group_stubs = self.scope == SummaryScope::Grand; let left = if span_group_stubs && columns.first().is_some_and(|c| c.is_group_stub()) { 0 } else { @@ -183,6 +182,7 @@ impl Summary { .and_then(ParameterValue::as_str) .map_or_else(|| self.operation.clone(), str::to_string); Ok(SummaryRow { + scope: self.scope, top: ParameterValue::is_str(self.settings.get("place"), "top"), label, frame: summary_frame(df, self, range)?, From ead970f914034a7579e6d93cd004db50ab1ff81f Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 24 Nov 2026 15:00:02 +0100 Subject: [PATCH 13/37] initial styling --- src/execute/table/layout.rs | 124 +++++++++++++++++++++++++++++------ src/execute/table/summary.rs | 46 +++++++++++-- src/table/layout.rs | 30 +++++++++ src/writer/html.rs | 46 +++++++++++++ 4 files changed, 220 insertions(+), 26 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 32b1233f0..149cbd3f6 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -7,7 +7,7 @@ use std::collections::HashMap; use super::format::resolve_column_properties; use super::stub::{create_row_labels, create_stubhead}; -use super::summary::SummaryChunk; +use super::summary::{SummaryChunk, SummaryRow}; use crate::array_util::{column_to_strings, value_to_string}; use crate::naming; use crate::plot::facet::Facet; @@ -274,19 +274,27 @@ fn weave_group_summaries( { let key = key.as_ref().expect("filtered to group chunks"); debug_assert_eq!(chunk[0].group, *key, "summary chunks in group order"); - for summary in chunk_summaries.iter().filter(|s| s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns)); - new_rows.push(TableRow::summary(key.clone())); - } + let tops: Vec<&SummaryRow> = chunk_summaries.iter().filter(|s| s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &tops, + key.clone(), + columns, + ); for row in chunk.iter() { row_map[old_index] = new_rows.len(); new_rows.push(row.clone()); old_index += 1; } - for summary in chunk_summaries.iter().filter(|s| !s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns)); - new_rows.push(TableRow::summary(key.clone())); - } + let bottoms: Vec<&SummaryRow> = chunk_summaries.iter().filter(|s| !s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &bottoms, + key.clone(), + columns, + ); } let mut cells = cells; @@ -310,27 +318,55 @@ fn weave_grand_summaries( let Some((_, grand)) = summaries.iter().find(|(key, _)| key.is_none()) else { return (rows, cells); }; - let tops = grand.iter().filter(|s| s.top).count(); + let tops: Vec<&SummaryRow> = grand.iter().filter(|s| s.top).collect(); let mut cells = cells; for cell in &mut cells { - cell.offset_rows(tops); + cell.offset_rows(tops.len()); } let mut new_rows = Vec::with_capacity(rows.len() + grand.len()); let mut summary_cells = Vec::new(); - for summary in grand.iter().filter(|s| s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns)); - new_rows.push(TableRow::summary(Vec::new())); - } + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &tops, + Vec::new(), + columns, + ); new_rows.extend(rows); - for summary in grand.iter().filter(|s| !s.top) { - summary_cells.extend(summary.cells(new_rows.len(), columns)); - new_rows.push(TableRow::summary(Vec::new())); - } + let bottoms: Vec<&SummaryRow> = grand.iter().filter(|s| !s.top).collect(); + weave_summary_block( + &mut new_rows, + &mut summary_cells, + &bottoms, + Vec::new(), + columns, + ); summary_cells.extend(cells); (new_rows, summary_cells) } +/// Emit one grid row per clause row in `block`, marking the block's first +/// and last rows (both, when the block is one row) for the positional +/// classes. +fn weave_summary_block( + new_rows: &mut Vec, + summary_cells: &mut Vec, + block: &[&SummaryRow], + key: Vec, + columns: &[TableColumn], +) { + for (index, summary) in block.iter().enumerate() { + summary_cells.extend(summary.cells( + new_rows.len(), + columns, + index == 0, + index == block.len() - 1, + )); + new_rows.push(TableRow::summary(key.clone())); + } +} + /// Interleave group-label rows into the body. At each group boundary, emit /// one `GroupHeading` row per facet-variable level that changed, labels read /// from the group's first data row (so an unchanged outer variable isn't @@ -603,6 +639,56 @@ mod tests { ); } + #[test] + fn summary_cells_carry_their_blocks_position_classes() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![ + summary_clause("mean", SummaryScope::Grand, &["x"]), + summary_clause("median", SummaryScope::Grand, &["x"]), + ]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Header, two data rows, then the two-row grand block. + let has = |row: usize, class: TableClass| { + layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&class)) + }; + assert!(has(3, TableClass::GrandSummary)); + assert!(has(3, TableClass::GrandSummaryFirst)); + assert!(!has(3, TableClass::GrandSummaryLast)); + assert!(has(4, TableClass::GrandSummary)); + assert!(!has(4, TableClass::GrandSummaryFirst)); + assert!(has(4, TableClass::GrandSummaryLast)); + } + + #[test] + fn a_lone_summary_row_is_both_first_and_last() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + table.summaries = vec![summary_clause("mean", SummaryScope::Grand, &["x"])]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + let row = layout.rows.len() - 1; + assert!(layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&TableClass::GrandSummaryFirst) + && cell.classes.contains(&TableClass::GrandSummaryLast))); + } + #[test] fn group_summary_weaves_after_its_groups_heading_rows() { let frame = df! { diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 594e46a58..1dd4db433 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -15,7 +15,7 @@ use arrow::datatypes::DataType; use crate::array_util::{as_f64, cast_array, column_to_strings}; use crate::naming; use crate::params::ParameterValue; -use crate::table::{Format, Summary, SummaryScope, TableCell, TableColumn, TableRow}; +use crate::table::{Format, Summary, SummaryScope, TableCell, TableClass, TableColumn, TableRow}; use crate::{ColumnSection, DataFrame, GgsqlError, Result}; /// Validate `summaries` against the data and prepare the frame for summary @@ -74,9 +74,38 @@ impl SummaryRow { /// columns, then the computed values in their body columns. No cells in /// group-stub columns: a `GROUP` row's are covered by the merged stub /// cell; a `GRAND` row owns them by extending its label's colspan - /// leftward. - pub(super) fn cells(&self, row: usize, columns: &[TableColumn]) -> Vec { - let mut cells = vec![self.label_cell(row, columns)]; + /// leftward. `first`/`last` mark the row's position in its block (both + /// when the block is one row) for the positional style classes. + pub(super) fn cells( + &self, + row: usize, + columns: &[TableColumn], + first: bool, + last: bool, + ) -> Vec { + // Every cell in the row carries the same classes: the scope's base + // class plus the block's positional markers. + let (base, first_class, last_class) = match self.scope { + SummaryScope::Group => ( + TableClass::GroupSummary, + TableClass::GroupSummaryFirst, + TableClass::GroupSummaryLast, + ), + SummaryScope::Grand => ( + TableClass::GrandSummary, + TableClass::GrandSummaryFirst, + TableClass::GrandSummaryLast, + ), + }; + let mut classes = vec![base]; + if first { + classes.push(first_class); + } + if last { + classes.push(last_class); + } + + let mut cells = vec![self.label_cell(row, columns, &classes)]; cells.extend( columns .iter() @@ -88,8 +117,10 @@ impl SummaryRow { .column(&column.name) .map(|array| column_to_strings(array).remove(0)) .unwrap_or_default(); - TableCell::new_summary_value(row, index, content) - .with_properties(column.properties.clone()) + let mut cell = TableCell::new_summary_value(row, index, content) + .with_properties(column.properties.clone()); + cell.classes.extend_from_slice(&classes); + cell }), ); cells @@ -100,7 +131,7 @@ impl SummaryRow { /// stub column when summaries exist without one; `move_stub_columns` /// puts every stub-section column in one contiguous run, so the span /// covers only stub columns. - fn label_cell(&self, row: usize, columns: &[TableColumn]) -> TableCell { + fn label_cell(&self, row: usize, columns: &[TableColumn], classes: &[TableClass]) -> TableCell { let label_column = columns .iter() .position(|c| c.target == ColumnSection::Stub) @@ -123,6 +154,7 @@ impl SummaryRow { let mut cell = TableCell::new_summary_label(row, label_column, self.label.clone()); cell.left = left; cell.right = right; + cell.classes.extend_from_slice(classes); cell.with_properties(columns[label_column].properties.clone()) } } diff --git a/src/table/layout.rs b/src/table/layout.rs index 53a661885..671df7d10 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -167,6 +167,24 @@ pub enum TableClass { /// A group-label cell (`TableCellKind::GroupHeading`, gt's /// `gt_group_heading`). GroupHeading, + /// A cell in a `SUMMARISE GROUP` row (gt's `gt_summary_row`). + GroupSummary, + /// A cell in the first row of a group's summary block — carries the + /// border separating the block from what precedes it (gt's + /// `gt_first_summary_row`). + GroupSummaryFirst, + /// A cell in the last row of a group's summary block (gt's + /// `gt_last_summary_row`). + GroupSummaryLast, + /// A cell in a `SUMMARISE GRAND` row (gt's `gt_grand_summary_row`). + GrandSummary, + /// A cell in the first row of the grand-summary block — carries the + /// double border separating it from the body (gt's + /// `gt_first_grand_summary_row`). + GrandSummaryFirst, + /// A cell in the last row of the grand-summary block (gt's + /// `gt_last_grand_summary_row`). + GrandSummaryLast, /// Left/center/right-aligned cell content (gt's /// `gt_left`/`gt_center`/`gt_right`). AlignLeft, @@ -201,6 +219,12 @@ impl TableClass { TableClass::GroupHeadingRow, TableClass::RowGroupFirst, TableClass::SummaryRow, + TableClass::GroupSummary, + TableClass::GroupSummaryFirst, + TableClass::GroupSummaryLast, + TableClass::GrandSummary, + TableClass::GrandSummaryFirst, + TableClass::GrandSummaryLast, TableClass::AlignLeft, TableClass::AlignCenter, TableClass::AlignRight, @@ -231,6 +255,12 @@ impl std::fmt::Display for TableClass { TableClass::Caption => "caption", TableClass::Heading => "heading", TableClass::SummaryRow => "summary_row", + TableClass::GroupSummary => "group_summary", + TableClass::GroupSummaryFirst => "group_summary_first", + TableClass::GroupSummaryLast => "group_summary_last", + TableClass::GrandSummary => "grand_summary", + TableClass::GrandSummaryFirst => "grand_summary_first", + TableClass::GrandSummaryLast => "grand_summary_last", TableClass::GroupHeading => "group_heading", TableClass::GroupHeadingRow => "group_heading_row", TableClass::RowGroupFirst => "row_group_first", diff --git a/src/writer/html.rs b/src/writer/html.rs index eee032b6d..57eb0f07a 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -390,6 +390,52 @@ fn class_declarations(class: TableClass) -> &'static [(&'static str, &'static st ("border-top-color", "#D3D3D3"), ], TableClass::SummaryRow => &[], + TableClass::GroupSummary => &[ + ("color", "#333333"), + ("background-color", "#FFFFFF"), + ("text-transform", "inherit"), + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ], + TableClass::GroupSummaryFirst => &[ + ("border-top-style", "solid"), + ("border-top-width", "2px"), + ("border-top-color", "#D3D3D3"), + ], + TableClass::GroupSummaryLast => &[ + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ("border-bottom-style", "solid"), + ("border-bottom-width", "2px"), + ("border-bottom-color", "#D3D3D3"), + ], + TableClass::GrandSummary => &[ + ("color", "#333333"), + ("background-color", "#FFFFFF"), + ("text-transform", "inherit"), + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ], + TableClass::GrandSummaryFirst => &[ + ("padding-top", "8px"), + ("padding-bottom", "8px"), + ("padding-left", "5px"), + ("padding-right", "5px"), + ("border-top-style", "double"), + ("border-top-width", "3px"), + ("border-top-color", "#D3D3D3"), + ], + TableClass::GrandSummaryLast => &[ + ("border-bottom-style", "double"), + ("border-bottom-width", "3px"), + ("border-bottom-color", "#D3D3D3"), + ], TableClass::AlignLeft => &[("text-align", "left")], TableClass::AlignCenter => &[("text-align", "center")], TableClass::AlignRight => &[ From e1e1f9a345e7b3c63f62aecbdea54c5191749805 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 24 Nov 2026 16:53:02 +0100 Subject: [PATCH 14/37] Some nuances with borders --- src/execute/table/layout.rs | 48 ++++++++++++++++++++++++++++++++---- src/execute/table/summary.rs | 26 +++++++++++++------ src/table/layout.rs | 27 ++++++++++---------- src/writer/html.rs | 8 +++--- 4 files changed, 79 insertions(+), 30 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 149cbd3f6..4f82f88c1 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -281,6 +281,7 @@ fn weave_group_summaries( &tops, key.clone(), columns, + true, ); for row in chunk.iter() { row_map[old_index] = new_rows.len(); @@ -294,6 +295,7 @@ fn weave_group_summaries( &bottoms, key.clone(), columns, + false, ); } @@ -332,6 +334,7 @@ fn weave_grand_summaries( &tops, Vec::new(), columns, + true, ); new_rows.extend(rows); let bottoms: Vec<&SummaryRow> = grand.iter().filter(|s| !s.top).collect(); @@ -341,6 +344,7 @@ fn weave_grand_summaries( &bottoms, Vec::new(), columns, + false, ); summary_cells.extend(cells); (new_rows, summary_cells) @@ -348,13 +352,14 @@ fn weave_grand_summaries( /// Emit one grid row per clause row in `block`, marking the block's first /// and last rows (both, when the block is one row) for the positional -/// classes. +/// classes. `above` is whether the block sits above the rows it summarizes. fn weave_summary_block( new_rows: &mut Vec, summary_cells: &mut Vec, block: &[&SummaryRow], key: Vec, columns: &[TableColumn], + above: bool, ) { for (index, summary) in block.iter().enumerate() { summary_cells.extend(summary.cells( @@ -362,6 +367,7 @@ fn weave_summary_block( columns, index == 0, index == block.len() - 1, + above, )); new_rows.push(TableRow::summary(key.clone())); } @@ -653,7 +659,9 @@ mod tests { let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); - // Header, two data rows, then the two-row grand block. + // Header, two data rows, then the two-row grand block: the double + // border on the edge touching the body, the group's solid one on + // the far edge. let has = |row: usize, class: TableClass| { layout .cells @@ -663,10 +671,40 @@ mod tests { }; assert!(has(3, TableClass::GrandSummary)); assert!(has(3, TableClass::GrandSummaryFirst)); - assert!(!has(3, TableClass::GrandSummaryLast)); + assert!(!has(3, TableClass::SummaryLast)); assert!(has(4, TableClass::GrandSummary)); assert!(!has(4, TableClass::GrandSummaryFirst)); - assert!(has(4, TableClass::GrandSummaryLast)); + assert!(has(4, TableClass::SummaryLast)); + } + + #[test] + fn a_top_grand_block_puts_its_double_border_against_the_body() { + let frame = df! { + "x" => vec![1.5, 3.5], + } + .unwrap(); + let mut table = Table::new(); + let mut first = summary_clause("mean", SummaryScope::Grand, &["x"]); + first.settings = crate::params! { "place" => "top" }; + let mut second = summary_clause("median", SummaryScope::Grand, &["x"]); + second.settings = crate::params! { "place" => "top" }; + table.summaries = vec![first, second]; + + let layout = resolve_layout_with_summaries(&frame, &table, None).unwrap(); + + // Header, then the two-row grand block above the data rows: the far + // edge gets the group's solid border, the body edge the double one. + let has = |row: usize, class: TableClass| { + layout + .cells + .iter() + .filter(|cell| cell.top == row) + .all(|cell| cell.classes.contains(&class)) + }; + assert!(has(1, TableClass::SummaryFirst)); + assert!(!has(1, TableClass::GrandSummaryLast)); + assert!(!has(2, TableClass::SummaryFirst)); + assert!(has(2, TableClass::GrandSummaryLast)); } #[test] @@ -686,7 +724,7 @@ mod tests { .iter() .filter(|cell| cell.top == row) .all(|cell| cell.classes.contains(&TableClass::GrandSummaryFirst) - && cell.classes.contains(&TableClass::GrandSummaryLast))); + && cell.classes.contains(&TableClass::SummaryLast))); } #[test] diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 1dd4db433..9e65d8ddb 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -75,27 +75,37 @@ impl SummaryRow { /// group-stub columns: a `GROUP` row's are covered by the merged stub /// cell; a `GRAND` row owns them by extending its label's colspan /// leftward. `first`/`last` mark the row's position in its block (both - /// when the block is one row) for the positional style classes. + /// when the block is one row) and `above` whether the block sits above + /// the rows it summarizes; together they pick the positional style + /// classes. pub(super) fn cells( &self, row: usize, columns: &[TableColumn], first: bool, last: bool, + above: bool, ) -> Vec { // Every cell in the row carries the same classes: the scope's base - // class plus the block's positional markers. - let (base, first_class, last_class) = match self.scope { - SummaryScope::Group => ( + // class plus the block's positional markers. A group block gets the + // solid border on both outer edges; a grand block gets it on its + // far edge and the double border on the edge touching the body. + let (base, first_class, last_class) = match (self.scope, above) { + (SummaryScope::Group, _) => ( TableClass::GroupSummary, - TableClass::GroupSummaryFirst, - TableClass::GroupSummaryLast, + TableClass::SummaryFirst, + TableClass::SummaryLast, ), - SummaryScope::Grand => ( + (SummaryScope::Grand, true) => ( TableClass::GrandSummary, - TableClass::GrandSummaryFirst, + TableClass::SummaryFirst, TableClass::GrandSummaryLast, ), + (SummaryScope::Grand, false) => ( + TableClass::GrandSummary, + TableClass::GrandSummaryFirst, + TableClass::SummaryLast, + ), }; let mut classes = vec![base]; if first { diff --git a/src/table/layout.rs b/src/table/layout.rs index 671df7d10..4269fb522 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -169,21 +169,22 @@ pub enum TableClass { GroupHeading, /// A cell in a `SUMMARISE GROUP` row (gt's `gt_summary_row`). GroupSummary, - /// A cell in the first row of a group's summary block — carries the - /// border separating the block from what precedes it (gt's + /// A cell in the first row of a summary block — carries the border + /// separating the block from what precedes it (gt's /// `gt_first_summary_row`). - GroupSummaryFirst, - /// A cell in the last row of a group's summary block (gt's + SummaryFirst, + /// A cell in the last row of a summary block (gt's /// `gt_last_summary_row`). - GroupSummaryLast, + SummaryLast, /// A cell in a `SUMMARISE GRAND` row (gt's `gt_grand_summary_row`). GrandSummary, - /// A cell in the first row of the grand-summary block — carries the - /// double border separating it from the body (gt's + /// A cell in the first row of a bottom-placed grand-summary block — + /// carries the double border separating the block from the body (gt's /// `gt_first_grand_summary_row`). GrandSummaryFirst, - /// A cell in the last row of the grand-summary block (gt's - /// `gt_last_grand_summary_row`). + /// A cell in the last row of a top-placed grand-summary block — carries + /// the double border separating the block from the body (gt's + /// `gt_last_grand_summary_row_top`). GrandSummaryLast, /// Left/center/right-aligned cell content (gt's /// `gt_left`/`gt_center`/`gt_right`). @@ -220,8 +221,8 @@ impl TableClass { TableClass::RowGroupFirst, TableClass::SummaryRow, TableClass::GroupSummary, - TableClass::GroupSummaryFirst, - TableClass::GroupSummaryLast, + TableClass::SummaryFirst, + TableClass::SummaryLast, TableClass::GrandSummary, TableClass::GrandSummaryFirst, TableClass::GrandSummaryLast, @@ -256,8 +257,8 @@ impl std::fmt::Display for TableClass { TableClass::Heading => "heading", TableClass::SummaryRow => "summary_row", TableClass::GroupSummary => "group_summary", - TableClass::GroupSummaryFirst => "group_summary_first", - TableClass::GroupSummaryLast => "group_summary_last", + TableClass::SummaryFirst => "summary_first", + TableClass::SummaryLast => "summary_last", TableClass::GrandSummary => "grand_summary", TableClass::GrandSummaryFirst => "grand_summary_first", TableClass::GrandSummaryLast => "grand_summary_last", diff --git a/src/writer/html.rs b/src/writer/html.rs index 57eb0f07a..6d6719d8c 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -399,12 +399,12 @@ fn class_declarations(class: TableClass) -> &'static [(&'static str, &'static st ("padding-left", "5px"), ("padding-right", "5px"), ], - TableClass::GroupSummaryFirst => &[ + TableClass::SummaryFirst => &[ ("border-top-style", "solid"), ("border-top-width", "2px"), ("border-top-color", "#D3D3D3"), ], - TableClass::GroupSummaryLast => &[ + TableClass::SummaryLast => &[ ("padding-top", "8px"), ("padding-bottom", "8px"), ("padding-left", "5px"), @@ -428,12 +428,12 @@ fn class_declarations(class: TableClass) -> &'static [(&'static str, &'static st ("padding-left", "5px"), ("padding-right", "5px"), ("border-top-style", "double"), - ("border-top-width", "3px"), + ("border-top-width", "6px"), ("border-top-color", "#D3D3D3"), ], TableClass::GrandSummaryLast => &[ ("border-bottom-style", "double"), - ("border-bottom-width", "3px"), + ("border-bottom-width", "6px"), ("border-bottom-color", "#D3D3D3"), ], TableClass::AlignLeft => &[("text-align", "left")], From 0a1f956a9748a98e8d8d33ae323e2b33a6f66ec1 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 10:45:42 +0100 Subject: [PATCH 15/37] expand operations --- src/execute/table/summary.rs | 109 +++++++++++++++++++++++++++++++---- 1 file changed, 98 insertions(+), 11 deletions(-) diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 9e65d8ddb..d502d493a 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -2,8 +2,8 @@ //! data and prepares the frame for summary rows, `compute_summaries` runs //! the aggregate operations on it. //! -//! Only `mean` and `median` exist so far; the rest of `SUMMARY_OPERATIONS` -//! lands once the execution pipeline is wired end-to-end. +//! All of `SUMMARY_OPERATIONS` are folds over a column's values except +//! `count`, which is type-free and counts rows or non-null values. use std::collections::HashMap; use std::ops::Range; @@ -265,17 +265,64 @@ fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Res /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { + // `count` is type-free: rows when nulls propagate, non-null values when + // dropped. Unlike the numeric operations, nulls never make it NULL. + if operation.eq_ignore_ascii_case("count") { + let count = if drop_nulls { + array.len() - array.logical_null_count() + } else { + array.len() + }; + return Ok(Some(count as f64)); + } let values = numeric_values(array, operation, drop_nulls)?; let Some(values) = values else { return Ok(None); }; - match operation.to_ascii_lowercase().as_str() { - "mean" => Ok(Some(values.iter().sum::() / values.len() as f64)), - "median" => Ok(Some(quantile(values, 0.5))), - _ => Err(GgsqlError::InternalError(format!( - "SUMMARISE operation '{operation}' is not implemented" - ))), - } + let v = &values; + let n = v.len() as f64; + let result = match operation.to_ascii_lowercase().as_str() { + "sum" => v.iter().sum(), + "prod" => v.iter().product(), + "min" => min(v), + "max" => max(v), + "range" => max(v) - min(v), + "mid" => (min(v) + max(v)) / 2.0, + "mean" => v.iter().sum::() / n, + "geomean" => (v.iter().map(|x| x.ln()).sum::() / n).exp(), + "harmean" => n / v.iter().map(|x| 1.0 / x).sum::(), + "rms" => (v.iter().map(|x| x * x).sum::() / n).sqrt(), + "sdev" => variance(v).sqrt(), + "var" => variance(v), + "iqr" => quantile(values.clone(), 0.75) - quantile(values.clone(), 0.25), + "median" | "p50" => quantile(values.clone(), 0.5), + "p05" => quantile(values.clone(), 0.05), + "p10" => quantile(values.clone(), 0.10), + "p25" => quantile(values.clone(), 0.25), + "p75" => quantile(values.clone(), 0.75), + "p90" => quantile(values.clone(), 0.90), + "p95" => quantile(values.clone(), 0.95), + _ => { + return Err(GgsqlError::InternalError(format!( + "SUMMARISE operation '{operation}' is not implemented" + ))) + } + }; + Ok(Some(result)) +} + +/// Population variance, matching the plot stats' `VAR_POP`. +fn variance(values: &[f64]) -> f64 { + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|x| (x - mean).powi(2)).sum::() / values.len() as f64 +} + +fn min(values: &[f64]) -> f64 { + values.iter().fold(f64::INFINITY, |a, &b| a.min(b)) +} + +fn max(values: &[f64]) -> f64 { + values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b)) } /// Extract a column's values as f64. Returns `None` when the result should be @@ -359,9 +406,49 @@ mod tests { } #[test] - fn unimplemented_operation_is_rejected() { + fn unknown_operation_is_rejected() { let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0])); - assert!(summary_stat("geomean", &array, false).is_err()); + assert!(summary_stat("first", &array, false).is_err()); + } + + #[test] + fn count_is_type_free() { + let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None, Some("b")])); + assert_eq!(summary_stat("count", &strings, false).unwrap(), Some(3.0)); + assert_eq!(summary_stat("count", &strings, true).unwrap(), Some(2.0)); + } + + #[test] + fn count_of_an_empty_slice_is_zero() { + let array: ArrayRef = Arc::new(Float64Array::from(Vec::::new())); + assert_eq!(summary_stat("count", &array, false).unwrap(), Some(0.0)); + } + + fn stat(operation: &str, values: &[f64]) -> f64 { + let array: ArrayRef = Arc::new(Float64Array::from(values.to_vec())); + summary_stat(operation, &array, false).unwrap().unwrap() + } + + #[test] + fn numeric_operations() { + let v = &[1.0, 2.0, 3.0, 4.0]; + assert_eq!(stat("sum", v), 10.0); + assert_eq!(stat("prod", v), 24.0); + assert_eq!(stat("min", v), 1.0); + assert_eq!(stat("max", v), 4.0); + assert_eq!(stat("range", v), 3.0); + assert_eq!(stat("mid", v), 2.5); + assert_eq!(stat("mean", v), 2.5); + assert_eq!(stat("geomean", v), (24.0_f64).powf(0.25)); + assert_eq!(stat("harmean", v), 4.0 / (1.0 + 0.5 + 1.0 / 3.0 + 0.25)); + assert_eq!(stat("rms", v), ((1.0 + 4.0 + 9.0 + 16.0) / 4.0_f64).sqrt()); + assert_eq!(stat("sdev", v), 1.25_f64.sqrt()); + assert_eq!(stat("var", v), 1.25); + assert_eq!(stat("iqr", v), 1.5); + assert_eq!(stat("median", v), 2.5); + assert_eq!(stat("p50", v), 2.5); + assert!((stat("p05", v) - 1.15).abs() < 1e-12); + assert!((stat("p95", v) - 3.85).abs() < 1e-12); } fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { From b4384cfdacc67a53719668ba90440a4598c3bad9 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 11:30:54 +0100 Subject: [PATCH 16/37] adapt to zygos --- src/execute/table/layout.rs | 3 +-- src/execute/table/summary.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index c91c35788..b14019bf8 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -835,8 +835,7 @@ mod tests { wildcard: false, target: Some(ColumnSection::Stub), settings: Parameters::new(), - value_mapping: None, - value_template: None, + renaming: Default::default(), }; let mut table = Table::new(); table.formats = vec![stub("a"), stub("b")]; diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index d502d493a..1b2b92205 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -619,8 +619,7 @@ mod tests { wildcard: false, target: Some(ColumnSection::Stub), settings: Parameters::new(), - value_mapping: None, - value_template: None, + renaming: Default::default(), } } From 20389a4e6386b9d8734ee989853f9c2e3912eeff Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 12:10:49 +0100 Subject: [PATCH 17/37] apply format to summary cells --- src/execute/table/layout.rs | 2 +- src/execute/table/mod.rs | 2 +- src/execute/table/summary.rs | 167 ++++++++++++++++++++++++++++++++--- 3 files changed, 156 insertions(+), 15 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index b14019bf8..c2e3c685a 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -554,7 +554,7 @@ mod tests { let formats = setup_formats(&df, &table.formats, &spans)?; setup_summaries(&mut df, &formats, &table.summaries)?; let columns = setup_columns(&df, &spans, &labels, &formats, facet); - let computed = compute_summaries(&df, &rows, &table.summaries)?; + let computed = compute_summaries(&df, &rows, &table.summaries, &formats)?; let df = apply_formats(&df, &formats)?; build_cells(&df, columns, rows, &spans, &titles, facet, &computed) } diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 1f49a0f6d..8c43c20f3 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -88,7 +88,7 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result>, Vec); /// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. /// Chunks with no matching clauses are omitted. Placement within a chunk is /// the weavers' concern; they read each row's `top`. +/// +/// A summarised column's `FORMAT` renaming formats its summary value just +/// like the body cells. pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], summaries: &[Summary], + formats: &HashMap, ) -> Result> { if summaries.is_empty() { return Ok(Vec::new()); @@ -205,7 +210,11 @@ pub(super) fn compute_summaries( let rows = summaries .iter() .filter(|s| s.scope == scope) - .map(|summary| summary.new_row(df, &range)) + .map(|summary| { + let mut row = summary.new_row(df, &range)?; + format_summary_frame(&mut row.frame, summary, formats)?; + Ok(row) + }) .collect::>>()?; if !rows.is_empty() { out.push((key, rows)); @@ -261,6 +270,32 @@ fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Res DataFrame::new(columns) } +/// Apply each summarised column's `FORMAT` renaming to a one-row summary +/// frame, turning the formatted columns into display text — the same +/// treatment `apply_formats` gives the body cells, per value. +fn format_summary_frame( + frame: &mut DataFrame, + summary: &Summary, + formats: &HashMap, +) -> Result<()> { + for column in &summary.columns { + let Some(format) = formats.get(column) else { + continue; + }; + if format.renaming.rename_is_empty() && format.renaming.template().is_none() { + continue; + } + let array = frame.column(column)?.clone(); + let mut resolved = crate::format::resolve_column_values(&array, &format.renaming) + .map_err(GgsqlError::ValidationError)?; + let text = resolved + .remove(0) + .unwrap_or_else(|| value_to_string(&array, 0)); + *frame = frame.with_column(column, Arc::new(StringArray::from(vec![text])) as ArrayRef)?; + } + Ok(()) +} + /// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. @@ -484,8 +519,13 @@ mod tests { .unwrap(); let rows = body_rows(&[&[], &[], &[]]); - let computed = - compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["x"])]).unwrap(); + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &HashMap::new(), + ) + .unwrap(); assert_eq!(computed.len(), 1); let (key, rows) = &computed[0]; @@ -505,8 +545,13 @@ mod tests { // Two nested-facet groups, contiguous after setup_rows' reorder. let rows = body_rows(&[&[2, 0], &[2, 0], &[2, 1], &[2, 1]]); - let computed = - compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Group, &["x"])], + &HashMap::new(), + ) + .unwrap(); assert_eq!(computed.len(), 2); assert_eq!(computed[0].0, Some(vec![2, 0])); @@ -531,7 +576,7 @@ mod tests { }; let below = summary("median", SummaryScope::Group, &["x"]); - let computed = compute_summaries(&df, &rows, &[below, above]).unwrap(); + let computed = compute_summaries(&df, &rows, &[below, above], &HashMap::new()).unwrap(); let order: Vec<(Vec, &str, bool)> = computed .iter() @@ -566,7 +611,7 @@ mod tests { ..summary("mean", SummaryScope::Grand, &["x"]) }; - let computed = compute_summaries(&df, &rows, &[labelled]).unwrap(); + let computed = compute_summaries(&df, &rows, &[labelled], &HashMap::new()).unwrap(); assert_eq!(computed[0].1[0].label, "Average"); } @@ -579,8 +624,13 @@ mod tests { .unwrap(); let rows = body_rows(&[&[], &[]]); - let computed = - compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Group, &["x"])]).unwrap(); + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Group, &["x"])], + &HashMap::new(), + ) + .unwrap(); assert_eq!(computed.len(), 1); assert_eq!(computed[0].0, Some(vec![])); @@ -604,6 +654,7 @@ mod tests { &df, &rows, &[summary("mean", SummaryScope::Grand, &["x"]), drop], + &HashMap::new(), ) .unwrap(); @@ -623,6 +674,91 @@ mod tests { } } + fn renaming_format(renaming: zygos::LabelSpec) -> Format { + Format { + columns: Vec::new(), + wildcard: false, + target: None, + settings: Parameters::new(), + renaming, + } + } + + #[test] + fn a_columns_format_formats_its_summary_value() { + let df = crate::df! { + "x" => vec![1.0, 2.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut renaming = zygos::LabelSpec::new(); + renaming.set_template("${:num %.2f}"); + let formats = HashMap::from([("x".to_string(), renaming_format(renaming))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("x").unwrap()), + vec!["$1.50"] + ); + } + + #[test] + fn a_rename_applies_to_a_summary_value() { + let df = crate::df! { + "x" => vec![0.0, 0.0], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut renaming = zygos::LabelSpec::new(); + renaming.rename(zygos::Value::String("0".into()), "-"); + let formats = HashMap::from([("x".to_string(), renaming_format(renaming))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["x"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("x").unwrap()), + vec!["-"] + ); + } + + #[test] + fn a_renaming_formats_a_count_of_a_non_numeric_column() { + let df = crate::df! { + "text" => vec!["a", "b"], + } + .unwrap(); + let rows = body_rows(&[&[], &[]]); + let mut renaming = zygos::LabelSpec::new(); + renaming.set_template("[{}]"); + let formats = HashMap::from([("text".to_string(), renaming_format(renaming))]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("count", SummaryScope::Grand, &["text"])], + &formats, + ) + .unwrap(); + + assert_eq!( + column_to_strings(computed[0].1[0].frame.column("text").unwrap()), + vec!["[2]"] + ); + } + #[test] fn setup_adds_an_empty_label_column_when_no_stub_exists() { let mut df = crate::df! { @@ -699,7 +835,12 @@ mod tests { .unwrap(); let rows = body_rows(&[&[]]); - let result = compute_summaries(&df, &rows, &[summary("mean", SummaryScope::Grand, &["y"])]); + let result = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["y"])], + &HashMap::new(), + ); assert!(result.is_err()); } } From 71e7c37e5d04d635abd26a7ef79a2699ab267c29 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 13:11:49 +0100 Subject: [PATCH 18/37] wire up summary templates --- src/execute/table/layout.rs | 6 ++- src/execute/table/summary.rs | 24 +++++++---- src/lib.rs | 2 +- src/parser/builder.rs | 43 +++++++++++++++---- src/table/mod.rs | 2 +- src/table/summary.rs | 55 ++++++++++++++++++++----- tree-sitter-ggsql/grammar.js | 5 ++- tree-sitter-ggsql/test/corpus/basic.txt | 26 ++++++++++++ 8 files changed, 129 insertions(+), 34 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index c2e3c685a..30261d1eb 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -513,7 +513,9 @@ mod tests { use super::*; use crate::df; use crate::plot::{ParameterValue, Parameters}; - use crate::table::{extract_table_titles, Summary, SummaryScope, TableCellKind}; + use crate::table::{ + extract_table_titles, Summary, SummaryOperation, SummaryScope, TableCellKind, + }; use crate::{ColumnSection, GgsqlError, Spanner, Table}; /// Runs the same steps `resolve_table_with_reader` does, minus the @@ -561,7 +563,7 @@ mod tests { fn summary_clause(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { Summary { - operation: operation.to_string(), + operation: SummaryOperation::Stat(operation.to_string()), scope, columns: columns.iter().map(|c| c.to_string()).collect(), settings: Parameters::new(), diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 34eb2d5a6..1f76f9ee5 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -15,7 +15,9 @@ use arrow::datatypes::DataType; use crate::array_util::{as_f64, cast_array, column_to_strings, value_to_string}; use crate::naming; use crate::params::ParameterValue; -use crate::table::{Format, Summary, SummaryScope, TableCell, TableClass, TableColumn, TableRow}; +use crate::table::{ + Format, Summary, SummaryOperation, SummaryScope, TableCell, TableClass, TableColumn, TableRow, +}; use crate::{ColumnSection, DataFrame, GgsqlError, Result}; /// Validate `summaries` against the data and prepare the frame for summary @@ -231,7 +233,7 @@ impl Summary { .settings .get("rowlabel") .and_then(ParameterValue::as_str) - .map_or_else(|| self.operation.clone(), str::to_string); + .map_or_else(|| self.operation.to_string(), str::to_string); Ok(SummaryRow { scope: self.scope, top: ParameterValue::is_str(self.settings.get("place"), "top"), @@ -256,11 +258,17 @@ fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Res summary.operation )) })?; - let value = summary_stat( - &summary.operation, - &array.slice(range.start, range.len()), - drop_nulls, - )?; + let value = match &summary.operation { + SummaryOperation::Stat(name) => { + summary_stat(name, &array.slice(range.start, range.len()), drop_nulls)? + } + SummaryOperation::Template(_) => { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {}: template summaries are not supported yet", + summary.operation + ))) + } + }; Ok(( column.clone(), Arc::new(Float64Array::from(vec![value])) as ArrayRef, @@ -488,7 +496,7 @@ mod tests { fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { Summary { - operation: operation.to_string(), + operation: SummaryOperation::Stat(operation.to_string()), scope, columns: columns.iter().map(|c| c.to_string()).collect(), settings: Parameters::new(), diff --git a/src/lib.rs b/src/lib.rs index 7fe6c63ea..3531dd208 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,7 +75,7 @@ pub use plot::{ // Re-export the parse-time Plot/Table result and the Table stub pub use spec::Spec; -pub use table::{ColumnSection, Format, SelectionItem, Spanner, Summary, SummaryScope, Table}; +pub use table::{ColumnSection, Format, SelectionItem, Spanner, Summary, Table}; // Re-export aesthetic classification utilities pub use plot::aesthetic::{ diff --git a/src/parser/builder.rs b/src/parser/builder.rs index 59eab4562..34b14e036 100644 --- a/src/parser/builder.rs +++ b/src/parser/builder.rs @@ -8,10 +8,8 @@ use crate::plot::layer::geom::Geom; use crate::plot::projection::resolve_coord; use crate::plot::scale::{color_to_hex, is_color_aesthetic, is_user_facet_aesthetic, Transform}; use crate::plot::*; -use crate::{ - ColumnSection, Format, GgsqlError, Result, SelectionItem, Spanner, Spec, Summary, SummaryScope, - Table, -}; +use crate::table::*; +use crate::{GgsqlError, Result, Spec}; use std::collections::HashMap; use tree_sitter::Node; @@ -529,7 +527,10 @@ fn build_summarise_clause(node: &Node, source: &SourceTree) -> Result { let operation_node = node.child_by_field_name("operation").ok_or_else(|| { GgsqlError::ParseError("Missing operation in SUMMARISE clause".to_string()) })?; - let operation = naming::unquote_ident(&source.get_text(&operation_node)); + let operation = match operation_node.kind() { + "string" => SummaryOperation::Template(parse_string_node(&operation_node, source)), + _ => SummaryOperation::Stat(naming::unquote_ident(&source.get_text(&operation_node))), + }; let scope = match node.child_by_field_name("scope") { Some(scope_node) => match source.get_text(&scope_node).to_lowercase().as_str() { @@ -1855,7 +1856,10 @@ mod tests { let table = specs[0].as_table().expect("expected a Table spec"); assert_eq!(table.summaries.len(), 1); - assert_eq!(table.summaries[0].operation, "mean"); + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("mean".to_string()) + ); assert_eq!(table.summaries[0].scope, SummaryScope::Group); assert_eq!(table.summaries[0].columns, vec!["foo", "bar"]); assert!(table.summaries[0].settings.is_empty()); @@ -1881,7 +1885,22 @@ mod tests { let specs = parse_test_specs("TABULATE * FROM sales SUMMARIZE MEAN OF foo").unwrap(); let table = specs[0].as_table().expect("expected a Table spec"); - assert_eq!(table.summaries[0].operation, "MEAN"); + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("MEAN".to_string()) + ); + } + + #[test] + fn test_tabulate_summarise_template_operation() { + let specs = + parse_test_specs("TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev}' OF foo").unwrap(); + let table = specs[0].as_table().expect("expected a Table spec"); + + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Template("{mean} +/- {sdev}".to_string()) + ); } #[test] @@ -1893,9 +1912,15 @@ mod tests { let table = specs[0].as_table().expect("expected a Table spec"); assert_eq!(table.summaries.len(), 2); - assert_eq!(table.summaries[0].operation, "mean"); + assert_eq!( + table.summaries[0].operation, + SummaryOperation::Stat("mean".to_string()) + ); assert_eq!(table.summaries[0].scope, SummaryScope::Group); - assert_eq!(table.summaries[1].operation, "max"); + assert_eq!( + table.summaries[1].operation, + SummaryOperation::Stat("max".to_string()) + ); assert_eq!(table.summaries[1].scope, SummaryScope::Grand); assert_eq!(table.summaries[1].columns, vec!["foo", "bar"]); } diff --git a/src/table/mod.rs b/src/table/mod.rs index 2b581c515..4bfadd737 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -21,7 +21,7 @@ pub(crate) use layout::{ pub use layout::{TableCell, TableCellKind, TableClass, TableColumn, TableLayout, TableRow}; pub use spanner::Spanner; pub(crate) use spanner::{create_spanners, reorder_table_columns}; -pub use summary::{Summary, SummaryScope, SUMMARY_OPERATIONS}; +pub use summary::{Summary, SummaryOperation, SummaryScope, SUMMARY_OPERATIONS}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; diff --git a/src/table/summary.rs b/src/table/summary.rs index dc6c68e2b..52cdb07ce 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -8,10 +8,8 @@ use crate::params::{DefaultParamValue, ParamConstraint, ParamDefinition, Paramet /// per group — or a single row over all rows for `GRAND`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Summary { - /// The aggregate operation (e.g. `mean`), verbatim as written — it doubles - /// as the default row label. Matching against the operation vocabulary is - /// case-insensitive at execution time. - pub operation: String, + /// The aggregate operation, verbatim as written. + pub operation: SummaryOperation, /// Which rows the operation aggregates over. pub scope: SummaryScope, /// The columns to summarise, in the order written. @@ -21,6 +19,29 @@ pub struct Summary { pub settings: Parameters, } +/// What a `SUMMARISE` clause computes per column: either one named stat, or +/// a template whose `{stat}` placeholders are each evaluated and interpolated +/// into the cell text. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SummaryOperation { + /// A bare stat name (e.g. `mean`) — it doubles as the default row label. + /// Matching against the operation vocabulary is case-insensitive at + /// execution time. + Stat(String), + /// A template literal (e.g. `{mean} +/- {sdev}`), placeholders intact. + Template(String), +} + +impl std::fmt::Display for SummaryOperation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SummaryOperation::Stat(name) => write!(f, "{name}"), + SummaryOperation::Template(template) => write!(f, "'{template}'"), + } + } +} + /// Which rows a `SUMMARISE` clause aggregates over. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -65,17 +86,22 @@ const SUMMARY_PARAMS: &[ParamDefinition] = &[ ]; impl Summary { - /// Validate `operation` against `SUMMARY_OPERATIONS`, case-insensitively. + /// Validate a `Stat` operation against `SUMMARY_OPERATIONS`, + /// case-insensitively. A `Template` is not checked against the + /// vocabulary here. pub fn validate_operation(&self) -> Result<(), String> { + let SummaryOperation::Stat(name) = &self.operation else { + return Ok(()); + }; if SUMMARY_OPERATIONS .iter() - .any(|op| self.operation.eq_ignore_ascii_case(op)) + .any(|op| name.eq_ignore_ascii_case(op)) { Ok(()) } else { Err(format!( "Unknown operation '{}'. Valid operations: {}", - self.operation, + name, crate::or_list_quoted(SUMMARY_OPERATIONS, '\'') )) } @@ -95,7 +121,7 @@ mod tests { fn summary_with_settings(settings: Parameters) -> Summary { Summary { - operation: "mean".to_string(), + operation: SummaryOperation::Stat("mean".to_string()), scope: SummaryScope::Group, columns: vec!["a".to_string()], settings, @@ -139,16 +165,23 @@ mod tests { .validate_operation() .is_ok()); let mut summary = summary_with_settings(Parameters::new()); - summary.operation = "MEAN".to_string(); + summary.operation = SummaryOperation::Stat("MEAN".to_string()); assert!(summary.validate_operation().is_ok()); } #[test] fn summary_validate_operation_rejects_unknown_and_positional() { let mut summary = summary_with_settings(Parameters::new()); - summary.operation = "meen".to_string(); + summary.operation = SummaryOperation::Stat("meen".to_string()); assert!(summary.validate_operation().is_err()); - summary.operation = "first".to_string(); + summary.operation = SummaryOperation::Stat("first".to_string()); assert!(summary.validate_operation().is_err()); } + + #[test] + fn summary_validate_operation_passes_a_template() { + let mut summary = summary_with_settings(Parameters::new()); + summary.operation = SummaryOperation::Template("{meen}".to_string()); + assert!(summary.validate_operation().is_ok()); + } } diff --git a/tree-sitter-ggsql/grammar.js b/tree-sitter-ggsql/grammar.js index d97d17249..d77f15e86 100644 --- a/tree-sitter-ggsql/grammar.js +++ b/tree-sitter-ggsql/grammar.js @@ -722,11 +722,12 @@ module.exports = grammar({ // SUMMARISE — adds aggregate rows to the table. One clause per operation; // clauses repeat like FORMAT, each contributing its own summary row(s). // GROUP (default) summarises within each facet group, GRAND over all rows. - // The operation is a plain identifier; validity is checked downstream. + // The operation is a plain identifier (a stat name) or a string template + // with {stat} placeholders; validity is checked downstream. summarise_clause: $ => seq( choice(caseInsensitive('SUMMARISE'), caseInsensitive('SUMMARIZE')), optional(field('scope', $.summarise_scope)), - field('operation', $.identifier), + field('operation', choice($.identifier, $.string)), caseInsensitive('OF'), $.column_list, optional($.setting_clause) diff --git a/tree-sitter-ggsql/test/corpus/basic.txt b/tree-sitter-ggsql/test/corpus/basic.txt index 4e6941e86..9fdfa5ba6 100644 --- a/tree-sitter-ggsql/test/corpus/basic.txt +++ b/tree-sitter-ggsql/test/corpus/basic.txt @@ -5159,6 +5159,32 @@ TABULATE * FROM sales SUMMARISE GRAND sdev OF foo SETTING place => 'top' value: (parameter_value (string)))))))) +================================================================================ +TABULATE SUMMARISE template operation +================================================================================ + +TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev}' OF foo + +-------------------------------------------------------------------------------- + +(query + (tabulate_statement + (tabulate_keyword) + (column_selection + (mapping_list + (mapping_element + (wildcard_mapping)))) + (single_source_from + source: (qualified_name + (identifier + (bare_identifier)))) + (tab_clause + (summarise_clause + operation: (string) + (column_list + (identifier + (bare_identifier))))))) + ================================================================================ TABULATE SUMMARIZE spelling alias ================================================================================ From bff2c6cf150f3c12563fbb18184856a396b23b61 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 13:39:54 +0100 Subject: [PATCH 19/37] parsing/validation of template --- src/table/summary.rs | 205 +++++++++++++++++++++++++++++++++++-------- src/validate.rs | 27 +++++- 2 files changed, 194 insertions(+), 38 deletions(-) diff --git a/src/table/summary.rs b/src/table/summary.rs index 52cdb07ce..55f1c73c2 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -42,6 +42,101 @@ impl std::fmt::Display for SummaryOperation { } } +impl SummaryOperation { + /// Validate against `SUMMARY_OPERATIONS`, case-insensitively: a `Stat` + /// directly, a `Template`'s placeholders one by one. + pub fn validate(&self) -> Result<(), String> { + let unknown = |name: &str| { + format!( + "Unknown operation '{}'. Valid operations: {}", + name, + crate::or_list_quoted(SUMMARY_OPERATIONS, '\'') + ) + }; + let known = |name: &str| { + SUMMARY_OPERATIONS + .iter() + .any(|op| name.eq_ignore_ascii_case(op)) + }; + match self { + SummaryOperation::Stat(name) if !known(name) => Err(unknown(name)), + SummaryOperation::Stat(_) => Ok(()), + SummaryOperation::Template(template) => { + for segment in parse_template(template)? { + if let TemplateSegment::Stat { name, .. } = segment { + if !known(&name) { + return Err(unknown(&name)); + } + } + } + Ok(()) + } + } + } +} + +/// One piece of a `SUMMARISE` template: literal text, or a `{name:spec}` +/// placeholder naming a stat to evaluate and interpolate. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum TemplateSegment { + /// Text copied to the cell verbatim. + Literal(String), + /// A `{name}` or `{name:spec}` placeholder. `spec` is the zygos label + /// spec with the `%`-sugar already expanded (`{sd:%.1f}` stores + /// `num %.1f`). + Stat { name: String, spec: Option }, +} + +/// Split a template literal into text and placeholder segments. `{` opens a +/// placeholder and must be terminated and non-empty; `}` outside a +/// placeholder is literal text. Matching against `SUMMARY_OPERATIONS` happens +/// in [`SummaryOperation::validate`], not here. +pub(crate) fn parse_template(template: &str) -> Result, String> { + let mut segments = Vec::new(); + let mut literal = String::new(); + let mut rest = template; + while let Some(open) = rest.find('{') { + literal.push_str(&rest[..open]); + rest = &rest[open + 1..]; + let Some(close) = rest.find('}') else { + return Err(format!("Missing '}}' in SUMMARISE template '{template}'")); + }; + let placeholder = rest[..close].trim(); + rest = &rest[close + 1..]; + if !literal.is_empty() { + segments.push(TemplateSegment::Literal(std::mem::take(&mut literal))); + } + if placeholder.is_empty() { + return Err(format!("Empty '{{}}' in SUMMARISE template '{template}'")); + } + let (name, spec) = match placeholder.split_once(':') { + Some((name, spec)) => (name.trim(), Some(spec.trim())), + None => (placeholder, None), + }; + if name.is_empty() { + return Err(format!( + "Missing operation name before ':' in SUMMARISE template '{template}'" + )); + } + segments.push(TemplateSegment::Stat { + name: name.to_string(), + spec: spec.map(|spec| { + // `{sd:%.1f}` is sugar for `{sd:num %.1f}`. + if let Some(printf) = spec.strip_prefix('%') { + format!("num %{printf}") + } else { + spec.to_string() + } + }), + }); + } + literal.push_str(rest); + if !literal.is_empty() { + segments.push(TemplateSegment::Literal(literal)); + } + Ok(segments) +} + /// Which rows a `SUMMARISE` clause aggregates over. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -86,27 +181,6 @@ const SUMMARY_PARAMS: &[ParamDefinition] = &[ ]; impl Summary { - /// Validate a `Stat` operation against `SUMMARY_OPERATIONS`, - /// case-insensitively. A `Template` is not checked against the - /// vocabulary here. - pub fn validate_operation(&self) -> Result<(), String> { - let SummaryOperation::Stat(name) = &self.operation else { - return Ok(()); - }; - if SUMMARY_OPERATIONS - .iter() - .any(|op| name.eq_ignore_ascii_case(op)) - { - Ok(()) - } else { - Err(format!( - "Unknown operation '{}'. Valid operations: {}", - name, - crate::or_list_quoted(SUMMARY_OPERATIONS, '\'') - )) - } - } - /// Validate `settings` against `SUMMARY_PARAMS` and resolve each to its /// effective value: the user's value if present, otherwise the /// definition's default. @@ -160,28 +234,85 @@ mod tests { } #[test] - fn summary_validate_operation_accepts_case_insensitively() { - assert!(summary_with_settings(Parameters::new()) - .validate_operation() + fn summary_operation_validate_accepts_case_insensitively() { + assert!(SummaryOperation::Stat("mean".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Stat("MEAN".to_string()) + .validate() .is_ok()); - let mut summary = summary_with_settings(Parameters::new()); - summary.operation = SummaryOperation::Stat("MEAN".to_string()); - assert!(summary.validate_operation().is_ok()); } #[test] - fn summary_validate_operation_rejects_unknown_and_positional() { - let mut summary = summary_with_settings(Parameters::new()); - summary.operation = SummaryOperation::Stat("meen".to_string()); - assert!(summary.validate_operation().is_err()); - summary.operation = SummaryOperation::Stat("first".to_string()); - assert!(summary.validate_operation().is_err()); + fn summary_operation_validate_rejects_unknown_and_positional() { + assert!(SummaryOperation::Stat("meen".to_string()) + .validate() + .is_err()); + assert!(SummaryOperation::Stat("first".to_string()) + .validate() + .is_err()); + } + + #[test] + fn summary_operation_validate_checks_a_templates_placeholders() { + assert!(SummaryOperation::Template("{mean} +/- {SDEV}".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Template("{mean} +/- {meen}".to_string()) + .validate() + .is_err()); + } + + #[test] + fn parse_template_splits_literals_and_stats() { + let segments = parse_template("{mean} +/- {sdev:num %.3f} (n={count})").unwrap(); + assert_eq!( + segments, + vec![ + TemplateSegment::Stat { + name: "mean".to_string(), + spec: None + }, + TemplateSegment::Literal(" +/- ".to_string()), + TemplateSegment::Stat { + name: "sdev".to_string(), + spec: Some("num %.3f".to_string()) + }, + TemplateSegment::Literal(" (n=".to_string()), + TemplateSegment::Stat { + name: "count".to_string(), + spec: None + }, + TemplateSegment::Literal(")".to_string()), + ] + ); + } + + #[test] + fn parse_template_expands_the_printf_sugar() { + let segments = parse_template("{sd:%.1f}").unwrap(); + assert_eq!( + segments, + vec![TemplateSegment::Stat { + name: "sd".to_string(), + spec: Some("num %.1f".to_string()) + }] + ); + } + + #[test] + fn parse_template_treats_a_stray_close_brace_as_literal() { + let segments = parse_template("a } b").unwrap(); + assert_eq!( + segments, + vec![TemplateSegment::Literal("a } b".to_string())] + ); } #[test] - fn summary_validate_operation_passes_a_template() { - let mut summary = summary_with_settings(Parameters::new()); - summary.operation = SummaryOperation::Template("{meen}".to_string()); - assert!(summary.validate_operation().is_ok()); + fn parse_template_rejects_unterminated_and_empty_placeholders() { + assert!(parse_template("{mean").is_err()); + assert!(parse_template("{}").is_err()); + assert!(parse_template("{:num}").is_err()); } } diff --git a/src/validate.rs b/src/validate.rs index 33b3797a7..441cf4ec6 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -352,7 +352,7 @@ pub fn validate(query: &str) -> Result { // And each SUMMARISE's operation and SETTING parameters. for (idx, summary) in table.summaries.iter().enumerate() { - if let Err(e) = summary.validate_operation() { + if let Err(e) = summary.operation.validate() { errors.push(ValidationError { message: format!("SUMMARISE {}: {}", idx + 1, e), location: None, @@ -462,6 +462,31 @@ mod tests { assert!(!validated.valid()); } + #[test] + fn test_validate_summarise_accepts_a_template_with_known_stats() { + let validated = + validate("TABULATE * FROM sales SUMMARISE '{mean:num %.2f} +/- {SDEV}' OF foo") + .unwrap(); + assert!(validated.valid()); + } + + #[test] + fn test_validate_summarise_rejects_a_template_with_an_unknown_stat() { + let validated = + validate("TABULATE * FROM sales SUMMARISE '{mean} of {meen}' OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0] + .message + .contains("SUMMARISE 1: Unknown operation 'meen'")); + } + + #[test] + fn test_validate_summarise_rejects_a_malformed_template() { + let validated = validate("TABULATE * FROM sales SUMMARISE '{mean' OF foo").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.contains("Missing '}'")); + } + #[test] fn test_validate_summarise_rejects_a_bad_setting() { let validated = From 8ff5df917deee5c7066d3db4168dd49ae6df2922 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 14:22:05 +0100 Subject: [PATCH 20/37] compute templates --- src/execute/table/mod.rs | 79 ++++++++++++++++ src/execute/table/summary.rs | 170 ++++++++++++++++++++++------------- src/table/mod.rs | 1 + src/table/summary.rs | 120 ++++++++++++++++--------- 4 files changed, 266 insertions(+), 104 deletions(-) diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 8c43c20f3..d0282e4bc 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -955,6 +955,85 @@ mod integration_tests { assert_eq!(value.content, "2"); } + #[test] + fn test_tabulate_summarise_template_renders_stats_and_strips_the_default_label() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{mean} +/- {sdev:num %.2f}' OF id", + &reader, + ) + .unwrap(); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel) + .unwrap(); + assert_eq!(label.content, "mean +/- sdev"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.left == label.right + 1) + .unwrap(); + assert_eq!(value.content, "2 +/- 0.82"); + } + + #[test] + fn test_tabulate_summarise_template_expands_the_printf_sugar() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{sdev:%.2f}' OF id", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "0.82"); + } + + #[test] + fn test_tabulate_summarise_template_ignores_the_column_format() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales FORMAT id RENAMING * => '[{}]' SUMMARISE '{mean}' OF id", + &reader, + ) + .unwrap(); + + // Templates self-format; a naked operation would take the renaming + // and render "[2]". + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "2"); + } + + #[test] + fn test_tabulate_summarise_template_renders_a_null_stat_as_null() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "null of 2"); + } + #[test] fn test_tabulate_summarise_separated_facet_rekeys_the_summary_chunks() { let reader = reader_with_region_sales(); diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 1f76f9ee5..1bc127975 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -16,7 +16,8 @@ use crate::array_util::{as_f64, cast_array, column_to_strings, value_to_string}; use crate::naming; use crate::params::ParameterValue; use crate::table::{ - Format, Summary, SummaryOperation, SummaryScope, TableCell, TableClass, TableColumn, TableRow, + parse_template, Format, Summary, SummaryOperation, SummaryScope, TableCell, TableClass, + TableColumn, TableRow, TemplateSegment, }; use crate::{ColumnSection, DataFrame, GgsqlError, Result}; @@ -67,8 +68,8 @@ pub(super) struct SummaryRow { /// The row's stub label: `rowlabel`, else the operation name. pub label: String, /// One-row frame of the computed values; its schema names the - /// summarised columns. Numeric unless the column's `FORMAT` renaming - /// stringified it. + /// summarised columns. Numeric for a bare operation (unless the + /// column's `FORMAT` renaming stringified it), string for a template. pub frame: DataFrame, } @@ -182,8 +183,8 @@ pub(super) type SummaryChunk = (Option>, Vec); /// Chunks with no matching clauses are omitted. Placement within a chunk is /// the weavers' concern; they read each row's `top`. /// -/// A summarised column's `FORMAT` renaming formats its summary value just -/// like the body cells. +/// A bare operation's summary value takes its column's `FORMAT` renaming +/// just like the body cells; a template self-formats via zygos. pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], @@ -194,58 +195,79 @@ pub(super) fn compute_summaries( return Ok(Vec::new()); } // Chunks the clauses emit into: one contiguous range per group, then one - // range over all rows for the GRAND clauses. - let mut chunks: Vec<(Option>, Range)> = Vec::new(); + // range over all rows for the GRAND clauses. Each accumulates its rows. + struct Chunk { + key: Option>, + range: Range, + rows: Vec, + } + let mut chunks: Vec = Vec::new(); let mut start = 0; for chunk in rows.chunk_by(|a, b| a.group == b.group) { - chunks.push((Some(chunk[0].group.clone()), start..start + chunk.len())); + chunks.push(Chunk { + key: Some(chunk[0].group.clone()), + range: start..start + chunk.len(), + rows: Vec::new(), + }); start += chunk.len(); } - chunks.push((None, 0..rows.len())); + chunks.push(Chunk { + key: None, + range: 0..rows.len(), + rows: Vec::new(), + }); - let mut out = Vec::new(); - for (key, range) in chunks { - let scope = match key { - Some(_) => SummaryScope::Group, - None => SummaryScope::Grand, + // Clause-outer: the label, placement and parsed template are clause-level + // facts, computed once and shared by every group's row. + for summary in summaries { + let template = match &summary.operation { + SummaryOperation::Template(template) => { + Some(parse_template(template).map_err(GgsqlError::ValidationError)?) + } + SummaryOperation::Stat(_) => None, }; - let rows = summaries - .iter() - .filter(|s| s.scope == scope) - .map(|summary| { - let mut row = summary.new_row(df, &range)?; - format_summary_frame(&mut row.frame, summary, formats)?; - Ok(row) - }) - .collect::>>()?; - if !rows.is_empty() { - out.push((key, rows)); - } - } - Ok(out) -} - -impl Summary { - /// Build this clause's row over `range`: placement, label and computed - /// values. - pub(super) fn new_row(&self, df: &DataFrame, range: &Range) -> Result { - let label = self + let label = summary .settings .get("rowlabel") .and_then(ParameterValue::as_str) - .map_or_else(|| self.operation.to_string(), str::to_string); - Ok(SummaryRow { - scope: self.scope, - top: ParameterValue::is_str(self.settings.get("place"), "top"), - label, - frame: summary_frame(df, self, range)?, - }) + .map_or_else(|| summary.operation.as_label(), str::to_string); + let top = ParameterValue::is_str(summary.settings.get("place"), "top"); + let targets = match summary.scope { + SummaryScope::Group => 0..chunks.len() - 1, + SummaryScope::Grand => chunks.len() - 1..chunks.len(), + }; + for index in targets { + let chunk = &mut chunks[index]; + let mut frame = summary_frame(df, summary, template.as_deref(), &chunk.range)?; + // Templates self-format; a bare operation takes the column's + // FORMAT renaming. + if template.is_none() { + format_summary_frame(&mut frame, &summary.columns, formats)?; + } + chunk.rows.push(SummaryRow { + scope: summary.scope, + top, + label: label.clone(), + frame, + }); + } } + Ok(chunks + .into_iter() + .filter_map(|chunk| (!chunk.rows.is_empty()).then_some((chunk.key, chunk.rows))) + .collect()) } -/// Compute one clause's frame over the rows in `range`: one row, one -/// nullable-f64 column per summarised column. -fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Result { +/// Compute one clause's frame over the rows in `range`: one row, one column +/// per summarised column. A bare operation yields a nullable-f64 column; a +/// template (`Some` segments, which `compute_summaries` supplies for every +/// template clause) a string column with the template rendered against it. +fn summary_frame( + df: &DataFrame, + summary: &Summary, + template: Option<&[TemplateSegment]>, + range: &Range, +) -> Result { let drop_nulls = ParameterValue::is_str(summary.settings.get("missing"), "drop"); let columns = summary @@ -258,35 +280,63 @@ fn summary_frame(df: &DataFrame, summary: &Summary, range: &Range) -> Res summary.operation )) })?; - let value = match &summary.operation { - SummaryOperation::Stat(name) => { - summary_stat(name, &array.slice(range.start, range.len()), drop_nulls)? - } - SummaryOperation::Template(_) => { - return Err(GgsqlError::ValidationError(format!( - "SUMMARISE {}: template summaries are not supported yet", - summary.operation - ))) + let slice = array.slice(range.start, range.len()); + let cell: ArrayRef = match template { + Some(segments) => Arc::new(StringArray::from(vec![render_template( + segments, &slice, drop_nulls, + )?])), + None => { + let SummaryOperation::Stat(name) = &summary.operation else { + unreachable!("compute_summaries parses every template clause") + }; + Arc::new(Float64Array::from(vec![summary_stat( + name, &slice, drop_nulls, + )?])) } }; - Ok(( - column.clone(), - Arc::new(Float64Array::from(vec![value])) as ArrayRef, - )) + Ok((column.clone(), cell)) }) .collect::>>()?; DataFrame::new(columns) } +/// Render a template against one column's slice: literals verbatim, each +/// placeholder's stat computed over the slice and rendered through its +/// pre-compiled zygos template. A NULL stat renders as the literal "null", +/// like the body cells. +fn render_template( + segments: &[TemplateSegment], + slice: &ArrayRef, + drop_nulls: bool, +) -> Result { + let mut text = String::new(); + for segment in segments { + match segment { + TemplateSegment::Literal(literal) => text.push_str(literal), + TemplateSegment::Stat { name, template } => { + match summary_stat(name, slice, drop_nulls)? { + Some(value) => text.push_str( + &template + .format(&zygos::Value::Number(value), None) + .unwrap_or_default(), + ), + None => text.push_str("null"), + } + } + } + } + Ok(text) +} + /// Apply each summarised column's `FORMAT` renaming to a one-row summary /// frame, turning the formatted columns into display text — the same /// treatment `apply_formats` gives the body cells, per value. fn format_summary_frame( frame: &mut DataFrame, - summary: &Summary, + columns: &[String], formats: &HashMap, ) -> Result<()> { - for column in &summary.columns { + for column in columns { let Some(format) = formats.get(column) else { continue; }; diff --git a/src/table/mod.rs b/src/table/mod.rs index 4bfadd737..503324380 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -21,6 +21,7 @@ pub(crate) use layout::{ pub use layout::{TableCell, TableCellKind, TableClass, TableColumn, TableLayout, TableRow}; pub use spanner::Spanner; pub(crate) use spanner::{create_spanners, reorder_table_columns}; +pub(crate) use summary::{parse_template, TemplateSegment}; pub use summary::{Summary, SummaryOperation, SummaryScope, SUMMARY_OPERATIONS}; use serde::{Deserialize, Serialize}; diff --git a/src/table/summary.rs b/src/table/summary.rs index 55f1c73c2..03b9cb3d7 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -43,6 +43,27 @@ impl std::fmt::Display for SummaryOperation { } impl SummaryOperation { + /// The default row label: a `Stat`'s name; a `Template`'s literal text + /// with each placeholder reduced to its bare operation name + /// (`{mean:num %.2f} +/- {sdev}` becomes `mean +/- sdev`). + pub(crate) fn as_label(&self) -> String { + match self { + SummaryOperation::Stat(name) => name.clone(), + // A template that reaches here unparseable keeps its raw text; + // execution parses (and errors) before building any label. + SummaryOperation::Template(template) => match parse_template(template) { + Ok(segments) => segments + .iter() + .map(|segment| match segment { + TemplateSegment::Literal(text) => text.as_str(), + TemplateSegment::Stat { name, .. } => name.as_str(), + }) + .collect(), + Err(_) => template.clone(), + }, + } + } + /// Validate against `SUMMARY_OPERATIONS`, case-insensitively: a `Stat` /// directly, a `Template`'s placeholders one by one. pub fn validate(&self) -> Result<(), String> { @@ -77,14 +98,17 @@ impl SummaryOperation { /// One piece of a `SUMMARISE` template: literal text, or a `{name:spec}` /// placeholder naming a stat to evaluate and interpolate. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone)] pub(crate) enum TemplateSegment { /// Text copied to the cell verbatim. Literal(String), - /// A `{name}` or `{name:spec}` placeholder. `spec` is the zygos label - /// spec with the `%`-sugar already expanded (`{sd:%.1f}` stores - /// `num %.1f`). - Stat { name: String, spec: Option }, + /// A `{name}` or `{name:spec}` placeholder, its zygos template + /// pre-compiled: `{:spec}`, or `{}` without a spec. The `%`-sugar is + /// already expanded (`{sd:%.1f}` compiles `{:num %.1f}`). + Stat { + name: String, + template: zygos::Template, + }, } /// Split a template literal into text and placeholder segments. `{` opens a @@ -118,16 +142,15 @@ pub(crate) fn parse_template(template: &str) -> Result, Str "Missing operation name before ':' in SUMMARISE template '{template}'" )); } + // `{sd:%.1f}` is sugar for `{sd:num %.1f}`. + let source = match spec { + Some(spec) if spec.starts_with('%') => format!("{{:num {spec}}}"), + Some(spec) => format!("{{:{spec}}}"), + None => "{}".to_string(), + }; segments.push(TemplateSegment::Stat { name: name.to_string(), - spec: spec.map(|spec| { - // `{sd:%.1f}` is sugar for `{sd:num %.1f}`. - if let Some(printf) = spec.strip_prefix('%') { - format!("num %{printf}") - } else { - spec.to_string() - } - }), + template: zygos::Template::parse(&source), }); } literal.push_str(rest); @@ -264,49 +287,58 @@ mod tests { } #[test] - fn parse_template_splits_literals_and_stats() { - let segments = parse_template("{mean} +/- {sdev:num %.3f} (n={count})").unwrap(); + fn summary_operation_as_label_strips_a_templates_specs() { + assert_eq!( + SummaryOperation::Template("{mean:num %.2f} +/- {sdev}".to_string()).as_label(), + "mean +/- sdev" + ); assert_eq!( - segments, - vec![ - TemplateSegment::Stat { - name: "mean".to_string(), - spec: None - }, - TemplateSegment::Literal(" +/- ".to_string()), - TemplateSegment::Stat { - name: "sdev".to_string(), - spec: Some("num %.3f".to_string()) - }, - TemplateSegment::Literal(" (n=".to_string()), - TemplateSegment::Stat { - name: "count".to_string(), - spec: None - }, - TemplateSegment::Literal(")".to_string()), - ] + SummaryOperation::Stat("MEAN".to_string()).as_label(), + "MEAN" ); } + #[test] + fn parse_template_splits_literals_and_stats() { + let segments = parse_template("{mean} +/- {sdev:num %.3f} (n={count})").unwrap(); + let stat = |index: usize| match &segments[index] { + TemplateSegment::Stat { name, template } => (name.as_str(), template.source()), + TemplateSegment::Literal(_) => panic!("segment {index} is a literal"), + }; + let literal = |index: usize| match &segments[index] { + TemplateSegment::Literal(text) => text.as_str(), + TemplateSegment::Stat { .. } => panic!("segment {index} is a stat"), + }; + + assert_eq!(segments.len(), 6); + assert_eq!(stat(0), ("mean", "{}")); + assert_eq!(literal(1), " +/- "); + assert_eq!(stat(2), ("sdev", "{:num %.3f}")); + assert_eq!(literal(3), " (n="); + assert_eq!(stat(4), ("count", "{}")); + assert_eq!(literal(5), ")"); + } + #[test] fn parse_template_expands_the_printf_sugar() { let segments = parse_template("{sd:%.1f}").unwrap(); - assert_eq!( - segments, - vec![TemplateSegment::Stat { - name: "sd".to_string(), - spec: Some("num %.1f".to_string()) - }] - ); + match &segments[0] { + TemplateSegment::Stat { name, template } => { + assert_eq!(name, "sd"); + assert_eq!(template.source(), "{:num %.1f}"); + } + TemplateSegment::Literal(_) => panic!("expected a stat segment"), + } } #[test] fn parse_template_treats_a_stray_close_brace_as_literal() { let segments = parse_template("a } b").unwrap(); - assert_eq!( - segments, - vec![TemplateSegment::Literal("a } b".to_string())] - ); + assert_eq!(segments.len(), 1); + match &segments[0] { + TemplateSegment::Literal(text) => assert_eq!(text, "a } b"), + TemplateSegment::Stat { .. } => panic!("expected a literal segment"), + } } #[test] From f7732dc22cab36eba2b209863003c5117e1fa01c Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 14:52:29 +0100 Subject: [PATCH 21/37] add extra operations --- src/execute/table/summary.rs | 88 ++++++++++++++++++++++++++++++------ src/table/summary.rs | 30 ++++++++++-- 2 files changed, 102 insertions(+), 16 deletions(-) diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 1bc127975..0c7f639d4 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -2,10 +2,10 @@ //! data and prepares the frame for summary rows, `compute_summaries` runs //! the aggregate operations on it. //! -//! All of `SUMMARY_OPERATIONS` are folds over a column's values except -//! `count`, which is type-free and counts rows or non-null values. +//! All of `SUMMARY_OPERATIONS` are folds over a column's numeric values +//! except the type-free tallies `count`, `n_distinct` and `n_missing`. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::sync::Arc; @@ -358,15 +358,21 @@ fn format_summary_frame( /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { - // `count` is type-free: rows when nulls propagate, non-null values when - // dropped. Unlike the numeric operations, nulls never make it NULL. - if operation.eq_ignore_ascii_case("count") { - let count = if drop_nulls { - array.len() - array.logical_null_count() - } else { - array.len() - }; - return Ok(Some(count as f64)); + // The type-free tallies bypass the numeric fold: `count` counts rows or + // non-null values, `n_missing` measures nulls so never goes NULL itself. + let op = operation.to_ascii_lowercase(); + match op.as_str() { + "count" => { + let count = if drop_nulls { + array.len() - array.logical_null_count() + } else { + array.len() + }; + return Ok(Some(count as f64)); + } + "n_missing" => return Ok(Some(array.logical_null_count() as f64)), + "n_distinct" => return n_distinct(array, drop_nulls), + _ => {} } let values = numeric_values(array, operation, drop_nulls)?; let Some(values) = values else { @@ -374,7 +380,7 @@ pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Resu }; let v = &values; let n = v.len() as f64; - let result = match operation.to_ascii_lowercase().as_str() { + let result = match op.as_str() { "sum" => v.iter().sum(), "prod" => v.iter().product(), "min" => min(v), @@ -386,6 +392,7 @@ pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Resu "harmean" => n / v.iter().map(|x| 1.0 / x).sum::(), "rms" => (v.iter().map(|x| x * x).sum::() / n).sqrt(), "sdev" => variance(v).sqrt(), + "se" => variance(v).sqrt() / n.sqrt(), "var" => variance(v), "iqr" => quantile(values.clone(), 0.75) - quantile(values.clone(), 0.25), "median" | "p50" => quantile(values.clone(), 0.5), @@ -404,6 +411,31 @@ pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Resu Ok(Some(result)) } +/// Count a column's distinct non-null values: NULL when nulls propagate. +/// Numeric arrays compare on f64 bits so display rounding can't merge two +/// values; other types compare on their string representation. +fn n_distinct(array: &ArrayRef, drop_nulls: bool) -> Result> { + if array.logical_null_count() > 0 && !drop_nulls { + return Ok(None); + } + let len = if array.data_type().is_numeric() { + let f64s = cast_array(array, &DataType::Float64)?; + as_f64(&f64s)? + .iter() + .flatten() + .map(f64::to_bits) + .collect::>() + .len() + } else { + (0..array.len()) + .filter(|&idx| !array.is_null(idx)) + .map(|idx| value_to_string(array, idx)) + .collect::>() + .len() + }; + Ok(Some(len as f64)) +} + /// Population variance, matching the plot stats' `VAR_POP`. fn variance(values: &[f64]) -> f64 { let mean = values.iter().sum::() / values.len() as f64; @@ -517,6 +549,35 @@ mod tests { assert_eq!(summary_stat("count", &array, false).unwrap(), Some(0.0)); } + #[test] + fn n_missing_counts_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); + assert_eq!(summary_stat("n_missing", &array, false).unwrap(), Some(1.0)); + assert_eq!(summary_stat("n_missing", &array, true).unwrap(), Some(1.0)); + } + + #[test] + fn n_distinct_counts_distinct_values() { + let numeric: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 2, 3, 1])); + assert_eq!( + summary_stat("n_distinct", &numeric, false).unwrap(), + Some(3.0) + ); + + let strings: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "a"])); + assert_eq!( + summary_stat("n_distinct", &strings, false).unwrap(), + Some(2.0) + ); + } + + #[test] + fn n_distinct_propagates_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(2.0)])); + assert_eq!(summary_stat("n_distinct", &array, false).unwrap(), None); + assert_eq!(summary_stat("n_distinct", &array, true).unwrap(), Some(2.0)); + } + fn stat(operation: &str, values: &[f64]) -> f64 { let array: ArrayRef = Arc::new(Float64Array::from(values.to_vec())); summary_stat(operation, &array, false).unwrap().unwrap() @@ -536,6 +597,7 @@ mod tests { assert_eq!(stat("harmean", v), 4.0 / (1.0 + 0.5 + 1.0 / 3.0 + 0.25)); assert_eq!(stat("rms", v), ((1.0 + 4.0 + 9.0 + 16.0) / 4.0_f64).sqrt()); assert_eq!(stat("sdev", v), 1.25_f64.sqrt()); + assert_eq!(stat("se", v), 1.25_f64.sqrt() / 2.0); assert_eq!(stat("var", v), 1.25); assert_eq!(stat("iqr", v), 1.5); assert_eq!(stat("median", v), 2.5); diff --git a/src/table/summary.rs b/src/table/summary.rs index 03b9cb3d7..75e9045eb 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -174,10 +174,34 @@ pub enum SummaryScope { /// Operations a `SUMMARISE` clause accepts: the plot aggregate vocabulary /// (`AGG_NAMES`) minus the order-dependent positional ones (`first`, `last`, -/// `diff`), which need row-order machinery tables don't have. +/// `diff`), which need row-order machinery tables don't have, plus `se` and +/// the type-free tallies `n_distinct` and `n_missing`. pub const SUMMARY_OPERATIONS: &[&str] = &[ - "count", "sum", "prod", "min", "max", "range", "mid", "mean", "geomean", "harmean", "rms", - "median", "sdev", "var", "iqr", "p05", "p10", "p25", "p50", "p75", "p90", "p95", + "count", + "n_distinct", + "n_missing", + "sum", + "prod", + "min", + "max", + "range", + "mid", + "mean", + "geomean", + "harmean", + "rms", + "median", + "sdev", + "se", + "var", + "iqr", + "p05", + "p10", + "p25", + "p50", + "p75", + "p90", + "p95", ]; /// `SETTING` parameters `SUMMARISE` accepts. From f19ed422d4b49a8584be4cafa7d69ee2a9abbf62 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Wed, 25 Nov 2026 16:24:49 +0100 Subject: [PATCH 22/37] experiment with summary expressions --- src/execute/table/mod.rs | 23 +++ src/execute/table/summary.rs | 76 +++++++- src/table/mod.rs | 2 +- src/table/summary.rs | 353 +++++++++++++++++++++++++++++++++-- 4 files changed, 429 insertions(+), 25 deletions(-) diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index d0282e4bc..b0c6aec5a 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -978,6 +978,29 @@ mod integration_tests { assert_eq!(value.content, "2 +/- 0.82"); } + #[test] + fn test_tabulate_summarise_template_evaluates_placeholder_arithmetic() { + let reader = reader_with_sales(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM sales SUMMARISE '{mean-sdev:%.2f} - {mean+sdev:%.2f}' OF id", + &reader, + ) + .unwrap(); + + let label = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryLabel) + .unwrap(); + assert_eq!(label.content, "mean - sdev - mean + sdev"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue && c.left == label.right + 1) + .unwrap(); + assert_eq!(value.content, "1.18 - 2.82"); + } + #[test] fn test_tabulate_summarise_template_expands_the_printf_sugar() { let reader = reader_with_sales(); diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 0c7f639d4..5aab8e900 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -16,8 +16,8 @@ use crate::array_util::{as_f64, cast_array, column_to_strings, value_to_string}; use crate::naming; use crate::params::ParameterValue; use crate::table::{ - parse_template, Format, Summary, SummaryOperation, SummaryScope, TableCell, TableClass, - TableColumn, TableRow, TemplateSegment, + parse_template, BinOp, Format, StatExpr, Summary, SummaryOperation, SummaryScope, TableCell, + TableClass, TableColumn, TableRow, TemplateSegment, }; use crate::{ColumnSection, DataFrame, GgsqlError, Result}; @@ -301,20 +301,22 @@ fn summary_frame( } /// Render a template against one column's slice: literals verbatim, each -/// placeholder's stat computed over the slice and rendered through its -/// pre-compiled zygos template. A NULL stat renders as the literal "null", -/// like the body cells. +/// placeholder's expression evaluated over the slice and rendered through its +/// pre-compiled zygos template. A NULL expression renders as the literal +/// "null", like the body cells. Stats are memoized in `cache` across all of +/// the template's placeholders, so a repeated stat computes once per cell. fn render_template( segments: &[TemplateSegment], slice: &ArrayRef, drop_nulls: bool, ) -> Result { + let mut cache = HashMap::new(); let mut text = String::new(); for segment in segments { match segment { TemplateSegment::Literal(literal) => text.push_str(literal), - TemplateSegment::Stat { name, template } => { - match summary_stat(name, slice, drop_nulls)? { + TemplateSegment::Stat { expr, template } => { + match eval_stat_expr(expr, slice, drop_nulls, &mut cache)? { Some(value) => text.push_str( &template .format(&zygos::Value::Number(value), None) @@ -328,6 +330,44 @@ fn render_template( Ok(text) } +/// Evaluate a template placeholder's expression over one column's slice: +/// stat leaves via `summary_stat`, combined with the operators. A NULL leaf +/// makes the whole expression NULL. +fn eval_stat_expr( + expr: &StatExpr, + slice: &ArrayRef, + drop_nulls: bool, + cache: &mut HashMap>, +) -> Result> { + match expr { + StatExpr::Stat(name) => { + let key = name.to_ascii_lowercase(); + if let Some(value) = cache.get(&key) { + return Ok(*value); + } + let value = summary_stat(name, slice, drop_nulls)?; + cache.insert(key, value); + Ok(value) + } + StatExpr::Number(n) => Ok(Some(*n)), + StatExpr::Neg(inner) => Ok(eval_stat_expr(inner, slice, drop_nulls, cache)?.map(|v| -v)), + StatExpr::Binary(op, lhs, rhs) => { + let (Some(lhs), Some(rhs)) = ( + eval_stat_expr(lhs, slice, drop_nulls, cache)?, + eval_stat_expr(rhs, slice, drop_nulls, cache)?, + ) else { + return Ok(None); + }; + Ok(Some(match op { + BinOp::Add => lhs + rhs, + BinOp::Sub => lhs - rhs, + BinOp::Mul => lhs * rhs, + BinOp::Div => lhs / rhs, + })) + } + } +} + /// Apply each summarised column's `FORMAT` renaming to a one-row summary /// frame, turning the formatted columns into display text — the same /// treatment `apply_formats` gives the body cells, per value. @@ -578,6 +618,28 @@ mod tests { assert_eq!(summary_stat("n_distinct", &array, true).unwrap(), Some(2.0)); } + fn eval(template: &str, array: &ArrayRef, drop_nulls: bool) -> String { + let segments = parse_template(template).unwrap(); + render_template(&segments, array, drop_nulls).unwrap() + } + + #[test] + fn template_arithmetic_combines_stats() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])); + assert_eq!(eval("{mean+10}", &array, false), "12"); + assert_eq!(eval("{(3-mean)*2}", &array, false), "2"); + // A repeated stat computes once and combines cleanly. + assert_eq!(eval("{mean/mean}", &array, false), "1"); + assert_eq!(eval("{-mean}", &array, false), "−2"); + } + + #[test] + fn template_arithmetic_propagates_nulls() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0), None])); + assert_eq!(eval("{mean-sdev}", &array, false), "null"); + assert_eq!(eval("{mean-sdev:%.1f}", &array, true), "1.0"); + } + fn stat(operation: &str, values: &[f64]) -> f64 { let array: ArrayRef = Arc::new(Float64Array::from(values.to_vec())); summary_stat(operation, &array, false).unwrap().unwrap() diff --git a/src/table/mod.rs b/src/table/mod.rs index 503324380..088753025 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -21,7 +21,7 @@ pub(crate) use layout::{ pub use layout::{TableCell, TableCellKind, TableClass, TableColumn, TableLayout, TableRow}; pub use spanner::Spanner; pub(crate) use spanner::{create_spanners, reorder_table_columns}; -pub(crate) use summary::{parse_template, TemplateSegment}; +pub(crate) use summary::{parse_template, BinOp, StatExpr, TemplateSegment}; pub use summary::{Summary, SummaryOperation, SummaryScope, SUMMARY_OPERATIONS}; use serde::{Deserialize, Serialize}; diff --git a/src/table/summary.rs b/src/table/summary.rs index 75e9045eb..8149cb294 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -44,7 +44,7 @@ impl std::fmt::Display for SummaryOperation { impl SummaryOperation { /// The default row label: a `Stat`'s name; a `Template`'s literal text - /// with each placeholder reduced to its bare operation name + /// with each placeholder reduced to its bare expression /// (`{mean:num %.2f} +/- {sdev}` becomes `mean +/- sdev`). pub(crate) fn as_label(&self) -> String { match self { @@ -55,8 +55,8 @@ impl SummaryOperation { Ok(segments) => segments .iter() .map(|segment| match segment { - TemplateSegment::Literal(text) => text.as_str(), - TemplateSegment::Stat { name, .. } => name.as_str(), + TemplateSegment::Literal(text) => text.clone(), + TemplateSegment::Stat { expr, .. } => expr.to_string(), }) .collect(), Err(_) => template.clone(), @@ -84,9 +84,11 @@ impl SummaryOperation { SummaryOperation::Stat(_) => Ok(()), SummaryOperation::Template(template) => { for segment in parse_template(template)? { - if let TemplateSegment::Stat { name, .. } = segment { - if !known(&name) { - return Err(unknown(&name)); + if let TemplateSegment::Stat { expr, .. } = segment { + for name in expr.stat_names() { + if !known(name) { + return Err(unknown(name)); + } } } } @@ -96,21 +98,242 @@ impl SummaryOperation { } } -/// One piece of a `SUMMARISE` template: literal text, or a `{name:spec}` -/// placeholder naming a stat to evaluate and interpolate. +/// One piece of a `SUMMARISE` template: literal text, or a `{expr:spec}` +/// placeholder whose expression is evaluated and interpolated. #[derive(Debug, Clone)] pub(crate) enum TemplateSegment { /// Text copied to the cell verbatim. Literal(String), - /// A `{name}` or `{name:spec}` placeholder, its zygos template + /// A `{expr}` or `{expr:spec}` placeholder, its zygos template /// pre-compiled: `{:spec}`, or `{}` without a spec. The `%`-sugar is /// already expanded (`{sd:%.1f}` compiles `{:num %.1f}`). Stat { - name: String, + expr: StatExpr, template: zygos::Template, }, } +/// An arithmetic expression over `SUMMARISE` operations, as written inside a +/// template placeholder: `mean`, `mean-sdev`, `(mean-sdev)*2`. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum StatExpr { + /// An operation name, resolved against the column at execution time. + Stat(String), + /// A numeric literal. + Number(f64), + /// `lhs op rhs`. + Binary(BinOp, Box, Box), + /// `-expr`. + Neg(Box), +} + +/// The arithmetic operators a [`StatExpr`] combines values with. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) enum BinOp { + Add, + Sub, + Mul, + Div, +} + +impl StatExpr { + /// Every operation name the expression references. + pub(crate) fn stat_names(&self) -> Vec<&str> { + fn collect<'a>(expr: &'a StatExpr, names: &mut Vec<&'a str>) { + match expr { + StatExpr::Stat(name) => names.push(name), + StatExpr::Number(_) => {} + StatExpr::Binary(_, lhs, rhs) => { + collect(lhs, names); + collect(rhs, names); + } + StatExpr::Neg(inner) => collect(inner, names), + } + } + let mut names = Vec::new(); + collect(self, &mut names); + names + } +} + +impl BinOp { + fn precedence(self) -> u8 { + match self { + BinOp::Add | BinOp::Sub => 0, + BinOp::Mul | BinOp::Div => 1, + } + } +} + +impl StatExpr { + /// Write the expression, parenthesizing a child binary only where its + /// grouping differs from what operator precedence would imply. + fn fmt_with( + &self, + f: &mut std::fmt::Formatter<'_>, + parent: Option<(BinOp, bool)>, + ) -> std::fmt::Result { + if let (Some((parent_op, is_rhs)), StatExpr::Binary(op, ..)) = (parent, self) { + let parenthesized = op.precedence() < parent_op.precedence() + || (is_rhs + && op.precedence() == parent_op.precedence() + && matches!(parent_op, BinOp::Sub | BinOp::Div)); + if parenthesized { + write!(f, "(")?; + } + self.fmt_with(f, None)?; + return if parenthesized { + write!(f, ")") + } else { + Ok(()) + }; + } + match self { + StatExpr::Stat(name) => write!(f, "{name}"), + StatExpr::Number(n) => write!(f, "{n}"), + StatExpr::Binary(op, lhs, rhs) => { + let symbol = match op { + BinOp::Add => "+", + BinOp::Sub => "-", + BinOp::Mul => "*", + BinOp::Div => "/", + }; + lhs.fmt_with(f, Some((*op, false)))?; + write!(f, " {symbol} ")?; + rhs.fmt_with(f, Some((*op, true))) + } + StatExpr::Neg(inner) => { + write!(f, "-")?; + match inner.as_ref() { + StatExpr::Binary(..) | StatExpr::Neg(_) => write!(f, "({inner})"), + _ => inner.fmt_with(f, None), + } + } + } + } +} + +impl std::fmt::Display for StatExpr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.fmt_with(f, None) + } +} + +/// Parse a template placeholder's arithmetic expression: operation names and +/// numbers combined with `+ - * /`, parentheses and unary minus. +pub(crate) fn parse_stat_expr(source: &str) -> Result { + struct Parser<'a> { + source: &'a [u8], + pos: usize, + } + impl Parser<'_> { + fn peek(&self) -> Option { + self.source.get(self.pos).copied() + } + fn ws(&mut self) { + while matches!(self.peek(), Some(c) if c.is_ascii_whitespace()) { + self.pos += 1; + } + } + fn expr(&mut self) -> Result { + let mut lhs = self.term()?; + loop { + self.ws(); + let op = match self.peek() { + Some(b'+') => BinOp::Add, + Some(b'-') => BinOp::Sub, + _ => return Ok(lhs), + }; + self.pos += 1; + lhs = StatExpr::Binary(op, Box::new(lhs), Box::new(self.term()?)); + } + } + fn term(&mut self) -> Result { + let mut lhs = self.factor()?; + loop { + self.ws(); + let op = match self.peek() { + Some(b'*') => BinOp::Mul, + Some(b'/') => BinOp::Div, + _ => return Ok(lhs), + }; + self.pos += 1; + lhs = StatExpr::Binary(op, Box::new(lhs), Box::new(self.factor()?)); + } + } + fn factor(&mut self) -> Result { + self.ws(); + match self.peek() { + Some(b'-') => { + self.pos += 1; + Ok(StatExpr::Neg(Box::new(self.factor()?))) + } + Some(b'+') => { + self.pos += 1; + self.factor() + } + Some(b'(') => { + self.pos += 1; + let inner = self.expr()?; + self.ws(); + if self.peek() == Some(b')') { + self.pos += 1; + Ok(inner) + } else { + Err("Missing ')'".to_string()) + } + } + Some(c) if c.is_ascii_digit() || c == b'.' => self.number(), + Some(c) if c.is_ascii_alphabetic() || c == b'_' => Ok(self.ident()), + Some(c) => Err(format!("Unexpected '{}'", c as char)), + None => Err("Expected an operation name or number".to_string()), + } + } + fn number(&mut self) -> Result { + let start = self.pos; + while matches!(self.peek(), Some(c) if c.is_ascii_digit() || c == b'.') { + self.pos += 1; + } + // An exponent is taken only when it has at least one digit, so + // `1e` leaves the `e` to error as an unexpected character. + if matches!(self.peek(), Some(b'e' | b'E')) { + let mut pos = self.pos + 1; + if matches!(self.source.get(pos), Some(b'+' | b'-')) { + pos += 1; + } + if matches!(self.source.get(pos), Some(c) if c.is_ascii_digit()) { + self.pos = pos; + while matches!(self.peek(), Some(c) if c.is_ascii_digit()) { + self.pos += 1; + } + } + } + let text = std::str::from_utf8(&self.source[start..self.pos]).unwrap(); + text.parse::() + .map(StatExpr::Number) + .map_err(|_| format!("Invalid number '{text}'")) + } + fn ident(&mut self) -> StatExpr { + let start = self.pos; + while matches!(self.peek(), Some(c) if c.is_ascii_alphanumeric() || c == b'_') { + self.pos += 1; + } + let text = std::str::from_utf8(&self.source[start..self.pos]).unwrap(); + StatExpr::Stat(text.to_string()) + } + } + let mut parser = Parser { + source: source.as_bytes(), + pos: 0, + }; + let expr = parser.expr()?; + parser.ws(); + match parser.peek() { + Some(c) => Err(format!("Unexpected '{}'", c as char)), + None => Ok(expr), + } +} + /// Split a template literal into text and placeholder segments. `{` opens a /// placeholder and must be terminated and non-empty; `}` outside a /// placeholder is literal text. Matching against `SUMMARY_OPERATIONS` happens @@ -149,7 +372,8 @@ pub(crate) fn parse_template(template: &str) -> Result, Str None => "{}".to_string(), }; segments.push(TemplateSegment::Stat { - name: name.to_string(), + expr: parse_stat_expr(name) + .map_err(|err| format!("{err} in SUMMARISE template '{{{placeholder}}}'"))?, template: zygos::Template::parse(&source), }); } @@ -308,6 +532,12 @@ mod tests { assert!(SummaryOperation::Template("{mean} +/- {meen}".to_string()) .validate() .is_err()); + assert!(SummaryOperation::Template("{mean+1.96*se}".to_string()) + .validate() + .is_ok()); + assert!(SummaryOperation::Template("{mean+meen}".to_string()) + .validate() + .is_err()); } #[test] @@ -320,13 +550,17 @@ mod tests { SummaryOperation::Stat("MEAN".to_string()).as_label(), "MEAN" ); + assert_eq!( + SummaryOperation::Template("{mean-sdev:%.1f}".to_string()).as_label(), + "mean - sdev" + ); } #[test] fn parse_template_splits_literals_and_stats() { let segments = parse_template("{mean} +/- {sdev:num %.3f} (n={count})").unwrap(); let stat = |index: usize| match &segments[index] { - TemplateSegment::Stat { name, template } => (name.as_str(), template.source()), + TemplateSegment::Stat { expr, template } => (expr.to_string(), template.source()), TemplateSegment::Literal(_) => panic!("segment {index} is a literal"), }; let literal = |index: usize| match &segments[index] { @@ -335,11 +569,11 @@ mod tests { }; assert_eq!(segments.len(), 6); - assert_eq!(stat(0), ("mean", "{}")); + assert_eq!(stat(0), ("mean".to_string(), "{}")); assert_eq!(literal(1), " +/- "); - assert_eq!(stat(2), ("sdev", "{:num %.3f}")); + assert_eq!(stat(2), ("sdev".to_string(), "{:num %.3f}")); assert_eq!(literal(3), " (n="); - assert_eq!(stat(4), ("count", "{}")); + assert_eq!(stat(4), ("count".to_string(), "{}")); assert_eq!(literal(5), ")"); } @@ -347,8 +581,8 @@ mod tests { fn parse_template_expands_the_printf_sugar() { let segments = parse_template("{sd:%.1f}").unwrap(); match &segments[0] { - TemplateSegment::Stat { name, template } => { - assert_eq!(name, "sd"); + TemplateSegment::Stat { expr, template } => { + assert_eq!(expr.to_string(), "sd"); assert_eq!(template.source(), "{:num %.1f}"); } TemplateSegment::Literal(_) => panic!("expected a stat segment"), @@ -371,4 +605,89 @@ mod tests { assert!(parse_template("{}").is_err()); assert!(parse_template("{:num}").is_err()); } + + #[test] + fn parse_stat_expr_applies_precedence_and_parentheses() { + // `*` binds tighter than `-`. + assert_eq!( + parse_stat_expr("mean-sdev*2").unwrap(), + StatExpr::Binary( + BinOp::Sub, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Stat("sdev".to_string())), + Box::new(StatExpr::Number(2.0)), + )), + ) + ); + assert_eq!( + parse_stat_expr("(mean - sdev) * 2").unwrap(), + StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Binary( + BinOp::Sub, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Stat("sdev".to_string())), + )), + Box::new(StatExpr::Number(2.0)), + ) + ); + } + + #[test] + fn parse_stat_expr_handles_unary_minus_and_decimals() { + assert_eq!( + parse_stat_expr("-mean").unwrap(), + StatExpr::Neg(Box::new(StatExpr::Stat("mean".to_string()))) + ); + assert_eq!( + parse_stat_expr("mean+.5").unwrap(), + StatExpr::Binary( + BinOp::Add, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Number(0.5)), + ) + ); + } + + #[test] + fn parse_stat_expr_handles_unary_plus_and_scientific_notation() { + assert_eq!( + parse_stat_expr("+mean").unwrap(), + StatExpr::Stat("mean".to_string()) + ); + assert_eq!( + parse_stat_expr("mean*1.5e-2").unwrap(), + StatExpr::Binary( + BinOp::Mul, + Box::new(StatExpr::Stat("mean".to_string())), + Box::new(StatExpr::Number(0.015)), + ) + ); + assert_eq!(parse_stat_expr("2E3").unwrap(), StatExpr::Number(2000.0)); + // No digit after `e`: the `e` is not part of the number. + assert!(parse_stat_expr("1e").is_err()); + } + + #[test] + fn parse_stat_expr_rejects_malformed_input() { + assert!(parse_stat_expr("mean-").is_err()); + assert!(parse_stat_expr("(mean").is_err()); + assert!(parse_stat_expr("mean sdev").is_err()); + assert!(parse_stat_expr("mean % sdev").is_err()); + assert!(parse_stat_expr("1.2.3").is_err()); + } + + #[test] + fn stat_expr_display_keeps_grouping() { + assert_eq!( + parse_stat_expr("(mean - sdev) * 2").unwrap().to_string(), + "(mean - sdev) * 2" + ); + assert_eq!( + parse_stat_expr("mean-sdev*2").unwrap().to_string(), + "mean - sdev * 2" + ); + } } From 62c1028764852983f1d7d9e0c0bc6da44fe696d5 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 10:20:19 +0100 Subject: [PATCH 23/37] add docs --- CHANGELOG.md | 1 + doc/syntax/clause/summarise.qmd | 193 ++++++++++++++++++++++++++++++++ doc/vendor/SKILL.md | 21 ++++ 3 files changed, 215 insertions(+) create mode 100644 doc/syntax/clause/summarise.qmd diff --git a/CHANGELOG.md b/CHANGELOG.md index a7f9a6d15..cefada03c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - `SPAN` groups columns under a shared header cell (spanner). - `FORMAT` configures how a column's cells are displayed. - `FACET` sets row groups. + - `SUMMARISE` computes aggregates over rows. - `Writer::write_table` renders a resolved table, taking the new public `TableLayout` — the table's cells bundled with their column and row metadata. diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd new file mode 100644 index 000000000..a62fb142c --- /dev/null +++ b/doc/syntax/clause/summarise.qmd @@ -0,0 +1,193 @@ +--- +title: "Summarise values into new rows" +--- + +Numerical values can be summarised and displayed in dedicated rows. +This is helpful to display observations alongside statistics in the table. +`SUMMARISE` can be repeated to compute multiple summaries. + +## Clause syntax + +```ggsql +SUMMARISE [GROUP | GRAND] OF , ... + SETTING => , ... +``` + +Also accepts the spelling `SUMMARIZE`. + +## Scope + +```ggsql +[GROUP | GRAND] +``` + +The scope directly following the `SUMMARISE` clause determines which rows the operation aggregates over. +Setting the scope to `GROUP` will compute the summary for each group determined by `FACET` clauses separately. +The `GRAND` scope will compute the summary for all rows. +Without spelling out a scope, the default will be `GROUP`. +When no groups are declared by `FACET` and the scope is set to `GROUP`, all rows are treated as belonging to the same group. +The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a diffrence in style and label spanning. + +## Operation + +```ggsql + +``` + +This part of the clause can be an identifier or a string representing an expression. +When using an identifier, one of the following operations are available: + +* Counting: `count`, `n_distinct`, `n_missing`. +* Totals: `sum`, `prod`. +* Extremes: `min`, `max`, `range` (max - min), `mid` (min + max) / 2. +* Centrality: `mean`, geometric mean `geomean`, harmonic mean `harmean`, root-mean-square `rms`, `median`. +* Dispersion: standard deviation `sdev`, standard error `se`, variance `var`, interquartile range `iqr`. Note `sdev`, `se` and `var` are population statistics, not sample statistics. +* Percentiles: `p05`, `p10`, `p25`, `p50` (median), `p75`, `p90`, `p95`. + +When using a string as an expression, you can use any of the identifiers in curly braces. +For example `'{mean}'` will display the mean via expression. +The expressions can be used to display multiple metrics in a single cell, e.g. `'{median} ({p25}, {p75})'` will display the median and interquartile range in one cell. +Inside the brackets, you can use limited arithmetic. +The operands include the operation identifiers listed above (like `mean`, `sdev`), numeric literals (`2`, `0.5`) and scientific notation (`1e6`). +The `+`, `-` unary operators and `+`, `-`, `*` and `/` binary operators and `(`/`)` parentheses for grouping. +For example you can use `'({mean - 1.96 * se}, {mean + 1.96 * se})'` to display a 95% confidence interval (assuming normal distribution) in parentheses separated by a comma. + +For the naked, non-string identifiers the formatting of the cell values is applied externally via `FORMAT` clauses. +The string expressions can be self-formatting via the same syntax as [scale breaks](scale.qmd#break-formatting). +All summary metrics are assumed to be numeric. +As such, the `:num` formatter is implied and does not need to be written out in full. +The expression `'{mean:%.2f}'` will display the mean with two decimal points in printf-style. +Other formatters can be used, e.g. `{max:bytes}` to display base-1024 size. +When using arithmetic, the formatting is placed at the end and is applied to the result so that `'{mean + sdev:%.2f}'` rounds the expression to two decimals. + +## Column selection + +```ggsql +OF , ... +``` + +The `SUMMARISE` clause requires a comma-separated list of columns to aggregate. +The columns must be part of the `TABULATE` selection. +Only the 'counting' operations listed above can be applied to columns of any type, the other operations require numeric columns. + +## Settings + +```ggsql +SETTING => +``` + +The `SETTING` sub-clause is typical with key-value pairs. +It currently takes the following parameters: + +* `place`: the location of the summary rows relative to the body rows they summarise. +Can be `'top'` to place the summary rows at the top of each group or table, or `'bottom'` (default) to place the summary rows after the body rows. +* `rowlabel`: A string for the label of the summary row. The default `null` falls back to printing the operation, where string expression operations are displayed without formatting details. +* `missing`: A string option for how to treat `null` values in the table. +The default `'propagate'` will list any non-counting operation as `null`, and counting operations include null-rows. +Can be set to `'drop'` to explicitly ignore `null` values in aggregates and ignore these rows in counting operations. + +## Examples + +A summary without groups will summarise all rows. + +```{ggsql} +CREATE TEMP TABLE my_data AS +SELECT DISTINCT ON (species, island, sex) * FROM ggsql:penguins +WHERE bill_len IS NOT NULL AND sex IS NOT NULL + +TABULATE * FROM my_data +SUMMARISE mean OF bill_len, bill_dep +``` + +A grand summary will always summarise all rows, and is displayed with a stronger border. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE GRAND mean OF bill_len, bill_dep +``` + +Groups can be specified using `FACET`. + +```{ggsql} +TABULATE * FROM my_data +FACET island +SUMMARISE mean OF bill_len, bill_dep +``` + +The labels of summary rows compose with regular body row labels in the stub. + +```{ggsql} +TABULATE * FROM my_data +FACET island +FORMAT STUB species +SUMMARISE mean OF bill_len, bill_dep +``` + +The display of the label in the stub can be changed using the `rowlabel` setting. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE mean OF bill_len, bill_dep + SETTING rowlabel => 'Average' +``` + +The summary cells are subject to `FORMAT` when using plain identifiers, along with the body rows. + +```{ggsql} +TABULATE * FROM my_data +FACET species +FORMAT bill_len, bill_dep RENAMING * => '{:num %.2f}' +SUMMARISE mean OF bill_len, bill_dep +``` + +To specifically format the summary values, you can use the expression string form. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE '📏 {mean:%.2f}' OF bill_len, bill_dep +``` + +You can use repeated summaries. +The order in which the summaries are declared determine the order of the rows. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE p25 OF bill_len, bill_dep +SUMMARISE p50 OF bill_len, bill_dep +SUMMARISE p75 OF bill_len, bill_dep +``` + +Or display related summaries in a single cell. + +```{ggsql} +TABULATE * FROM my_data +SUMMARISE '{p50:%.2f} ({p25:%.2f}, {p75:%.2f})' OF bill_len, bill_dep +``` + +When data contains 'null' values, they propagate to aggregate metrics (but not necessarily count metrics). +Notice how the summary of `bill_len` comes out as 'null'. + +```{ggsql} +SELECT species, island, sex, + CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len, + bill_dep, flipper_len, body_mass +FROM my_data + +TABULATE * +SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep +``` + +You can ignore 'null' values by using the `missing => 'drop'` setting. + +```{ggsql} +SELECT species, island, sex, + CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len, + bill_dep, flipper_len, body_mass +FROM my_data + +TABULATE * +SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep + SETTING missing => 'drop' +``` diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index c7afd5d17..7e7d16de3 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -194,6 +194,27 @@ TABULATE * FORMAT body_mass SETTING hjust => 'right' RENAMING null => '-', * => '{:num %.0f}g' ``` +### SUMMARISE + +Adds summary rows computed over the table's rows: one per `FACET` group (`GROUP`, default) or a single row over all rows (`GRAND`, rendered with a stronger border; its label spans group stub columns). Repeatable — clause order is row order within a boundary. Also spelled `SUMMARIZE`. Columns must be part of the TABULATE selection. + +``` +SUMMARISE [GROUP | GRAND] OF , ... + SETTING => , ... +``` + +- **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns. +- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`). A template self-formats and ignores the column's `FORMAT` renaming; a bare operation takes it. +- **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop). + +```ggsql +TABULATE * FROM ggsql:penguins +FACET island +FORMAT STUB species +SUMMARISE mean OF bill_len, bill_dep +SUMMARISE GRAND '{mean:%.1f} ± {se:%.1f}' OF bill_len SETTING rowlabel => 'Mean ± SE' +``` + --- ## Layer types From 3ca9c77341e3f065c222542a7c5fa5154d375624 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 11:43:02 +0100 Subject: [PATCH 24/37] support for temporal columns --- doc/syntax/clause/summarise.qmd | 57 +++- doc/vendor/SKILL.md | 4 +- src/execute/table/summary.rs | 488 ++++++++++++++++++++++++++------ 3 files changed, 461 insertions(+), 88 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index a62fb142c..51513504a 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -37,12 +37,33 @@ The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is large This part of the clause can be an identifier or a string representing an expression. When using an identifier, one of the following operations are available: -* Counting: `count`, `n_distinct`, `n_missing`. -* Totals: `sum`, `prod`. -* Extremes: `min`, `max`, `range` (max - min), `mid` (min + max) / 2. -* Centrality: `mean`, geometric mean `geomean`, harmonic mean `harmean`, root-mean-square `rms`, `median`. -* Dispersion: standard deviation `sdev`, standard error `se`, variance `var`, interquartile range `iqr`. Note `sdev`, `se` and `var` are population statistics, not sample statistics. -* Percentiles: `p05`, `p10`, `p25`, `p50` (median), `p75`, `p90`, `p95`. +| Name | Description | Numeric | Date(time) | Other | +|------|-------------|:-------:|:----------:|:-----:| +| `count` | Number of rows | ✓ | ✓ | ✓ | +| `n_distinct` | Number of distinct values | ✓ | ✓ | ✓ | +| `n_missing` | Number of nulls | ✓ | ✓ | ✓ | +| `sum` | Sum | ✓ | | | +| `prod` | Product | ✓ | | | +| `min` | Minimum | ✓ | ✓ | | +| `max` | Maximum | ✓ | ✓ | | +| `range` | max − min | ✓ | ✓ | | +| `mid` | (min + max) / 2 | ✓ | ✓ | | +| `mean` | Arithmetic mean | ✓ | ✓ | | +| `geomean` | Geometric mean | ✓ | | | +| `harmean` | Harmonic mean | ✓ | | | +| `rms` | Root-mean-square | ✓ | | | +| `median` | Median | ✓ | ✓ | | +| `sdev` | Standard deviation (population, ÷ n) | ✓ | ✓ | | +| `se` | Standard error (population, ÷ n) | ✓ | ✓ | | +| `var` | Variance (population, ÷ n) | ✓ | | | +| `iqr` | Interquartile range | ✓ | ✓ | | +| `p05` | 5th percentile | ✓ | ✓ | | +| `p10` | 10th percentile | ✓ | ✓ | | +| `p25` | 25th percentile | ✓ | ✓ | | +| `p50` | 50th percentile (median) | ✓ | ✓ | | +| `p75` | 75th percentile | ✓ | ✓ | | +| `p90` | 90th percentile | ✓ | ✓ | | +| `p95` | 95th percentile | ✓ | ✓ | | When using a string as an expression, you can use any of the identifiers in curly braces. For example `'{mean}'` will display the mean via expression. @@ -60,6 +81,10 @@ The expression `'{mean:%.2f}'` will display the mean with two decimal points in Other formatters can be used, e.g. `{max:bytes}` to display base-1024 size. When using arithmetic, the formatting is placed at the end and is applied to the result so that `'{mean + sdev:%.2f}'` rounds the expression to two decimals. +Date and timestamp columns accept the order statistics (`min`, `max`, `mid`, `mean`, `median` and the percentiles), returning a date or timestamp, and `range`, `sdev`, `se` and `iqr`, returning a duration. +A date or timestamp renders as ISO text or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic it becomes a plain number: days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. +A date-valued `mean` or `mid` rounds to the nearest whole day. + ## Column selection ```ggsql @@ -68,7 +93,7 @@ OF , ... The `SUMMARISE` clause requires a comma-separated list of columns to aggregate. The columns must be part of the `TABULATE` selection. -Only the 'counting' operations listed above can be applied to columns of any type, the other operations require numeric columns. +The 'counting' operations listed above can be applied to columns of any type, the order and dispersion statistics also accept date and timestamp columns, and the remaining operations require numeric columns. ## Settings @@ -191,3 +216,21 @@ TABULATE * SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep SETTING missing => 'drop' ``` + +Date and timestamp columns can be summarised with the order statistics, formatted with `:time`, and `range` gives their span as a duration. + +```{ggsql} +CREATE TEMP TABLE launches AS +SELECT * FROM (VALUES + ('Alpha', DATE '2024-01-15'), + ('Alpha', DATE '2024-02-10'), + ('Beta', DATE '2024-03-01'), + ('Beta', DATE '2024-03-20')) AS t(product, launched) + +TABULATE * FROM launches +FACET product +SUMMARISE '{min:time %d %b %Y} – {max}' OF launched + SETTING rowlabel => 'Dates' +SUMMARISE '{range:duration d}' OF launched + SETTING rowlabel => 'Duration' +``` \ No newline at end of file diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index 7e7d16de3..53333488a 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -203,8 +203,8 @@ SUMMARISE [GROUP | GRAND] OF , ... SETTING => , ... ``` -- **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns. -- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`). A template self-formats and ignores the column's `FORMAT` renaming; a bare operation takes it. +- **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns, except that date/timestamp columns also accept the order statistics (`min max mid mean median p*`, returning a date/timestamp) and `range sdev se iqr` (returning a duration). +- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats and ignores the column's `FORMAT` renaming; a bare operation takes it. - **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop). ```ggsql diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 5aab8e900..29c90a055 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -2,15 +2,22 @@ //! data and prepares the frame for summary rows, `compute_summaries` runs //! the aggregate operations on it. //! -//! All of `SUMMARY_OPERATIONS` are folds over a column's numeric values -//! except the type-free tallies `count`, `n_distinct` and `n_missing`. +//! Most of `SUMMARY_OPERATIONS` are folds over a column's numeric values. +//! The tallies `count`, `n_distinct` and `n_missing` are type-free, and +//! date/timestamp columns accept the order statistics (returning a temporal +//! value) and the spread statistics (returning a duration). use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::sync::Arc; -use arrow::array::{Array, ArrayRef, Float64Array, StringArray}; -use arrow::datatypes::DataType; +use arrow::array::{ + Array, ArrayRef, Date32Array, Date64Array, Float64Array, StringArray, + TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, + TimestampSecondArray, +}; +use arrow::datatypes::{DataType, TimeUnit}; +use zygos::Value; use crate::array_util::{as_f64, cast_array, column_to_strings, value_to_string}; use crate::naming; @@ -68,8 +75,10 @@ pub(super) struct SummaryRow { /// The row's stub label: `rowlabel`, else the operation name. pub label: String, /// One-row frame of the computed values; its schema names the - /// summarised columns. Numeric for a bare operation (unless the - /// column's `FORMAT` renaming stringified it), string for a template. + /// summarised columns. Numeric for a bare operation — the column's + /// temporal type for a date-valued statistic on a date/timestamp + /// column — string for a template. A `FORMAT` renaming may stringify + /// any of these. pub frame: DataFrame, } @@ -289,9 +298,7 @@ fn summary_frame( let SummaryOperation::Stat(name) = &summary.operation else { unreachable!("compute_summaries parses every template clause") }; - Arc::new(Float64Array::from(vec![summary_stat( - name, &slice, drop_nulls, - )?])) + value_array(&summary_stat(name, &slice, drop_nulls)?, slice.data_type()) } }; Ok((column.clone(), cell)) @@ -317,11 +324,9 @@ fn render_template( TemplateSegment::Literal(literal) => text.push_str(literal), TemplateSegment::Stat { expr, template } => { match eval_stat_expr(expr, slice, drop_nulls, &mut cache)? { - Some(value) => text.push_str( - &template - .format(&zygos::Value::Number(value), None) - .unwrap_or_default(), - ), + Some(value) => { + text.push_str(&template.format(&value, None).unwrap_or_default()) + } None => text.push_str("null"), } } @@ -331,26 +336,30 @@ fn render_template( } /// Evaluate a template placeholder's expression over one column's slice: -/// stat leaves via `summary_stat`, combined with the operators. A NULL leaf -/// makes the whole expression NULL. +/// stat leaves via `summary_stat` keep their type, so a date-valued leaf +/// renders through zygos's temporal formatting; any arithmetic projects the +/// operands to plain numbers via [`leaf_f64`]. A NULL leaf makes the whole +/// expression NULL. fn eval_stat_expr( expr: &StatExpr, slice: &ArrayRef, drop_nulls: bool, - cache: &mut HashMap>, -) -> Result> { + cache: &mut HashMap>, +) -> Result> { match expr { StatExpr::Stat(name) => { let key = name.to_ascii_lowercase(); if let Some(value) = cache.get(&key) { - return Ok(*value); + return Ok(value.clone()); } let value = summary_stat(name, slice, drop_nulls)?; - cache.insert(key, value); + cache.insert(key, value.clone()); Ok(value) } - StatExpr::Number(n) => Ok(Some(*n)), - StatExpr::Neg(inner) => Ok(eval_stat_expr(inner, slice, drop_nulls, cache)?.map(|v| -v)), + StatExpr::Number(n) => Ok(Some(Value::Number(*n))), + StatExpr::Neg(inner) => Ok(eval_stat_expr(inner, slice, drop_nulls, cache)? + .and_then(|v| leaf_f64(&v)) + .map(|v| Value::Number(-v))), StatExpr::Binary(op, lhs, rhs) => { let (Some(lhs), Some(rhs)) = ( eval_stat_expr(lhs, slice, drop_nulls, cache)?, @@ -358,16 +367,30 @@ fn eval_stat_expr( ) else { return Ok(None); }; - Ok(Some(match op { + let (Some(lhs), Some(rhs)) = (leaf_f64(&lhs), leaf_f64(&rhs)) else { + return Ok(None); + }; + Ok(Some(Value::Number(match op { BinOp::Add => lhs + rhs, BinOp::Sub => lhs - rhs, BinOp::Mul => lhs * rhs, BinOp::Div => lhs / rhs, - })) + }))) } } } +/// Project a stat leaf to a plain number for arithmetic: days for dates, +/// seconds for datetimes, itself for numbers. +fn leaf_f64(value: &Value) -> Option { + match value { + Value::Number(n) => Some(*n), + Value::Date(days) => Some(*days as f64), + Value::DateTime(us) => Some(*us as f64 / 1e6), + _ => None, + } +} + /// Apply each summarised column's `FORMAT` renaming to a one-row summary /// frame, turning the formatted columns into display text — the same /// treatment `apply_formats` gives the body cells, per value. @@ -397,7 +420,12 @@ fn format_summary_frame( /// Compute one `SUMMARISE` operation over a column. With `drop_nulls`, nulls /// are ignored; otherwise a single null makes the result `None` (NULL), as /// does an empty input. Matching on `operation` is case-insensitive. -pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { +/// +/// Numeric columns yield [`Value::Number`]. Date/timestamp columns accept +/// the order statistics, which yield the column's own kind of temporal +/// value, and the spread statistics, which yield a duration as a number of +/// days (dates) or seconds (timestamps); the other folds reject them. +pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Result> { // The type-free tallies bypass the numeric fold: `count` counts rows or // non-null values, `n_missing` measures nulls so never goes NULL itself. let op = operation.to_ascii_lowercase(); @@ -408,19 +436,26 @@ pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Resu } else { array.len() }; - return Ok(Some(count as f64)); + return Ok(Some(Value::Number(count as f64))); } - "n_missing" => return Ok(Some(array.logical_null_count() as f64)), - "n_distinct" => return n_distinct(array, drop_nulls), + "n_missing" => return Ok(Some(Value::Number(array.logical_null_count() as f64))), + "n_distinct" => return Ok(n_distinct(array, drop_nulls)?.map(Value::Number)), _ => {} } - let values = numeric_values(array, operation, drop_nulls)?; - let Some(values) = values else { - return Ok(None); + let Some(kind) = ValueKind::of(array.data_type()) else { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {operation} requires a numeric, date or timestamp column, not {}", + array.data_type() + ))); }; + kind.summary_stat(&op, array, drop_nulls) +} + +/// Fold one statistic over already-extracted values. +fn fold_stat(operation: &str, values: Vec) -> Result { let v = &values; let n = v.len() as f64; - let result = match op.as_str() { + let result = match operation { "sum" => v.iter().sum(), "prod" => v.iter().product(), "min" => min(v), @@ -448,7 +483,170 @@ pub fn summary_stat(operation: &str, array: &ArrayRef, drop_nulls: bool) -> Resu ))) } }; - Ok(Some(result)) + Ok(result) +} + +/// The flavour of column a fold operates on, fixing the unit its statistics +/// are computed in and how the result is wrapped. +enum ValueKind { + /// Any numeric type; statistics computed and reported as-is. + Numeric, + /// Date32/Date64; statistics computed and durations reported in days. + Date, + /// Any timestamp; statistics computed in µs, durations reported in + /// seconds. + DateTime, +} + +impl ValueKind { + fn of(dtype: &DataType) -> Option { + match dtype { + _ if dtype.is_numeric() => Some(Self::Numeric), + DataType::Date32 | DataType::Date64 => Some(Self::Date), + DataType::Timestamp(_, _) => Some(Self::DateTime), + _ => None, + } + } + + fn summary_stat( + &self, + operation: &str, + array: &ArrayRef, + drop_nulls: bool, + ) -> Result> { + // Temporal columns accept the order statistics, which return a + // value of the column's own kind, and the spread statistics, which + // return a duration. + let date_valued = matches!( + operation, + "min" + | "max" + | "mid" + | "mean" + | "median" + | "p05" + | "p10" + | "p25" + | "p50" + | "p75" + | "p90" + | "p95" + ); + let duration = matches!(operation, "range" | "sdev" | "se" | "iqr"); + if !matches!(self, Self::Numeric) && !date_valued && !duration { + return Err(GgsqlError::ValidationError(format!( + "SUMMARISE {operation} does not support {}", + array.data_type() + ))); + } + let Some(values) = self.values(array, drop_nulls)? else { + return Ok(None); + }; + let result = fold_stat(operation, values)?; + Ok(Some(match self { + Self::Numeric => Value::Number(result), + kind if date_valued => kind.typed(result), + kind => Value::Number(kind.duration(result)), + })) + } + + /// Extract the column's values in the kind's compute unit (unchanged + /// for numbers, days for dates, µs for timestamps). Returns `None` when + /// the result should be NULL: the input is empty, all-null, or holds + /// nulls without `drop_nulls`. + fn values(&self, array: &ArrayRef, drop_nulls: bool) -> Result>> { + let scale = match array.data_type() { + DataType::Date32 => 1.0, + DataType::Date64 => 1.0 / 86_400_000.0, + DataType::Timestamp(unit, _) => match unit { + TimeUnit::Second => 1e6, + TimeUnit::Millisecond => 1e3, + TimeUnit::Microsecond => 1.0, + TimeUnit::Nanosecond => 1e-3, + }, + _ => 1.0, + }; + // Timestamps don't cast to Float64 directly; going through Int64 + // first is lossless for every accepted dtype. + let f64s: ArrayRef = if array.data_type() == &DataType::Float64 { + array.clone() + } else if matches!(self, Self::Numeric) { + cast_array(array, &DataType::Float64)? + } else { + cast_array(&cast_array(array, &DataType::Int64)?, &DataType::Float64)? + }; + let array = as_f64(&f64s)?; + if array.is_empty() || (array.logical_null_count() > 0 && !drop_nulls) { + return Ok(None); + } + let values: Vec = array.iter().flatten().map(|v| v * scale).collect(); + Ok((!values.is_empty()).then_some(values)) + } + + /// Wrap a date-valued result in its temporal value, rounding to the + /// column's precision (whole days / whole µs). + fn typed(&self, value: f64) -> Value { + match self { + Self::Numeric => unreachable!("the numeric arm wraps directly"), + Self::Date => Value::Date(value.round() as i32), + Self::DateTime => Value::DateTime(value.round() as i64), + } + } + + /// Convert a duration from the compute unit to the reported unit (days + /// for dates, seconds for timestamps). + fn duration(&self, value: f64) -> f64 { + match self { + Self::Numeric => unreachable!("the numeric arm wraps directly"), + Self::Date => value, + Self::DateTime => value / 1e6, + } + } +} + +/// Build the one-cell array holding a bare operation's result. A date-valued +/// result keeps the summarised column's temporal type (and timezone) so it +/// displays and formats like a body cell; everything else is a Float64. +fn value_array(value: &Option, dtype: &DataType) -> ArrayRef { + let Some(value) = value else { + let dtype = match ValueKind::of(dtype) { + Some(ValueKind::Date | ValueKind::DateTime) => dtype.clone(), + _ => DataType::Float64, + }; + return arrow::array::new_null_array(&dtype, 1); + }; + match (value, dtype) { + (Value::Date(days), DataType::Date32) => Arc::new(Date32Array::from(vec![Some(*days)])), + (Value::Date(days), DataType::Date64) => { + Arc::new(Date64Array::from(vec![Some(*days as i64 * 86_400_000)])) + } + (Value::DateTime(us), DataType::Timestamp(unit, tz)) => { + let us = *us; + match unit { + TimeUnit::Second => Arc::new( + TimestampSecondArray::from(vec![Some(us / 1_000_000)]) + .with_timezone_opt(tz.clone()), + ), + TimeUnit::Millisecond => Arc::new( + TimestampMillisecondArray::from(vec![Some(us / 1_000)]) + .with_timezone_opt(tz.clone()), + ), + TimeUnit::Microsecond => Arc::new( + TimestampMicrosecondArray::from(vec![Some(us)]).with_timezone_opt(tz.clone()), + ), + TimeUnit::Nanosecond => Arc::new( + TimestampNanosecondArray::from(vec![Some(us * 1_000)]) + .with_timezone_opt(tz.clone()), + ), + } + } + _ => { + let Value::Number(n) = value else { + unreachable!("summary_stat yields Date/DateTime only on temporal columns") + }; + Arc::new(Float64Array::from(vec![Some(*n)])) + } + } } /// Count a column's distinct non-null values: NULL when nulls propagate. @@ -490,28 +688,6 @@ fn max(values: &[f64]) -> f64 { values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b)) } -/// Extract a column's values as f64. Returns `None` when the result should be -/// NULL: the input is empty, all-null, or holds nulls without `drop_nulls`. -fn numeric_values(array: &ArrayRef, operation: &str, drop_nulls: bool) -> Result>> { - if !array.data_type().is_numeric() { - return Err(GgsqlError::ValidationError(format!( - "SUMMARISE {operation} requires a numeric column, not {}", - array.data_type() - ))); - } - let f64s: ArrayRef = if array.data_type() == &DataType::Float64 { - array.clone() - } else { - cast_array(array, &DataType::Float64)? - }; - let array = as_f64(&f64s)?; - if array.is_empty() || (array.logical_null_count() > 0 && !drop_nulls) { - return Ok(None); - } - let values: Vec = array.iter().flatten().collect(); - Ok((!values.is_empty()).then_some(values)) -} - /// Linear-interpolated quantile. /// Uses the `quantile_cont` convention, R's default `quantile(type = 7)`. fn quantile(mut values: Vec, q: f64) -> f64 { @@ -529,39 +705,44 @@ mod tests { use arrow::array::{Float64Array, Int64Array, StringArray}; use std::sync::Arc; + /// Unwrap a `summary_stat` result to its plain number. + fn num(result: Result>) -> Option { + result.unwrap().and_then(|v| v.as_number()) + } + #[test] fn nulls_propagate_by_default() { let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); - assert_eq!(summary_stat("mean", &array, false).unwrap(), None); - assert_eq!(summary_stat("median", &array, false).unwrap(), None); + assert_eq!(num(summary_stat("mean", &array, false)), None); + assert_eq!(num(summary_stat("median", &array, false)), None); } #[test] fn drop_nulls_ignores_them() { let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); - assert_eq!(summary_stat("mean", &array, true).unwrap(), Some(2.0)); - assert_eq!(summary_stat("median", &array, true).unwrap(), Some(2.0)); + assert_eq!(num(summary_stat("mean", &array, true)), Some(2.0)); + assert_eq!(num(summary_stat("median", &array, true)), Some(2.0)); } #[test] fn mean_accepts_integer_columns() { let array: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3])); - assert_eq!(summary_stat("MEAN", &array, false).unwrap(), Some(2.0)); + assert_eq!(num(summary_stat("MEAN", &array, false)), Some(2.0)); } #[test] fn median_interpolates_even_counts() { let odd: ArrayRef = Arc::new(Float64Array::from(vec![3.0, 1.0, 2.0])); - assert_eq!(summary_stat("median", &odd, false).unwrap(), Some(2.0)); + assert_eq!(num(summary_stat("median", &odd, false)), Some(2.0)); let even: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])); - assert_eq!(summary_stat("median", &even, false).unwrap(), Some(2.5)); + assert_eq!(num(summary_stat("median", &even, false)), Some(2.5)); } #[test] fn all_null_input_is_none() { let array: ArrayRef = Arc::new(Float64Array::from(vec![None::, None])); - assert_eq!(summary_stat("mean", &array, true).unwrap(), None); + assert_eq!(num(summary_stat("mean", &array, true)), None); } #[test] @@ -579,43 +760,37 @@ mod tests { #[test] fn count_is_type_free() { let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None, Some("b")])); - assert_eq!(summary_stat("count", &strings, false).unwrap(), Some(3.0)); - assert_eq!(summary_stat("count", &strings, true).unwrap(), Some(2.0)); + assert_eq!(num(summary_stat("count", &strings, false)), Some(3.0)); + assert_eq!(num(summary_stat("count", &strings, true)), Some(2.0)); } #[test] fn count_of_an_empty_slice_is_zero() { let array: ArrayRef = Arc::new(Float64Array::from(Vec::::new())); - assert_eq!(summary_stat("count", &array, false).unwrap(), Some(0.0)); + assert_eq!(num(summary_stat("count", &array, false)), Some(0.0)); } #[test] fn n_missing_counts_nulls() { let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(3.0)])); - assert_eq!(summary_stat("n_missing", &array, false).unwrap(), Some(1.0)); - assert_eq!(summary_stat("n_missing", &array, true).unwrap(), Some(1.0)); + assert_eq!(num(summary_stat("n_missing", &array, false)), Some(1.0)); + assert_eq!(num(summary_stat("n_missing", &array, true)), Some(1.0)); } #[test] fn n_distinct_counts_distinct_values() { let numeric: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 2, 3, 1])); - assert_eq!( - summary_stat("n_distinct", &numeric, false).unwrap(), - Some(3.0) - ); + assert_eq!(num(summary_stat("n_distinct", &numeric, false)), Some(3.0)); let strings: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "a"])); - assert_eq!( - summary_stat("n_distinct", &strings, false).unwrap(), - Some(2.0) - ); + assert_eq!(num(summary_stat("n_distinct", &strings, false)), Some(2.0)); } #[test] fn n_distinct_propagates_nulls() { let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), None, Some(2.0)])); - assert_eq!(summary_stat("n_distinct", &array, false).unwrap(), None); - assert_eq!(summary_stat("n_distinct", &array, true).unwrap(), Some(2.0)); + assert_eq!(num(summary_stat("n_distinct", &array, false)), None); + assert_eq!(num(summary_stat("n_distinct", &array, true)), Some(2.0)); } fn eval(template: &str, array: &ArrayRef, drop_nulls: bool) -> String { @@ -642,7 +817,7 @@ mod tests { fn stat(operation: &str, values: &[f64]) -> f64 { let array: ArrayRef = Arc::new(Float64Array::from(values.to_vec())); - summary_stat(operation, &array, false).unwrap().unwrap() + num(summary_stat(operation, &array, false)).unwrap() } #[test] @@ -668,6 +843,161 @@ mod tests { assert!((stat("p95", v) - 3.85).abs() < 1e-12); } + /// 2024-01-15, 2024-01-16, 2024-01-18 as days since the epoch. + fn dates() -> ArrayRef { + Arc::new(Date32Array::from(vec![19737, 19738, 19740])) + } + + #[test] + fn date_valued_ops_on_dates_return_dates() { + assert!(matches!( + summary_stat("min", &dates(), false).unwrap(), + Some(Value::Date(19737)) + )); + assert!(matches!( + summary_stat("max", &dates(), false).unwrap(), + Some(Value::Date(19740)) + )); + assert!(matches!( + summary_stat("median", &dates(), false).unwrap(), + Some(Value::Date(19738)) + )); + // (19737 + 19740) / 2 = 19738.5, rounding to 19739. + assert!(matches!( + summary_stat("mid", &dates(), false).unwrap(), + Some(Value::Date(19739)) + )); + } + + #[test] + fn a_mean_of_dates_rounds_to_a_whole_day() { + // Mean of 19737 and 19738 falls on 19737.5. + let array: ArrayRef = Arc::new(Date32Array::from(vec![19737, 19738])); + assert!(matches!( + summary_stat("mean", &array, false).unwrap(), + Some(Value::Date(19738)) + )); + } + + #[test] + fn spread_ops_on_dates_return_days() { + assert!(matches!( + summary_stat("range", &dates(), false).unwrap(), + Some(Value::Number(3.0)) + )); + assert!(matches!( + summary_stat("iqr", &dates(), false).unwrap(), + Some(Value::Number(1.5)) + )); + } + + #[test] + fn spread_ops_on_timestamps_return_seconds() { + let array: ArrayRef = Arc::new(TimestampSecondArray::from(vec![0, 10, 50])); + assert!(matches!( + summary_stat("range", &array, false).unwrap(), + Some(Value::Number(50.0)) + )); + // Population variance of 0, 10, 50 is 1400/3. + assert!(matches!( + summary_stat("sdev", &array, false).unwrap(), + Some(Value::Number(s)) if (s * s - 1400.0 / 3.0).abs() < 1e-9 + )); + } + + #[test] + fn date_valued_ops_on_timestamps_return_datetimes() { + let array: ArrayRef = Arc::new(TimestampMillisecondArray::from(vec![1_000, 3_000, 5_000])); + assert!(matches!( + summary_stat("min", &array, false).unwrap(), + Some(Value::DateTime(1_000_000)) + )); + assert!(matches!( + summary_stat("median", &array, false).unwrap(), + Some(Value::DateTime(3_000_000)) + )); + } + + #[test] + fn other_folds_reject_temporal_columns() { + for op in ["sum", "prod", "geomean", "harmean", "rms", "var"] { + assert!( + summary_stat(op, &dates(), false).is_err(), + "{op} should reject a date column" + ); + } + } + + #[test] + fn tallies_still_accept_temporal_columns() { + assert_eq!(num(summary_stat("count", &dates(), false)), Some(3.0)); + assert_eq!(num(summary_stat("n_distinct", &dates(), false)), Some(3.0)); + } + + #[test] + fn temporal_nulls_propagate_by_default() { + let array: ArrayRef = Arc::new(Date32Array::from(vec![Some(19737), None])); + assert!(summary_stat("min", &array, false).unwrap().is_none()); + assert!(matches!( + summary_stat("min", &array, true).unwrap(), + Some(Value::Date(19737)) + )); + } + + #[test] + fn templates_format_date_leaves_as_dates() { + assert_eq!(eval("{min}", &dates(), false), "2024-01-15"); + assert_eq!(eval("{min:time %d %b %Y}", &dates(), false), "15 Jan 2024"); + } + + #[test] + fn template_arithmetic_on_dates_is_a_number_of_days() { + assert_eq!(eval("{max-min}", &dates(), false), "3"); + assert_eq!(eval("{max-min:duration d}", &dates(), false), "3d"); + assert_eq!(eval("{(max-min)/7:%.4f}", &dates(), false), "0.4286"); + } + + #[test] + fn a_date_summary_frame_keeps_the_date_type() { + let df = DataFrame::new(vec![("d".to_string(), dates())]).unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("mean", SummaryScope::Grand, &["d"])], + &HashMap::new(), + ) + .unwrap(); + + let array = computed[0].1[0].frame.column("d").unwrap(); + assert_eq!(array.data_type(), &DataType::Date32); + // 19737.67 rounds to 19738: 2024-01-16. + assert_eq!(column_to_strings(array), vec!["2024-01-16"]); + } + + #[test] + fn a_timestamp_summary_frame_keeps_the_timestamp_type() { + let column: ArrayRef = Arc::new(TimestampSecondArray::from(vec![0, 3600, 7200])); + let df = DataFrame::new(vec![("t".to_string(), column)]).unwrap(); + let rows = body_rows(&[&[], &[], &[]]); + + let computed = compute_summaries( + &df, + &rows, + &[summary("max", SummaryScope::Grand, &["t"])], + &HashMap::new(), + ) + .unwrap(); + + let array = computed[0].1[0].frame.column("t").unwrap(); + assert_eq!( + array.data_type(), + &DataType::Timestamp(TimeUnit::Second, None) + ); + assert_eq!(column_to_strings(array), vec!["1970-01-01T02:00:00"]); + } + fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { Summary { operation: SummaryOperation::Stat(operation.to_string()), From 5b694d0428682ef20c159ed044f08b8c601766c4 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 13:25:01 +0100 Subject: [PATCH 25/37] filler cells --- doc/syntax/clause/summarise.qmd | 12 ++++++ doc/vendor/SKILL.md | 2 +- src/execute/table/mod.rs | 65 ++++++++++++++++++++++++++++++++- src/execute/table/summary.rs | 11 +++++- src/table/summary.rs | 6 +++ 5 files changed, 92 insertions(+), 4 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index 51513504a..317015636 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -110,6 +110,8 @@ Can be `'top'` to place the summary rows at the top of each group or table, or ` * `missing`: A string option for how to treat `null` values in the table. The default `'propagate'` will list any non-counting operation as `null`, and counting operations include null-rows. Can be set to `'drop'` to explicitly ignore `null` values in aggregates and ignore these rows in counting operations. +* `blank`: A string displayed in cells of the summary row whose column are not summarised. +The default is an em dash (`'—'`); set it to `''` for empty cells. ## Examples @@ -157,6 +159,16 @@ SUMMARISE mean OF bill_len, bill_dep SETTING rowlabel => 'Average' ``` +The display of non-summary cells can be changed using the `blank` setting. +Using an empty string (`''`) leaves these cells empty. + +```{ggsql} +TABULATE * FROM my_data +FACET species +SUMMARISE mean OF bill_len, bill_dep + SETTING blank => '' +``` + The summary cells are subject to `FORMAT` when using plain identifiers, along with the body rows. ```{ggsql} diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index 53333488a..b3246c110 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -205,7 +205,7 @@ SUMMARISE [GROUP | GRAND] OF , ... - **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns, except that date/timestamp columns also accept the order statistics (`min max mid mean median p*`, returning a date/timestamp) and `range sdev se iqr` (returning a duration). - **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats and ignores the column's `FORMAT` renaming; a bare operation takes it. -- **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop). +- **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop), `blank` (display text for cells in columns the clause does not summarise; default `'—'` — a summarised column that computes to null still reports `null`). ```ggsql TABULATE * FROM ggsql:penguins diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index b0c6aec5a..b685f4a23 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -876,13 +876,14 @@ mod integration_tests { .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 1) .unwrap(); assert_eq!(value.content, "2"); - // The non-summarised column's cell is blank. + // The non-summarised column's cell shows the blank fill, an em dash + // by default. let blank = resolved .cells() .iter() .find(|c| c.kind == TableCellKind::SummaryValue && c.top == 4 && c.left == 2) .unwrap(); - assert_eq!(blank.content, ""); + assert_eq!(blank.content, "—"); } #[test] @@ -1057,6 +1058,66 @@ mod integration_tests { assert_eq!(value.content, "null of 2"); } + #[test] + fn test_tabulate_summarise_fills_unsummarised_cells_with_the_blank_default() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES (1.0, 'a'), (2.0, 'b')) AS t(x, y)", + ) + .unwrap(); + let resolved = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE mean OF x", &reader).unwrap(); + + let contents: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::SummaryValue) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(contents, ["1.5", "—"]); + } + + #[test] + fn test_tabulate_summarise_blank_setting_customises_the_fill() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql( + "CREATE TABLE t AS SELECT * FROM (VALUES (1.0, 'a'), (2.0, 'b')) AS t(x, y)", + ) + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE mean OF x SETTING blank => 'N/A'", + &reader, + ) + .unwrap(); + + let contents: Vec<&str> = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::SummaryValue) + .map(|c| c.content.as_str()) + .collect(); + assert_eq!(contents, ["1.5", "N/A"]); + } + + #[test] + fn test_tabulate_summarise_null_value_reports_null_not_the_blank_fill() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE mean OF x", &reader).unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "null"); + } + #[test] fn test_tabulate_summarise_separated_facet_rekeys_the_summary_chunks() { let reader = reader_with_region_sales(); diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 29c90a055..85617b4fa 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -74,6 +74,9 @@ pub(super) struct SummaryRow { pub top: bool, /// The row's stub label: `rowlabel`, else the operation name. pub label: String, + /// Display text for a body cell in a column the clause did not + /// summarise: the `blank` setting, em dash by default. + pub blank: String, /// One-row frame of the computed values; its schema names the /// summarised columns. Numeric for a bare operation — the column's /// temporal type for a date-valued statistic on a date/timestamp @@ -139,7 +142,7 @@ impl SummaryRow { .frame .column(&column.name) .map(|array| column_to_strings(array).remove(0)) - .unwrap_or_default(); + .unwrap_or_else(|_| self.blank.clone()); let mut cell = TableCell::new_summary_value(row, index, content) .with_properties(column.properties.clone()); cell.classes.extend_from_slice(&classes); @@ -241,6 +244,11 @@ pub(super) fn compute_summaries( .and_then(ParameterValue::as_str) .map_or_else(|| summary.operation.as_label(), str::to_string); let top = ParameterValue::is_str(summary.settings.get("place"), "top"); + let blank = summary + .settings + .get("blank") + .and_then(ParameterValue::as_str) + .unwrap_or("—"); let targets = match summary.scope { SummaryScope::Group => 0..chunks.len() - 1, SummaryScope::Grand => chunks.len() - 1..chunks.len(), @@ -257,6 +265,7 @@ pub(super) fn compute_summaries( scope: summary.scope, top, label: label.clone(), + blank: blank.to_string(), frame, }); } diff --git a/src/table/summary.rs b/src/table/summary.rs index 8149cb294..11b654d3d 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -449,6 +449,12 @@ const SUMMARY_PARAMS: &[ParamDefinition] = &[ default: DefaultParamValue::String("propagate"), constraint: ParamConstraint::string_option(&["propagate", "drop"]), }, + ParamDefinition { + // Display text for an empty cell in a summary row. + name: "blank", + default: DefaultParamValue::String("—"), + constraint: ParamConstraint::string(), + }, ]; impl Summary { From e56fb079d5574aba1e00741bfe09eeeef80590f1 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 16:03:17 +0100 Subject: [PATCH 26/37] float columns share precision --- doc/vendor/SKILL.md | 1 + src/execute/table/format.rs | 93 ++++++++++++++++++++++++------------ src/execute/table/layout.rs | 6 +-- src/execute/table/mod.rs | 93 ++++++++++++++++++++++++++++++++++-- src/execute/table/summary.rs | 81 +++++++++++++++++++++++-------- src/format.rs | 75 ++++++++++++++++++++++++++++- 6 files changed, 291 insertions(+), 58 deletions(-) diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index b3246c110..6a3da2f50 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -184,6 +184,7 @@ Configures cell display and column placement. - A SPAN id may stand in for its columns: `FORMAT Q1, price SETTING hjust => 'right'` - Settings: `hjust` (`'left'`/`'right'`/`'centre'`/`'center'` or 0–1; default right for numeric/stub, left otherwise), `width` (`'100px'` or `'20%'`) - `RENAMING` works like SCALE's: direct replacement (`'adelie' => 'Pygoscelis adeliae'`), `null` on the right suppresses the cell, unquoted `null` on the left matches missing values, and `* => '...'` formats every value with a template (`{:lower}`, `{:num %.0f}`, etc.) +- Without a RENAMING, float columns display at a shared per-column precision: the most decimals any value needs (each value the fewest that faithfully represents it), so whole values pad (`50.0` beside `39.1`) and SUMMARISE results round to the same precision. Integer columns display bare. ```ggsql SELECT * FROM ggsql:penguins LIMIT 5 diff --git a/src/execute/table/format.rs b/src/execute/table/format.rs index e71186781..59c66dc48 100644 --- a/src/execute/table/format.rs +++ b/src/execute/table/format.rs @@ -1,11 +1,13 @@ //! `TABULATE FORMAT` resolution: `setup_formats` validates `SETTING` //! parameters and reshapes the per-clause formats into one `Format` per -//! column, `apply_formats` replaces a column's values with their display -//! text (`RENAMING`), and `resolve_column_properties` resolves a column's -//! `SETTING` display properties. +//! column, `apply_formatting` replaces a column's values with their display +//! text (`RENAMING`, or the float display precision from `display_decimals`), +//! and `resolve_column_properties` resolves a column's `SETTING` display +//! properties. use std::collections::HashMap; +use arrow::array::Array; use arrow::datatypes::DataType; use crate::array_util::{new_str_array, value_to_string}; @@ -89,38 +91,69 @@ fn expand_format_columns( Ok(columns) } -/// Replace every column in `df` named in `formats` with its resolved -/// display text. A column whose `Format` has no `RENAMING` at all -/// (`renaming` empty) is left untouched. -pub(super) fn apply_formats( +/// Replace display-affecting columns in `df` with their display text. A +/// column named in `formats` with a `RENAMING` (mapping or template) gets +/// its resolved labels; a float column gets padded to its display decimals +/// (see `display_decimals`). Everything else is left untouched. +pub(super) fn apply_formatting( df: &DataFrame, formats: &HashMap, ) -> Result { let mut df = df.clone(); - for (name, format) in formats { - // Skip the per-row formatting pass for a column nobody asked to - // reformat — the common `FORMAT ... SETTING ...` case. - let has_renaming = - !format.renaming.rename_is_empty() || format.renaming.template().is_some(); - if !has_renaming { - continue; - } - + for name in df.get_column_names() { + let format = formats.get(&name); + // A column whose format carries no renaming — the common + // `FORMAT ... SETTING ...` case — skips the renaming pass. + let has_renaming = format + .is_some_and(|f| !f.renaming.rename_is_empty() || f.renaming.template().is_some()); let array = df - .column(name) - .expect("setup_formats already checked this column exists") + .column(&name) + .expect("the names come from this frame") .clone(); - let resolved = crate::format::resolve_column_values(&array, &format.renaming) - .map_err(|e| GgsqlError::ValidationError(format!("FORMAT column '{name}': {e}")))?; - let display: Vec> = resolved - .into_iter() - .enumerate() - .map(|(row, value)| Some(value.unwrap_or_else(|| value_to_string(&array, row)))) + if has_renaming { + let format = format.expect("has_renaming implies a format"); + let resolved = crate::format::resolve_column_values(&array, &format.renaming) + .map_err(|e| GgsqlError::ValidationError(format!("FORMAT column '{name}': {e}")))?; + + let display: Vec> = resolved + .into_iter() + .enumerate() + .map(|(row, value)| Some(value.unwrap_or_else(|| value_to_string(&array, row)))) + .collect(); + let display_refs: Vec> = display.iter().map(|s| s.as_deref()).collect(); + + df = df.with_column(&name, new_str_array(display_refs))?; + continue; + } + + // A renamed column's labels are its display, so only un-renamed + // columns reach the padding pass. Needing no decimals keeps the + // bare integer display. + let d = crate::format::display_decimals(&array); + if d == 0 { + continue; + } + let display: Vec> = (0..array.len()) + .map(|i| { + if array.is_null(i) { + None + } else { + Some(match array.data_type() { + DataType::Float64 => { + let v = crate::array_util::as_f64(&array).unwrap().value(i); + format!("{v:.d$}") + } + _ => { + let v = f64::from(crate::array_util::as_f32(&array).unwrap().value(i)); + format!("{v:.d$}") + } + }) + } + }) .collect(); let display_refs: Vec> = display.iter().map(|s| s.as_deref()).collect(); - - df = df.with_column(name, new_str_array(display_refs))?; + df = df.with_column(&name, new_str_array(display_refs))?; } Ok(df) @@ -313,7 +346,7 @@ mod tests { let frame = df! { "price" => vec![1.0f64, 2.0] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("{}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["1", "2"]); } @@ -323,7 +356,7 @@ mod tests { let frame = df! { "price" => vec![1.0f64, 2.0] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("${:num %.2f}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["$1.00", "$2.00"]); } @@ -334,7 +367,7 @@ mod tests { let mapping = Some(HashMap::from([("0".to_string(), Some("-".to_string()))])); let formats = HashMap::from([("price".to_string(), format_with("{:num %.2f}", mapping))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["-", "5.00"]); } @@ -344,7 +377,7 @@ mod tests { let frame = df! { "price" => vec![Some(1.0f64), None] }.unwrap(); let formats = HashMap::from([("price".to_string(), format_with("{:num %.2f}", None))]); - let result = apply_formats(&frame, &formats).unwrap(); + let result = apply_formatting(&frame, &formats).unwrap(); assert_eq!(column_content(&result, "price"), vec!["1.00", "null"]); } diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 30261d1eb..91d566644 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -508,7 +508,7 @@ fn merge_group_stub_cells( #[cfg(test)] mod tests { - use super::super::format::{apply_formats, setup_formats}; + use super::super::format::{apply_formatting, setup_formats}; use super::super::summary::{compute_summaries, setup_summaries}; use super::*; use crate::df; @@ -530,7 +530,7 @@ mod tests { .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(df, &table.formats, &spans)?; let columns = setup_columns(df, &spans, &labels, &formats, None); - let df = apply_formats(df, &formats)?; + let df = apply_formatting(df, &formats)?; let rows = vec![TableRow::body(); df.height()]; build_cells(&df, columns, rows, &spans, &titles, None, &[]) } @@ -557,7 +557,7 @@ mod tests { setup_summaries(&mut df, &formats, &table.summaries)?; let columns = setup_columns(&df, &spans, &labels, &formats, facet); let computed = compute_summaries(&df, &rows, &table.summaries, &formats)?; - let df = apply_formats(&df, &formats)?; + let df = apply_formatting(&df, &formats)?; build_cells(&df, columns, rows, &spans, &titles, facet, &computed) } diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index b685f4a23..2933b43f3 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -14,7 +14,7 @@ mod stub; mod summary; use facet::collapse_group_columns; -use format::{apply_formats, setup_formats}; +use format::{apply_formatting, setup_formats}; use layout::{build_cells, setup_columns, setup_rows}; use summary::{compute_summaries, setup_summaries}; @@ -74,7 +74,7 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Result Vec { + let mut contents: Vec = resolved + .cells() + .iter() + .filter(|c| c.kind == TableCellKind::Body) + .map(|c| c.content.clone()) + .collect(); + contents.sort(); + contents + } + + fn resolve_doubles(query: &str, values: &str) -> ResolvedTable { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql(&format!( + "CREATE TABLE t AS SELECT CAST(v AS DOUBLE) AS x FROM (VALUES {values}) AS t(v)" + )) + .unwrap(); + resolve_table_with_reader(query, &reader).unwrap() + } + + #[test] + fn test_tabulate_float_column_pads_to_a_shared_precision() { + let resolved = resolve_doubles("TABULATE * FROM t", "(39.1), (37.7), (50.0)"); + assert_eq!(body_contents(&resolved), ["37.7", "39.1", "50.0"]); + } + + #[test] + fn test_tabulate_float_precision_ignores_binary_noise() { + let resolved = resolve_doubles("TABULATE * FROM t", "(0.1 + 0.2), (1.5)"); + assert_eq!(body_contents(&resolved), ["0.3", "1.5"]); + } + + #[test] + fn test_tabulate_float_precision_keeps_real_decimals() { + let resolved = resolve_doubles("TABULATE * FROM t", "(1.25), (3.75)"); + assert_eq!(body_contents(&resolved), ["1.25", "3.75"]); + } + + #[test] + fn test_tabulate_format_renaming_overrides_inferred_precision() { + let resolved = resolve_doubles( + "TABULATE * FROM t FORMAT x RENAMING * => '{:num %.3f}'", + "(1.5), (2.0)", + ); + assert_eq!(body_contents(&resolved), ["1.500", "2.000"]); + } + + #[test] + fn test_tabulate_summarise_matches_the_column_precision() { + let resolved = resolve_doubles( + "TABULATE * FROM t SUMMARISE mean OF x", + "(39.1), (37.7), (50.0)", + ); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "42.3"); + } + + #[test] + fn test_tabulate_summarise_pads_an_exactly_whole_mean() { + let resolved = resolve_doubles("TABULATE * FROM t SUMMARISE mean OF x", "(41.5), (42.5)"); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "42.0"); + } + + #[test] + fn test_tabulate_summarise_count_keeps_integer_display() { + let resolved = resolve_doubles( + "TABULATE * FROM t SUMMARISE count OF x", + "(39.1), (37.7), (50.0)", + ); + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "3"); + } + #[test] fn test_tabulate_summarise_separated_facet_rekeys_the_summary_chunks() { let reader = reader_with_region_sales(); diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 85617b4fa..c891ea583 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -229,6 +229,20 @@ pub(super) fn compute_summaries( rows: Vec::new(), }); + // Display decimals for every summarised column, computed once and + // shared by every clause and chunk. + let columns: HashSet<&str> = summaries + .iter() + .flat_map(|summary| summary.columns.iter().map(String::as_str)) + .collect(); + let decimals: HashMap<&str, usize> = columns + .into_iter() + .filter_map(|column| { + let d = crate::format::display_decimals(df.column(column).ok()?); + (d > 0).then_some((column, d)) + }) + .collect(); + // Clause-outer: the label, placement and parsed template are clause-level // facts, computed once and shared by every group's row. for summary in summaries { @@ -256,11 +270,8 @@ pub(super) fn compute_summaries( for index in targets { let chunk = &mut chunks[index]; let mut frame = summary_frame(df, summary, template.as_deref(), &chunk.range)?; - // Templates self-format; a bare operation takes the column's - // FORMAT renaming. - if template.is_none() { - format_summary_frame(&mut frame, &summary.columns, formats)?; - } + // A bare operation's frame is made display-ready here (renaming, display decimals). + format_summary_frame(&mut frame, summary, formats, &decimals)?; chunk.rows.push(SummaryRow { scope: summary.scope, top, @@ -400,27 +411,55 @@ fn leaf_f64(value: &Value) -> Option { } } -/// Apply each summarised column's `FORMAT` renaming to a one-row summary -/// frame, turning the formatted columns into display text — the same -/// treatment `apply_formats` gives the body cells, per value. +/// Make a bare-operation summary frame display-ready, per column: an +/// explicit `FORMAT` renaming (mapping or template) becomes the display +/// text; an un-renamed float column pads to its body column's display +/// decimals — the same treatment `apply_formatting` gives the body +/// cells. Tallies are counts and keep their integer display. `decimals` +/// covers every summarised column, computed once in `compute_summaries`. fn format_summary_frame( frame: &mut DataFrame, - columns: &[String], + summary: &Summary, formats: &HashMap, + decimals: &HashMap<&str, usize>, ) -> Result<()> { - for column in columns { - let Some(format) = formats.get(column) else { - continue; - }; - if format.renaming.rename_is_empty() && format.renaming.template().is_none() { - continue; - } + // Templates self-format so these are skipped + let SummaryOperation::Stat(operation) = &summary.operation else { + return Ok(()); + }; + // Tallies pad to no decimals: they are counts and keep their integer + // display. + let tally = matches!( + operation.to_ascii_lowercase().as_str(), + "count" | "n_distinct" | "n_missing" + ); + for column in &summary.columns { + let renaming = formats + .get(column) + .map(|format| &format.renaming) + .filter(|renaming| !renaming.rename_is_empty() || renaming.template().is_some()); let array = frame.column(column)?.clone(); - let mut resolved = crate::format::resolve_column_values(&array, &format.renaming) - .map_err(GgsqlError::ValidationError)?; - let text = resolved - .remove(0) - .unwrap_or_else(|| value_to_string(&array, 0)); + let text = if let Some(renaming) = renaming { + let mut resolved = crate::format::resolve_column_values(&array, renaming) + .map_err(GgsqlError::ValidationError)?; + resolved + .remove(0) + .unwrap_or_else(|| value_to_string(&array, 0)) + } else { + if tally { + continue; + } + let Some(&d) = decimals.get(column.as_str()) else { + continue; + }; + let Ok(floats) = crate::array_util::as_f64(&array) else { + continue; + }; + if array.is_null(0) { + continue; + } + format!("{:.1$}", floats.value(0), d) + }; *frame = frame.with_column(column, Arc::new(StringArray::from(vec![text])) as ArrayRef)?; } Ok(()) diff --git a/src/format.rs b/src/format.rs index 95ea05071..fd99b9470 100644 --- a/src/format.rs +++ b/src/format.rs @@ -17,7 +17,7 @@ use arrow::array::{Array, ArrayRef, BooleanArray, Int64Array, UInt64Array}; use arrow::datatypes::DataType; use zygos::{LabelSpec, Value}; -use crate::array_util::{as_f64, as_str, cast_array, new_str_array}; +use crate::array_util::{as_f32, as_f64, as_str, cast_array, new_str_array}; use crate::plot::ArrayElement; /// Serde mirror for [`zygos::LabelSpec`], which is dependency-free and has no @@ -412,6 +412,56 @@ pub fn format_dataframe_column( .map_err(|e| format!("Failed to replace column: {}", e)) } +/// Decimal places to display a float column consistently: the most any +/// non-null value needs, each value asking for the fewest decimals that +/// round-trip within float noise (`f64::EPSILON.sqrt()`, relative). +/// Non-float columns need none. +pub fn display_decimals(column: &ArrayRef) -> usize { + let decimals: Box + '_> = match column.data_type() { + DataType::Float64 => Box::new( + as_f64(column) + .unwrap() + .iter() + .map(|v| v.unwrap_or(f64::NAN)), + ), + DataType::Float32 => Box::new( + as_f32(column) + .unwrap() + .iter() + .map(|v| f64::from(v.unwrap_or(f32::NAN))), + ), + _ => return 0, + }; + // Search each value only upward from the running maximum: a value + // fitting at fewer decimals cannot lower it, and a fit at `d` fits at + // every larger `d`, so nothing below the maximum needs checking. + let mut max = 0; + for v in decimals { + max = minimal_decimals(v, max); + if max == 15 { + break; + } + } + max +} + +/// Fewest decimal places that represent `v` within float noise: the +/// smallest `d >= from` whose rounded value is within +/// `f64::EPSILON.sqrt()` (relative) of `v`. Caps at 15, past which an f64 +/// carries no real information. Non-finite values contribute nothing. +fn minimal_decimals(v: f64, from: usize) -> usize { + if !v.is_finite() { + return from; + } + let tol = f64::EPSILON.sqrt() * v.abs().max(1.0); + (from..=15) + .find(|&d| { + let factor = 10f64.powi(d as i32); + ((v * factor).round() / factor - v).abs() <= tol + }) + .unwrap_or(15) +} + #[cfg(test)] mod tests { use super::*; @@ -426,6 +476,29 @@ mod tests { breaks.iter().map(|n| ArrayElement::Number(*n)).collect() } + fn floats(values: &[f64]) -> ArrayRef { + std::sync::Arc::new(arrow::array::Float64Array::from(values.to_vec())) + } + + #[test] + fn display_decimals_pads_to_the_widest_value() { + assert_eq!(display_decimals(&floats(&[39.1, 37.7, 50.0])), 1); + assert_eq!(display_decimals(&floats(&[1.25, 3.75])), 2); + } + + #[test] + fn display_decimals_trims_binary_float_noise() { + assert_eq!(display_decimals(&floats(&[0.1 + 0.2, 1.5])), 1); + assert_eq!(display_decimals(&floats(&[std::f64::consts::PI])), 7); + } + + #[test] + fn display_decimals_is_zero_for_whole_and_non_float_columns() { + assert_eq!(display_decimals(&floats(&[50.0, 60.0])), 0); + let ints: ArrayRef = std::sync::Arc::new(arrow::array::Int64Array::from(vec![1, 2])); + assert_eq!(display_decimals(&ints), 0); + } + fn strings(breaks: &[&str]) -> Vec { breaks .iter() From 7e72c0d8266fc4e0049dc8c368fafc40f779af50 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 16:42:02 +0100 Subject: [PATCH 27/37] Deal with template nulls --- doc/syntax/clause/summarise.qmd | 2 + doc/vendor/SKILL.md | 2 +- src/execute/table/mod.rs | 44 +++++++++++- src/execute/table/summary.rs | 117 ++++++++++++++++++++------------ src/format.rs | 18 +++++ 5 files changed, 138 insertions(+), 45 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index 317015636..d2a339798 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -72,9 +72,11 @@ Inside the brackets, you can use limited arithmetic. The operands include the operation identifiers listed above (like `mean`, `sdev`), numeric literals (`2`, `0.5`) and scientific notation (`1e6`). The `+`, `-` unary operators and `+`, `-`, `*` and `/` binary operators and `(`/`)` parentheses for grouping. For example you can use `'({mean - 1.96 * se}, {mean + 1.96 * se})'` to display a 95% confidence interval (assuming normal distribution) in parentheses separated by a comma. +If any placeholder in a string expression comes out `null` (see `missing` below), the whole cell comes out `null`. For the naked, non-string identifiers the formatting of the cell values is applied externally via `FORMAT` clauses. The string expressions can be self-formatting via the same syntax as [scale breaks](scale.qmd#break-formatting). +A string-expression cell ignores a `FORMAT` wildcard renaming, but direct renamings still apply — including `null => …` to replace a null result. All summary metrics are assumed to be numeric. As such, the `:num` formatter is implied and does not need to be written out in full. The expression `'{mean:%.2f}'` will display the mean with two decimal points in printf-style. diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index 6a3da2f50..ff23b9d75 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -205,7 +205,7 @@ SUMMARISE [GROUP | GRAND] OF , ... ``` - **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns, except that date/timestamp columns also accept the order statistics (`min max mid mean median p*`, returning a date/timestamp) and `range sdev se iqr` (returning a duration). -- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats and ignores the column's `FORMAT` renaming; a bare operation takes it. +- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats: the column's `FORMAT` wildcard renaming does not apply, but direct renamings do (including `null => …` — a null placeholder nulls the whole cell); a bare operation takes the full renaming. - **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop), `blank` (display text for cells in columns the clause does not summarise; default `'—'` — a summarised column that computes to null still reports `null`). ```ggsql diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 2933b43f3..ec9fca3f0 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -1039,7 +1039,47 @@ mod integration_tests { } #[test] - fn test_tabulate_summarise_template_renders_a_null_stat_as_null() { + fn test_tabulate_summarise_template_null_is_targetable_by_a_direct_renaming() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x FORMAT x RENAMING null => ''", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, ""); + } + + #[test] + fn test_tabulate_summarise_template_ignores_a_wildcard_renaming() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (2.0)) AS t(x)") + .unwrap(); + let resolved = resolve_table_with_reader( + "TABULATE * FROM t SUMMARISE '{mean} of {count}' OF x FORMAT x RENAMING * => '{:num %.2f}'", + &reader, + ) + .unwrap(); + + let value = resolved + .cells() + .iter() + .find(|c| c.kind == TableCellKind::SummaryValue) + .unwrap(); + assert_eq!(value.content, "1.5 of 2"); + } + + #[test] + fn test_tabulate_summarise_template_nulls_the_whole_cell_on_a_null_stat() { let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); reader .execute_sql("CREATE TABLE t AS SELECT * FROM (VALUES (1.0), (NULL)) AS t(x)") @@ -1055,7 +1095,7 @@ mod integration_tests { .iter() .find(|c| c.kind == TableCellKind::SummaryValue) .unwrap(); - assert_eq!(value.content, "null of 2"); + assert_eq!(value.content, "null"); } #[test] diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index c891ea583..575a85780 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -196,7 +196,8 @@ pub(super) type SummaryChunk = (Option>, Vec); /// the weavers' concern; they read each row's `top`. /// /// A bare operation's summary value takes its column's `FORMAT` renaming -/// just like the body cells; a template self-formats via zygos. +/// just like the body cells; a template self-formats via zygos, honouring +/// only direct renamings from the column's `FORMAT`. pub(super) fn compute_summaries( df: &DataFrame, rows: &[TableRow], @@ -270,7 +271,8 @@ pub(super) fn compute_summaries( for index in targets { let chunk = &mut chunks[index]; let mut frame = summary_frame(df, summary, template.as_deref(), &chunk.range)?; - // A bare operation's frame is made display-ready here (renaming, display decimals). + // The frame is made display-ready here (renaming, display + // decimals); a template's cells take direct renamings only. format_summary_frame(&mut frame, summary, formats, &decimals)?; chunk.rows.push(SummaryRow { scope: summary.scope, @@ -329,30 +331,28 @@ fn summary_frame( /// Render a template against one column's slice: literals verbatim, each /// placeholder's expression evaluated over the slice and rendered through its -/// pre-compiled zygos template. A NULL expression renders as the literal -/// "null", like the body cells. Stats are memoized in `cache` across all of +/// pre-compiled zygos template. A NULL placeholder makes the whole cell +/// NULL, like a bare operation. Stats are memoized in `cache` across all of /// the template's placeholders, so a repeated stat computes once per cell. fn render_template( segments: &[TemplateSegment], slice: &ArrayRef, drop_nulls: bool, -) -> Result { +) -> Result> { let mut cache = HashMap::new(); let mut text = String::new(); for segment in segments { match segment { TemplateSegment::Literal(literal) => text.push_str(literal), TemplateSegment::Stat { expr, template } => { - match eval_stat_expr(expr, slice, drop_nulls, &mut cache)? { - Some(value) => { - text.push_str(&template.format(&value, None).unwrap_or_default()) - } - None => text.push_str("null"), - } + let Some(value) = eval_stat_expr(expr, slice, drop_nulls, &mut cache)? else { + return Ok(None); + }; + text.push_str(&template.format(&value, None).unwrap_or_default()) } } } - Ok(text) + Ok(Some(text)) } /// Evaluate a template placeholder's expression over one column's slice: @@ -411,42 +411,50 @@ fn leaf_f64(value: &Value) -> Option { } } -/// Make a bare-operation summary frame display-ready, per column: an -/// explicit `FORMAT` renaming (mapping or template) becomes the display -/// text; an un-renamed float column pads to its body column's display -/// decimals — the same treatment `apply_formatting` gives the body -/// cells. Tallies are counts and keep their integer display. `decimals` -/// covers every summarised column, computed once in `compute_summaries`. +/// Make a summary frame display-ready, per column: an explicit `FORMAT` +/// renaming (mapping or template) becomes the display text; an un-renamed +/// float column pads to its body column's display decimals — the same +/// treatment `apply_formatting` gives the body cells. A template's cells +/// are already-rendered strings, so they honour only direct renamings +/// (including `null`), never the wildcard template, and never pad. +/// Tallies are counts and keep their integer display. `decimals` covers +/// every summarised column, computed once in `compute_summaries`. fn format_summary_frame( frame: &mut DataFrame, summary: &Summary, formats: &HashMap, decimals: &HashMap<&str, usize>, ) -> Result<()> { - // Templates self-format so these are skipped - let SummaryOperation::Stat(operation) = &summary.operation else { - return Ok(()); - }; + let template = matches!(summary.operation, SummaryOperation::Template(_)); // Tallies pad to no decimals: they are counts and keep their integer // display. - let tally = matches!( - operation.to_ascii_lowercase().as_str(), - "count" | "n_distinct" | "n_missing" - ); + let tally = match &summary.operation { + SummaryOperation::Stat(operation) => matches!( + operation.to_ascii_lowercase().as_str(), + "count" | "n_distinct" | "n_missing" + ), + SummaryOperation::Template(_) => false, + }; for column in &summary.columns { let renaming = formats .get(column) .map(|format| &format.renaming) - .filter(|renaming| !renaming.rename_is_empty() || renaming.template().is_some()); + .filter(|renaming| { + !renaming.rename_is_empty() || (!template && renaming.template().is_some()) + }); let array = frame.column(column)?.clone(); let text = if let Some(renaming) = renaming { - let mut resolved = crate::format::resolve_column_values(&array, renaming) - .map_err(GgsqlError::ValidationError)?; + let mut resolved = if template { + crate::format::resolve_column_values_direct(&array, renaming) + } else { + crate::format::resolve_column_values(&array, renaming) + } + .map_err(GgsqlError::ValidationError)?; resolved .remove(0) .unwrap_or_else(|| value_to_string(&array, 0)) } else { - if tally { + if template || tally { continue; } let Some(&d) = decimals.get(column.as_str()) else { @@ -841,7 +849,7 @@ mod tests { assert_eq!(num(summary_stat("n_distinct", &array, true)), Some(2.0)); } - fn eval(template: &str, array: &ArrayRef, drop_nulls: bool) -> String { + fn eval(template: &str, array: &ArrayRef, drop_nulls: bool) -> Option { let segments = parse_template(template).unwrap(); render_template(&segments, array, drop_nulls).unwrap() } @@ -849,18 +857,31 @@ mod tests { #[test] fn template_arithmetic_combines_stats() { let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0])); - assert_eq!(eval("{mean+10}", &array, false), "12"); - assert_eq!(eval("{(3-mean)*2}", &array, false), "2"); + assert_eq!(eval("{mean+10}", &array, false).as_deref(), Some("12")); + assert_eq!(eval("{(3-mean)*2}", &array, false).as_deref(), Some("2")); // A repeated stat computes once and combines cleanly. - assert_eq!(eval("{mean/mean}", &array, false), "1"); - assert_eq!(eval("{-mean}", &array, false), "−2"); + assert_eq!(eval("{mean/mean}", &array, false).as_deref(), Some("1")); + assert_eq!(eval("{-mean}", &array, false).as_deref(), Some("−2")); } #[test] fn template_arithmetic_propagates_nulls() { let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0), None])); - assert_eq!(eval("{mean-sdev}", &array, false), "null"); - assert_eq!(eval("{mean-sdev:%.1f}", &array, true), "1.0"); + assert_eq!(eval("{mean-sdev}", &array, false), None); + assert_eq!( + eval("{mean-sdev:%.1f}", &array, true).as_deref(), + Some("1.0") + ); + } + + #[test] + fn a_null_placeholder_nulls_the_whole_cell() { + let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0), None])); + assert_eq!(eval("{mean} +/- {sdev}", &array, false), None); + assert_eq!( + eval("{mean} +/- {sdev}", &array, true).as_deref(), + Some("1.5 +/- 0.5") + ); } fn stat(operation: &str, values: &[f64]) -> f64 { @@ -994,15 +1015,27 @@ mod tests { #[test] fn templates_format_date_leaves_as_dates() { - assert_eq!(eval("{min}", &dates(), false), "2024-01-15"); - assert_eq!(eval("{min:time %d %b %Y}", &dates(), false), "15 Jan 2024"); + assert_eq!( + eval("{min}", &dates(), false).as_deref(), + Some("2024-01-15") + ); + assert_eq!( + eval("{min:time %d %b %Y}", &dates(), false).as_deref(), + Some("15 Jan 2024") + ); } #[test] fn template_arithmetic_on_dates_is_a_number_of_days() { - assert_eq!(eval("{max-min}", &dates(), false), "3"); - assert_eq!(eval("{max-min:duration d}", &dates(), false), "3d"); - assert_eq!(eval("{(max-min)/7:%.4f}", &dates(), false), "0.4286"); + assert_eq!(eval("{max-min}", &dates(), false).as_deref(), Some("3")); + assert_eq!( + eval("{max-min:duration d}", &dates(), false).as_deref(), + Some("3d") + ); + assert_eq!( + eval("{(max-min)/7:%.4f}", &dates(), false).as_deref(), + Some("0.4286") + ); } #[test] diff --git a/src/format.rs b/src/format.rs index fd99b9470..6b07e6dfb 100644 --- a/src/format.rs +++ b/src/format.rs @@ -173,6 +173,24 @@ pub fn resolve_column_values( Ok(render_labels(spec, &values, false, Some(""), None)) } +/// Like [`resolve_column_values`], but consulting only the spec's direct +/// renames — the wildcard template is ignored. For already-rendered text +/// (a `SUMMARISE` template cell), where re-rendering a string through a +/// numeric template is meaningless. +pub fn resolve_column_values_direct( + column: &ArrayRef, + spec: &LabelSpec, +) -> Result>, String> { + let mut direct = LabelSpec::new(); + for (key, label) in spec.renames() { + match label { + Some(label) => direct.rename(key.clone(), label), + None => direct.suppress(key.clone()), + }; + } + resolve_column_values(column, &direct) +} + /// Shared label rendering behind [`label_elements`] and /// [`resolve_column_values`]. `share_precision` derives `{}` decimal /// precision across the un-renamed values (scale breaks) or renders each From a597d8027d7a97b2b383391b9e1d8124bb77ae4d Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 26 Nov 2026 16:56:28 +0100 Subject: [PATCH 28/37] editorialise comments --- src/execute/table/layout.rs | 8 ++------ src/execute/table/summary.rs | 27 +++++++++++---------------- src/format.rs | 9 ++++----- src/table/summary.rs | 6 ++---- 4 files changed, 19 insertions(+), 31 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 91d566644..8b06e33fe 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -242,10 +242,7 @@ fn create_body(df: &DataFrame, columns: &[TableColumn]) -> Vec { } /// Interleave the `GROUP` chunks' rows into the body, in data space: each -/// chunk's `top` rows, then the chunk itself, then its bottom rows. Runs -/// before the facet passes — summary rows carry their group's key, so the -/// row-driven group-stub merge spans them and group-heading offsets cover -/// them like data rows. +/// chunk's `top` rows, then the chunk itself, then its bottom rows. fn weave_group_summaries( rows: Vec, cells: Vec, @@ -309,8 +306,7 @@ fn weave_group_summaries( } /// Place the `GRAND` chunk's rows: `top` rows above the whole body, bottom -/// rows below it. Runs after the facet passes — a grand row belongs to no -/// group, so nothing about it should merge or shift with group machinery. +/// rows below it. fn weave_grand_summaries( rows: Vec, cells: Vec, diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 575a85780..c98b979a7 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -153,10 +153,7 @@ impl SummaryRow { } /// The row's label cell, spanning every stub column — leftward over the - /// group-stub columns too for a `GRAND` row. `setup_summaries` adds a - /// stub column when summaries exist without one; `move_stub_columns` - /// puts every stub-section column in one contiguous run, so the span - /// covers only stub columns. + /// group-stub columns too for a `GRAND` row. fn label_cell(&self, row: usize, columns: &[TableColumn], classes: &[TableClass]) -> TableCell { let label_column = columns .iter() @@ -290,9 +287,9 @@ pub(super) fn compute_summaries( } /// Compute one clause's frame over the rows in `range`: one row, one column -/// per summarised column. A bare operation yields a nullable-f64 column; a -/// template (`Some` segments, which `compute_summaries` supplies for every -/// template clause) a string column with the template rendered against it. +/// per summarised column. A bare operation yields a one-cell column of the +/// operation's value (see [`value_array`]); a template yields a string +/// column with the template rendered against the slice. fn summary_frame( df: &DataFrame, summary: &Summary, @@ -332,8 +329,8 @@ fn summary_frame( /// Render a template against one column's slice: literals verbatim, each /// placeholder's expression evaluated over the slice and rendered through its /// pre-compiled zygos template. A NULL placeholder makes the whole cell -/// NULL, like a bare operation. Stats are memoized in `cache` across all of -/// the template's placeholders, so a repeated stat computes once per cell. +/// NULL. Stats are memoized in `cache` across the template's placeholders, +/// so a repeated stat computes once per cell. fn render_template( segments: &[TemplateSegment], slice: &ArrayRef, @@ -413,12 +410,10 @@ fn leaf_f64(value: &Value) -> Option { /// Make a summary frame display-ready, per column: an explicit `FORMAT` /// renaming (mapping or template) becomes the display text; an un-renamed -/// float column pads to its body column's display decimals — the same -/// treatment `apply_formatting` gives the body cells. A template's cells -/// are already-rendered strings, so they honour only direct renamings +/// float column pads to its body column's display decimals. A template's +/// cells are already-rendered strings, so they honour only direct renamings /// (including `null`), never the wildcard template, and never pad. -/// Tallies are counts and keep their integer display. `decimals` covers -/// every summarised column, computed once in `compute_summaries`. +/// `decimals` covers every summarised column. fn format_summary_frame( frame: &mut DataFrame, summary: &Summary, @@ -706,13 +701,13 @@ fn value_array(value: &Option, dtype: &DataType) -> ArrayRef { } /// Count a column's distinct non-null values: NULL when nulls propagate. -/// Numeric arrays compare on f64 bits so display rounding can't merge two -/// values; other types compare on their string representation. fn n_distinct(array: &ArrayRef, drop_nulls: bool) -> Result> { if array.logical_null_count() > 0 && !drop_nulls { return Ok(None); } let len = if array.data_type().is_numeric() { + // Bits, not display text: two values that round to the same display + // string still count as distinct let f64s = cast_array(array, &DataType::Float64)?; as_f64(&f64s)? .iter() diff --git a/src/format.rs b/src/format.rs index 6b07e6dfb..f34802d74 100644 --- a/src/format.rs +++ b/src/format.rs @@ -431,9 +431,7 @@ pub fn format_dataframe_column( } /// Decimal places to display a float column consistently: the most any -/// non-null value needs, each value asking for the fewest decimals that -/// round-trip within float noise (`f64::EPSILON.sqrt()`, relative). -/// Non-float columns need none. +/// non-null value needs. Non-float columns need none. pub fn display_decimals(column: &ArrayRef) -> usize { let decimals: Box + '_> = match column.data_type() { DataType::Float64 => Box::new( @@ -465,13 +463,14 @@ pub fn display_decimals(column: &ArrayRef) -> usize { /// Fewest decimal places that represent `v` within float noise: the /// smallest `d >= from` whose rounded value is within -/// `f64::EPSILON.sqrt()` (relative) of `v`. Caps at 15, past which an f64 -/// carries no real information. Non-finite values contribute nothing. +/// `f64::EPSILON.sqrt()` (relative) of `v`. Caps at 15. Non-finite values +/// contribute nothing. fn minimal_decimals(v: f64, from: usize) -> usize { if !v.is_finite() { return from; } let tol = f64::EPSILON.sqrt() * v.abs().max(1.0); + // Past 15 decimals an f64 carries no real information (from..=15) .find(|&d| { let factor = 10f64.powi(d as i32); diff --git a/src/table/summary.rs b/src/table/summary.rs index 11b654d3d..542266154 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -336,8 +336,7 @@ pub(crate) fn parse_stat_expr(source: &str) -> Result { /// Split a template literal into text and placeholder segments. `{` opens a /// placeholder and must be terminated and non-empty; `}` outside a -/// placeholder is literal text. Matching against `SUMMARY_OPERATIONS` happens -/// in [`SummaryOperation::validate`], not here. +/// placeholder is literal text. pub(crate) fn parse_template(template: &str) -> Result, String> { let mut segments = Vec::new(); let mut literal = String::new(); @@ -398,8 +397,7 @@ pub enum SummaryScope { /// Operations a `SUMMARISE` clause accepts: the plot aggregate vocabulary /// (`AGG_NAMES`) minus the order-dependent positional ones (`first`, `last`, -/// `diff`), which need row-order machinery tables don't have, plus `se` and -/// the type-free tallies `n_distinct` and `n_missing`. +/// `diff`), plus `se` and the type-free tallies `n_distinct` and `n_missing`. pub const SUMMARY_OPERATIONS: &[&str] = &[ "count", "n_distinct", From b7a2b0a3b14fbf63a6cb5b8f8222656583cf1b41 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 1 Dec 2026 14:01:08 +0100 Subject: [PATCH 29/37] update wording of doc based on comment --- doc/syntax/clause/summarise.qmd | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index d2a339798..4c7957bbb 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -2,7 +2,7 @@ title: "Summarise values into new rows" --- -Numerical values can be summarised and displayed in dedicated rows. +Values can be summarised and displayed in dedicated rows. This is helpful to display observations alongside statistics in the table. `SUMMARISE` can be repeated to compute multiple summaries. @@ -35,6 +35,7 @@ The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is large ``` This part of the clause can be an identifier or a string representing an expression. +The identifiers are the same ones used in stat [aggregation](draw.qmd#aggregate-functions) in plots. When using an identifier, one of the following operations are available: | Name | Description | Numeric | Date(time) | Other | From 9bd8b9dbaf83b77a1493e4fd5ca95da38ab675db Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Tue, 1 Dec 2026 14:14:32 +0100 Subject: [PATCH 30/37] error on 0 row summaries --- doc/syntax/clause/summarise.qmd | 1 + doc/vendor/SKILL.md | 2 +- src/execute/table/mod.rs | 16 ++++++++++++++++ src/execute/table/summary.rs | 10 ++++++++-- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index 4c7957bbb..63b9054d0 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -27,6 +27,7 @@ The `GRAND` scope will compute the summary for all rows. Without spelling out a scope, the default will be `GROUP`. When no groups are declared by `FACET` and the scope is set to `GROUP`, all rows are treated as belonging to the same group. The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a diffrence in style and label spanning. +A query result with no rows cannot be summarised: `SUMMARISE` errors on an empty table. ## Operation diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index ff23b9d75..878347cde 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -197,7 +197,7 @@ TABULATE * ### SUMMARISE -Adds summary rows computed over the table's rows: one per `FACET` group (`GROUP`, default) or a single row over all rows (`GRAND`, rendered with a stronger border; its label spans group stub columns). Repeatable — clause order is row order within a boundary. Also spelled `SUMMARIZE`. Columns must be part of the TABULATE selection. +Adds summary rows computed over the table's rows: one per `FACET` group (`GROUP`, default) or a single row over all rows (`GRAND`, rendered with a stronger border; its label spans group stub columns). Repeatable — clause order is row order within a boundary. Also spelled `SUMMARIZE`. Columns must be part of the TABULATE selection. Errors on an empty query result. ``` SUMMARISE [GROUP | GRAND] OF , ... diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index ec9fca3f0..dca0534d2 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -1158,6 +1158,22 @@ mod integration_tests { assert_eq!(value.content, "null"); } + #[test] + fn test_tabulate_summarise_errors_on_an_empty_table() { + let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); + reader + .execute_sql("CREATE TABLE t AS SELECT CAST(1 AS DOUBLE) AS x WHERE 1 = 0") + .unwrap(); + let result = + resolve_table_with_reader("TABULATE * FROM t SUMMARISE GRAND count OF x", &reader); + let Err(error) = result else { + panic!("SUMMARISE must error on an empty table"); + }; + assert!(error + .to_string() + .contains("cannot summarise an empty table")); + } + fn body_contents(resolved: &ResolvedTable) -> Vec { let mut contents: Vec = resolved .cells() diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index c98b979a7..c0570e7a1 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -189,8 +189,9 @@ pub(super) type SummaryChunk = (Option>, Vec); /// Compute every `SUMMARISE` clause against the (unformatted) data: one /// chunk per group, in display order (`setup_rows` leaves rows /// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. -/// Chunks with no matching clauses are omitted. Placement within a chunk is -/// the weavers' concern; they read each row's `top`. +/// An empty table errors: there is nothing to summarise. Chunks with no +/// matching clauses are omitted. Placement within a chunk is the weavers' +/// concern; they read each row's `top`. /// /// A bare operation's summary value takes its column's `FORMAT` renaming /// just like the body cells; a template self-formats via zygos, honouring @@ -204,6 +205,11 @@ pub(super) fn compute_summaries( if summaries.is_empty() { return Ok(Vec::new()); } + if rows.is_empty() { + return Err(GgsqlError::ValidationError( + "SUMMARISE: cannot summarise an empty table".to_string(), + )); + } // Chunks the clauses emit into: one contiguous range per group, then one // range over all rows for the GRAND clauses. Each accumulates its rows. struct Chunk { From 1711b82468ae7036b35a038755c081b7cf166dbe Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 09:53:34 +0100 Subject: [PATCH 31/37] resolve settings in setup --- src/execute/table/layout.rs | 4 +-- src/execute/table/mod.rs | 4 +-- src/execute/table/summary.rs | 61 ++++++++++++++++++++++-------------- src/table/summary.rs | 18 +++++++++-- 4 files changed, 58 insertions(+), 29 deletions(-) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 8b06e33fe..43028df3d 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -550,9 +550,9 @@ mod tests { .resolve_spanners(&labels, Some(&column_names)) .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(&df, &table.formats, &spans)?; - setup_summaries(&mut df, &formats, &table.summaries)?; + let summaries = setup_summaries(&mut df, &formats, &table.summaries)?; let columns = setup_columns(&df, &spans, &labels, &formats, facet); - let computed = compute_summaries(&df, &rows, &table.summaries, &formats)?; + let computed = compute_summaries(&df, &rows, &summaries, &formats)?; let df = apply_formatting(&df, &formats)?; build_cells(&df, columns, rows, &spans, &titles, facet, &computed) } diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index dca0534d2..02bcfb515 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -78,7 +78,7 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result 'left'` facet keeps its columns as group stubs, so check // for body columns rather than emptiness. @@ -88,7 +88,7 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result, summaries: &[Summary], -) -> Result<()> { +) -> Result> { if summaries.is_empty() { - return Ok(()); + return Ok(Vec::new()); } + let mut resolved = Vec::with_capacity(summaries.len()); + let column_names = df.get_column_names(); for summary in summaries { - for column in &summary.columns { - if df.column(column).is_err() { - return Err(GgsqlError::ValidationError(format!( - "SUMMARISE {}: no column '{column}' in the query result", - summary.operation - ))); - } - } + summary + .validate_columns(&column_names) + .map_err(GgsqlError::ValidationError)?; + resolved.push(Summary { + settings: summary + .resolve_settings() + .map_err(GgsqlError::ValidationError)?, + ..summary.clone() + }); } if !formats .values() @@ -59,7 +63,7 @@ pub(super) fn setup_summaries( Arc::new(StringArray::from(vec![""; df.height()])), )?; } - Ok(()) + Ok(resolved) } /// One `SUMMARISE` row, ready for weaving into the table's grid: placement, @@ -189,6 +193,7 @@ pub(super) type SummaryChunk = (Option>, Vec); /// Compute every `SUMMARISE` clause against the (unformatted) data: one /// chunk per group, in display order (`setup_rows` leaves rows /// group-contiguous), then one `None`-keyed `GRAND` chunk over all rows. +/// The clauses arrive with settings resolved by [`setup_summaries`]. /// An empty table errors: there is nothing to summarise. Chunks with no /// matching clauses are omitted. Placement within a chunk is the weavers' /// concern; they read each row's `top`. @@ -266,7 +271,7 @@ pub(super) fn compute_summaries( .settings .get("blank") .and_then(ParameterValue::as_str) - .unwrap_or("—"); + .expect("setup_summaries resolves every clause's settings"); let targets = match summary.scope { SummaryScope::Group => 0..chunks.len() - 1, SummaryScope::Grand => chunks.len() - 1..chunks.len(), @@ -308,6 +313,8 @@ fn summary_frame( .columns .iter() .map(|column| { + // setup_summaries' validate_columns guarantees presence; this + // guards direct callers. let array = df.column(column).map_err(|_| { GgsqlError::ValidationError(format!( "SUMMARISE {}: no column '{column}' in the query result", @@ -1081,11 +1088,19 @@ mod tests { } fn summary(operation: &str, scope: SummaryScope, columns: &[&str]) -> Summary { - Summary { + resolved(Summary { operation: SummaryOperation::Stat(operation.to_string()), scope, columns: columns.iter().map(|c| c.to_string()).collect(), settings: Parameters::new(), + }) + } + + /// `compute_summaries` expects clauses with resolved settings. + fn resolved(summary: Summary) -> Summary { + Summary { + settings: summary.resolve_settings().unwrap(), + ..summary } } @@ -1164,10 +1179,10 @@ mod tests { } .unwrap(); let rows = body_rows(&[&[0], &[1]]); - let above = Summary { + let above = resolved(Summary { settings: crate::params! { "place" => "top" }, ..summary("mean", SummaryScope::Group, &["x"]) - }; + }); let below = summary("median", SummaryScope::Group, &["x"]); let computed = compute_summaries(&df, &rows, &[below, above], &HashMap::new()).unwrap(); @@ -1200,10 +1215,10 @@ mod tests { } .unwrap(); let rows = body_rows(&[&[]]); - let labelled = Summary { + let labelled = resolved(Summary { settings: crate::params! { "rowlabel" => "Average" }, ..summary("mean", SummaryScope::Grand, &["x"]) - }; + }); let computed = compute_summaries(&df, &rows, &[labelled], &HashMap::new()).unwrap(); @@ -1239,10 +1254,10 @@ mod tests { .unwrap(); let rows = body_rows(&[&[], &[], &[]]); - let drop = Summary { + let drop = resolved(Summary { settings: crate::params! { "missing" => "drop" }, ..summary("mean", SummaryScope::Grand, &["x"]) - }; + }); let computed = compute_summaries( &df, diff --git a/src/table/summary.rs b/src/table/summary.rs index 542266154..0cb0a5cb4 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -430,8 +430,7 @@ pub const SUMMARY_OPERATIONS: &[&str] = &[ const SUMMARY_PARAMS: &[ParamDefinition] = &[ ParamDefinition { name: "place", - // No default: an unset place resolves at execution time. - default: DefaultParamValue::Null, + default: DefaultParamValue::String("bottom"), constraint: ParamConstraint::string_option(&["top", "bottom"]), }, ParamDefinition { @@ -462,6 +461,21 @@ impl Summary { pub fn resolve_settings(&self) -> Result { crate::params::resolve_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") } + + /// Check this clause's columns against the real query result's column + /// names. + pub fn validate_columns(&self, column_names: &[String]) -> Result<(), String> { + for column in &self.columns { + if !column_names.contains(column) { + return Err(format!( + "SUMMARISE {}: no column '{column}' in the query result", + self.operation + )); + } + } + + Ok(()) + } } #[cfg(test)] From c390eee65d3a09fa00188d3838056abb8d56451f Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 13:47:08 +0100 Subject: [PATCH 32/37] shape some logic into the chaos of parameter validation --- src/AGENTS.md | 12 ++++++ src/execute/table/format.rs | 12 +++--- src/execute/table/layout.rs | 6 +-- src/execute/table/mod.rs | 7 ++-- src/params.rs | 67 +++++++++++++----------------- src/table/facet.rs | 35 +++++++++++----- src/table/mod.rs | 81 ++++++++++++++++++++++++++++--------- src/table/spanner.rs | 26 ++++++++---- src/table/summary.rs | 30 +++++++++----- src/validate.rs | 63 ++++++----------------------- 10 files changed, 194 insertions(+), 145 deletions(-) diff --git a/src/AGENTS.md b/src/AGENTS.md index 2f4d92514..d70314d08 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -61,6 +61,18 @@ Grammar lives in [`/tree-sitter-ggsql/`](../tree-sitter-ggsql/) — when adding **Caching layer.** `CachingReader` (`cache.rs`) wraps a primary reader plus an in-memory `CacheBackend`, splitting work across two `Reader` surfaces. **`execute_sql` = source**: base reads of the user's data plus user setup/DML run on the primary (with result memoization), except `ggsql:` builtins, the `__ggsql_cache_meta__` table, and reads that reference a cache-resident internal table, which go to the cache. **`execute_sql_cached` = compute**: all dialect-generated/derived SQL (schema probes, stats, projection/map transforms, spatial setup, final layer queries — everything operating on `__ggsql_*` tables) runs on the cache; it defaults to `execute_sql` so a plain reader runs everything on one connection. Cache routing is by **exact-identifier membership** in the set of tables registered into the cache. Memoization keys on `hash(primary_uri + sql)` and is tracked in the `__ggsql_cache_meta__` table inside the cache backend. Each memoized read is bounded by a **TTL** (default 300s) and the whole memo by an **LRU byte budget** (default 512 MB); both are configurable via `CacheConfig` (env `GGSQL_CACHE_DISABLED`/`GGSQL_CACHE_TTL`/`GGSQL_CACHE_MAX_BYTES`, or per-connection URI query parameters `?cache_ttl=…&cache_max_bytes=…&cache_disabled=…`). The `__ggsql_cache_meta__` table is queryable for introspection (`SELECT * FROM __ggsql_cache_meta__`). Pure/non-visual SQL (CLI table fallback, Jupyter) goes through `execute_sql` so it reads the primary rather than the empty cache. `Reader::materialize_table` (default = `CREATE TEMP TABLE` on the reader, no Rust roundtrip) is overridden to read the body via the source surface and `register()` the result into the cache, so the primary is never written to; `Reader::caches_sources()` (default `false`, `true` for `CachingReader`) gates the executor's per-layer source staging: file sources are staged on the cache surface, while identifiers go through `materialize_table`, which routes the read to the cache (CTEs, builtins, cache-resident tables) or the primary as needed. `dialect()` returns the **cache** dialect, and every compute-surface failure is prefixed with the cache backend's scheme (``on the `duckdb` cache backend: …``) so a cache-dialect driver error is not mistaken for one from the user's own connection. Selected via the composite `+://` scheme (`reader_from_uri` / `split_cache_uri`) or the CLI `--cache` flag; off by default. The memo's bookkeeping — registering a table, its row in `__ggsql_cache_meta__`, LRU eviction under the byte budget — is `CacheTables`, which other callers use on a backend of their own (the Jupyter kernel's results API does, without wrapping the user's reader). An entry can be **pinned**, exempting it from eviction until unpinned (pins are kept in memory, not in the metadata table); `CachingReader` never pins, and the TTL and enabled checks stay in `CachingReader`. `CacheTables` takes a byte budget rather than a `CacheConfig`; `put` and `put_pinned` add entries, `contains` checks for one, and `evict_to`/`total_bytes`/`pinned_bytes` let a caller with a wider budget evict to that instead, `evict_to` returning the keys it evicted. Only an existing entry can be pinned. +### Validation vs execution + +`validate()` ([validate.rs](validate.rs)) runs every check possible with knowledge of the struct alone — no reader, no `DataFrame`, no `Labels`. Anything needing the query result's schema or sibling-clause context is execution's job, in `setup_*` functions under `execute/`. + +The shared machinery lives in `params.rs`: `validate_parameters` (check only; absence is always valid), `with_defaults` (fill defaults; assumes validated input), and `resolve_parameters` = the two composed. Each AST struct exposes what its consumers call: + +- `validate_settings()` — called from the struct's `validate()`, which `Table::validate()` aggregates with clause-index prefixes ("SPAN 1: …"). +- `resolve_settings()` — validate + fill in one step, for execute-side consumers that handle one clause at a time. +- `with_default_settings()` — fill only, for consumers that validate and fill at different moments (e.g. `setup_formats` validates per clause before merging, fills after). + +Don't add a `resolve_settings` that has no caller; don't give a `setup_*` function struct-local work that `validate()` could run. + ### `execute/` The pipeline that takes a parsed `Plot` (or `Table`) plus a `Reader` and produces a `ResolvedPlot` (or `ResolvedTable`) — typed data per layer, scales resolved, casts applied; for tables, cells laid out with spans, stub and formats. Submodules: diff --git a/src/execute/table/format.rs b/src/execute/table/format.rs index 59c66dc48..33f4ea13b 100644 --- a/src/execute/table/format.rs +++ b/src/execute/table/format.rs @@ -17,7 +17,7 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner}; /// Validate every FORMAT's `SETTING` parameters, then reshape `formats` /// into one `Format` per column it covers. `spans` must already be resolved -/// (`Table::resolve_spanners`) — a name matching a SPAN id expands to that +/// (`Table::setup_spanners`) — a name matching a SPAN id expands to that /// span's columns. pub(super) fn setup_formats( df: &DataFrame, @@ -26,7 +26,7 @@ pub(super) fn setup_formats( ) -> Result> { for (idx, format) in formats.iter().enumerate() { format - .resolve_settings() + .validate_settings() .map_err(|e| GgsqlError::ValidationError(format!("FORMAT {}: {}", idx + 1, e)))?; } @@ -49,12 +49,10 @@ pub(super) fn setup_formats( } // A column no clause claimed a section for resolves to the body. - // Settings were validated per clause above; resolving again post-merge - // only fills defaults. + // Settings were validated per clause above, so post-merge only fills + // defaults. for format in resolved.values_mut() { - format.settings = format - .resolve_settings() - .map_err(GgsqlError::ValidationError)?; + format.settings = format.with_default_settings(); format.target.get_or_insert(ColumnSection::Body); } Ok(resolved) diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 43028df3d..6697edfcb 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -24,7 +24,7 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner}; /// any `gather`-ing spanner and then for stub columns. A `place => 'top'` /// facet consumes its columns as group labels; a `place => 'left'` facet /// keeps them as group stub columns. `spans` must already be resolved -/// (`Table::resolve_spanners`). +/// (`Table::setup_spanners`). pub(super) fn setup_columns( df: &DataFrame, spans: &[Spanner], @@ -522,7 +522,7 @@ mod tests { let titles = extract_table_titles(&mut labels); let column_names = df.get_column_names(); let spans = table - .resolve_spanners(&labels, Some(&column_names)) + .setup_spanners(&labels, &column_names) .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(df, &table.formats, &spans)?; let columns = setup_columns(df, &spans, &labels, &formats, None); @@ -547,7 +547,7 @@ mod tests { let (mut df, rows) = setup_rows(df.clone(), facet)?; let column_names = df.get_column_names(); let spans = table - .resolve_spanners(&labels, Some(&column_names)) + .setup_spanners(&labels, &column_names) .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(&df, &table.formats, &spans)?; let summaries = setup_summaries(&mut df, &formats, &table.summaries)?; diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 02bcfb515..eb5f445fb 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -47,7 +47,8 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Result, - ) -> Result, String> { - self.validate(value)?; - Ok(value.cloned().or_else(|| self.to_parameter_value())) - } - /// Convert the default value to a ParameterValue, if not Null pub fn to_parameter_value(&self) -> Option { match &self.default { @@ -1444,22 +1432,44 @@ pub fn reject_unknown_parameters( )) } -/// Validate `properties` against `definitions` and resolve each parameter -/// to its effective value: the user's value if present, otherwise the -/// definition's default. Returns a new map with defaults filled. -pub fn resolve_parameters( +/// Validate `properties` against `definitions`: no unknown keys, and every +/// present value passes its definition's constraint. Absence is always +/// valid — defaults are [`resolve_parameters`]' business. +pub fn validate_parameters( properties: &Parameters, definitions: &[ParamDefinition], context: &str, -) -> Result { +) -> Result<(), String> { reject_unknown_parameters(properties, definitions, context)?; + for param in definitions { + param.validate(properties.get(param.name))?; + } + Ok(()) +} + +/// Each parameter's effective value: the user's value if present, +/// otherwise the definition's default. Assumes `properties` passes +/// [`validate_parameters`]. +pub fn with_defaults(properties: &Parameters, definitions: &[ParamDefinition]) -> Parameters { let mut resolved = properties.clone(); for param in definitions { - if let Some(value) = param.resolve(properties.get(param.name))? { + if let Some(value) = param.to_parameter_value() { resolved.entry(param.name.to_string()).or_insert(value); } } - Ok(resolved) + resolved +} + +/// Validate `properties` against `definitions` and resolve each parameter +/// to its effective value: the user's value if present, otherwise the +/// definition's default. Returns a new map with defaults filled. +pub fn resolve_parameters( + properties: &Parameters, + definitions: &[ParamDefinition], + context: &str, +) -> Result { + validate_parameters(properties, definitions, context)?; + Ok(with_defaults(properties, definitions)) } #[cfg(test)] @@ -1479,25 +1489,6 @@ mod tests { .validate(Some(value)) } - #[test] - fn param_definition_resolve_prefers_user_value_then_default() { - let def = ParamDefinition { - name: "bins", - default: DefaultParamValue::Number(30.0), - constraint: ParamConstraint::count(1.0), - }; - let present = Some(10.0.into()); - // User value wins over the default, absent falls back to the default, - // and a Null default means no value. - assert_eq!(def.resolve(present.as_ref()).unwrap(), Some(10.0.into())); - assert_eq!(def.resolve(None).unwrap(), Some(30.0.into())); - let no_default = ParamDefinition { - default: DefaultParamValue::Null, - ..def - }; - assert_eq!(no_default.resolve(None).unwrap(), None); - } - #[test] fn reject_unknown_parameters_lists_valid_names() { let defs = [ParamDefinition { diff --git a/src/table/facet.rs b/src/table/facet.rs index 015eff22e..4787013e9 100644 --- a/src/table/facet.rs +++ b/src/table/facet.rs @@ -32,9 +32,18 @@ const TABLE_FACET_PARAMS: &[ParamDefinition] = &[ }, ]; +/// Validate a table facet's settings: no unknown keys, every present value +/// within its constraint. Passes `None` straight through. +pub(crate) fn validate_settings(facet: &Option) -> Result<(), String> { + if let Some(facet) = facet { + crate::params::validate_parameters(&facet.properties, TABLE_FACET_PARAMS, "FACET setting")?; + } + Ok(()) +} + /// Validate a table facet's settings, apply defaults, and return the /// resolved facet. Passes `None` straight through. -pub(crate) fn setup_facet(facet: &Option) -> Result, String> { +pub(crate) fn resolve_settings(facet: &Option) -> Result, String> { let Some(facet) = facet else { return Ok(None); }; @@ -71,10 +80,10 @@ mod tests { } #[test] - fn setup_materializes_default_settings() { + fn resolve_settings_materializes_default_settings() { let facet = table_facet(Parameters::new()); - let resolved = setup_facet(&Some(facet)).unwrap().unwrap(); + let resolved = resolve_settings(&Some(facet)).unwrap().unwrap(); assert_eq!(resolved.properties.get("place"), Some(&"left".into())); assert_eq!(resolved.properties.get("missing"), Some(&"last".into())); @@ -82,23 +91,31 @@ mod tests { } #[test] - fn setup_passes_none_through() { - assert_eq!(setup_facet(&None).unwrap(), None); + fn resolve_settings_passes_none_through() { + assert_eq!(resolve_settings(&None).unwrap(), None); } #[test] - fn setup_rejects_an_invalid_place_value() { + fn validate_settings_rejects_an_invalid_place_value() { let settings = crate::params! { "place" => "bottom" }; - assert!(setup_facet(&Some(table_facet(settings))).is_err()); + assert!(validate_settings(&Some(table_facet(settings))).is_err()); + } + + #[test] + fn validate_settings_accepts_none_and_defaults() { + assert!(validate_settings(&None).is_ok()); + assert!(validate_settings(&Some(table_facet(Parameters::new()))).is_ok()); } #[test] fn groups_are_woven_only_when_place_is_top() { let settings = crate::params! { "place" => "top" }; - let woven = setup_facet(&Some(table_facet(settings))).unwrap().unwrap(); + let woven = resolve_settings(&Some(table_facet(settings))) + .unwrap() + .unwrap(); assert!(groups_are_woven(&woven)); - let left = setup_facet(&Some(table_facet(Parameters::new()))) + let left = resolve_settings(&Some(table_facet(Parameters::new()))) .unwrap() .unwrap(); assert!(!groups_are_woven(&left)); diff --git a/src/table/mod.rs b/src/table/mod.rs index 088753025..4f2692457 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -13,7 +13,7 @@ mod layout; mod spanner; mod summary; -pub(crate) use facet::{groups_are_woven, setup_facet}; +pub(crate) use facet::{groups_are_woven, resolve_settings as resolve_facet_settings}; pub(crate) use layout::{ compose_header, create_caption, create_column_labels, create_heading, extract_table_titles, move_stub_columns, standardise_hjust, Slot, TableTitles, @@ -164,7 +164,7 @@ impl Table { /// STUB or FACET column, or a FORMAT STUB over a FACET column. Takes /// already-`resolve_spanner_ids`-resolved spans, so every check compares /// real column names, never a SPAN id. Needs no DataFrame, so this runs - /// from both `validate()` and real execution (`resolve_spanners`). + /// from both `validate()` and real execution (`setup_spanners`). pub fn validate_boundaries(&self, resolved_spans: &[Spanner]) -> Result<(), String> { let stub_columns: Vec = self .formats @@ -199,22 +199,54 @@ impl Table { Ok(()) } + /// Validate everything checkable without the query result's schema: + /// each clause's settings, spanner ids, feature boundaries, and each + /// `SUMMARISE`'s operation. Column existence is execution's job. + /// Returns one message per problem found. + pub fn validate(&self) -> Vec { + let mut errors = Vec::new(); + for (idx, spanner) in self.spans.iter().enumerate() { + if let Err(e) = spanner.validate() { + errors.push(format!("SPAN {}: {}", idx + 1, e)); + } + } + match self.resolve_spanner_ids() { + Ok(resolved_spans) => { + if let Err(e) = self.validate_boundaries(&resolved_spans) { + errors.push(e); + } + } + Err(e) => errors.push(e), + } + for (idx, format) in self.formats.iter().enumerate() { + if let Err(e) = format.validate() { + errors.push(format!("FORMAT {}: {}", idx + 1, e)); + } + } + for (idx, summary) in self.summaries.iter().enumerate() { + if let Err(e) = summary.validate() { + errors.push(format!("SUMMARISE {}: {}", idx + 1, e)); + } + } + if let Err(e) = facet::validate_settings(&self.facet) { + errors.push(format!("FACET: {}", e)); + } + errors + } + /// Fully resolve this table's spanners for execution: settings /// validated and defaults filled, `OVER` ids folded, feature boundaries /// checked, columns checked against the real schema, and each `label` /// overlaid with any `LABEL => ...` entry. - pub fn resolve_spanners( + pub fn setup_spanners( &self, labels: &Labels, - column_names: Option<&[String]>, + column_names: &[String], ) -> Result, String> { let spans = self.resolve_spanner_ids()?; self.validate_boundaries(&spans)?; - // None (validate()'s case) skips this: no real schema to check. - if let Some(names) = column_names { - for span in &spans { - span.validate_columns(names)?; - } + for span in &spans { + span.validate_columns(column_names)?; } spans @@ -345,11 +377,22 @@ impl Format { } } - /// Validate `settings` against `FORMAT_PARAMS` and resolve each to its - /// effective value: the user's value if present, otherwise the - /// definition's default. - pub fn resolve_settings(&self) -> Result { - crate::params::resolve_parameters(&self.settings, FORMAT_PARAMS, "FORMAT setting") + /// Validate everything checkable without the query result's schema: + /// `settings` against `FORMAT_PARAMS`. + pub fn validate(&self) -> Result<(), String> { + self.validate_settings() + } + + /// Validate `settings` against `FORMAT_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, FORMAT_PARAMS, "FORMAT setting") + } + + /// Each setting's effective value: the user's value if present, + /// otherwise the `FORMAT_PARAMS` default. Assumes `settings` already + /// passes validation. + pub fn with_default_settings(&self) -> Parameters { + crate::params::with_defaults(&self.settings, FORMAT_PARAMS) } } @@ -427,30 +470,30 @@ mod tests { fn format_validate_settings_accepts_a_string_hjust() { let settings = crate::params! { "hjust" => "right" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] fn format_validate_settings_accepts_a_numeric_hjust() { let settings = crate::params! { "hjust" => 0.25 }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] fn format_validate_settings_rejects_an_unrecognized_string() { let settings = crate::params! { "hjust" => "up" }; - assert!(format_with_settings(settings).resolve_settings().is_err()); + assert!(format_with_settings(settings).validate_settings().is_err()); } #[test] fn format_validate_settings_accepts_a_percent_or_pixel_width() { let settings = crate::params! { "width" => "20%" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); let settings = crate::params! { "width" => "240px" }; - assert!(format_with_settings(settings).resolve_settings().is_ok()); + assert!(format_with_settings(settings).validate_settings().is_ok()); } #[test] diff --git a/src/table/spanner.rs b/src/table/spanner.rs index b114617f6..5fe9aeb78 100644 --- a/src/table/spanner.rs +++ b/src/table/spanner.rs @@ -30,7 +30,8 @@ pub struct Spanner { /// `SETTING` parameters `SPAN` accepts — one static name/default/constraint /// list, mirroring how a `GeomTrait` declares `default_params()`, so -/// `Spanner::resolve_settings` doesn't hand-roll its own type checks per key. +/// `Spanner::validate_settings` doesn't hand-roll its own type checks per +/// key. const SPAN_PARAMS: &[ParamDefinition] = &[ ParamDefinition { name: "gather", @@ -47,6 +48,17 @@ const SPAN_PARAMS: &[ParamDefinition] = &[ ]; impl Spanner { + /// Validate everything checkable without the query result's schema: + /// `settings` against `SPAN_PARAMS`. + pub fn validate(&self) -> Result<(), String> { + self.validate_settings() + } + + /// Validate `settings` against `SPAN_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, SPAN_PARAMS, "SPAN setting") + } + /// Validate `settings` against `SPAN_PARAMS` and resolve each to its /// effective value: the user's value if present, otherwise the /// definition's default. @@ -127,7 +139,7 @@ fn gather_columns(columns: Vec, members: &[String]) -> Vec, members: &[String]) -> Vec, members: &[String]) -> Vec Vec { let mut levels: Vec = Vec::with_capacity(spans.len()); @@ -372,7 +384,7 @@ mod tests { } #[test] - #[should_panic(expected = "Table::resolve_spanners already validated")] + #[should_panic(expected = "Table::setup_spanners already validated")] fn gather_columns_panics_on_an_unvalidated_unknown_column() { let columns = vec![column("a", "a"), column("b", "b")]; @@ -673,10 +685,10 @@ mod tests { } #[test] - fn resolve_settings_accepts_valid_gather_and_level() { + fn validate_settings_accepts_valid_gather_and_level() { let settings = crate::params! { "gather" => false, "level" => 2.0 }; - assert!(spanner_with_settings(settings).resolve_settings().is_ok()); + assert!(spanner_with_settings(settings).validate_settings().is_ok()); } #[test] diff --git a/src/table/summary.rs b/src/table/summary.rs index 0cb0a5cb4..8ae747b88 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -455,6 +455,18 @@ const SUMMARY_PARAMS: &[ParamDefinition] = &[ ]; impl Summary { + /// Validate everything checkable without the query result's schema: the + /// operation and `settings`. + pub fn validate(&self) -> Result<(), String> { + self.operation.validate()?; + self.validate_settings() + } + + /// Validate `settings` against `SUMMARY_PARAMS`. + pub fn validate_settings(&self) -> Result<(), String> { + crate::params::validate_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") + } + /// Validate `settings` against `SUMMARY_PARAMS` and resolve each to its /// effective value: the user's value if present, otherwise the /// definition's default. @@ -492,34 +504,34 @@ mod tests { } #[test] - fn summary_resolve_settings_accepts_place_and_rowlabel() { + fn summary_validate_settings_accepts_place_and_rowlabel() { let settings = crate::params! { "place" => "top", "rowlabel" => "Average" }; - assert!(summary_with_settings(settings).resolve_settings().is_ok()); + assert!(summary_with_settings(settings).validate_settings().is_ok()); } #[test] - fn summary_resolve_settings_accepts_missing_options() { + fn summary_validate_settings_accepts_missing_options() { for value in ["propagate", "drop"] { let settings = crate::params! { "missing" => value }; - assert!(summary_with_settings(settings).resolve_settings().is_ok()); + assert!(summary_with_settings(settings).validate_settings().is_ok()); } let settings = crate::params! { "missing" => "ignore" }; - assert!(summary_with_settings(settings).resolve_settings().is_err()); + assert!(summary_with_settings(settings).validate_settings().is_err()); } #[test] - fn summary_resolve_settings_rejects_a_non_string_rowlabel() { + fn summary_validate_settings_rejects_a_non_string_rowlabel() { let settings = crate::params! { "rowlabel" => 1.0 }; - assert!(summary_with_settings(settings).resolve_settings().is_err()); + assert!(summary_with_settings(settings).validate_settings().is_err()); } #[test] - fn summary_resolve_settings_rejects_an_unknown_setting() { + fn summary_validate_settings_rejects_an_unknown_setting() { let settings = crate::params! { "colour" => "red" }; - assert!(summary_with_settings(settings).resolve_settings().is_err()); + assert!(summary_with_settings(settings).validate_settings().is_err()); } #[test] diff --git a/src/validate.rs b/src/validate.rs index 441cf4ec6..a211d6aac 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -312,58 +312,14 @@ pub fn validate(query: &str) -> Result { }); } - // Validate each SPAN's SETTING parameters (unknown key, or wrong shape - // for a recognized one) — mirrors the per-layer settings validation - // above. + // Validate the table's clauses (settings, spanner ids, boundaries, + // operations) — mirrors the per-layer settings validation above. if let Some(table) = first_table { - for (idx, spanner) in table.spans.iter().enumerate() { - if let Err(e) = spanner.resolve_settings() { - errors.push(ValidationError { - message: format!("SPAN {}: {}", idx + 1, e), - location: None, - }); - } - } - - match table.resolve_spanner_ids() { - Ok(resolved_spans) => { - if let Err(e) = table.validate_boundaries(&resolved_spans) { - errors.push(ValidationError { - message: e, - location: None, - }); - } - } - Err(e) => errors.push(ValidationError { - message: e, + for message in table.validate() { + errors.push(ValidationError { + message, location: None, - }), - } - - // Validate each FORMAT's SETTING parameters the same way. - for (idx, format) in table.formats.iter().enumerate() { - if let Err(e) = format.resolve_settings() { - errors.push(ValidationError { - message: format!("FORMAT {}: {}", idx + 1, e), - location: None, - }); - } - } - - // And each SUMMARISE's operation and SETTING parameters. - for (idx, summary) in table.summaries.iter().enumerate() { - if let Err(e) = summary.operation.validate() { - errors.push(ValidationError { - message: format!("SUMMARISE {}: {}", idx + 1, e), - location: None, - }); - } - if let Err(e) = summary.resolve_settings() { - errors.push(ValidationError { - message: format!("SUMMARISE {}: {}", idx + 1, e), - location: None, - }); - } + }); } } @@ -441,6 +397,13 @@ mod tests { assert!(!validated.valid()); } + #[test] + fn test_validate_table_facet_rejects_an_unknown_setting() { + let validated = validate("TABULATE * FROM sales FACET region SETTING bogus => 1").unwrap(); + assert!(!validated.valid()); + assert!(validated.errors()[0].message.starts_with("FACET: ")); + } + #[test] fn test_validate_summarise_rejects_an_unknown_operation() { let validated = validate("TABULATE * FROM sales SUMMARISE meen OF foo").unwrap(); From 24e0b04ce34ece5b270c291cbea33370578df154 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 13:54:59 +0100 Subject: [PATCH 33/37] harden boundaries of summary columns --- src/table/mod.rs | 54 +++++++++++++++++++++++++++++++++++++++++++- src/table/summary.rs | 11 +++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/table/mod.rs b/src/table/mod.rs index 4f2692457..ca6057fa1 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -161,7 +161,8 @@ impl Table { } /// Reject columns claimed by two table features at once: a SPAN over a - /// STUB or FACET column, or a FORMAT STUB over a FACET column. Takes + /// STUB or FACET column, a FORMAT STUB over a FACET column, or a + /// SUMMARISE of a STUB or FACET column. Takes /// already-`resolve_spanner_ids`-resolved spans, so every check compares /// real column names, never a SPAN id. Needs no DataFrame, so this runs /// from both `validate()` and real execution (`setup_spanners`). @@ -183,6 +184,11 @@ impl Table { span.validate_boundary(&stub_columns, "stub") .map_err(|e| format!("SPAN {}: {}", idx + 1, e))?; } + for (idx, summary) in self.summaries.iter().enumerate() { + summary + .validate_boundary(&stub_columns, "stub") + .map_err(|e| format!("SUMMARISE {}: {}", idx + 1, e))?; + } let Some(facet) = &self.facet else { return Ok(()); @@ -195,6 +201,11 @@ impl Table { if let Some(name) = facet_variables.iter().find(|v| stub_columns.contains(v)) { return Err(format!("FORMAT STUB cannot target FACET group '{name}'")); } + for (idx, summary) in self.summaries.iter().enumerate() { + summary + .validate_boundary(&facet_variables, "facet") + .map_err(|e| format!("SUMMARISE {}: {}", idx + 1, e))?; + } Ok(()) } @@ -545,6 +556,47 @@ mod tests { assert!(error.contains("cannot include stub column")); } + #[test] + fn validate_boundaries_rejects_a_summary_of_a_stub_column() { + let table = Table { + formats: vec![Format { + columns: vec!["a".to_string()], + wildcard: false, + target: Some(ColumnSection::Stub), + ..format_with_settings(Parameters::new()) + }], + summaries: vec![Summary { + operation: SummaryOperation::Stat("mean".to_string()), + columns: vec!["a".to_string()], + scope: SummaryScope::Grand, + settings: Parameters::new(), + }], + ..Table::new() + }; + + let resolved = table.resolve_spanner_ids().unwrap(); + let error = table.validate_boundaries(&resolved).unwrap_err(); + assert!(error.contains("SUMMARISE 1: cannot summarise stub column 'a'")); + } + + #[test] + fn validate_boundaries_rejects_a_summary_of_a_facet_column() { + let table = Table { + facet: Some(table_facet(&["a"])), + summaries: vec![Summary { + operation: SummaryOperation::Stat("mean".to_string()), + columns: vec!["a".to_string()], + scope: SummaryScope::Group, + settings: Parameters::new(), + }], + ..Table::new() + }; + + let resolved = table.resolve_spanner_ids().unwrap(); + let error = table.validate_boundaries(&resolved).unwrap_err(); + assert!(error.contains("SUMMARISE 1: cannot summarise facet column 'a'")); + } + fn table_facet(variables: &[&str]) -> crate::plot::facet::Facet { crate::plot::facet::Facet { layout: crate::plot::facet::FacetLayout::Wrap { diff --git a/src/table/summary.rs b/src/table/summary.rs index 8ae747b88..6523ea3ba 100644 --- a/src/table/summary.rs +++ b/src/table/summary.rs @@ -474,6 +474,17 @@ impl Summary { crate::params::resolve_parameters(&self.settings, SUMMARY_PARAMS, "SUMMARISE setting") } + /// Check this summary's columns against `off_limits`, columns claimed + /// by another feature — `context` names that feature in the error + /// (e.g. `"stub"`, `"facet"`). + pub fn validate_boundary(&self, off_limits: &[String], context: &str) -> Result<(), String> { + if let Some(name) = self.columns.iter().find(|name| off_limits.contains(name)) { + return Err(format!("cannot summarise {context} column '{name}'")); + } + + Ok(()) + } + /// Check this clause's columns against the real query result's column /// names. pub fn validate_columns(&self, column_names: &[String]) -> Result<(), String> { From 113ab366aa1a905f47fa182ea21364ccf16e4d59 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 14:24:21 +0100 Subject: [PATCH 34/37] few more review comments --- doc/syntax/clause/summarise.qmd | 2 +- src/execute/table/summary.rs | 3 ++- src/format.rs | 16 +++++++++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index 63b9054d0..e0a0d9712 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -112,7 +112,7 @@ It currently takes the following parameters: Can be `'top'` to place the summary rows at the top of each group or table, or `'bottom'` (default) to place the summary rows after the body rows. * `rowlabel`: A string for the label of the summary row. The default `null` falls back to printing the operation, where string expression operations are displayed without formatting details. * `missing`: A string option for how to treat `null` values in the table. -The default `'propagate'` will list any non-counting operation as `null`, and counting operations include null-rows. +The default `'propagate'` will list any non-counting operation as `null`, while the tallies `count` and `n_missing` include null-rows — note that `n_distinct` is not a tally and comes out `null` when the column contains any. Can be set to `'drop'` to explicitly ignore `null` values in aggregates and ignore these rows in counting operations. * `blank`: A string displayed in cells of the summary row whose column are not summarised. The default is an em dash (`'—'`); set it to `''` for empty cells. diff --git a/src/execute/table/summary.rs b/src/execute/table/summary.rs index 535fa6fb3..95d04cd2c 100644 --- a/src/execute/table/summary.rs +++ b/src/execute/table/summary.rs @@ -358,7 +358,8 @@ fn render_template( let Some(value) = eval_stat_expr(expr, slice, drop_nulls, &mut cache)? else { return Ok(None); }; - text.push_str(&template.format(&value, None).unwrap_or_default()) + // format() returns None only for Value::Null, excluded above + text.push_str(&template.format(&value, None).expect("value is non-null")) } } } diff --git a/src/format.rs b/src/format.rs index f34802d74..575f63429 100644 --- a/src/format.rs +++ b/src/format.rs @@ -462,14 +462,13 @@ pub fn display_decimals(column: &ArrayRef) -> usize { } /// Fewest decimal places that represent `v` within float noise: the -/// smallest `d >= from` whose rounded value is within -/// `f64::EPSILON.sqrt()` (relative) of `v`. Caps at 15. Non-finite values -/// contribute nothing. +/// smallest `d >= from` whose rounded value is within a few ULP of `v`. +/// Caps at 15. Non-finite values contribute nothing. fn minimal_decimals(v: f64, from: usize) -> usize { if !v.is_finite() { return from; } - let tol = f64::EPSILON.sqrt() * v.abs().max(1.0); + let tol = 4.0 * f64::EPSILON * v.abs(); // Past 15 decimals an f64 carries no real information (from..=15) .find(|&d| { @@ -506,7 +505,14 @@ mod tests { #[test] fn display_decimals_trims_binary_float_noise() { assert_eq!(display_decimals(&floats(&[0.1 + 0.2, 1.5])), 1); - assert_eq!(display_decimals(&floats(&[std::f64::consts::PI])), 7); + // An irrational value rounds at no decimal count: full precision. + assert_eq!(display_decimals(&floats(&[std::f64::consts::PI])), 15); + } + + #[test] + fn display_decimals_keeps_real_low_order_digits() { + assert_eq!(display_decimals(&floats(&[1234567.01])), 2); + assert_eq!(display_decimals(&floats(&[1e-8])), 8); } #[test] From 25d34115a3df261dd1b3f81c96a30f06e4372d6d Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 14:24:36 +0100 Subject: [PATCH 35/37] add navigation for summarise doc --- doc/_quarto.yml | 4 ++++ doc/syntax/index.qmd | 1 + 2 files changed, 5 insertions(+) diff --git a/doc/_quarto.yml b/doc/_quarto.yml index fb298d88c..2ef9bd5d0 100644 --- a/doc/_quarto.yml +++ b/doc/_quarto.yml @@ -64,6 +64,8 @@ website: href: syntax/clause/format.qmd - text: "`FACET`" href: syntax/clause/facet-tabulate.qmd + - text: "`SUMMARISE`" + href: syntax/clause/summarise.qmd - text: Gallery href: gallery/index.qmd - href: faq.qmd @@ -131,6 +133,8 @@ website: href: syntax/clause/format.qmd - text: "`FACET`" href: syntax/clause/facet-tabulate.qmd + - text: "`SUMMARISE`" + href: syntax/clause/summarise.qmd - section: Layers contents: - section: Types diff --git a/doc/syntax/index.qmd b/doc/syntax/index.qmd index f00a94101..ac03602cb 100644 --- a/doc/syntax/index.qmd +++ b/doc/syntax/index.qmd @@ -20,6 +20,7 @@ ggsql augments the standard SQL syntax with a number of new clauses to describe - [`SPAN`](clause/span.qmd) can be used to group columns and display a label across them - [`FORMAT`](clause/format.qmd) declares formatting for columns - [`FACET`](clause/facet-tabulate.qmd) enables row-grouping operations on tables +- [`SUMMARISE`](clause/summarise.qmd) adds rows with summarised values to the table ## Layers There are many different layers to choose from when visualising your data. Some are straightforward translations of your data into visual marks such as a point layer, while others perform more or less complicated calculations like e.g. the histogram layer. A layer is selected by providing the layer name after the `DRAW` clause From 22f403d77e47500091d0992b375f8fb9fc8d395c Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 14:31:46 +0100 Subject: [PATCH 36/37] phrasing --- doc/syntax/clause/summarise.qmd | 2 +- src/table/mod.rs | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd index e0a0d9712..16affcd8f 100644 --- a/doc/syntax/clause/summarise.qmd +++ b/doc/syntax/clause/summarise.qmd @@ -26,7 +26,7 @@ Setting the scope to `GROUP` will compute the summary for each group determined The `GRAND` scope will compute the summary for all rows. Without spelling out a scope, the default will be `GROUP`. When no groups are declared by `FACET` and the scope is set to `GROUP`, all rows are treated as belonging to the same group. -The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a diffrence in style and label spanning. +The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a difference in style and label spanning. A query result with no rows cannot be summarised: `SUMMARISE` errors on an empty table. ## Operation diff --git a/src/table/mod.rs b/src/table/mod.rs index ca6057fa1..652d0a409 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -162,10 +162,12 @@ impl Table { /// Reject columns claimed by two table features at once: a SPAN over a /// STUB or FACET column, a FORMAT STUB over a FACET column, or a - /// SUMMARISE of a STUB or FACET column. Takes - /// already-`resolve_spanner_ids`-resolved spans, so every check compares - /// real column names, never a SPAN id. Needs no DataFrame, so this runs - /// from both `validate()` and real execution (`setup_spanners`). + /// SUMMARISE of a STUB or FACET column. + /// + /// `resolved_spans` must come from `resolve_spanner_ids`, so every check + /// compares real column names, never a SPAN id. Needs no DataFrame, so + /// this runs from both `validate()` and real execution + /// (`setup_spanners`). pub fn validate_boundaries(&self, resolved_spans: &[Spanner]) -> Result<(), String> { let stub_columns: Vec = self .formats From 506a1eb57b2da107280053a247a7c7b06020a5a7 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Thu, 3 Dec 2026 16:03:51 +0100 Subject: [PATCH 37/37] surface validation errors --- src/execute/table/mod.rs | 3 +++ src/reader/mod.rs | 3 +++ src/validate.rs | 15 +++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index d4fb255fb..f79821550 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -37,6 +37,9 @@ use crate::{DataFrame, GgsqlError, Result, SelectionItem, Spec}; /// UPDATE, DELETE) ahead of a TABULATE run here. pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result { let validated = validate(query)?; + if let Some(message) = validated.invalid_reason() { + return Err(GgsqlError::ValidationError(message)); + } let warnings: Vec = validated.warnings().to_vec(); let source_tree = SourceTree::new(query)?; diff --git a/src/reader/mod.rs b/src/reader/mod.rs index babd69830..e941eaa80 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -1862,6 +1862,9 @@ pub struct ColumnInfo { /// — see that function's doc comment for how the two relate. pub fn resolve_plot_with_reader(reader: &dyn Reader, query: &str) -> Result { let validated = validate(query)?; + // No early return on invalid here: plot validation runs before the + // execution-time transforms (e.g. the rule geom's setup_layer hook moving + // a SETTING intercept into mappings), so it has false positives. let warnings: Vec = validated.warnings().to_vec(); let prepared_data = prepare_data_with_reader(query, reader)?; diff --git a/src/validate.rs b/src/validate.rs index df6c2f575..04c6562b8 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -56,6 +56,21 @@ impl Validated { pub fn warnings(&self) -> &[ValidationWarning] { &self.warnings } + + /// The validation errors joined into one message, when the query is invalid. + pub fn invalid_reason(&self) -> Option { + if self.valid { + None + } else { + Some( + self.errors + .iter() + .map(|e| e.message.as_str()) + .collect::>() + .join("\n"), + ) + } + } } /// A validation error (fatal).