diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3ad6284a..c3985105c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@
- `SPAN` groups columns under a shared header cell (spanner).
- `FORMAT` configures how a column's cells are displayed.
- `FACET` sets row groups.
+ - `SUMMARISE` computes aggregates over rows.
- `Writer::write_table` renders a resolved table, taking the new public
`TableLayout` — the table's cells bundled with their column and row
metadata.
diff --git a/doc/_quarto.yml b/doc/_quarto.yml
index a3296ce46..9066d88d3 100644
--- a/doc/_quarto.yml
+++ b/doc/_quarto.yml
@@ -64,6 +64,8 @@ website:
href: syntax/clause/format.qmd
- text: "`FACET`"
href: syntax/clause/facet-tabulate.qmd
+ - text: "`SUMMARISE`"
+ href: syntax/clause/summarise.qmd
- text: Gallery
href: gallery/index.qmd
- href: faq.qmd
@@ -131,6 +133,8 @@ website:
href: syntax/clause/format.qmd
- text: "`FACET`"
href: syntax/clause/facet-tabulate.qmd
+ - text: "`SUMMARISE`"
+ href: syntax/clause/summarise.qmd
- section: Layers
contents:
- section: Types
diff --git a/doc/ggsql.xml b/doc/ggsql.xml
index 90de554f3..abc14b0a7 100644
--- a/doc/ggsql.xml
+++ b/doc/ggsql.xml
@@ -391,6 +391,8 @@
+
+
@@ -439,6 +441,8 @@
+
+
@@ -480,6 +484,8 @@
+
+
@@ -520,6 +526,8 @@
+
+
@@ -568,6 +576,8 @@
+
+
@@ -612,6 +622,8 @@
+
+
@@ -655,6 +667,8 @@
+
+
@@ -690,6 +704,8 @@
+
+
@@ -728,6 +744,8 @@
+
+
@@ -769,6 +787,8 @@
+
+
@@ -805,6 +825,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -821,6 +882,8 @@
+
+
diff --git a/doc/syntax/clause/summarise.qmd b/doc/syntax/clause/summarise.qmd
new file mode 100644
index 000000000..d1172069a
--- /dev/null
+++ b/doc/syntax/clause/summarise.qmd
@@ -0,0 +1,252 @@
+---
+title: "Summarise values into new rows"
+---
+
+Values can be summarised and displayed in dedicated rows.
+This is helpful to display observations alongside statistics in the table.
+`SUMMARISE` can be repeated to compute multiple summaries.
+
+## Clause syntax
+
+```ggsql
+SUMMARISE [GROUP | GRAND] OF , ...
+ SETTING => , ...
+```
+
+Also accepts the spelling `SUMMARIZE`.
+
+## Scope
+
+```ggsql
+[GROUP | GRAND]
+```
+
+The scope directly following the `SUMMARISE` clause determines which rows the operation aggregates over.
+Setting the scope to `GROUP` will compute the summary for each group determined by `FACET` clauses separately.
+The `GRAND` scope will compute the summary for all rows.
+Without spelling out a scope, the default will be `GROUP`.
+When no groups are declared by `FACET` and the scope is set to `GROUP`, all rows are treated as belonging to the same group.
+The difference between a `FACET`-less `GROUP` scope and a `GRAND` scope is largely a difference in style and label spanning.
+A query result with no rows cannot be summarised: `SUMMARISE` errors on an empty table.
+
+## Operation
+
+```ggsql
+
+```
+
+This part of the clause can be an identifier or a string representing an expression.
+The identifiers are the same ones used in stat [aggregation](draw.qmd#aggregate-functions) in plots.
+When using an identifier, one of the following operations are available:
+
+| Name | Description | Numeric | Date(time) | Other |
+|------|-------------|:-------:|:----------:|:-----:|
+| `count` | Number of rows | ✓ | ✓ | ✓ |
+| `n_distinct` | Number of distinct values | ✓ | ✓ | ✓ |
+| `n_missing` | Number of nulls | ✓ | ✓ | ✓ |
+| `sum` | Sum | ✓ | | |
+| `prod` | Product | ✓ | | |
+| `min` | Minimum | ✓ | ✓ | |
+| `max` | Maximum | ✓ | ✓ | |
+| `range` | max − min | ✓ | ✓ | |
+| `mid` | (min + max) / 2 | ✓ | ✓ | |
+| `mean` | Arithmetic mean | ✓ | ✓ | |
+| `geomean` | Geometric mean | ✓ | | |
+| `harmean` | Harmonic mean | ✓ | | |
+| `rms` | Root-mean-square | ✓ | | |
+| `median` | Median | ✓ | ✓ | |
+| `sdev` | Standard deviation (population, ÷ n) | ✓ | ✓ | |
+| `se` | Standard error (population, ÷ n) | ✓ | ✓ | |
+| `var` | Variance (population, ÷ n) | ✓ | | |
+| `iqr` | Interquartile range | ✓ | ✓ | |
+| `p05` | 5th percentile | ✓ | ✓ | |
+| `p10` | 10th percentile | ✓ | ✓ | |
+| `p25` | 25th percentile | ✓ | ✓ | |
+| `p50` | 50th percentile (median) | ✓ | ✓ | |
+| `p75` | 75th percentile | ✓ | ✓ | |
+| `p90` | 90th percentile | ✓ | ✓ | |
+| `p95` | 95th percentile | ✓ | ✓ | |
+
+When using a string as an expression, you can use any of the identifiers in curly braces.
+For example `'{mean}'` will display the mean via expression.
+The expressions can be used to display multiple metrics in a single cell, e.g. `'{median} ({p25}, {p75})'` will display the median and interquartile range in one cell.
+Inside the brackets, you can use limited arithmetic.
+The operands include the operation identifiers listed above (like `mean`, `sdev`), numeric literals (`2`, `0.5`) and scientific notation (`1e6`).
+The `+`, `-` unary operators and `+`, `-`, `*` and `/` binary operators and `(`/`)` parentheses for grouping.
+For example you can use `'({mean - 1.96 * se}, {mean + 1.96 * se})'` to display a 95% confidence interval (assuming normal distribution) in parentheses separated by a comma.
+If any placeholder in a string expression comes out `null` (see `missing` below), the whole cell comes out `null`.
+
+For the naked, non-string identifiers the formatting of the cell values is applied externally via `FORMAT` clauses.
+The string expressions can be self-formatting via the same syntax as [scale breaks](scale.qmd#break-formatting).
+A string-expression cell ignores a `FORMAT` wildcard label, but direct labels still apply — including `null => …` to replace a null result.
+All summary metrics are assumed to be numeric.
+As such, the `:num` formatter is implied and does not need to be written out in full.
+The expression `'{mean:%.2f}'` will display the mean with two decimal points in printf-style.
+Other formatters can be used, e.g. `{max:bytes}` to display base-1024 size.
+When using arithmetic, the formatting is placed at the end and is applied to the result so that `'{mean + sdev:%.2f}'` rounds the expression to two decimals.
+
+Date and timestamp columns accept the order statistics (`min`, `max`, `mid`, `mean`, `median` and the percentiles), returning a date or timestamp, and `range`, `sdev`, `se` and `iqr`, returning a duration.
+A date or timestamp renders as ISO text or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic it becomes a plain number: days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration.
+A date-valued `mean` or `mid` rounds to the nearest whole day.
+
+## Column selection
+
+```ggsql
+OF , ...
+```
+
+The `SUMMARISE` clause requires a comma-separated list of columns to aggregate.
+The columns must be part of the `TABULATE` selection.
+The 'counting' operations listed above can be applied to columns of any type, the order and dispersion statistics also accept date and timestamp columns, and the remaining operations require numeric columns.
+
+## Settings
+
+```ggsql
+SETTING =>
+```
+
+The `SETTING` sub-clause is typical with key-value pairs.
+It currently takes the following parameters:
+
+* `place`: the location of the summary rows relative to the body rows they summarise.
+Can be `'top'` to place the summary rows at the top of each group or table, or `'bottom'` (default) to place the summary rows after the body rows.
+* `rowlabel`: A string for the label of the summary row. The default `null` falls back to printing the operation, where string expression operations are displayed without formatting details.
+* `missing`: A string option for how to treat `null` values in the table.
+The default `'propagate'` will list any non-counting operation as `null`, while the tallies `count` and `n_missing` include null-rows — note that `n_distinct` is not a tally and comes out `null` when the column contains any.
+Can be set to `'drop'` to explicitly ignore `null` values in aggregates and ignore these rows in counting operations.
+* `blank`: A string displayed in cells of the summary row whose column are not summarised.
+The default is an em dash (`'—'`); set it to `''` for empty cells.
+
+## Examples
+
+A summary without groups will summarise all rows.
+
+```{ggsql}
+CREATE TEMP TABLE my_data AS
+SELECT DISTINCT ON (species, island, sex) * FROM ggsql:penguins
+WHERE bill_len IS NOT NULL AND sex IS NOT NULL
+
+TABULATE * FROM my_data
+SUMMARISE mean OF bill_len, bill_dep
+```
+
+A grand summary will always summarise all rows, and is displayed with a stronger border.
+
+```{ggsql}
+TABULATE * FROM my_data
+SUMMARISE GRAND mean OF bill_len, bill_dep
+```
+
+Groups can be specified using `FACET`.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET island
+SUMMARISE mean OF bill_len, bill_dep
+```
+
+The labels of summary rows compose with regular body row labels in the stub.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET island
+FORMAT STUB species
+SUMMARISE mean OF bill_len, bill_dep
+```
+
+The display of the label in the stub can be changed using the `rowlabel` setting.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET species
+SUMMARISE mean OF bill_len, bill_dep
+ SETTING rowlabel => 'Average'
+```
+
+The display of non-summary cells can be changed using the `blank` setting.
+Using an empty string (`''`) leaves these cells empty.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET species
+SUMMARISE mean OF bill_len, bill_dep
+ SETTING blank => ''
+```
+
+The summary cells are subject to `FORMAT` when using plain identifiers, along with the body rows.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET species
+FORMAT bill_len, bill_dep LABEL * => '{:num %.2f}'
+SUMMARISE mean OF bill_len, bill_dep
+```
+
+To specifically format the summary values, you can use the expression string form.
+
+```{ggsql}
+TABULATE * FROM my_data
+FACET species
+SUMMARISE '📏 {mean:%.2f}' OF bill_len, bill_dep
+```
+
+You can use repeated summaries.
+The order in which the summaries are declared determine the order of the rows.
+
+```{ggsql}
+TABULATE * FROM my_data
+SUMMARISE p25 OF bill_len, bill_dep
+SUMMARISE p50 OF bill_len, bill_dep
+SUMMARISE p75 OF bill_len, bill_dep
+```
+
+Or display related summaries in a single cell.
+
+```{ggsql}
+TABULATE * FROM my_data
+SUMMARISE '{p50:%.2f} ({p25:%.2f}, {p75:%.2f})' OF bill_len, bill_dep
+```
+
+When data contains 'null' values, they propagate to aggregate metrics (but not necessarily count metrics).
+Notice how the summary of `bill_len` comes out as 'null'.
+
+```{ggsql}
+SELECT species, island, sex,
+ CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len,
+ bill_dep, flipper_len, body_mass
+FROM my_data
+
+TABULATE *
+SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep
+```
+
+You can ignore 'null' values by using the `missing => 'drop'` setting.
+
+```{ggsql}
+SELECT species, island, sex,
+ CASE WHEN island = 'Biscoe' THEN NULL ELSE bill_len END AS bill_len,
+ bill_dep, flipper_len, body_mass
+FROM my_data
+
+TABULATE *
+SUMMARISE '{mean:%.2f}' OF bill_len, bill_dep
+ SETTING missing => 'drop'
+```
+
+Date and timestamp columns can be summarised with the order statistics, formatted with `:time`, and `range` gives their span as a duration.
+
+```{ggsql}
+CREATE TEMP TABLE launches AS
+SELECT * FROM (VALUES
+ ('Alpha', DATE '2024-01-15'),
+ ('Alpha', DATE '2024-02-10'),
+ ('Beta', DATE '2024-03-01'),
+ ('Beta', DATE '2024-03-20')) AS t(product, launched)
+
+TABULATE * FROM launches
+FACET product
+SUMMARISE '{min:time %d %b %Y} – {max}' OF launched
+ SETTING rowlabel => 'Dates'
+SUMMARISE '{range:duration d}' OF launched
+ SETTING rowlabel => 'Duration'
+```
\ No newline at end of file
diff --git a/doc/syntax/index.qmd b/doc/syntax/index.qmd
index 7f78d5c7a..31ea43d3e 100644
--- a/doc/syntax/index.qmd
+++ b/doc/syntax/index.qmd
@@ -20,6 +20,7 @@ ggsql augments the standard SQL syntax with a number of new clauses to describe
- [`SPAN`](clause/span.qmd) can be used to group columns and display a label across them
- [`FORMAT`](clause/format.qmd) declares formatting for columns
- [`FACET`](clause/facet-tabulate.qmd) enables row-grouping operations on tables
+- [`SUMMARISE`](clause/summarise.qmd) adds rows with summarised values to the table
## Layers
There are many different layers to choose from when visualising your data. Some are straightforward translations of your data into visual marks such as a point layer, while others perform more or less complicated calculations like e.g. the histogram layer. A layer is selected by providing the layer name after the `DRAW` clause
diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md
index c62e9fdc2..35ee3d04b 100644
--- a/doc/vendor/SKILL.md
+++ b/doc/vendor/SKILL.md
@@ -184,6 +184,7 @@ Configures cell display and column placement.
- A SPAN id may stand in for its columns: `FORMAT Q1, price SETTING hjust => 'right'`
- Settings: `hjust` (`'left'`/`'right'`/`'centre'`/`'center'` or 0–1; default right for numeric/stub, left otherwise), `width` (`'100px'` or `'20%'`)
- `LABEL` works like SCALE's: direct replacement (`'adelie' => 'Pygoscelis adeliae'`), `null` on the right suppresses the cell, unquoted `null` on the left matches missing values, and `* => '...'` formats every value with a template (`{:lower}`, `{:num %.0f}`, etc.)
+- Without a LABEL, float columns display at a shared per-column precision: the most decimals any value needs (each value the fewest that faithfully represents it), so whole values pad (`50.0` beside `39.1`) and SUMMARISE results round to the same precision. Integer columns display bare.
```ggsql
SELECT * FROM ggsql:penguins LIMIT 5
@@ -194,6 +195,27 @@ TABULATE *
FORMAT body_mass SETTING hjust => 'right' LABEL null => '-', * => '{:num %.0f}g'
```
+### SUMMARISE
+
+Adds summary rows computed over the table's rows: one per `FACET` group (`GROUP`, default) or a single row over all rows (`GRAND`, rendered with a stronger border; its label spans group stub columns). Repeatable — clause order is row order within a boundary. Also spelled `SUMMARIZE`. Columns must be part of the TABULATE selection. Errors on an empty query result.
+
+```
+SUMMARISE [GROUP | GRAND] OF , ...
+ SETTING => , ...
+```
+
+- **Operation** — an identifier: tallies `count n_distinct n_missing` (any column type); sums `sum prod`; extremes `min max range mid`; centrality `mean geomean harmean rms median`; dispersion `sdev se var iqr` (population statistics, ÷ n); percentiles `p05 p10 p25 p50 p75 p90 p95`. All but the tallies require numeric columns, except that date/timestamp columns also accept the order statistics (`min max mid mean median p*`, returning a date/timestamp) and `range sdev se iqr` (returning a duration).
+- **Template** — or a string with `{expr}` placeholders interpolated into the cell: `'{median} ({p25}, {p75})'`. Expressions allow `+ - * /`, parentheses, unary `+`/`-`, numeric literals incl. scientific notation (`'{mean - 1.96 * se}'`). Per-placeholder formatting follows the placeholder after `:`; `num` is implied (`'{mean:%.2f}'` = `'{mean:num %.2f}'`; also `:bytes`, `:duration`, `:time`). A bare date/timestamp leaf renders ISO or via `:time` (`'{min:time %d %b %Y}'`); in arithmetic a date/timestamp operand becomes a plain number — days for dates, seconds for timestamps — so `'{max-min:duration d}'` renders a date range as a duration. A template self-formats: the column's `FORMAT` wildcard renaming does not apply, but direct renamings do (including `null => …` — a null placeholder nulls the whole cell); a bare operation takes the full renaming.
+- **Settings** — `place` (`'bottom'` default / `'top'` — summary rows before or after the group/table body), `rowlabel` (stub label; default the operation, templates without their format specs), `missing` (`'propagate'` default — any null makes a non-tally summary null; `'drop'` — ignore nulls. `count` counts rows under propagate, non-null values under drop), `blank` (display text for cells in columns the clause does not summarise; default `'—'` — a summarised column that computes to null still reports `null`).
+
+```ggsql
+TABULATE * FROM ggsql:penguins
+FACET island
+FORMAT STUB species
+SUMMARISE mean OF bill_len, bill_dep
+SUMMARISE GRAND '{mean:%.1f} ± {se:%.1f}' OF bill_len SETTING rowlabel => 'Mean ± SE'
+```
+
---
## Layer types
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 79ce15702..6b2072bb8 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -63,6 +63,18 @@ Grammar lives in [`/tree-sitter-ggsql/`](../tree-sitter-ggsql/) — when adding
**Caching layer.** `CachingReader` (`cache.rs`) wraps a primary reader plus an in-memory `CacheBackend`, splitting work across two `Reader` surfaces. **`execute_sql` = source**: base reads of the user's data plus user setup/DML run on the primary (with result memoization), except `ggsql:` builtins, the `__ggsql_cache_meta__` table, and reads that reference a cache-resident internal table, which go to the cache. **`execute_sql_cached` = compute**: all dialect-generated/derived SQL (schema probes, stats, projection/map transforms, spatial setup, final layer queries — everything operating on `__ggsql_*` tables) runs on the cache; it defaults to `execute_sql` so a plain reader runs everything on one connection. Cache routing is by **exact-identifier membership** in the set of tables registered into the cache. Memoization keys on `hash(primary_uri + sql)` and is tracked in the `__ggsql_cache_meta__` table inside the cache backend. Each memoized read is bounded by a **TTL** (default 300s) and the whole memo by an **LRU byte budget** (default 512 MB); both are configurable via `CacheConfig` (env `GGSQL_CACHE_DISABLED`/`GGSQL_CACHE_TTL`/`GGSQL_CACHE_MAX_BYTES`, or per-connection URI query parameters `?cache_ttl=…&cache_max_bytes=…&cache_disabled=…`). The `__ggsql_cache_meta__` table is queryable for introspection (`SELECT * FROM __ggsql_cache_meta__`). Pure/non-visual SQL (CLI table fallback, Jupyter) goes through `execute_sql` so it reads the primary rather than the empty cache. `Reader::materialize_table` (default = `CREATE TEMP TABLE` on the reader, no Rust roundtrip) is overridden to read the body via the source surface and `register()` the result into the cache, so the primary is never written to; `Reader::caches_sources()` (default `false`, `true` for `CachingReader`) gates the executor's per-layer source staging: file sources are staged on the cache surface, while identifiers go through `materialize_table`, which routes the read to the cache (CTEs, builtins, cache-resident tables) or the primary as needed. `dialect()` returns the **cache** dialect, and every compute-surface failure is prefixed with the cache backend's scheme (``on the `duckdb` cache backend: …``) so a cache-dialect driver error is not mistaken for one from the user's own connection. Selected via the composite `+://` scheme (`reader_from_uri` / `split_cache_uri`) or the CLI `--cache` flag; off by default. The memo's bookkeeping — registering a table, its row in `__ggsql_cache_meta__`, LRU eviction under the byte budget — is `CacheTables`, which other callers use on a backend of their own (the Jupyter kernel's results API does, without wrapping the user's reader). An entry can be **pinned**, exempting it from eviction until unpinned (pins are kept in memory, not in the metadata table); `CachingReader` never pins, and the TTL and enabled checks stay in `CachingReader`. `CacheTables` takes a byte budget rather than a `CacheConfig`; `put` and `put_pinned` add entries, `contains` checks for one, and `evict_to`/`total_bytes`/`pinned_bytes` let a caller with a wider budget evict to that instead, `evict_to` returning the keys it evicted. Only an existing entry can be pinned.
+### Validation vs execution
+
+`validate()` ([validate.rs](validate.rs)) runs every check possible with knowledge of the struct alone — no reader, no `DataFrame`, no `Labels`. Anything needing the query result's schema or sibling-clause context is execution's job, in `setup_*` functions under `execute/`.
+
+The shared machinery lives in `params.rs`: `validate_parameters` (check only; absence is always valid), `with_defaults` (fill defaults; assumes validated input), and `resolve_parameters` = the two composed. Each AST struct exposes what its consumers call:
+
+- `validate_settings()` — called from the struct's `validate()`, which `Table::validate()` aggregates with clause-index prefixes ("SPAN 1: …").
+- `resolve_settings()` — validate + fill in one step, for execute-side consumers that handle one clause at a time.
+- `with_default_settings()` — fill only, for consumers that validate and fill at different moments (e.g. `setup_formats` validates per clause before merging, fills after).
+
+Don't add a `resolve_settings` that has no caller; don't give a `setup_*` function struct-local work that `validate()` could run.
+
### `execute/`
The pipeline that takes a parsed `Plot` (or `Table`) plus a `Reader` and produces a `ResolvedPlot` (or `ResolvedTable`) — typed data per layer, scales resolved, casts applied; for tables, cells laid out with spans, stub and formats. Submodules:
diff --git a/src/execute/table/facet.rs b/src/execute/table/facet.rs
index 90f55f5ec..0bb9c2791 100644
--- a/src/execute/table/facet.rs
+++ b/src/execute/table/facet.rs
@@ -9,7 +9,7 @@ use crate::array_util::value_to_string;
use crate::dataframe::into_array_ref;
use crate::plot::facet::{distinct_levels, level_keys, order_levels, Facet, FacetLayout, LevelKey};
use crate::plot::ParameterValue;
-use crate::table::{TableColumn, TableRow};
+use crate::table::TableColumn;
use crate::{ColumnSection, DataFrame};
/// Assign each `df` row its group key: one rank per facet variable (see
@@ -56,36 +56,37 @@ fn facet_columns<'a>(facet: &Facet, df: &'a DataFrame) -> Result bool {
+ matches!(
+ facet.properties.get("separator"),
+ Some(ParameterValue::String(_))
+ ) && facet.get_variables().len() > 1
+}
+
/// Collapse a separated facet into one variable: join the facet variables'
/// (formatted) values per row into a column named for the first variable,
-/// drop the originals, renumber the rows' group keys to single ids, and
-/// reduce the facet to that variable. Group stub columns in `columns` are
-/// replaced by one, keeping the first's label and properties. Passes
-/// everything through unchanged when the facet sets no `separator` or has a
-/// single variable.
-/// The table pieces `collapse_group_columns` rewrites for a separated facet.
-type Collapsed = (DataFrame, Vec, Vec, Option);
-
+/// drop the originals, and reduce the facet to that variable. Group stub
+/// columns in `columns` are replaced by one, keeping the first's label and
+/// properties. The rows' group keys are already single ids — `setup_rows`
+/// renumbers them at birth. Passes everything through unchanged unless
+/// [`collapses`] applies.
pub(super) fn collapse_group_columns(
df: DataFrame,
mut columns: Vec,
- mut rows: Vec,
facet: Option<&Facet>,
-) -> Result {
- let Some(facet) = facet else {
- return Ok((df, columns, rows, None));
+) -> Result<(DataFrame, Vec, Option), String> {
+ let Some(facet) = facet.filter(|f| collapses(f)) else {
+ return Ok((df, columns, facet.cloned()));
};
let separator = match facet.properties.get("separator") {
Some(ParameterValue::String(separator)) => separator.clone(),
- _ => return Ok((df, columns, rows, Some(facet.clone()))),
+ _ => unreachable!("collapses gates on a separator"),
};
- // One variable has nothing to join.
- let variables = facet.get_variables();
- if variables.len() == 1 {
- return Ok((df, columns, rows, Some(facet.clone())));
- }
// The joined column takes the first variable's name.
+ let variables = facet.get_variables();
let name = variables[0].clone();
let arrays: Vec<&ArrayRef> = variables
@@ -106,17 +107,6 @@ pub(super) fn collapse_group_columns(
.and_then(|df| df.with_column(&name, into_array_ref(joined)))
.map_err(|e| e.to_string())?;
- // Single-id keys: rows are group-sorted, so the id is the chunk index.
- let mut id = 0;
- let mut previous: Option> = None;
- for row in &mut rows {
- if previous.as_ref().is_some_and(|key| *key != row.group) {
- id += 1;
- }
- previous = Some(std::mem::take(&mut row.group));
- row.group = vec![id];
- }
-
// Replace the group stub columns with one, at the first's position.
if let Some(position) = columns.iter().position(|c| c.is_group_stub()) {
let mut joined_column = columns[position].clone();
@@ -135,7 +125,7 @@ pub(super) fn collapse_group_columns(
resolved: facet.resolved,
};
- Ok((df, columns, rows, Some(facet)))
+ Ok((df, columns, Some(facet)))
}
/// Rank one facet variable's rows: non-null levels in the scale-free facet
diff --git a/src/execute/table/format.rs b/src/execute/table/format.rs
index e112f95cb..a31670ec9 100644
--- a/src/execute/table/format.rs
+++ b/src/execute/table/format.rs
@@ -1,11 +1,13 @@
//! `TABULATE FORMAT` resolution: `setup_formats` validates `SETTING`
//! parameters and reshapes the per-clause formats into one `Format` per
-//! column, `apply_formats` replaces a column's values with their display
-//! text (`LABEL`), and `resolve_column_properties` resolves a column's
-//! `SETTING` display properties.
+//! column, `apply_formatting` replaces a column's values with their display
+//! text (`LABEL`, or the float display precision from `display_decimals`),
+//! and `resolve_column_properties` resolves a column's `SETTING` display
+//! properties.
use std::collections::HashMap;
+use arrow::array::Array;
use arrow::datatypes::DataType;
use crate::array_util::{new_str_array, value_to_string};
@@ -15,7 +17,7 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner};
/// Validate every FORMAT's `SETTING` parameters, then reshape `formats`
/// into one `Format` per column it covers. `spans` must already be resolved
-/// (`Table::resolve_spanners`) — a name matching a SPAN id expands to that
+/// (`Table::setup_spanners`) — a name matching a SPAN id expands to that
/// span's columns.
pub(super) fn setup_formats(
df: &DataFrame,
@@ -24,7 +26,7 @@ pub(super) fn setup_formats(
) -> Result> {
for (idx, format) in formats.iter().enumerate() {
format
- .resolve_settings()
+ .validate_settings()
.map_err(|e| GgsqlError::ValidationError(format!("FORMAT {}: {}", idx + 1, e)))?;
}
@@ -47,12 +49,10 @@ pub(super) fn setup_formats(
}
// A column no clause claimed a section for resolves to the body.
- // Settings were validated per clause above; resolving again post-merge
- // only fills defaults.
+ // Settings were validated per clause above, so post-merge only fills
+ // defaults.
for format in resolved.values_mut() {
- format.settings = format
- .resolve_settings()
- .map_err(GgsqlError::ValidationError)?;
+ format.settings = format.with_default_settings();
format.target.get_or_insert(ColumnSection::Body);
}
Ok(resolved)
@@ -89,38 +89,69 @@ fn expand_format_columns(
Ok(columns)
}
-/// Replace every column in `df` named in `formats` with its resolved
-/// display text. A column whose `Format` has no `LABEL` at all
-/// (`label_spec` empty) is left untouched.
-pub(super) fn apply_formats(
+/// Replace display-affecting columns in `df` with their display text. A
+/// column named in `formats` with a `LABEL` (mapping or template) gets
+/// its resolved labels; a float column gets padded to its display decimals
+/// (see `display_decimals`). Everything else is left untouched.
+pub(super) fn apply_formatting(
df: &DataFrame,
formats: &HashMap,
) -> Result {
let mut df = df.clone();
- for (name, format) in formats {
- // Skip the per-row formatting pass for a column nobody asked to
- // reformat — the common `FORMAT ... SETTING ...` case.
- let has_labels =
- !format.label_spec.rename_is_empty() || format.label_spec.template().is_some();
- if !has_labels {
- continue;
- }
-
+ for name in df.get_column_names() {
+ let format = formats.get(&name);
+ // A column whose format carries no labels — the common
+ // `FORMAT ... SETTING ...` case — skips the labelling pass.
+ let has_labels = format
+ .is_some_and(|f| !f.label_spec.rename_is_empty() || f.label_spec.template().is_some());
let array = df
- .column(name)
- .expect("setup_formats already checked this column exists")
+ .column(&name)
+ .expect("the names come from this frame")
.clone();
- let resolved = crate::format::resolve_column_values(&array, &format.label_spec)
- .map_err(|e| GgsqlError::ValidationError(format!("FORMAT column '{name}': {e}")))?;
- let display: Vec