diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f76a91d..71974b7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ ### Added +- New `aggregate` SETTING on Identity-stat layers (point, line, area, bar, ribbon, +range, segment, arrow, rule, text). By default it collapses each group to a +single row by replacing every numeric mapping in place with its aggregated +value. Accepts a single string or array of strings; entries are either +unprefixed defaults (`'mean'`) or per-aesthetic targets (`'y:max'`, +`'color:median'`). Up to two defaults may be supplied — the first applies to +lower-half aesthetics plus all non-range layers, the second to upper-half +(`max`/`end` suffix). Numeric mappings without a target or applicable default +are dropped with a warning. Targeting the same aesthetic more than once +(e.g. `aggregate => ('y:min', 'y:max')`) produces one row per function with +a synthetic `aggregate` column tagging each row, available for `REMAPPING` to +another aesthetic; targets with a single function and the unprefixed defaults +are reused unchanged across the exploded rows. The `aggregate` column's value +is built from the dedup-and-joined function names of all exploded targets at +each row, separated by `/` (so `('y:min', 'y:max', 'color:sum', 'color:prod')` +yields `'min/sum'` and `'max/prod'`). Mixed lengths above 1 are an error. - Add cell delimiters and code lens actions to the Positron extension (#366) - ODBC is now turned on for the CLI as well (#344) - `FROM` can now come before `VISUALIZE`, mirroring the DuckDB style. This means @@ -37,6 +53,7 @@ portion (#364). - Removed polars from dependency list along with all its transient dependencies. Rewrote DataFrame struct on top of arrow (#350) - Moved ggsql-python to its own repo (posit-dev/ggsql-python) and cleaned up any additional references to it - Moved ggsql-r to its own repo (posit-dev/ggsql-r) +- The `orientation` setting on `ribbon` and `range` layers. With explicit `xmin`/`xmax` or `ymin`/`ymax` mappings, orientation is unambiguous and is auto-detected from the mappings; the override is no longer needed. ## [2.7.0] - 2026-04-20 diff --git a/doc/syntax/clause/draw.qmd b/doc/syntax/clause/draw.qmd index 31bf8f3a..070e5740 100644 --- a/doc/syntax/clause/draw.qmd +++ b/doc/syntax/clause/draw.qmd @@ -76,6 +76,47 @@ The `SETTING` clause can be used for two different things: #### Position A special setting is `position` which controls how overlapping objects are repositioned to avoid overlapping etc. Position adjustments have special mapping requirements so all position adjustments will not be relevant for all layer types. Different layers have different defaults as detailed in their documentation. You can read about each different position adjustment at [their own documentation sites](../index.qmd#position-adjustments). +#### Aggregate +Some layers support aggregation of their data through the `aggregate` setting. These layers will state this. `aggregate` collapses each group to a single row, replacing every numeric mapping in place with its aggregated value. Groups are defined by `PARTITION BY` together with all discrete mappings. + +The setting takes a single string or an array of strings. Each string is one of: + +* **Untargeted** — `''` (no prefix). With one untargeted aggregation the function applies to every numeric mapping that doesn't have a targeted aggregation. With two untargeted aggregations the first is used for the lower side of range layers (e.g. `x`/`xmin`) plus all non-range layers, and the second is used for the upper side of range layers (e.g. `xend`/`xmax`). More than two untargeted aggregations is an error. +* **Targeted** — `':'`. Applies `func` to the named aesthetic only (`` is a user-facing name like `x`, `y`, `xmin`, `xmax`, `xend`, `yend`, `color`, `size`, …). A target overrides any untargeted aggregation for that aesthetic. + +A numeric mapping is dropped from the layer with a warning, when it has neither a target nor an applicable default . + +You can also target the same aesthetic more than once to produce **multiple rows per group** — one for each function. For example `aggregate => ('y:min', 'y:max')` emits a min row and a max row per group, so a single `DRAW line` produces two summary lines that connect within each group rather than across them. + +The stat exposes a synthetic `aggregate` column tagging each row, which you can pick up with a `REMAPPING` to drive another aesthetic — e.g. `REMAPPING aggregate AS stroke` to colour the two lines differently. The column's value is built from the per-row function names of the *exploded* targets, deduplicated, and joined with `/`: + +* `aggregate => ('y:min', 'y:max')` → rows tagged `'min'`, `'max'`. +* `aggregate => ('y:min', 'y:max', 'color:median')` → rows tagged `'min'`, `'max'` (the single-function `color` target is recycled across rows and is not part of the label). +* `aggregate => ('y:min', 'y:max', 'color:sum', 'color:prod')` → rows tagged `'min/sum'`, `'max/prod'`. +* `aggregate => ('y:mean', 'y:max', 'color:mean', 'color:prod')` → rows tagged `'mean'`, `'max/prod'` (the duplicate `'mean'` collapses). + + +When several aesthetics are targeted with the same number of functions, they explode in lockstep (row 1 uses each aesthetic's first function, row 2 the second, and so on); aesthetics with a single function — and the unprefixed defaults — are reused unchanged across every row. Mixing different lengths above 1 is an error. + +The simple functions are: + +* `'count'`: Non-null tally of the bound column. +* `'sum'` and `'prod'`: The sum or product +* `'min'`, `'max'`, `'range'`, and `'mid'`: Extremes, max - min, and (min + max) / 2 +* `'mean'`, and `'median'`: Central tendency +* `'geomean'`, `'harmean'`, and `'rms'`: Geometric, harmonic, and root-mean-square +* `'sdev'`, `'var'`, `'iqr'`, and `'se'`: Standard deviation, variance, interquartile range, and standard error +* `'p05'`, `'p10'`, `'p25'`, `'p50'`, `'p75'`, `'p90'`, and `'p95'`: Percentiles +* `'first'` and `'last'`: The first or last value in the group, in row order + +For band functions you combine an offset with an expansion, potentially multiplied. An example could be `'mean-1.96sdev'` which does exactly what you'd expect it to be. The general form is `±` with `` being optional (defaults to `1`). + +Allowed offsets are: `'mean'`, `'median'`, `'geomean'`, `'harmean'`, `'rms'`, `'sum'`, `'prod'`, `'min'`, `'max'`, `'mid'`, and `'p05'`–`'p95'` + +Allowed expansions are: `'sdev'`, `'se'`, `'var'`, `'iqr'`, and `'range'` + +In the single-row (reduction) case aggregation applies in place — no `REMAPPING` is needed and no synthetic column is added. Only the multi-row (explosion) case described above introduces the synthetic `aggregate` column. + ### `FILTER` ```ggsql FILTER diff --git a/doc/syntax/layer/type/area.qmd b/doc/syntax/layer/type/area.qmd index a72b059f..623b00a2 100644 --- a/doc/syntax/layer/type/area.qmd +++ b/doc/syntax/layer/type/area.qmd @@ -25,9 +25,14 @@ The following aesthetics are recognised by the area layer. * `orientation`: The orientation of the layer, see the [Orientation section](#orientation). One of the following: * `'aligned'` to align the layer's primary axis with the coordinate system's first axis. * `'transposed'` to align the layer's primary axis with the coordinate system's second axis. +* `aggregate` Aggregation functions to apply per group: + * `null` apply no group aggregation (default). + * A single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation -The area layer sorts the data along its primary axis +This layer supports aggregation through the `aggregate` setting. Aggregation groups are defined by `PARTITION BY`, all discrete mappings, but also the primary axis. Within each group, every numeric mapping is replaced in place by its aggregated value. Use a default like `'mean'` or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. + +Further, the area layer sorts the data along its primary axis before returning it. ## Orientation Area plots are sorted and connected along their primary axis. Since the primary axis cannot be deduced from the mapping it must be specified using the `orientation` setting. E.g. if you wish to create a vertical area plot you need to set `orientation => 'transposed'` to indicate that the primary layer axis follows the second axis of the coordinate system. diff --git a/doc/syntax/layer/type/bar.qmd b/doc/syntax/layer/type/bar.qmd index d34a4953..e71ba3f2 100644 --- a/doc/syntax/layer/type/bar.qmd +++ b/doc/syntax/layer/type/bar.qmd @@ -25,10 +25,13 @@ The bar layer has no required aesthetics ## Settings * `position`: Position adjustment. One of `'identity'`, `'stack'` (default), `'dodge'`, or `'jitter'` * `width`: The width of the bars as a proportion of the available width (0 to 1) +* `aggregate`: Aggregation functions to apply per group if the secondary position has been mapped. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation If the secondary axis has not been mapped the layer will calculate counts for you and display these as the secondary axis. +If the secondary axis has been mapped you can apply aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY`, all discrete mappings, and the primary axis, every numeric mapping is replaced in place by its aggregated value. Use a default like `'mean'` or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. + ### Properties * `weight`: If mapped, the sum of the weights within each group is calculated instead of the count in each group @@ -116,3 +119,15 @@ DRAW bar MAPPING species AS fill PROJECT TO polar ``` + +Use a different type of aggregation for the bars through the `aggregate` setting. The `range` layer needs both `ymin` and `ymax` mapped; with two defaults, the first is applied to the lower bound and the second to the upper bound. + +```{ggsql} +VISUALISE species AS x FROM ggsql:penguins +DRAW bar + MAPPING body_mass AS y + SETTING aggregate => 'mean', fill => 'steelblue' +DRAW range + MAPPING body_mass AS ymin, body_mass AS ymax + SETTING aggregate => ('mean-1.96sdev', 'mean+1.96sdev') +``` diff --git a/doc/syntax/layer/type/line.qmd b/doc/syntax/layer/type/line.qmd index 3ec9ec21..acbe32f3 100644 --- a/doc/syntax/layer/type/line.qmd +++ b/doc/syntax/layer/type/line.qmd @@ -24,9 +24,13 @@ The following aesthetics are recognised by the line layer. * `orientation`: The orientation of the layer, see the [Orientation section](#orientation). One of the following: * `'aligned'` to align the layer's primary axis with the coordinate system's first axis. * `'transposed'` to align the layer's primary axis with the coordinate system's second axis. +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation -The line layer sorts the data along its primary axis. +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY`, all discrete mappings, and the primary axis, every numeric mapping is replaced in place by its aggregated value to produce a summary trace. Use a default like `'mean'` to summarise the secondary axis, or target other aesthetics with `':'` (e.g. `'color:median'`). To draw min/max envelope lines, use a separate `DRAW line` layer per function, or use a [`range` layer](range.qmd) for a single range mark. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. + +Further, the line layer sorts the data along its primary axis before returning it. + If the line has a variable `stroke` or `opacity` aesthetic within groups, the line is broken into segments. Each segment gets the property of the preceding datapoint, so the last datapoint in a group does not transfer these properties. @@ -89,4 +93,14 @@ VISUALISE x, y FROM data DRAW line MAPPING z AS linewidth SCALE linewidth TO (0, 30) -``` \ No newline at end of file +``` + +Use aggregation to draw min and max lines from a set of observations on a single layer. Targeting `y` twice produces one summary row per function within the same group. A synthetic `aggregate` column tags each row with the different function names, that you can remap to colour the lines distinctly: + +```{ggsql} +VISUALISE Day AS x, Temp AS y FROM ggsql:airquality +DRAW line + REMAPPING aggregate AS stroke + SETTING aggregate => ('y:min', 'y:max') +DRAW point +``` diff --git a/doc/syntax/layer/type/point.qmd b/doc/syntax/layer/type/point.qmd index a64ca258..46eb13ed 100644 --- a/doc/syntax/layer/type/point.qmd +++ b/doc/syntax/layer/type/point.qmd @@ -23,9 +23,10 @@ The following aesthetics are recognised by the point layer. ## Settings * `position`: Position adjustment. One of `'identity'` (default), `'stack'`, `'dodge'`, or `'jitter'` +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation -The point layer does not transform its data but passes it through unchanged +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value. Use a default like `'mean'` or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. ## Orientation The point layer has no orientation. The axes are treated symmetrically. @@ -72,3 +73,13 @@ VISUALISE species AS x, bill_dep AS y FROM ggsql:penguins DRAW point SETTING position => 'jitter', distribution => 'density' ``` + +Use aggregation to show a single point per group + +```{ggsql} +VISUALISE species AS x, island AS y, body_mass AS fill, body_mass AS size + FROM ggsql:penguins +DRAW point + SETTING aggregate => ('fill:mean', 'size:count') +SCALE size TO (5, 20) +``` diff --git a/doc/syntax/layer/type/range.qmd b/doc/syntax/layer/type/range.qmd index d3982bd6..2f3f116a 100644 --- a/doc/syntax/layer/type/range.qmd +++ b/doc/syntax/layer/type/range.qmd @@ -22,9 +22,10 @@ The following aesthetics are recognised by the range layer. ## Settings * `width`: The width of the hinges in points (must be >= 0). Defaults to 10. Can be set to `null` to not display hinges. +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and the *Data transformation* section below. ## Data transformation -The range layer does not transform its data but passes it through unchanged. +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value, producing one range per group. Range is a range layer with two defaults: the first applies to the start point (`xmin`/`ymin`) and the second applies to the end point (`xmax`/`ymax`). Use a single default like `'mean'` to apply the same function to all values, or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. ## Orientation The orientation of range layers is deduced directly from the mapping, because the interval is mapped to the secondary axis. To create a horizontal range layer, you map the independent variable to `y` instead of `x` and the interval to `xmin` and `xmax` (assuming a default Cartesian coordinate system). @@ -108,3 +109,15 @@ DRAW range MAPPING low AS ymin, high AS ymax SETTING width => null ``` + +Use aggregation to calculate bounds dynamically + +```{ggsql} +VISUALISE body_mass AS x, species AS y FROM ggsql:penguins +DRAW range + MAPPING body_mass AS xmin, body_mass AS xmax + SETTING aggregate => ('min', 'max'), width => null +DRAW point + REMAPPING aggregate AS fill + SETTING aggregate => ('x:min', 'x:max'), size => 20, opacity => 1 +``` diff --git a/doc/syntax/layer/type/ribbon.qmd b/doc/syntax/layer/type/ribbon.qmd index 50a38d25..742328f4 100644 --- a/doc/syntax/layer/type/ribbon.qmd +++ b/doc/syntax/layer/type/ribbon.qmd @@ -23,9 +23,10 @@ The following aesthetics are recognised by the ribbon layer. ## Settings * `position`: Position adjustment. One of `'identity'` (default), `'stack'`, `'dodge'`, or `'jitter'` +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and the *Data transformation* section below. ## Data transformation -The ribbon layer sorts the data along its primary axis +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value, producing one ribbon per group. Ribon is a range layer: with two defaults the first applies to the start point (`xmin`/`ymin`) and the second applies to the end point (`xmax`/`ymax`). Use a single default like `'mean'` to apply the same function to all values, or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. ## Orientation Ribbon layers are sorted and connected along their primary axis. The orientation is deduced directly from the mapping, because the interval is mapped to the secondary axis. To create a vertical ribbon layer you map the independent variable to `y` instead of `x` and the interval to `xmin` and `xmax` (assuming a default Cartesian coordinate system). @@ -59,3 +60,11 @@ DRAW ribbon DRAW line MAPPING MeanTemp AS y ``` + +Use aggregation to calculate bounds on the fly + +```{ggsql} +VISUALISE Day AS x, Temp AS ymin, Temp AS ymax FROM ggsql:airquality +DRAW ribbon + SETTING aggregate => ('min', 'max') +``` diff --git a/doc/syntax/layer/type/rule.qmd b/doc/syntax/layer/type/rule.qmd index 71a2ceb4..470ea39e 100644 --- a/doc/syntax/layer/type/rule.qmd +++ b/doc/syntax/layer/type/rule.qmd @@ -25,8 +25,10 @@ The following aesthetics are recognised by the rule layer. ## Settings * `position`: Position adjustment. One of `'identity'` (default), `'stack'`, `'dodge'`, or `'jitter'` +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value. Use a default like `'mean'` or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. For diagonal lines, the position aesthetic determines the intercept: @@ -110,4 +112,14 @@ VISUALISE FROM ggsql:penguins intercept AS y, label AS colour FROM lines -``` \ No newline at end of file +``` + +Show a max rule for a timeseries + +```{ggsql} +VISUALISE Temp AS y FROM ggsql:airquality +DRAW line + MAPPING Date AS x +DRAW rule + SETTING aggregate => 'max' +``` diff --git a/doc/syntax/layer/type/segment.qmd b/doc/syntax/layer/type/segment.qmd index 7553aef9..ac759829 100644 --- a/doc/syntax/layer/type/segment.qmd +++ b/doc/syntax/layer/type/segment.qmd @@ -25,9 +25,10 @@ For axis-aligned intervals where one coordinate is shared between the start and ## Settings * `position`: Position adjustment. One of `'identity'` (default), `'stack'`, `'dodge'`, or `'jitter'` +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ## Data transformation -The segment layer does not transform its data but passes it through unchanged. +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value, producing one segment per group. Segment is a range layer: with two defaults the first applies to the start point (`x`/`y`) and the second applies to the end point (`xend`/`yend`). Use a single default like `'mean'` to apply the same function to all four endpoints, or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. ## Orientation The segment layer has no orientations. The axes are treated symmetrically. diff --git a/doc/syntax/layer/type/text.qmd b/doc/syntax/layer/type/text.qmd index fa9d010a..1cca11d9 100644 --- a/doc/syntax/layer/type/text.qmd +++ b/doc/syntax/layer/type/text.qmd @@ -35,6 +35,7 @@ The following aesthetics are recognised by the text layer. * a 2-element numeric array `[h, v]` where the first number is the horizontal offset and the second number is the vertical offset. * `format` Formatting specifier, see explanation below. * `position`: Position adjustment. One of `'identity'` (default), `'stack'`, `'dodge'`, or `'jitter'` +* `aggregate`: Aggregation functions to apply per group. Either a single string or an array of strings. See an overview of aggregation function in [the `DRAW` documentation](../../clause/draw.qmd#aggregate) and more information in the *Data transformation* section below. ### Format The `format` setting can take a string that will be used in formatting the `label` aesthetic. @@ -66,7 +67,7 @@ Known formatters are: * `x`/`X`: Unsigned hexadecimal ## Data transformation -The text layer does not transform its data but passed it through unchanged. +This layer supports aggregation through the `aggregate` setting. Within each group, defined by `PARTITION BY` and all discrete mappings, every numeric mapping is replaced in place by its aggregated value. Use a default like `'mean'` or target individual aesthetics with `':'`. See [the `DRAW` documentation](../../clause/draw.qmd#aggregate) for the full setting shape. ## Orientation The text layer has no orientation. The axes are treated symmetrically. @@ -146,3 +147,14 @@ PLACE text x => (40, 50, 50), y => (19, 19, 15) ``` + +Use aggregation to place labels at their centroid. + +```{ggsql} +VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins +DRAW point + MAPPING species AS fill +DRAW text + MAPPING species AS label + SETTING aggregate => 'mean', stroke => 'white', fontweight => 'bold', fontsize => 20 +``` diff --git a/src/execute/layer.rs b/src/execute/layer.rs index 6af5c641..8ada0d8c 100644 --- a/src/execute/layer.rs +++ b/src/execute/layer.rs @@ -187,11 +187,16 @@ pub fn apply_remappings_post_query(df: DataFrame, layer: &Layer) -> Result = df .get_column_names() .into_iter() - .filter(|name| naming::is_stat_column(name)) + .filter(|name| { + naming::is_stat_column(name) && !layer.partition_by.contains(&name.to_string()) + }) .collect(); if !stat_cols.is_empty() { df = df.drop_many(&stat_cols)?; @@ -436,6 +441,7 @@ pub fn apply_layer_transforms( scales: &[Scale], dialect: &dyn SqlDialect, execute_query: &F, + aesthetic_ctx: &AestheticContext, ) -> Result where F: Fn(&str) -> Result, @@ -511,6 +517,7 @@ where &layer.parameters, execute_query, dialect, + aesthetic_ctx, )?; // Flip user remappings BEFORE merging defaults for Transposed orientation. @@ -584,6 +591,37 @@ where layer.mappings.aesthetics.remove(aes); } + // Auto-remap stat columns whose names match aesthetics that were + // consumed by the stat (e.g. Aggregate's per-aesthetic outputs). The + // geom can't list these in `default_remappings` because the set of + // mapped aesthetics is dynamic per layer. + for stat in &stat_columns { + if final_remappings.contains_key(stat) { + continue; + } + if consumed_aesthetics.contains(stat) { + final_remappings.insert(stat.clone(), stat.clone()); + } + } + + // The synthetic `aggregate` stat column produced by an exploded + // Aggregate stat tags each row with its function name. For mark + // types that connect rows within a group (line, area, path, + // polygon) we add this column to `layer.partition_by` so e.g. + // `aggregate => ('y:min', 'y:max')` renders as two separate lines + // rather than one zigzag through both. Resolves to the post-rename + // data-column name: if the user remapped `aggregate AS `, the + // prefixed aesthetic column; otherwise the stat column. + if stat_columns.iter().any(|s| s == "aggregate") { + let partition_col = match final_remappings.get("aggregate") { + Some(aes) => naming::aesthetic_column(aes), + None => naming::stat_column("aggregate"), + }; + if !layer.partition_by.contains(&partition_col) { + layer.partition_by.push(partition_col); + } + } + // Apply stat_columns to layer aesthetics using the remappings for stat in &stat_columns { if let Some(aesthetic) = final_remappings.get(stat) { diff --git a/src/execute/mod.rs b/src/execute/mod.rs index e3b50b95..40efdfc8 100644 --- a/src/execute/mod.rs +++ b/src/execute/mod.rs @@ -116,24 +116,38 @@ fn validate( } } - // Validate remapping source columns are valid stat columns for this geom + // Validate remapping source columns are valid stat columns for this geom. + // Geoms that opt into the Aggregate stat (`supports_aggregate`) also accept + // `aggregate`, `count`, and any position aesthetic name as a stat source. let valid_stat_columns = layer.geom.valid_stat_columns(); + let supports_aggregate = layer.geom.supports_aggregate(); for stat_value in layer.remappings.aesthetics.values() { if let Some(stat_col) = stat_value.column_name() { - if !valid_stat_columns.contains(&stat_col) { - if valid_stat_columns.is_empty() { + let is_aggregate_stat_col = supports_aggregate + && (stat_col == "aggregate" + || stat_col == "count" + || crate::plot::aesthetic::is_position_aesthetic(stat_col)); + if !valid_stat_columns.contains(&stat_col) && !is_aggregate_stat_col { + if valid_stat_columns.is_empty() && !supports_aggregate { return Err(GgsqlError::ValidationError(format!( "Layer {}: REMAPPING not supported for geom '{}' (no stat transform)", idx + 1, layer.geom ))); } else { + let mut valid: Vec = + valid_stat_columns.iter().map(|s| s.to_string()).collect(); + if supports_aggregate { + valid.push("aggregate".to_string()); + valid.push("count".to_string()); + } + let valid_refs: Vec<&str> = valid.iter().map(|s| s.as_str()).collect(); return Err(GgsqlError::ValidationError(format!( "Layer {}: REMAPPING references unknown stat column '{}'. Valid stat columns for geom '{}' are: {}", idx + 1, stat_col, layer.geom, - crate::and_list(valid_stat_columns) + crate::and_list(&valid_refs) ))); } } @@ -700,9 +714,14 @@ fn add_discrete_columns_to_partition_by( // Build set of excluded aesthetics that should not trigger auto-grouping: // - Stat-consumed aesthetics (transformed, not grouped) // - 'label' aesthetic (text content to display, not grouping categories) + // — except when `aggregate` is set on the layer, in which case label + // becomes a legitimate grouping key (e.g. "mean per species, place + // species name at the centroid"). let consumed_aesthetics = layer.geom.stat_consumed_aesthetics(); let mut excluded_aesthetics: HashSet<&str> = consumed_aesthetics.iter().copied().collect(); - excluded_aesthetics.insert("label"); + if !crate::plot::layer::geom::has_aggregate_param(&layer.parameters) { + excluded_aesthetics.insert("label"); + } for (aesthetic, value) in &layer.mappings.aesthetics { // Skip position aesthetics - these should not trigger auto-grouping. @@ -1175,6 +1194,7 @@ pub fn prepare_data_with_reader(query: &str, reader: &dyn Reader) -> Result bool { + true + } + + fn aggregate_domain_aesthetics(&self) -> &'static [&'static str] { + &["pos1"] + } + fn needs_stat_transform(&self, _aesthetics: &Mappings) -> bool { true } @@ -61,21 +70,31 @@ impl GeomTrait for Area { fn apply_stat_transform( &self, query: &str, - _schema: &crate::plot::Schema, - _aesthetics: &Mappings, - _group_by: &[String], - _parameters: &std::collections::HashMap, + schema: &crate::plot::Schema, + aesthetics: &Mappings, + group_by: &[String], + parameters: &std::collections::HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, - _dialect: &dyn crate::reader::SqlDialect, + dialect: &dyn crate::reader::SqlDialect, + aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> crate::Result { - // Area geom needs ordering by pos1 (domain axis) for proper rendering - let order_col = naming::aesthetic_column("pos1"); - Ok(StatResult::Transformed { - query: format!("{} ORDER BY {}", query, naming::quote_ident(&order_col)), - stat_columns: vec![], - dummy_columns: vec![], - consumed_aesthetics: vec![], - }) + let result = if has_aggregate_param(parameters) { + stat_aggregate::apply( + query, + schema, + aesthetics, + group_by, + parameters, + dialect, + aesthetic_ctx, + self.aggregate_domain_aesthetics(), + )? + } else { + StatResult::Identity + }; + // Area needs ordering by pos1 (domain axis) for proper rendering, in both + // the Identity and Aggregate paths. + Ok(wrap_with_order_by(query, result, "pos1")) } } diff --git a/src/plot/layer/geom/arrow.rs b/src/plot/layer/geom/arrow.rs index 375d9754..2e3369d2 100644 --- a/src/plot/layer/geom/arrow.rs +++ b/src/plot/layer/geom/arrow.rs @@ -39,6 +39,10 @@ impl GeomTrait for Arrow { }]; PARAMS } + + fn supports_aggregate(&self) -> bool { + true + } } impl std::fmt::Display for Arrow { diff --git a/src/plot/layer/geom/bar.rs b/src/plot/layer/geom/bar.rs index d64bce9f..f2990467 100644 --- a/src/plot/layer/geom/bar.rs +++ b/src/plot/layer/geom/bar.rs @@ -3,10 +3,11 @@ use std::collections::HashMap; use std::collections::HashSet; +use super::stat_aggregate; use super::types::{get_column_name, POSITION_VALUES}; use super::{ - DefaultAesthetics, DefaultParamValue, GeomTrait, GeomType, ParamConstraint, ParamDefinition, - StatResult, + has_aggregate_param, DefaultAesthetics, DefaultParamValue, GeomTrait, GeomType, + ParamConstraint, ParamDefinition, StatResult, }; use crate::naming; use crate::plot::types::{DefaultAestheticValue, ParameterValue}; @@ -79,6 +80,10 @@ impl GeomTrait for Bar { &["pos1", "pos2", "weight"] } + fn supports_aggregate(&self) -> bool { + true + } + fn needs_stat_transform(&self, _aesthetics: &Mappings) -> bool { true // Bar stat decides COUNT vs identity based on y mapping } @@ -89,10 +94,23 @@ impl GeomTrait for Bar { schema: &Schema, aesthetics: &Mappings, group_by: &[String], - _parameters: &HashMap, + parameters: &HashMap, _execute_query: &dyn Fn(&str) -> Result, - _dialect: &dyn SqlDialect, + dialect: &dyn SqlDialect, + aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> Result { + if has_aggregate_param(parameters) { + return stat_aggregate::apply( + query, + schema, + aesthetics, + group_by, + parameters, + dialect, + aesthetic_ctx, + self.aggregate_domain_aesthetics(), + ); + } stat_bar_count(query, schema, aesthetics, group_by) } } diff --git a/src/plot/layer/geom/boxplot.rs b/src/plot/layer/geom/boxplot.rs index fdc7bae6..5d99b358 100644 --- a/src/plot/layer/geom/boxplot.rs +++ b/src/plot/layer/geom/boxplot.rs @@ -95,6 +95,7 @@ impl GeomTrait for Boxplot { parameters: &HashMap, _execute_query: &dyn Fn(&str) -> Result, dialect: &dyn SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> Result { stat_boxplot(query, aesthetics, group_by, parameters, dialect) } diff --git a/src/plot/layer/geom/density.rs b/src/plot/layer/geom/density.rs index 89910be9..7198e491 100644 --- a/src/plot/layer/geom/density.rs +++ b/src/plot/layer/geom/density.rs @@ -111,6 +111,7 @@ impl GeomTrait for Density { parameters: &std::collections::HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, dialect: &dyn SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> crate::Result { // Density geom: no tails limit (don't set tails parameter, defaults to None) stat_density( diff --git a/src/plot/layer/geom/histogram.rs b/src/plot/layer/geom/histogram.rs index 66400e56..bfb80050 100644 --- a/src/plot/layer/geom/histogram.rs +++ b/src/plot/layer/geom/histogram.rs @@ -97,6 +97,7 @@ impl GeomTrait for Histogram { parameters: &HashMap, execute_query: &dyn Fn(&str) -> Result, dialect: &dyn SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> Result { stat_histogram( query, diff --git a/src/plot/layer/geom/line.rs b/src/plot/layer/geom/line.rs index a8ded3b1..a6fd8edd 100644 --- a/src/plot/layer/geom/line.rs +++ b/src/plot/layer/geom/line.rs @@ -1,12 +1,14 @@ //! Line geom implementation +use super::stat_aggregate; +use super::types::wrap_with_order_by; use super::{ - DefaultAesthetics, DefaultParamValue, GeomTrait, GeomType, ParamConstraint, ParamDefinition, - StatResult, + has_aggregate_param, DefaultAesthetics, DefaultParamValue, GeomTrait, GeomType, + ParamConstraint, ParamDefinition, StatResult, }; use crate::plot::layer::orientation::{ALIGNED, ORIENTATION_VALUES}; use crate::plot::types::DefaultAestheticValue; -use crate::{naming, Mappings}; +use crate::Mappings; /// Line geom - line charts with connected points #[derive(Debug, Clone, Copy)] @@ -39,6 +41,14 @@ impl GeomTrait for Line { PARAMS } + fn supports_aggregate(&self) -> bool { + true + } + + fn aggregate_domain_aesthetics(&self) -> &'static [&'static str] { + &["pos1"] + } + fn needs_stat_transform(&self, _aesthetics: &Mappings) -> bool { true } @@ -46,21 +56,31 @@ impl GeomTrait for Line { fn apply_stat_transform( &self, query: &str, - _schema: &crate::plot::Schema, - _aesthetics: &Mappings, - _group_by: &[String], - _parameters: &std::collections::HashMap, + schema: &crate::plot::Schema, + aesthetics: &Mappings, + group_by: &[String], + parameters: &std::collections::HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, - _dialect: &dyn crate::reader::SqlDialect, + dialect: &dyn crate::reader::SqlDialect, + aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> crate::Result { - // Line geom needs ordering by pos1 (domain axis) for proper rendering - let order_col = naming::aesthetic_column("pos1"); - Ok(StatResult::Transformed { - query: format!("{} ORDER BY {}", query, naming::quote_ident(&order_col)), - stat_columns: vec![], - dummy_columns: vec![], - consumed_aesthetics: vec![], - }) + let result = if has_aggregate_param(parameters) { + stat_aggregate::apply( + query, + schema, + aesthetics, + group_by, + parameters, + dialect, + aesthetic_ctx, + self.aggregate_domain_aesthetics(), + )? + } else { + StatResult::Identity + }; + // Line needs ordering by pos1 (domain axis) for proper rendering, in both + // the Identity and Aggregate paths. + Ok(wrap_with_order_by(query, result, "pos1")) } } diff --git a/src/plot/layer/geom/mod.rs b/src/plot/layer/geom/mod.rs index 56f97e11..b9493668 100644 --- a/src/plot/layer/geom/mod.rs +++ b/src/plot/layer/geom/mod.rs @@ -43,6 +43,7 @@ mod ribbon; mod rule; mod segment; mod smooth; +pub(crate) mod stat_aggregate; mod text; mod tile; mod violin; @@ -72,6 +73,7 @@ pub use text::Text; pub use tile::Tile; pub use violin::Violin; +use crate::plot::aesthetic::AestheticContext; use crate::plot::types::{ParameterValue, Schema}; use crate::reader::SqlDialect; @@ -192,20 +194,57 @@ pub trait GeomTrait: std::fmt::Debug + std::fmt::Display + Send + Sync { false } + /// Whether this geom accepts the `aggregate` SETTING parameter. + /// + /// Geoms that opt in gain a generic Aggregate stat that groups by discrete + /// mappings + PARTITION BY and emits one row per group, replacing every + /// numeric mapping (positional and material) with its aggregated value. + /// Statistical geoms (histogram, density, smooth, boxplot, violin) leave + /// this `false` to keep their bespoke stats. + fn supports_aggregate(&self) -> bool { + false + } + + /// Aesthetics that the Aggregate stat must keep as group keys rather than + /// aggregating, even if their bound column is continuous. This is for + /// geoms like line/area/ribbon where one axis is the *domain* — the + /// natural group identity of each row — and the user expects "summarise + /// the other axis per domain value" without writing an explicit target. + /// + /// Default empty; line/area/ribbon override to `&["pos1"]`. + fn aggregate_domain_aesthetics(&self) -> &'static [&'static str] { + &[] + } + /// Apply statistical transformation to the layer query. /// - /// The default implementation returns identity (no transformation). + /// The default implementation dispatches to the Aggregate stat when + /// `supports_aggregate()` is true and the `aggregate` parameter is set; + /// otherwise returns identity (no transformation). #[allow(clippy::too_many_arguments)] fn apply_stat_transform( &self, - _query: &str, - _schema: &Schema, - _aesthetics: &Mappings, - _group_by: &[String], - _parameters: &HashMap, + query: &str, + schema: &Schema, + aesthetics: &Mappings, + group_by: &[String], + parameters: &HashMap, _execute_query: &dyn Fn(&str) -> Result, - _dialect: &dyn SqlDialect, + dialect: &dyn SqlDialect, + aesthetic_ctx: &AestheticContext, ) -> Result { + if self.supports_aggregate() && has_aggregate_param(parameters) { + return stat_aggregate::apply( + query, + schema, + aesthetics, + group_by, + parameters, + dialect, + aesthetic_ctx, + self.aggregate_domain_aesthetics(), + ); + } Ok(StatResult::Identity) } @@ -248,10 +287,21 @@ pub trait GeomTrait: std::fmt::Debug + std::fmt::Display + Send + Sync { for param in self.default_params() { valid.push(param.name); } + if self.supports_aggregate() { + valid.push("aggregate"); + } valid } } +/// True when `parameters["aggregate"]` is set to a non-null string or array. +pub(crate) fn has_aggregate_param(parameters: &HashMap) -> bool { + match parameters.get("aggregate") { + Some(ParameterValue::String(_)) | Some(ParameterValue::Array(_)) => true, + _ => false, + } +} + /// Wrapper struct for geom trait objects /// /// This provides a convenient interface for working with geoms while hiding @@ -420,6 +470,7 @@ impl Geom { parameters: &HashMap, execute_query: &dyn Fn(&str) -> Result, dialect: &dyn SqlDialect, + aesthetic_ctx: &AestheticContext, ) -> Result { self.0.apply_stat_transform( query, @@ -429,6 +480,7 @@ impl Geom { parameters, execute_query, dialect, + aesthetic_ctx, ) } @@ -455,6 +507,11 @@ impl Geom { self.0.valid_settings() } + /// Whether this geom accepts the `aggregate` SETTING parameter. + pub fn supports_aggregate(&self) -> bool { + self.0.supports_aggregate() + } + /// Validate aesthetic mappings pub fn validate_aesthetics(&self, mappings: &Mappings) -> std::result::Result<(), String> { self.0.validate_aesthetics(mappings) diff --git a/src/plot/layer/geom/point.rs b/src/plot/layer/geom/point.rs index 3dafde2a..5101f2f0 100644 --- a/src/plot/layer/geom/point.rs +++ b/src/plot/layer/geom/point.rs @@ -38,6 +38,10 @@ impl GeomTrait for Point { }]; PARAMS } + + fn supports_aggregate(&self) -> bool { + true + } } impl std::fmt::Display for Point { diff --git a/src/plot/layer/geom/range.rs b/src/plot/layer/geom/range.rs index 3fee6815..5cacd874 100644 --- a/src/plot/layer/geom/range.rs +++ b/src/plot/layer/geom/range.rs @@ -44,6 +44,10 @@ impl GeomTrait for Range { ]; PARAMS } + + fn supports_aggregate(&self) -> bool { + true + } } impl std::fmt::Display for Range { diff --git a/src/plot/layer/geom/ribbon.rs b/src/plot/layer/geom/ribbon.rs index 87d4636c..5b2a390e 100644 --- a/src/plot/layer/geom/ribbon.rs +++ b/src/plot/layer/geom/ribbon.rs @@ -1,10 +1,11 @@ //! Ribbon geom implementation -use super::types::POSITION_VALUES; -use super::{DefaultAesthetics, GeomTrait, GeomType, StatResult}; +use super::stat_aggregate; +use super::types::{wrap_with_order_by, POSITION_VALUES}; +use super::{has_aggregate_param, DefaultAesthetics, GeomTrait, GeomType, StatResult}; use crate::plot::types::DefaultAestheticValue; use crate::plot::{DefaultParamValue, ParamConstraint, ParamDefinition}; -use crate::{naming, Mappings}; +use crate::Mappings; /// Ribbon geom - confidence bands and ranges #[derive(Debug, Clone, Copy)] @@ -39,6 +40,14 @@ impl GeomTrait for Ribbon { PARAMS } + fn supports_aggregate(&self) -> bool { + true + } + + fn aggregate_domain_aesthetics(&self) -> &'static [&'static str] { + &["pos1"] + } + fn needs_stat_transform(&self, _aesthetics: &Mappings) -> bool { true } @@ -46,21 +55,31 @@ impl GeomTrait for Ribbon { fn apply_stat_transform( &self, query: &str, - _schema: &crate::plot::Schema, - _aesthetics: &Mappings, - _group_by: &[String], - _parameters: &std::collections::HashMap, + schema: &crate::plot::Schema, + aesthetics: &Mappings, + group_by: &[String], + parameters: &std::collections::HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, - _dialect: &dyn crate::reader::SqlDialect, + dialect: &dyn crate::reader::SqlDialect, + aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> crate::Result { - // Ribbon geom needs ordering by pos1 (domain axis) for proper rendering - let order_col = naming::aesthetic_column("pos1"); - Ok(StatResult::Transformed { - query: format!("{} ORDER BY {}", query, naming::quote_ident(&order_col)), - stat_columns: vec![], - dummy_columns: vec![], - consumed_aesthetics: vec![], - }) + let result = if has_aggregate_param(parameters) { + stat_aggregate::apply( + query, + schema, + aesthetics, + group_by, + parameters, + dialect, + aesthetic_ctx, + self.aggregate_domain_aesthetics(), + )? + } else { + StatResult::Identity + }; + // Ribbon needs ordering by pos1 (domain axis) for proper rendering, in both + // the Identity and Aggregate paths. + Ok(wrap_with_order_by(query, result, "pos1")) } } diff --git a/src/plot/layer/geom/rule.rs b/src/plot/layer/geom/rule.rs index be434f7a..a495cb48 100644 --- a/src/plot/layer/geom/rule.rs +++ b/src/plot/layer/geom/rule.rs @@ -25,6 +25,10 @@ impl GeomTrait for Rule { } } + fn supports_aggregate(&self) -> bool { + true + } + fn validate_aesthetics(&self, mappings: &crate::Mappings) -> std::result::Result<(), String> { // Rule requires exactly one of pos1 or pos2 (XOR logic) let has_pos1 = mappings.contains_key("pos1"); diff --git a/src/plot/layer/geom/segment.rs b/src/plot/layer/geom/segment.rs index 3066d8a5..4dd7e65f 100644 --- a/src/plot/layer/geom/segment.rs +++ b/src/plot/layer/geom/segment.rs @@ -38,6 +38,10 @@ impl GeomTrait for Segment { }]; PARAMS } + + fn supports_aggregate(&self) -> bool { + true + } } impl std::fmt::Display for Segment { diff --git a/src/plot/layer/geom/smooth.rs b/src/plot/layer/geom/smooth.rs index 2f053235..f65111ee 100644 --- a/src/plot/layer/geom/smooth.rs +++ b/src/plot/layer/geom/smooth.rs @@ -100,6 +100,7 @@ impl GeomTrait for Smooth { parameters: &std::collections::HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, dialect: &dyn SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> crate::Result { // Get method from parameters (validated by ParamConstraint::string_option) let ParameterValue::String(method) = parameters.get("method").unwrap() else { diff --git a/src/plot/layer/geom/stat_aggregate.rs b/src/plot/layer/geom/stat_aggregate.rs new file mode 100644 index 00000000..8015fd0e --- /dev/null +++ b/src/plot/layer/geom/stat_aggregate.rs @@ -0,0 +1,1902 @@ +//! Aggregate stat — collapse each group to a single row by applying an +//! aggregate function per numeric mapping. +//! +//! When a layer's `aggregate` SETTING is set, this stat groups by discrete +//! mappings + PARTITION BY columns and emits one row per group. Each numeric +//! column-mapping (positional *and* material) is replaced in place by the +//! aggregated value of its bound column. Discrete mappings stay as group keys; +//! literal mappings pass through unchanged. +//! +//! # Setting shape +//! +//! `aggregate` accepts a single string or array of strings. Each string is +//! either: +//! +//! - **default** — `''` (no prefix). Up to two defaults may be supplied. +//! With one default it applies to every untargeted numeric mapping. With two +//! defaults the first applies to *lower-half* aesthetics (no suffix or `min` +//! suffix) plus all non-range geoms, and the second applies to *upper-half* +//! aesthetics (`max` or `end` suffix). More than two defaults is an error. +//! - **target** — `':'`. Applies `func` to the named aesthetic only. +//! `` is a user-facing name (`x`, `y`, `xmin`, `xmax`, `xend`, `yend`, +//! `color`, `size`, …); the stat resolves it to the internal name through +//! `AestheticContext`. +//! +//! Numeric mappings without a target *or* applicable default are dropped with +//! a warning to stderr. + +use std::collections::HashMap; + +use super::types::StatResult; +use crate::naming; +use crate::plot::aesthetic::AestheticContext; +use crate::plot::types::{ArrayElement, ParameterValue, Schema}; +use crate::reader::SqlDialect; +use crate::{GgsqlError, Mappings, Result}; + +/// All simple-aggregation function names accepted by the `aggregate` SETTING. +/// +/// Band names (e.g. `mean+sdev`, `median-0.5iqr`) are validated separately by +/// `parse_agg_name`, which checks the offset against `OFFSET_STATS` and the +/// expansion against `EXPANSION_STATS`. +pub const AGG_NAMES: &[&str] = &[ + // Tallies & sums + "count", "sum", "prod", // Extremes + "min", "max", "range", "mid", // Central tendency + "mean", "geomean", "harmean", "rms", "median", // Spread (standalone) + "sdev", "var", "iqr", // Percentiles + "p05", "p10", "p25", "p50", "p75", "p90", "p95", // Positional (row order in the group) + "first", "last", +]; + +/// Stats that can appear as the *offset* (left of `±`) in a band name like +/// `mean+sdev`. Single-value central or representative quantities only — +/// counts/spreads are excluded. +pub const OFFSET_STATS: &[&str] = &[ + "mean", "median", "geomean", "harmean", "rms", "sum", "prod", "min", "max", "mid", "p05", + "p10", "p25", "p50", "p75", "p90", "p95", +]; + +/// Stats that can appear as the *expansion* (right of `±[mod]`) in a band name. +/// Spread / dispersion measures only. +pub const EXPANSION_STATS: &[&str] = &["sdev", "se", "var", "iqr", "range"]; + +/// Parsed representation of any aggregate-function name. +/// +/// Simple aggregates (`mean`, `count`, `p25`) have `band == None`. Band names +/// (`mean+sdev`, `median-0.5iqr`) have `band == Some(...)` with the offset +/// stored in `offset` and the spread/multiplier in `band`. +#[derive(Debug, Clone, PartialEq)] +pub struct AggSpec { + pub offset: &'static str, + pub band: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Band { + pub sign: char, + pub mod_value: f64, + pub expansion: &'static str, +} + +fn resolve_static(name: &str, vocab: &'static [&'static str]) -> Option<&'static str> { + vocab.iter().copied().find(|v| *v == name) +} + +/// Parse an aggregate-function name into an `AggSpec`. Returns `None` on +/// invalid input (unknown stat, malformed band, or band with vocabulary +/// violation). +pub fn parse_agg_name(name: &str) -> Option { + if let Some(spec) = parse_band(name) { + return Some(spec); + } + resolve_static(name, AGG_NAMES).map(|offset| AggSpec { offset, band: None }) +} + +fn parse_band(name: &str) -> Option { + // Walk offsets longest-first so `median` matches before `mean`. + let mut offsets: Vec<&'static str> = OFFSET_STATS.to_vec(); + offsets.sort_by_key(|s| std::cmp::Reverse(s.len())); + + for offset in offsets { + let rest = match name.strip_prefix(offset) { + Some(r) => r, + None => continue, + }; + let (sign, after_sign) = match rest.chars().next() { + Some('+') => ('+', &rest[1..]), + Some('-') => ('-', &rest[1..]), + _ => continue, + }; + + let (mod_value, expansion_str) = parse_mod_and_remainder(after_sign); + let expansion = match resolve_static(expansion_str, EXPANSION_STATS) { + Some(e) => e, + None => continue, + }; + + return Some(AggSpec { + offset, + band: Some(Band { + sign, + mod_value, + expansion, + }), + }); + } + None +} + +fn parse_mod_and_remainder(s: &str) -> (f64, &str) { + let mut idx = 0; + let bytes = s.as_bytes(); + while idx < bytes.len() && bytes[idx].is_ascii_digit() { + idx += 1; + } + if idx < bytes.len() && bytes[idx] == b'.' { + let mut after_dot = idx + 1; + while after_dot < bytes.len() && bytes[after_dot].is_ascii_digit() { + after_dot += 1; + } + if after_dot > idx + 1 { + idx = after_dot; + } + } + if idx == 0 { + return (1.0, s); + } + let num_str = &s[..idx]; + let value: f64 = num_str.parse().unwrap_or(1.0); + (value, &s[idx..]) +} + +// ============================================================================= +// AggregateSpec — parsed representation of the `aggregate` SETTING. +// ============================================================================= + +/// Parsed `aggregate` SETTING. +/// +/// Up to two unprefixed defaults plus per-aesthetic targets. A target may be +/// named more than once; the multiple functions cause that aesthetic to +/// *explode* into multiple rows per group +#[derive(Debug, Clone, PartialEq)] +pub struct AggregateSpec { + pub default_lower: Option, + pub default_upper: Option, + /// Targets in declaration order. Each entry is `(user-facing aesthetic, + /// non-empty list of functions)`. Multiple SETTING entries with the same + /// aesthetic are merged into one list during parsing — the cumulative + /// length determines that aesthetic's explosion factor. + pub targets: Vec<(String, Vec)>, +} + +impl AggregateSpec { + fn new() -> Self { + Self { + default_lower: None, + default_upper: None, + targets: Vec::new(), + } + } + + /// Maximum target list length, or `1` if every target has a single function. + /// This is the number of exploded rows the stat will emit per group. + pub fn explosion_factor(&self) -> usize { + self.targets + .iter() + .map(|(_, fns)| fns.len()) + .max() + .unwrap_or(1) + .max(1) + } + + /// Per-row labels for the synthetic `aggregate` column. `None` for the + /// single-row case (no explosion), since the column only makes sense as a + /// row-differentiator and there's nothing to differentiate. + /// + /// For each row in `0..explosion_factor`, walks every *exploded* target + /// (length == n; length-1 recycled targets are skipped because they take + /// the same value on every row), collects each target's function name at + /// that row, deduplicates them while preserving declaration order, and + /// joins with `/`. + /// + /// Examples (with `n = 2`): + /// - `('y:min', 'y:max')` → `['min', 'max']` + /// - `('y:min', 'y:max', 'color:sum', 'color:prod')` → `['min/sum', 'max/prod']` + /// - `('y:mean', 'y:max', 'color:mean', 'color:prod')` → `['mean', 'max/prod']` + /// - `('y:min', 'y:max', 'color:median')` → `['min', 'max']` (color is recycled) + pub fn explosion_labels(&self) -> Option> { + let n = self.explosion_factor(); + if n <= 1 { + return None; + } + let exploded: Vec<&Vec> = self + .targets + .iter() + .filter(|(_, fns)| fns.len() == n) + .map(|(_, fns)| fns) + .collect(); + let labels = (0..n) + .map(|row| { + let mut parts: Vec = Vec::new(); + for fns in &exploded { + let label = agg_label(&fns[row]); + if !parts.contains(&label) { + parts.push(label); + } + } + parts.join("/") + }) + .collect(); + Some(labels) + } +} + +/// Human-readable label for an `AggSpec`. Re-emits simple names verbatim and +/// reconstructs band names like `mean+sdev`. +fn agg_label(spec: &AggSpec) -> String { + match &spec.band { + None => spec.offset.to_string(), + Some(b) => { + if b.mod_value == 1.0 { + format!("{}{}{}", spec.offset, b.sign, b.expansion) + } else { + format!("{}{}{}{}", spec.offset, b.sign, b.mod_value, b.expansion) + } + } + } +} + +/// Parse the `aggregate` SETTING value into an `AggregateSpec`. Returns +/// `Ok(None)` when the parameter is unset, null, or empty. Returns `Err(...)` +/// for malformed input. +pub fn parse_aggregate_param( + value: &ParameterValue, +) -> std::result::Result, String> { + let entries: Vec<&str> = match value { + ParameterValue::Null => return Ok(None), + ParameterValue::String(s) => vec![s.as_str()], + ParameterValue::Array(arr) => { + let mut out = Vec::with_capacity(arr.len()); + for el in arr { + match el { + ArrayElement::String(s) => out.push(s.as_str()), + ArrayElement::Null => continue, + _ => { + return Err("'aggregate' array entries must be strings or null".to_string()); + } + } + } + if out.is_empty() { + return Ok(None); + } + out + } + _ => return Err("'aggregate' must be a string, array of strings, or null".to_string()), + }; + + let mut spec = AggregateSpec::new(); + for entry in entries { + if let Some((aes, func)) = split_target(entry) { + if aes.is_empty() { + return Err(format!("'{}': aesthetic prefix is empty", entry)); + } + if func.is_empty() { + return Err(format!("'{}': aggregate function is empty", entry)); + } + let agg = parse_agg_name(func) + .ok_or_else(|| format!("'{}': {}", entry, diagnose_invalid_function_name(func)))?; + // Append to existing list for this aesthetic, or create one. + if let Some((_, fns)) = spec.targets.iter_mut().find(|(a, _)| a == aes) { + fns.push(agg); + } else { + spec.targets.push((aes.to_string(), vec![agg])); + } + } else { + let agg = parse_agg_name(entry).ok_or_else(|| diagnose_invalid_function_name(entry))?; + if spec.default_lower.is_none() { + spec.default_lower = Some(agg); + } else if spec.default_upper.is_none() { + spec.default_upper = Some(agg); + } else { + return Err(format!( + "'aggregate' accepts at most two unprefixed defaults; got a third: '{}'", + entry + )); + } + } + } + + if spec.default_lower.is_none() && spec.default_upper.is_none() && spec.targets.is_empty() { + return Ok(None); + } + + // Validate recycling: every target list must be length 1 or N (the max). + let n = spec.explosion_factor(); + if n > 1 { + for (aes, fns) in &spec.targets { + if fns.len() != 1 && fns.len() != n { + return Err(format!( + "aggregate target '{}' has {} functions; targets in an exploded layer must \ + have either 1 or {} functions (the longest target's count)", + aes, + fns.len(), + n + )); + } + } + } + + Ok(Some(spec)) +} + +/// Split an entry into `(aesthetic, function)` if it contains a `:`. Returns +/// `None` for an unprefixed entry like `'mean'`. +fn split_target(entry: &str) -> Option<(&str, &str)> { + entry.split_once(':') +} + +/// Validate the `aggregate` SETTING value at parse-time. Used by +/// `Layer::validate_settings`. Aesthetic-name resolution is deferred to +/// `apply()` because `AestheticContext` isn't available here. +pub fn validate_aggregate_param(value: &ParameterValue) -> std::result::Result<(), String> { + parse_aggregate_param(value).map(|_| ()) +} + +/// Build a per-role error message for a name that didn't parse. Re-walks the +/// input with looser rules to identify which side (offset / expansion) failed. +fn diagnose_invalid_function_name(name: &str) -> String { + if let Some(sign_idx) = name.find(['+', '-']) { + let offset_str = &name[..sign_idx]; + let after_sign = &name[sign_idx + 1..]; + let (_mod_value, expansion_str) = parse_mod_and_remainder(after_sign); + + let offset_known_simple = AGG_NAMES.contains(&offset_str); + let offset_known_band = OFFSET_STATS.contains(&offset_str); + let expansion_known_band = EXPANSION_STATS.contains(&expansion_str); + + if !offset_known_band { + if offset_known_simple { + return format!( + "'{}': '{}' is not a valid offset stat. Allowed offsets: {}", + name, + offset_str, + crate::or_list_quoted(OFFSET_STATS, '\''), + ); + } + return format!( + "'{}': '{}' is not a known stat. Allowed offsets: {}", + name, + offset_str, + crate::or_list_quoted(OFFSET_STATS, '\''), + ); + } + if !expansion_known_band { + return format!( + "'{}': '{}' is not a valid expansion stat. Allowed expansions: {}", + name, + expansion_str, + crate::or_list_quoted(EXPANSION_STATS, '\''), + ); + } + return format!("'{}' is not a valid aggregate function name", name); + } + format!( + "unknown aggregate function '{}'. Allowed: {} (or use a band like `mean+sdev`)", + name, + crate::or_list_quoted(AGG_NAMES, '\''), + ) +} + +// ============================================================================= +// SQL fragment helpers (per-column aggregate expressions). +// ============================================================================= + +/// Map a percentile function name (`p05`..`p95`, `median`) to its fraction. +fn percentile_fraction(func: &str) -> Option { + match func { + "median" | "p50" => Some(0.50), + "p05" => Some(0.05), + "p10" => Some(0.10), + "p25" => Some(0.25), + "p75" => Some(0.75), + "p90" => Some(0.90), + "p95" => Some(0.95), + _ => None, + } +} + +/// Build the inline SQL fragment for a *simple* stat (no band) applied to a +/// quoted column. Returns `None` when the dialect cannot express this +/// aggregate inline — for the percentile/iqr family that means the caller +/// switches to the correlated `sql_percentile` fallback; for other names it +/// means the dialect doesn't support that function and the stat layer raises +/// a clear error before SQL is built (see `validate_supported`). +fn simple_stat_sql_inline(name: &str, qcol: &str, dialect: &dyn SqlDialect) -> Option { + if let Some(frac) = percentile_fraction(name) { + let unquoted = unquote(qcol); + return dialect.sql_quantile_inline(&unquoted, frac); + } + if name == "iqr" { + let unquoted = unquote(qcol); + let p75 = dialect.sql_quantile_inline(&unquoted, 0.75)?; + let p25 = dialect.sql_quantile_inline(&unquoted, 0.25)?; + return Some(format!("({} - {})", p75, p25)); + } + dialect.sql_aggregate(name, qcol) +} + +/// Whether the dialect can produce SQL for this aggregate (inline or via the +/// percentile fallback). Used to surface a clear error before SQL is built. +fn dialect_supports(name: &str, dialect: &dyn SqlDialect) -> bool { + if percentile_fraction(name).is_some() || name == "iqr" { + // Always supported: percentile path falls back to a correlated subquery + // built from `sql_percentile`, which has a portable default. + return true; + } + dialect.sql_aggregate(name, "x").is_some() +} + +/// Walk every aggregate that will be emitted and confirm the dialect supports +/// it. Returns the list of unsupported function names, deduplicated. +fn unsupported_functions( + aggregated: &[(String, String, Vec)], + dialect: &dyn SqlDialect, +) -> Vec { + let mut missing: Vec = Vec::new(); + for (_, _, specs) in aggregated { + for spec in specs { + for name in [Some(spec.offset), spec.band.as_ref().map(|b| b.expansion)] + .into_iter() + .flatten() + { + if !dialect_supports(name, dialect) && !missing.iter().any(|m| m == name) { + missing.push(name.to_string()); + } + } + } + } + missing +} + +fn agg_sql_inline(spec: &AggSpec, qcol: &str, dialect: &dyn SqlDialect) -> Option { + let offset_sql = simple_stat_sql_inline(spec.offset, qcol, dialect)?; + match &spec.band { + None => Some(offset_sql), + Some(band) => { + let exp_sql = simple_stat_sql_inline(band.expansion, qcol, dialect)?; + Some(format_band( + &offset_sql, + band.sign, + band.mod_value, + &exp_sql, + )) + } + } +} + +fn format_band(offset: &str, sign: char, mod_value: f64, exp: &str) -> String { + if mod_value == 1.0 { + format!("({} {} {})", offset, sign, exp) + } else { + format!("({} {} {} * {})", offset, sign, mod_value, exp) + } +} + +/// Fallback SQL for a simple stat — used when a percentile component lacks +/// inline support. Emits a correlated `sql_percentile` subquery; falls +/// through to the inline form for everything else. +fn simple_stat_sql_fallback( + name: &str, + raw_col: &str, + dialect: &dyn SqlDialect, + src_alias: &str, + group_cols: &[String], +) -> String { + if let Some(frac) = percentile_fraction(name) { + return dialect.sql_percentile(raw_col, frac, src_alias, group_cols); + } + if name == "iqr" { + let p75 = dialect.sql_percentile(raw_col, 0.75, src_alias, group_cols); + let p25 = dialect.sql_percentile(raw_col, 0.25, src_alias, group_cols); + return format!("({} - {})", p75, p25); + } + let qcol = naming::quote_ident(raw_col); + simple_stat_sql_inline(name, &qcol, dialect).unwrap_or_else(|| "NULL".to_string()) +} + +fn agg_sql_fallback( + spec: &AggSpec, + raw_col: &str, + dialect: &dyn SqlDialect, + src_alias: &str, + group_cols: &[String], +) -> String { + let offset_sql = simple_stat_sql_fallback(spec.offset, raw_col, dialect, src_alias, group_cols); + match &spec.band { + None => offset_sql, + Some(band) => { + let exp_sql = + simple_stat_sql_fallback(band.expansion, raw_col, dialect, src_alias, group_cols); + format_band(&offset_sql, band.sign, band.mod_value, &exp_sql) + } + } +} + +fn needs_quantile_fallback(spec: &AggSpec, probe_col: &str, dialect: &dyn SqlDialect) -> bool { + if simple_needs_fallback(spec.offset, probe_col, dialect) { + return true; + } + if let Some(band) = &spec.band { + if simple_needs_fallback(band.expansion, probe_col, dialect) { + return true; + } + } + false +} + +fn simple_needs_fallback(name: &str, probe_col: &str, dialect: &dyn SqlDialect) -> bool { + if let Some(frac) = percentile_fraction(name) { + return dialect.sql_quantile_inline(probe_col, frac).is_none(); + } + if name == "iqr" { + return dialect.sql_quantile_inline(probe_col, 0.5).is_none(); + } + false +} + +fn unquote(qcol: &str) -> String { + let trimmed = qcol.trim_start_matches('"').trim_end_matches('"'); + trimmed.replace("\"\"", "\"") +} + +// ============================================================================= +// apply — entry point. +// ============================================================================= + +/// Resolve a user-facing target aesthetic name to one or more internal names +/// that are actually mapped on the layer. Handles three cases: +/// 1. The name maps directly through `AestheticContext` (e.g. `y` → `pos2`). +/// 2. The name is an alias from `AESTHETIC_ALIASES` (e.g. `color` → `stroke`, +/// `fill`); each target whose internal counterpart is mapped is included. +/// 3. The name is a material aesthetic with the same internal name (e.g. `size`). +/// +/// Returns the empty vector if no resolution finds a mapped aesthetic. +fn resolve_target_aesthetic( + user_aes: &str, + aesthetics: &Mappings, + aesthetic_ctx: &AestheticContext, +) -> Vec { + use crate::plot::layer::geom::types::AESTHETIC_ALIASES; + let mut out = Vec::new(); + if let Some(internal) = aesthetic_ctx.map_user_to_internal(user_aes) { + if aesthetics.aesthetics.contains_key(internal) { + out.push(internal.to_string()); + return out; + } + } + for (alias, targets) in AESTHETIC_ALIASES { + if *alias == user_aes { + for t in *targets { + let internal = aesthetic_ctx + .map_user_to_internal(t) + .map(|s| s.to_string()) + .unwrap_or_else(|| (*t).to_string()); + if aesthetics.aesthetics.contains_key(&internal) && !out.contains(&internal) { + out.push(internal); + } + } + return out; + } + } + if aesthetics.aesthetics.contains_key(user_aes) { + out.push(user_aes.to_string()); + } + out +} + +/// Classify an internal aesthetic name as upper-half or lower-half for the +/// purpose of default-aggregate routing. +/// +/// `min` suffix → lower; `max`/`end` → upper; no suffix → lower. Material +/// aesthetics (no position prefix) are always lower. +fn is_upper_half(internal_aes: &str) -> bool { + internal_aes.ends_with("max") || internal_aes.ends_with("end") +} + +/// Apply the Aggregate stat to a layer query. +/// +/// Returns `StatResult::Identity` when the `aggregate` parameter is unset, null, +/// or empty. Otherwise, builds a `GROUP BY` query producing one row per group +/// (the *reduce* path) — or, when at least one target lists multiple functions, +/// `N` rows per group with a synthetic `aggregate` column tagging each row +/// (the *explode* path). +#[allow(clippy::too_many_arguments)] +pub fn apply( + query: &str, + schema: &Schema, + aesthetics: &Mappings, + group_by: &[String], + parameters: &HashMap, + dialect: &dyn SqlDialect, + aesthetic_ctx: &AestheticContext, + domain_aesthetics: &[&'static str], +) -> Result { + let raw = match parameters.get("aggregate") { + None | Some(ParameterValue::Null) => return Ok(StatResult::Identity), + Some(v) => v, + }; + let spec = parse_aggregate_param(raw).map_err(GgsqlError::ValidationError)?; + let spec = match spec { + Some(s) => s, + None => return Ok(StatResult::Identity), + }; + let n = spec.explosion_factor(); + let labels = spec.explosion_labels(); + + // Resolve target keys (user-facing) → internal aesthetic names, keeping + // each target's function list. An alias like `color` expands to whichever + // of its targets (stroke/fill) is mapped on the layer; the same list + // applies to all of them. + let mut targets_internal: HashMap> = HashMap::new(); + for (user_aes, fns) in &spec.targets { + let resolved = resolve_target_aesthetic(user_aes, aesthetics, aesthetic_ctx); + if resolved.is_empty() { + return Err(GgsqlError::ValidationError(format!( + "aggregate target '{}' is not mapped on this layer", + user_aes + ))); + } + for internal in resolved { + if targets_internal.contains_key(&internal) { + return Err(GgsqlError::ValidationError(format!( + "aggregate target '{}' resolves to aesthetic '{}' which is already targeted", + user_aes, internal + ))); + } + targets_internal.insert(internal, fns.clone()); + } + } + + // Walk mappings. Three buckets: + // - aggregated: (internal_aes, raw_col, fns of length n) — each emits one column per row + // - kept_cols: discrete column-mappings — keep as group key + // - dropped: numeric mapping with no applicable function (warn & skip) + let mut aggregated: Vec<(String, String, Vec)> = Vec::new(); + let mut kept_cols: Vec = Vec::new(); + let mut dropped: Vec = Vec::new(); + + let mut entries: Vec<(&String, &crate::AestheticValue)> = + aesthetics.aesthetics.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + + for (aes, value) in entries { + let col = match value.column_name() { + Some(c) => c.to_string(), + None => continue, // literals & annotation columns pass through + }; + // Geom-declared domain aesthetics (e.g. `pos1` for line/area/ribbon) + // always become group keys — they identify each row, never get + // aggregated, never get dropped. + if domain_aesthetics.contains(&aes.as_str()) { + if !kept_cols.contains(&col) { + kept_cols.push(col); + } + continue; + } + let info = schema.iter().find(|c| c.name == col); + let is_discrete = info.map(|c| c.is_discrete).unwrap_or(false); + if is_discrete { + if !kept_cols.contains(&col) { + kept_cols.push(col); + } + continue; + } + + // Numeric mapping. Look up the function list (recycling to length n). + let fns: Option> = if let Some(list) = targets_internal.get(aes) { + if list.len() == n { + Some(list.clone()) + } else { + // Validated to be 1 or n during parsing; guard with a sanity check. + debug_assert_eq!(list.len(), 1); + Some(vec![list[0].clone(); n]) + } + } else { + let default = if is_upper_half(aes) { + spec.default_upper + .clone() + .or_else(|| spec.default_lower.clone()) + } else { + spec.default_lower.clone() + }; + default.map(|d| vec![d; n]) + }; + + match fns { + Some(list) => aggregated.push((aes.clone(), col, list)), + None => dropped.push(aes.clone()), + } + } + + // The *only* time we have nothing to aggregate but should still transform + // is when defaults exist but every numeric mapping was dropped — we still + // emit a GROUP BY to honour the grouping. If there are no aggregations and + // no kept columns and no group_by, return Identity. + if aggregated.is_empty() && kept_cols.is_empty() && group_by.is_empty() { + for d in &dropped { + eprintln!( + "Warning: aggregate dropped numeric mapping for aesthetic '{}' (no applicable default and no targeted function)", + aesthetic_ctx.map_internal_to_user(d) + ); + } + return Ok(StatResult::Identity); + } + + for d in &dropped { + eprintln!( + "Warning: aggregate dropped numeric mapping for aesthetic '{}' (no applicable default and no targeted function)", + aesthetic_ctx.map_internal_to_user(d) + ); + } + + // Group columns: PARTITION BY + discrete column-mappings, deduped. + let mut group_cols: Vec = Vec::new(); + for g in group_by { + if !group_cols.contains(g) { + group_cols.push(g.clone()); + } + } + for c in &kept_cols { + if !group_cols.contains(c) { + group_cols.push(c.clone()); + } + } + + let missing = unsupported_functions(&aggregated, dialect); + if !missing.is_empty() { + return Err(GgsqlError::ValidationError(format!( + "aggregate function(s) {} are not supported by this database backend", + crate::or_list_quoted(&missing, '\''), + ))); + } + + let transformed_query = match &labels { + Some(ls) => build_aggregate_query(query, &aggregated, &group_cols, ls, dialect), + None => build_group_by_query(query, &aggregated, &group_cols, dialect), + }; + + let mut stat_columns: Vec = aggregated.iter().map(|(a, _, _)| a.clone()).collect(); + let consumed_aesthetics: Vec = stat_columns.clone(); + // The synthetic `aggregate` column is only emitted for the multi-row + // (explosion) case, where it differentiates rows that share the same + // group key. + if labels.is_some() { + stat_columns.push("aggregate".to_string()); + } + + Ok(StatResult::Transformed { + query: transformed_query, + stat_columns, + dummy_columns: vec![], + consumed_aesthetics, + }) +} + +/// Build the single-row `WITH src AS () SELECT , +/// FROM src AS "__ggsql_qt__" GROUP BY ` query. Each aggregated +/// aesthetic's function list is length 1 here. +/// +/// Falls back to `dialect.sql_percentile()` per-column when an aggregate's +/// percentile component lacks inline support. +fn build_group_by_query( + query: &str, + aggregated: &[(String, String, Vec)], + group_cols: &[String], + dialect: &dyn SqlDialect, +) -> String { + let src_alias = "\"__ggsql_stat_src__\""; + let outer_alias = "\"__ggsql_qt__\""; + + let group_select: Vec = group_cols.iter().map(|c| naming::quote_ident(c)).collect(); + let group_by_clause = if group_cols.is_empty() { + String::new() + } else { + format!(" GROUP BY {}", group_select.join(", ")) + }; + + let mut select_parts: Vec = group_select.clone(); + + for (aes, raw_col, fns) in aggregated { + let agg = &fns[0]; + let stat_col = naming::stat_column(aes); + let qcol = naming::quote_ident(raw_col); + let expr = if needs_quantile_fallback(agg, raw_col, dialect) { + agg_sql_fallback(agg, raw_col, dialect, src_alias, group_cols) + } else { + agg_sql_inline(agg, &qcol, dialect) + .expect("agg_sql_inline must succeed when needs_quantile_fallback is false") + }; + select_parts.push(format!("{} AS {}", expr, naming::quote_ident(&stat_col))); + } + + format!( + "WITH {src} AS ({query}) SELECT {sel} FROM {src} AS {outer}{gb}", + src = src_alias, + query = query, + sel = select_parts.join(", "), + outer = outer_alias, + gb = group_by_clause, + ) +} + +/// Build the exploded `WITH src AS () UNION ALL +/// ...` query. One branch per row in `0..labels.len()`, each branch its own +/// `GROUP BY` with the row's aggregation functions and a literal label tagged +/// to `__ggsql_stat_aggregate__`. +fn build_aggregate_query( + query: &str, + aggregated: &[(String, String, Vec)], + group_cols: &[String], + labels: &[String], + dialect: &dyn SqlDialect, +) -> String { + let src_alias = "\"__ggsql_stat_src__\""; + let outer_alias = "\"__ggsql_qt__\""; + + let group_select: Vec = group_cols.iter().map(|c| naming::quote_ident(c)).collect(); + let group_by_clause = if group_cols.is_empty() { + String::new() + } else { + format!(" GROUP BY {}", group_select.join(", ")) + }; + + let stat_aggregate_col = naming::stat_column("aggregate"); + + let branches: Vec = labels + .iter() + .enumerate() + .map(|(row_idx, label)| { + let mut select_parts: Vec = group_select.clone(); + + for (aes, raw_col, fns) in aggregated { + let agg = &fns[row_idx]; + let stat_col = naming::stat_column(aes); + let qcol = naming::quote_ident(raw_col); + let expr = if needs_quantile_fallback(agg, raw_col, dialect) { + agg_sql_fallback(agg, raw_col, dialect, src_alias, group_cols) + } else { + agg_sql_inline(agg, &qcol, dialect) + .expect("agg_sql_inline must succeed when needs_quantile_fallback is false") + }; + select_parts.push(format!("{} AS {}", expr, naming::quote_ident(&stat_col))); + } + + select_parts.push(format!( + "{} AS {}", + func_literal(label), + naming::quote_ident(&stat_aggregate_col) + )); + + format!( + "SELECT {} FROM {} AS {}{}", + select_parts.join(", "), + src_alias, + outer_alias, + group_by_clause, + ) + }) + .collect(); + + format!( + "WITH {src} AS ({query}) {body}", + src = src_alias, + query = query, + body = branches.join(" UNION ALL "), + ) +} + +fn func_literal(s: &str) -> String { + format!("'{}'", s.replace('\'', "''")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plot::aesthetic::AestheticContext; + use crate::plot::types::{AestheticValue, ColumnInfo}; + use arrow::datatypes::DataType; + + /// A test dialect that mimics DuckDB: native QUANTILE_CONT plus the + /// row-positional FIRST / LAST aggregates. + struct InlineQuantileDialect; + impl SqlDialect for InlineQuantileDialect { + fn sql_quantile_inline(&self, column: &str, fraction: f64) -> Option { + Some(format!( + "QUANTILE_CONT({}, {})", + naming::quote_ident(column), + fraction + )) + } + + fn sql_aggregate(&self, name: &str, qcol: &str) -> Option { + match name { + "first" => Some(format!("FIRST({})", qcol)), + "last" => Some(format!("LAST({})", qcol)), + _ => crate::reader::default_sql_aggregate(name, qcol), + } + } + } + + /// A test dialect with no inline quantile support, exercising the + /// per-column `sql_percentile` fallback. + struct NoInlineQuantileDialect; + impl SqlDialect for NoInlineQuantileDialect {} + + fn col(name: &str) -> AestheticValue { + AestheticValue::Column { + name: name.to_string(), + original_name: None, + is_dummy: false, + } + } + + fn schema_for(cols: &[(&str, bool)]) -> Schema { + cols.iter() + .map(|(name, is_discrete)| ColumnInfo { + name: name.to_string(), + dtype: if *is_discrete { + DataType::Utf8 + } else { + DataType::Float64 + }, + is_discrete: *is_discrete, + min: None, + max: None, + }) + .collect() + } + + fn cartesian_ctx() -> AestheticContext { + AestheticContext::from_static(&["x", "y"], &[]) + } + + fn run( + params: ParameterValue, + aes: &Mappings, + schema: &Schema, + group_by: &[String], + dialect: &dyn SqlDialect, + ) -> Result { + run_with_domain(params, aes, schema, group_by, dialect, &[]) + } + + fn run_with_domain( + params: ParameterValue, + aes: &Mappings, + schema: &Schema, + group_by: &[String], + dialect: &dyn SqlDialect, + domain: &[&'static str], + ) -> Result { + let mut p = HashMap::new(); + p.insert("aggregate".to_string(), params); + let ctx = cartesian_ctx(); + apply( + "SELECT * FROM t", + schema, + aes, + group_by, + &p, + dialect, + &ctx, + domain, + ) + } + + fn arr(items: &[&str]) -> ParameterValue { + ParameterValue::Array( + items + .iter() + .map(|s| ArrayElement::String(s.to_string())) + .collect(), + ) + } + + // ---------- parser tests ---------- + + #[test] + fn parses_unset_and_null() { + assert_eq!(parse_aggregate_param(&ParameterValue::Null).unwrap(), None); + assert_eq!(parse_aggregate_param(&arr(&[])).unwrap(), None); + } + + #[test] + fn parses_single_default() { + let s = parse_aggregate_param(&ParameterValue::String("mean".to_string())) + .unwrap() + .unwrap(); + assert_eq!(s.default_lower.as_ref().map(|a| a.offset), Some("mean")); + assert!(s.default_upper.is_none()); + assert!(s.targets.is_empty()); + } + + #[test] + fn parses_two_defaults_in_order() { + let s = parse_aggregate_param(&arr(&["min", "max"])) + .unwrap() + .unwrap(); + assert_eq!(s.default_lower.as_ref().map(|a| a.offset), Some("min")); + assert_eq!(s.default_upper.as_ref().map(|a| a.offset), Some("max")); + } + + #[test] + fn three_unprefixed_defaults_is_error() { + let err = parse_aggregate_param(&arr(&["mean", "min", "max"])).unwrap_err(); + assert!(err.contains("at most two"), "got: {}", err); + } + + fn target_funcs<'a>(spec: &'a AggregateSpec, aes: &str) -> Option<&'a [AggSpec]> { + spec.targets + .iter() + .find(|(a, _)| a == aes) + .map(|(_, fns)| fns.as_slice()) + } + + #[test] + fn parses_targeted_entries() { + let s = parse_aggregate_param(&arr(&["mean", "y:max", "color:median"])) + .unwrap() + .unwrap(); + assert_eq!(s.default_lower.as_ref().map(|a| a.offset), Some("mean")); + assert_eq!(target_funcs(&s, "y").map(|fs| fs[0].offset), Some("max")); + assert_eq!( + target_funcs(&s, "color").map(|fs| fs[0].offset), + Some("median") + ); + } + + #[test] + fn duplicate_target_explodes_into_a_list() { + let s = parse_aggregate_param(&arr(&["y:min", "y:max"])) + .unwrap() + .unwrap(); + let fns = target_funcs(&s, "y").unwrap(); + assert_eq!(fns.len(), 2); + assert_eq!(fns[0].offset, "min"); + assert_eq!(fns[1].offset, "max"); + assert_eq!(s.explosion_factor(), 2); + assert_eq!( + s.explosion_labels(), + Some(vec!["min".to_string(), "max".to_string()]) + ); + } + + #[test] + fn multi_aesthetic_explosion_joins_unique_function_names() { + // Two exploded targets contribute distinct function names per row → 'min/sum', 'max/prod'. + let s = parse_aggregate_param(&arr(&["y:min", "y:max", "color:sum", "color:prod"])) + .unwrap() + .unwrap(); + assert_eq!( + s.explosion_labels(), + Some(vec!["min/sum".to_string(), "max/prod".to_string()]) + ); + } + + #[test] + fn multi_aesthetic_explosion_dedups_repeats() { + // y and color both use 'mean' at row 0 → label is just 'mean' (deduped). + let s = parse_aggregate_param(&arr(&["y:mean", "y:max", "color:mean", "color:prod"])) + .unwrap() + .unwrap(); + assert_eq!( + s.explosion_labels(), + Some(vec!["mean".to_string(), "max/prod".to_string()]) + ); + } + + #[test] + fn recycled_target_excluded_from_label() { + // color has length 1 → recycled, not exploded; label only reflects y's functions. + let s = parse_aggregate_param(&arr(&["y:min", "y:max", "color:median"])) + .unwrap() + .unwrap(); + assert_eq!( + s.explosion_labels(), + Some(vec!["min".to_string(), "max".to_string()]) + ); + } + + #[test] + fn single_row_returns_no_labels() { + // The aggregate column only makes sense as a row-differentiator, and a + // single-row aggregation has nothing to differentiate, so no labels. + let s = parse_aggregate_param(&ParameterValue::String("mean".to_string())) + .unwrap() + .unwrap(); + assert_eq!(s.explosion_labels(), None); + + let s = parse_aggregate_param(&arr(&["mean", "color:median"])) + .unwrap() + .unwrap(); + assert_eq!(s.explosion_labels(), None); + } + + #[test] + fn recycling_violation_is_error() { + // y has 2, color has 3 → mismatched, neither is 1 nor matches the longest. + let err = parse_aggregate_param(&arr(&[ + "y:min", + "y:max", + "color:p10", + "color:p50", + "color:p90", + ])) + .unwrap_err(); + assert!(err.contains("longest target"), "got: {}", err); + } + + #[test] + fn length_one_target_recycles_in_explosion() { + let s = parse_aggregate_param(&arr(&["y:min", "y:max", "color:median"])) + .unwrap() + .unwrap(); + assert_eq!(s.explosion_factor(), 2); + assert_eq!(target_funcs(&s, "color").map(|f| f.len()), Some(1)); + } + + #[test] + fn empty_prefix_is_error() { + let err = parse_aggregate_param(&ParameterValue::String(":mean".to_string())).unwrap_err(); + assert!(err.contains("aesthetic prefix"), "got: {}", err); + } + + #[test] + fn unknown_function_is_error() { + let err = parse_aggregate_param(&ParameterValue::String("nope".to_string())).unwrap_err(); + assert!(err.contains("unknown aggregate"), "got: {}", err); + } + + #[test] + fn band_functions_parse() { + let s = parse_aggregate_param(&arr(&["mean-sdev", "mean+sdev"])) + .unwrap() + .unwrap(); + assert_eq!(s.default_lower.as_ref().unwrap().offset, "mean"); + assert_eq!( + s.default_lower + .as_ref() + .unwrap() + .band + .as_ref() + .unwrap() + .expansion, + "sdev" + ); + assert_eq!( + s.default_lower + .as_ref() + .unwrap() + .band + .as_ref() + .unwrap() + .sign, + '-' + ); + assert_eq!(s.default_upper.as_ref().unwrap().offset, "mean"); + } + + // ---------- apply tests ---------- + + #[test] + fn returns_identity_when_param_unset() { + let aes = Mappings::new(); + let schema: Schema = vec![]; + let p: HashMap = HashMap::new(); + let ctx = cartesian_ctx(); + let result = apply( + "SELECT * FROM t", + &schema, + &aes, + &[], + &p, + &InlineQuantileDialect, + &ctx, + &[], + ) + .unwrap(); + assert_eq!(result, StatResult::Identity); + } + + #[test] + fn returns_identity_when_param_null() { + let aes = Mappings::new(); + let schema: Schema = vec![]; + let result = run( + ParameterValue::Null, + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + assert_eq!(result, StatResult::Identity); + } + + #[test] + fn single_default_applies_to_every_numeric_mapping() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let result = run( + ParameterValue::String("mean".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + consumed_aesthetics, + .. + } => { + assert!(query.contains("AVG(\"__ggsql_aes_pos1__\")"), "{}", query); + assert!(query.contains("AVG(\"__ggsql_aes_pos2__\")"), "{}", query); + // No GROUP BY when no discrete mappings or PARTITION BY — SQL + // collapses to a single row per query, which is correct. + assert!(!query.contains("CROSS JOIN")); + assert!(!query.contains("UNION ALL")); + assert_eq!(stat_columns.len(), 2); + assert!(stat_columns.contains(&"pos1".to_string())); + assert!(stat_columns.contains(&"pos2".to_string())); + assert_eq!(consumed_aesthetics.len(), 2); + } + _ => panic!("expected Transformed"), + } + } + + #[cfg(feature = "sqlite")] + #[test] + fn sqlite_dialect_emits_portable_stddev_and_rejects_first() { + use crate::reader::sqlite::SqliteDialect; + + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + + // sdev must not emit STDDEV_POP (SQLite has no such function). + let result = run( + ParameterValue::String("sdev".to_string()), + &aes, + &schema, + &[], + &SqliteDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!( + !query.contains("STDDEV_POP"), + "SQLite dialect must not emit STDDEV_POP, got: {query}" + ); + assert!(query.contains("SQRT") && query.contains("AVG"), "{query}"); + } + _ => panic!("expected Transformed"), + } + + // first / last route through the validation error rather than emitting + // SQL that SQLite cannot run. + let err = run( + ParameterValue::String("first".to_string()), + &aes, + &schema, + &[], + &SqliteDialect, + ) + .unwrap_err(); + assert!( + format!("{err}").contains("not supported"), + "expected unsupported-function error, got: {err}" + ); + } + + #[test] + fn unsupported_aggregate_errors_with_dialect_that_lacks_function() { + // AnsiDialect's default doesn't implement FIRST/LAST. + struct AnsiTestDialect; + impl SqlDialect for AnsiTestDialect {} + + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let err = run( + ParameterValue::String("first".to_string()), + &aes, + &schema, + &[], + &AnsiTestDialect, + ) + .unwrap_err(); + let msg = format!("{}", err); + assert!( + msg.contains("first") && msg.contains("not supported"), + "expected unsupported-function error mentioning 'first', got: {msg}" + ); + } + + #[test] + fn mid_emits_min_max_midpoint() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let result = run( + ParameterValue::String("mid".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!( + query + .contains("(MIN(\"__ggsql_aes_pos1__\") + MAX(\"__ggsql_aes_pos1__\")) / 2.0"), + "{}", + query + ); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn first_and_last_emit_positional_aggregates() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2min", col("__ggsql_aes_pos2min__")); + aes.insert("pos2max", col("__ggsql_aes_pos2max__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2min__", false), + ("__ggsql_aes_pos2max__", false), + ]); + let result = run( + arr(&["first", "last"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!(query.contains("FIRST(\"__ggsql_aes_pos2min__\")"), "{}", query); + assert!(query.contains("LAST(\"__ggsql_aes_pos2max__\")"), "{}", query); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn two_defaults_split_lower_and_upper_for_segment() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert("pos1end", col("__ggsql_aes_pos1end__")); + aes.insert("pos2end", col("__ggsql_aes_pos2end__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2__", false), + ("__ggsql_aes_pos1end__", false), + ("__ggsql_aes_pos2end__", false), + ]); + let result = run( + arr(&["min", "max"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + // pos1, pos2 use MIN; pos1end, pos2end use MAX. + assert!(query.contains("MIN(\"__ggsql_aes_pos1__\")"), "{}", query); + assert!(query.contains("MIN(\"__ggsql_aes_pos2__\")"), "{}", query); + assert!( + query.contains("MAX(\"__ggsql_aes_pos1end__\")"), + "{}", + query + ); + assert!( + query.contains("MAX(\"__ggsql_aes_pos2end__\")"), + "{}", + query + ); + assert!(!query.contains("MIN(\"__ggsql_aes_pos1end__\")")); + assert!(!query.contains("MAX(\"__ggsql_aes_pos1__\")")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn two_defaults_split_for_ribbon() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2min", col("__ggsql_aes_pos2min__")); + aes.insert("pos2max", col("__ggsql_aes_pos2max__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2min__", false), + ("__ggsql_aes_pos2max__", false), + ]); + let result = run( + arr(&["mean-sdev", "mean+sdev"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!(query.contains("STDDEV_POP(\"__ggsql_aes_pos2max__\")")); + assert!(query.contains("AVG(\"__ggsql_aes_pos2min__\")")); + // upper default (mean+sdev) goes to pos2max → '+' between AVG and STDDEV + let pos2max_section = query.split("__ggsql_aes_pos2max__\")").next().unwrap_or(""); + assert!(pos2max_section.contains('+') || query.contains("+ STDDEV_POP")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn targeted_prefix_overrides_default() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let result = run( + arr(&["mean", "y:max"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!(query.contains("AVG(\"__ggsql_aes_pos1__\")"), "{}", query); + assert!(query.contains("MAX(\"__ggsql_aes_pos2__\")"), "{}", query); + assert!(!query.contains("AVG(\"__ggsql_aes_pos2__\")")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn material_aesthetic_targeted_by_user_facing_name() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert("size", col("__ggsql_aes_size__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2__", false), + ("__ggsql_aes_size__", false), + ]); + let result = run( + arr(&["mean", "size:median"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + .. + } => { + assert!(query.contains("QUANTILE_CONT(\"__ggsql_aes_size__\", 0.5)")); + assert!(stat_columns.contains(&"size".to_string())); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn color_alias_targets_stroke_and_fill() { + // `color` is an alias that resolves to whichever of `stroke`/`fill` + // is actually mapped on the layer. + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert("fill", col("__ggsql_aes_fill__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2__", false), + ("__ggsql_aes_fill__", false), + ]); + let result = run( + arr(&["mean", "color:max"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + .. + } => { + assert!(query.contains("MAX(\"__ggsql_aes_fill__\")"), "{}", query); + assert!(query.contains("AVG(\"__ggsql_aes_pos1__\")")); + assert!(stat_columns.contains(&"fill".to_string())); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn explosion_emits_union_all_with_aggregate_label_column() { + // ('y:min', 'y:max') on a line-style layer → 2 rows per group, each + // tagged with the function name in __ggsql_stat_aggregate__. + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let result = run( + arr(&["y:min", "y:max"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + consumed_aesthetics, + .. + } => { + assert!(query.contains("UNION ALL"), "{}", query); + assert!(query.contains("MIN(\"__ggsql_aes_pos2__\")"), "{}", query); + assert!(query.contains("MAX(\"__ggsql_aes_pos2__\")"), "{}", query); + assert!(query.contains("'min' AS \"__ggsql_stat_aggregate\"")); + assert!(query.contains("'max' AS \"__ggsql_stat_aggregate\"")); + // Aesthetics consumed: pos2. The synthetic `aggregate` is in + // stat_columns but NOT consumed (it's a new column). + assert!(consumed_aesthetics.contains(&"pos2".to_string())); + assert!(!consumed_aesthetics.contains(&"aggregate".to_string())); + assert!(stat_columns.contains(&"aggregate".to_string())); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn explosion_recycles_length_one_targets_and_defaults() { + // ('mean', 'y:min', 'y:max', 'color:median'): + // - default 'mean' applies to non-targeted aesthetics, recycled + // - y is exploded into [min, max] → N=2 + // - color is targeted with one function → recycled to [median, median] + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert("fill", col("__ggsql_aes_fill__")); + aes.insert("size", col("__ggsql_aes_size__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2__", false), + ("__ggsql_aes_fill__", false), + ("__ggsql_aes_size__", false), + ]); + let result = run( + arr(&["mean", "y:min", "y:max", "color:median"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + // y is exploded → MIN and MAX appear in different branches + assert!(query.contains("MIN(\"__ggsql_aes_pos2__\")"), "{}", query); + assert!(query.contains("MAX(\"__ggsql_aes_pos2__\")")); + // color (alias → fill) is recycled → QUANTILE_CONT(.5) appears in BOTH branches + let median_count = query + .matches("QUANTILE_CONT(\"__ggsql_aes_fill__\", 0.5)") + .count(); + assert_eq!( + median_count, 2, + "color median should appear once per branch: {}", + query + ); + // size has no target → uses default 'mean' → AVG appears in both branches + let avg_size = query.matches("AVG(\"__ggsql_aes_size__\")").count(); + assert_eq!( + avg_size, 2, + "size mean should appear once per branch: {}", + query + ); + // pos1 (no target) → mean → AVG appears in both branches + let avg_pos1 = query.matches("AVG(\"__ggsql_aes_pos1__\")").count(); + assert_eq!(avg_pos1, 2); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn domain_aesthetic_kept_as_group_key_even_when_continuous() { + // Regression test for the line/area/ribbon case: the user writes + // DRAW line ... SETTING aggregate => ('y:min', 'y:max') + // and expects pos1 (the continuous time-axis column) to be a group + // key, not a dropped numeric mapping. The geom declares pos1 as a + // domain aesthetic; the stat keeps it as a group column. + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), // continuous, would be dropped without the domain hint + ("__ggsql_aes_pos2__", false), + ]); + let result = run_with_domain( + arr(&["y:min", "y:max"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + &["pos1"], + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + consumed_aesthetics, + .. + } => { + // pos1 is in the GROUP BY, not aggregated. + assert!( + query.contains("GROUP BY \"__ggsql_aes_pos1__\""), + "{}", + query + ); + assert!(!query.contains("MIN(\"__ggsql_aes_pos1__\")")); + assert!(!query.contains("MAX(\"__ggsql_aes_pos1__\")")); + // pos2 is exploded into MIN and MAX branches. + assert!(query.contains("MIN(\"__ggsql_aes_pos2__\")")); + assert!(query.contains("MAX(\"__ggsql_aes_pos2__\")")); + // pos1 is NOT consumed (kept), pos2 IS consumed. + assert!(!consumed_aesthetics.contains(&"pos1".to_string())); + assert!(consumed_aesthetics.contains(&"pos2".to_string())); + // synthetic aggregate column emitted in the explosion case. + assert!(stat_columns.contains(&"aggregate".to_string())); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn explosion_with_range_geom_two_defaults() { + // For ribbon: pos1 + pos2min (lower) + pos2max (upper). + // ('mean-sdev', 'mean+sdev', 'color:p25', 'color:p75'): + // - two defaults split lower/upper for range aesthetics + // - color is exploded → N=2 + // Result: two rows, with color taking p25 in row 0 and p75 in row 1; + // pos1/pos2min always use mean-sdev, pos2max always uses mean+sdev. + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2min", col("__ggsql_aes_pos2min__")); + aes.insert("pos2max", col("__ggsql_aes_pos2max__")); + aes.insert("fill", col("__ggsql_aes_fill__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2min__", false), + ("__ggsql_aes_pos2max__", false), + ("__ggsql_aes_fill__", false), + ]); + let result = run( + arr(&["mean-sdev", "mean+sdev", "color:p25", "color:p75"]), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + .. + } => { + assert!(query.contains("UNION ALL")); + // pos2max always uses mean+sdev (upper default) — a `+` between AVG and STDDEV + let upper_branch_marker = "AVG(\"__ggsql_aes_pos2max__\") + STDDEV_POP"; + assert!(query.contains(upper_branch_marker), "{}", query); + // color uses p25 in one branch, p75 in another + assert!(query.contains("QUANTILE_CONT(\"__ggsql_aes_fill__\", 0.25)")); + assert!(query.contains("QUANTILE_CONT(\"__ggsql_aes_fill__\", 0.75)")); + // Synthetic aggregate column is present + assert!(stat_columns.contains(&"aggregate".to_string())); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn discrete_mapping_becomes_group_key() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert("color", col("__ggsql_aes_color__")); + let schema = schema_for(&[ + ("__ggsql_aes_pos1__", false), + ("__ggsql_aes_pos2__", false), + ("__ggsql_aes_color__", true), // discrete! + ]); + let result = run( + ParameterValue::String("mean".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + .. + } => { + assert!( + query.contains("GROUP BY \"__ggsql_aes_color__\""), + "{}", + query + ); + assert!(!stat_columns.contains(&"color".to_string())); + assert!(query.contains("AVG(\"__ggsql_aes_pos1__\")")); + assert!(query.contains("AVG(\"__ggsql_aes_pos2__\")")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn literal_mapping_passes_through() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + aes.insert( + "fill", + AestheticValue::Literal(ParameterValue::String("steelblue".to_string())), + ); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let result = run( + ParameterValue::String("mean".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!(!query.contains("AVG(\"__ggsql_aes_fill__\")")); + assert!(query.contains("AVG(\"__ggsql_aes_pos1__\")")); + assert!(query.contains("AVG(\"__ggsql_aes_pos2__\")")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn untargeted_numeric_mapping_dropped_when_no_default() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + // Only `y` targeted, no default → x is dropped. + let result = run( + ParameterValue::String("y:mean".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { + query, + stat_columns, + .. + } => { + assert!(query.contains("AVG(\"__ggsql_aes_pos2__\")")); + assert!(!query.contains("\"__ggsql_aes_pos1__\"")); + assert_eq!(stat_columns, vec!["pos2".to_string()]); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn quantile_uses_dialect_inline_when_available() { + let mut aes = Mappings::new(); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos2__", false)]); + let result = run( + ParameterValue::String("p25".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + assert!(query.contains("QUANTILE_CONT")); + assert!(query.contains("0.25")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn quantile_falls_back_to_correlated_subquery_without_inline() { + let mut aes = Mappings::new(); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos2__", false)]); + let result = run( + ParameterValue::String("p25".to_string()), + &aes, + &schema, + &[], + &NoInlineQuantileDialect, + ) + .unwrap(); + match result { + StatResult::Transformed { query, .. } => { + // The fallback dialect's sql_percentile uses NTILE. + assert!(query.contains("NTILE(4)")); + // No explosion any more — single SELECT, no UNION ALL. + assert!(!query.contains("UNION ALL")); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn unknown_targeted_aesthetic_is_error() { + let mut aes = Mappings::new(); + aes.insert("pos1", col("__ggsql_aes_pos1__")); + aes.insert("pos2", col("__ggsql_aes_pos2__")); + let schema = schema_for(&[("__ggsql_aes_pos1__", false), ("__ggsql_aes_pos2__", false)]); + let err = run( + ParameterValue::String("size:mean".to_string()), + &aes, + &schema, + &[], + &InlineQuantileDialect, + ) + .unwrap_err(); + let msg = format!("{}", err); + assert!(msg.contains("not mapped"), "got: {}", msg); + } +} diff --git a/src/plot/layer/geom/text.rs b/src/plot/layer/geom/text.rs index 6ceb45f9..5909c34d 100644 --- a/src/plot/layer/geom/text.rs +++ b/src/plot/layer/geom/text.rs @@ -63,6 +63,10 @@ impl GeomTrait for Text { PARAMS } + fn supports_aggregate(&self) -> bool { + true + } + fn post_process( &self, df: DataFrame, diff --git a/src/plot/layer/geom/tile.rs b/src/plot/layer/geom/tile.rs index 3633f944..fea51d38 100644 --- a/src/plot/layer/geom/tile.rs +++ b/src/plot/layer/geom/tile.rs @@ -104,6 +104,7 @@ impl GeomTrait for Tile { parameters: &HashMap, _execute_query: &dyn Fn(&str) -> Result, _dialect: &dyn crate::reader::SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> Result { stat_tile(query, schema, aesthetics, group_by, parameters) } diff --git a/src/plot/layer/geom/types.rs b/src/plot/layer/geom/types.rs index fb0ab5b8..5f57cc0c 100644 --- a/src/plot/layer/geom/types.rs +++ b/src/plot/layer/geom/types.rs @@ -175,6 +175,43 @@ pub use crate::plot::types::ColumnInfo; /// Schema of a data source - list of columns with type info pub use crate::plot::types::Schema; +/// Wrap a stat result with `ORDER BY `. +/// +/// Used by line/area/ribbon to ensure the rendered output is sorted along the +/// domain axis whether or not the layer also goes through the Aggregate stat. +/// +/// - `Identity` → becomes `Transformed` with ` ORDER BY `, +/// empty `stat_columns`/`dummy_columns`/`consumed_aesthetics`. +/// - `Transformed` → wraps the existing query in +/// `SELECT * FROM () AS "__ggsql_ord__" ORDER BY ` and preserves +/// the stat metadata. +pub fn wrap_with_order_by(input_query: &str, result: StatResult, aesthetic: &str) -> StatResult { + let order_col = naming::aesthetic_column(aesthetic); + let order_quoted = naming::quote_ident(&order_col); + match result { + StatResult::Identity => StatResult::Transformed { + query: format!("{} ORDER BY {}", input_query, order_quoted), + stat_columns: vec![], + dummy_columns: vec![], + consumed_aesthetics: vec![], + }, + StatResult::Transformed { + query, + stat_columns, + dummy_columns, + consumed_aesthetics, + } => StatResult::Transformed { + query: format!( + "SELECT * FROM ({}) AS \"__ggsql_ord__\" ORDER BY {}", + query, order_quoted + ), + stat_columns, + dummy_columns, + consumed_aesthetics, + }, + } +} + /// Helper to extract column name from aesthetic value pub fn get_column_name(aesthetics: &Mappings, aesthetic: &str) -> Option { use crate::AestheticValue; @@ -260,6 +297,56 @@ mod tests { assert!(!aes.is_required("yend")); } + #[test] + fn wrap_with_order_by_identity_appends_order() { + let result = wrap_with_order_by("SELECT * FROM t", StatResult::Identity, "pos1"); + match result { + StatResult::Transformed { + query, + stat_columns, + dummy_columns, + consumed_aesthetics, + } => { + assert_eq!(query, "SELECT * FROM t ORDER BY \"__ggsql_aes_pos1__\""); + assert!(stat_columns.is_empty()); + assert!(dummy_columns.is_empty()); + assert!(consumed_aesthetics.is_empty()); + } + _ => panic!("expected Transformed"), + } + } + + #[test] + fn wrap_with_order_by_transformed_wraps_query_and_preserves_metadata() { + let inner = StatResult::Transformed { + query: "SELECT * FROM grouped".to_string(), + stat_columns: vec!["pos2".to_string(), "aggregate".to_string()], + dummy_columns: vec!["pos1".to_string()], + consumed_aesthetics: vec!["pos2".to_string()], + }; + let result = wrap_with_order_by("SELECT * FROM raw", inner, "pos1"); + match result { + StatResult::Transformed { + query, + stat_columns, + dummy_columns, + consumed_aesthetics, + } => { + assert_eq!( + query, + "SELECT * FROM (SELECT * FROM grouped) AS \"__ggsql_ord__\" ORDER BY \"__ggsql_aes_pos1__\"" + ); + assert_eq!( + stat_columns, + vec!["pos2".to_string(), "aggregate".to_string()] + ); + assert_eq!(dummy_columns, vec!["pos1".to_string()]); + assert_eq!(consumed_aesthetics, vec!["pos2".to_string()]); + } + _ => panic!("expected Transformed"), + } + } + #[test] fn test_color_alias_requires_stroke_or_fill() { // Geom with neither stroke nor fill: color alias should NOT be supported diff --git a/src/plot/layer/geom/violin.rs b/src/plot/layer/geom/violin.rs index 7fef55eb..6ee8d95b 100644 --- a/src/plot/layer/geom/violin.rs +++ b/src/plot/layer/geom/violin.rs @@ -123,6 +123,7 @@ impl GeomTrait for Violin { parameters: &HashMap, _execute_query: &dyn Fn(&str) -> crate::Result, dialect: &dyn crate::reader::SqlDialect, + _aesthetic_ctx: &crate::plot::aesthetic::AestheticContext, ) -> Result { stat_violin(query, aesthetics, group_by, parameters, dialect) } diff --git a/src/plot/layer/mod.rs b/src/plot/layer/mod.rs index 33321a48..1cea17ac 100644 --- a/src/plot/layer/mod.rs +++ b/src/plot/layer/mod.rs @@ -199,7 +199,10 @@ impl Layer { format!("`{}`", name) }; - // Check if all required aesthetics exist. + // Check if all required aesthetics exist. The Aggregate stat replaces + // mapped values in place — it never synthesises new aesthetics — so + // every required aesthetic must be mapped by the user regardless of + // the `aggregate` setting. let mut missing = Vec::new(); let mut position_reqs: Vec<(&str, u8, &str)> = Vec::new(); @@ -419,6 +422,10 @@ impl Layer { { validate_parameter(param_name, value, ¶m.constraint)?; } + // Or the shared `aggregate` param for Identity-stat geoms + else if param_name == "aggregate" && self.geom.supports_aggregate() { + crate::plot::layer::geom::stat_aggregate::validate_aggregate_param(value)?; + } // Otherwise it's a valid aesthetic setting (no constraint validation needed) } diff --git a/src/reader/duckdb.rs b/src/reader/duckdb.rs index 8d6a18aa..8cac61bd 100644 --- a/src/reader/duckdb.rs +++ b/src/reader/duckdb.rs @@ -41,6 +41,22 @@ impl super::SqlDialect for DuckDbDialect { ) } + fn sql_quantile_inline(&self, column: &str, fraction: f64) -> Option { + Some(format!( + "QUANTILE_CONT({}, {})", + naming::quote_ident(column), + fraction + )) + } + + fn sql_aggregate(&self, name: &str, qcol: &str) -> Option { + match name { + "first" => Some(format!("FIRST({})", qcol)), + "last" => Some(format!("LAST({})", qcol)), + _ => super::default_sql_aggregate(name, qcol), + } + } + fn sql_percentile(&self, column: &str, fraction: f64, from: &str, groups: &[String]) -> String { let group_filter = groups .iter() diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 6646ada1..7e02448f 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -215,6 +215,31 @@ pub trait SqlDialect { ) } + /// Inline-form quantile aggregate, usable directly in a `SELECT` list. + /// + /// Returns `Some(sql_fragment)` when the dialect supports a native quantile + /// aggregate that can be combined with other aggregates in the same `GROUP BY` + /// query (e.g. DuckDB's `QUANTILE_CONT`). Returns `None` when no native + /// inline form exists; callers should then fall back to [`sql_percentile`], + /// which produces a correlated scalar subquery. + fn sql_quantile_inline(&self, _column: &str, _fraction: f64) -> Option { + None + } + + /// SQL fragment for a simple aggregate function applied to an + /// already-quoted column expression. + /// + /// Returns `Some(expr)` when the dialect can express this aggregate inline + /// in a `GROUP BY` query. Returns `None` when the aggregate is not + /// supported by this backend; the stat layer surfaces a clear error. + /// + /// Names handled here are the entries of `stat_aggregate::AGG_NAMES` other + /// than the percentile/iqr family, which goes through [`sql_quantile_inline`] + /// / [`sql_percentile`] instead. + fn sql_aggregate(&self, name: &str, qcol: &str) -> Option { + default_sql_aggregate(name, qcol) + } + /// SQL literal for a date value (days since Unix epoch). fn sql_date_literal(&self, days_since_epoch: i32) -> String { format!( @@ -291,6 +316,33 @@ pub(crate) fn wrap_with_column_aliases(body_sql: &str, column_aliases: &[String] ) } +/// Default aggregate SQL emission, shared so dialects can opt into the standard +/// portable forms while overriding selected functions. +/// +/// Returns `None` for names this default can't express portably (today: the +/// `first` / `last` row-positional aggregates — backends that have a native +/// equivalent override [`SqlDialect::sql_aggregate`]). +pub fn default_sql_aggregate(name: &str, qcol: &str) -> Option { + let s = match name { + "count" => format!("COUNT({})", qcol), + "sum" => format!("SUM({})", qcol), + "prod" => format!("EXP(SUM(LN({})))", qcol), + "min" => format!("MIN({})", qcol), + "max" => format!("MAX({})", qcol), + "range" => format!("(MAX({c}) - MIN({c}))", c = qcol), + "mid" => format!("((MIN({c}) + MAX({c})) / 2.0)", c = qcol), + "mean" => format!("AVG({})", qcol), + "geomean" => format!("EXP(AVG(LN({})))", qcol), + "harmean" => format!("(COUNT({c}) * 1.0 / SUM(1.0 / {c}))", c = qcol), + "rms" => format!("SQRT(AVG({c} * {c}))", c = qcol), + "sdev" => format!("STDDEV_POP({})", qcol), + "se" => format!("(STDDEV_POP({c}) / SQRT(COUNT({c})))", c = qcol), + "var" => format!("VAR_POP({})", qcol), + _ => return None, + }; + Some(s) +} + pub struct AnsiDialect; impl SqlDialect for AnsiDialect {} diff --git a/src/reader/sqlite.rs b/src/reader/sqlite.rs index 67f1033b..15645f70 100644 --- a/src/reader/sqlite.rs +++ b/src/reader/sqlite.rs @@ -93,6 +93,23 @@ impl super::SqlDialect for SqliteDialect { ) } + /// Stock SQLite has no `STDDEV_POP` / `VAR_POP`, so express variance, + /// standard deviation, and standard error in portable arithmetic. Every + /// other aggregate falls through to the shared default. + fn sql_aggregate(&self, name: &str, qcol: &str) -> Option { + // Population variance with a `MAX(0, …)` floor against tiny negative + // floats from catastrophic cancellation. Both `MAX(a, b)` and `SQRT` + // are scalar functions in modern bundled SQLite (math-functions build). + let var_pop = || format!("MAX(0.0, AVG({c} * {c}) - AVG({c}) * AVG({c}))", c = qcol); + let s = match name { + "var" => var_pop(), + "sdev" => format!("SQRT({})", var_pop()), + "se" => format!("(SQRT({}) / SQRT(COUNT({c})))", var_pop(), c = qcol), + _ => return super::default_sql_aggregate(name, qcol), + }; + Some(s) + } + /// SQLite does not support `CREATE OR REPLACE`, so emit a drop-then-create /// pair. Column aliases are preserved portably via the default CTE wrapper. fn create_or_replace_temp_table_sql(