@sprigr/apps-reporting-core 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -3
  2. package/dist/index.js +146 -71
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -79,8 +79,8 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
79
79
  - **Stream** puts measures from more than one stream side by side over the whole period, such as invoiced beside ordered. It reads the view's own stream and every other stream its measures belong to. Each stream is grouped on its own under the same drill path, filters and keyword, then the results are folded to one row per member, so a formula can read sums from two streams. A member is listed when any of those streams has rows for it. Every stream read must carry each dimension the view uses. `streams` in the result lists them.
80
80
  - **A total view with a measure of another stream** compiles exactly as stream mode does, so a view saved as a total of stock beside sales needs no change of mode.
81
81
  - **A period, variance or period variance view with a measure of another stream** is compiled the same way: each stream is grouped on its own, over its own date column, then the results are folded to one row per member. A period view gets one column per period for every measure, a variance its current, earlier, variance and variance percentage columns, and a period variance those four for every period beside the same period of the comparison window, all named as in a view of one stream. A formula is worked out for each period from the folded sums, with that period's own days. A snapshot measure reads the latest day of each period, or of each window, in its own stream. Every stream read must carry each dimension the view uses, `streams` in the result lists them, and `compileRollupView` reads a rollup of each. The statement is always one column per period: the long shape is refused, and so is a view too wide for the route. A custom view reads one through its points, below.
82
- - **Matrix** groups by two dimensions: `group_by` gives the rows and `across` the columns. The result is long, one row per cell, and the grid pivots it. `__row` and `__col` say where a cell goes (0 is a total), `__total = 1` marks a column total and `__across_total = 1` a row total. Cells, row totals, column totals and the grand total come from one pass, each worked out from its own sums. Rows are sorted, paged and filtered on a measure by their row totals. `across.limit` keeps the first columns (12 unless given), picked by the first measure's column total or by code. Row totals and column totals are always returned, the column totals because they name the columns; the grand total comes with `options.total_row`. A page holds fewer rows than in other modes, since each row costs one result row per column kept and the column totals take one each; a `limit` above that is cut down, and `limit` in the result says what a page holds.
83
- - **Custom** builds each column on its own. `custom_columns` lists them and `measures` is not read. A column is one of three things. A data point: `point` names a measure, and may give its own `period` (the view's period when left out) and a `where` rule on one dimension, such as sales of one department last June. A comparison: `point` and `against`, shown as the difference or, with `show: 'percent'`, as a fraction of the second point; a blank counts as 0 and the percentage is blank when there is nothing to compare against, as in a variance. An expression: a formula over the column's own `points`, named by the letters the formula uses, with a `format` (`number` unless given). `hidden` keeps a column out of the result; it can still be sorted on. `sort.by` takes `code`, `property.<key>` or `column.<key>`, and the first shown column, descending, when left out. Every distinct data point is read once, in one pass over the rows of every window the columns use. Result columns are named `c__<key>`. `windows` in the result lists those windows and `window` runs from the earliest to the latest. The drill path, dimension filters, keyword, properties, the total, sum and average rows and hiding zero rows work as in total mode, the last three over the shown columns. A snapshot measure reads the latest day of its own point's window. A point may read a measure of another stream, such as stock on hand beside sales: each stream is then grouped in its own stage, over only the windows its points use, under the same drill path, filters and keyword, and the stages are folded to one row per member as in stream mode. The view's own stream is always read, every stream read must carry each dimension the view uses, and `streams` in the result lists them. A formula measure is read on the stream of the first measure it names, so one that mixes streams still refuses with `measure_not_on_stream`; put each stream's figure in its own point and combine them in an expression column. Nested rows are refused across streams.
82
+ - **Matrix** groups by two dimensions: `group_by` gives the rows and `across` the columns. The result is long, one row per cell, and the grid pivots it. `__row` and `__col` say where a cell goes (0 is a total), `__total = 1` marks a column total and `__across_total = 1` a row total. Cells, row totals, column totals and the grand total come from one pass, each worked out from its own sums. Rows are sorted, paged and filtered on a measure by their row totals. `across.limit` keeps the first columns (12 unless given), picked by the first measure's column total or by code. Row totals and column totals are always returned, the column totals because they name the columns; the grand total comes with `options.total_row`. A page holds fewer rows than in other modes, since each row costs one result row per column kept and the column totals take one each; a `limit` above that is cut down, and `limit` in the result says what a page holds. A matrix may read a measure of another stream, such as ordered beside sales: each stream groups the same four ways in its own stage, under the same drill path, filters and keyword, and the stages are folded by cell, so a formula that mixes streams is worked out at every level from the folded sums. Every stream read must carry both dimensions, and `streams` in the result lists them.
83
+ - **Custom** builds each column on its own. `custom_columns` lists them and `measures` is not read. A column is one of three things. A data point: `point` names a measure, and may give its own `period` (the view's period when left out) and a `where` rule on one dimension, such as sales of one department last June. A comparison: `point` and `against`, shown as the difference or, with `show: 'percent'`, as a fraction of the second point; a blank counts as 0 and the percentage is blank when there is nothing to compare against, as in a variance. An expression: a formula over the column's own `points`, named by the letters the formula uses, with a `format` (`number` unless given). `hidden` keeps a column out of the result; it can still be sorted on. `sort.by` takes `code`, `property.<key>` or `column.<key>`, and the first shown column, descending, when left out. Every distinct data point is read once, in one pass over the rows of every window the columns use. Result columns are named `c__<key>`. `windows` in the result lists those windows and `window` runs from the earliest to the latest. The drill path, dimension filters, keyword, properties, the total, sum and average rows and hiding zero rows work as in total mode, the last three over the shown columns. A snapshot measure reads the latest day of its own point's window. A point may read a measure of another stream, such as stock on hand beside sales: each stream is then grouped in its own stage, over only the windows its points use, under the same drill path, filters and keyword, and the stages are folded to one row per member as in stream mode. The view's own stream is always read, every stream read must carry each dimension the view uses, and `streams` in the result lists them. A formula measure that mixes streams, such as a fill rate of sales over ordered, is read as one point per measure it names, each on its own stream under the point's dates and rule, and the formula is worked out from those points. With nested rows, every level is grouped in each stream's stage, so each stream must carry every level.
84
84
  - **A period view that is too wide** for one column per period (the route takes 24,000 characters of SQL) is returned long instead: the matrix result with the periods as its columns, `shape: 'long'`, and `across` holding the period's number from the oldest. A period no row falls in has no cell. A total is worked out over the whole window, so `DAYS()` and a snapshot measure read the window there and the period on a cell. `sort.by` can still name one period of a shown measure. `periodShape` in the context forces `wide` or `long`; left out, the compiler goes long only when it must. A page holds fewer rows (153 with 12 periods), and `limit` in the result says how many.
85
85
  - **Activity** (`options.activity`): `with` lists members that have fact rows. `all` adds the members that have none, read from the dimension's own table. `without` lists only those, with no total row. The keyword, and the path steps and "and" filters on the group-by dimension or a dimension above it, narrow the member list; every filter decides what counts as activity.
86
86
  - **The others row** (`options.others_row`, modes `total`, `period` and `variance`): a view is focused when its drill path has a step on the group-by dimension itself. The others row is every member that step leaves out, as one row, with formulas worked out from its own sums. The total row is then the focused members' total. Without a focus there is no others row.
@@ -88,7 +88,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
88
88
  - **The average row** (`options.average_row`, same modes as the sum row): the plain mean of each measure column over the member rows of the list, on every page, after any filter on a measure. Blanks are skipped.
89
89
  - **The average column** (`options.average_column`, period mode with one column per period): one more column a measure, the mean of that measure's period columns on the same row, so the total row holds the mean of the period totals. A period with no value is skipped, not counted as zero. `sort.by` takes `average.<measure>`. Other modes ignore the option.
90
90
  - **Hiding zero rows** (`options.hide_zero_rows`, every grouped mode): leaves out a member whose every shown measure is zero or blank over the whole period, and in a variance over the earlier period too. Sales that net to zero are hidden even when single periods are not zero. The total row still counts those members; the row count and the average row do not.
91
- - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance`, `stream` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, matrix mode, a custom view of more than one stream, and the long shape of a period view. A view of more than one stream groups every level in each stream's own stage, so each stream must carry every level. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
91
+ - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance`, `stream` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, matrix mode, and the long shape of a period view. A view of more than one stream groups every level in each stream's own stage, so each stream must carry every level. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
92
92
  - **A snapshot measure** (a level, such as stock on hand) reads the rows of the latest day in each window. That day is the same for every member and is found before any filter, so the stream must hold every member's row on each snapshot day.
93
93
  - **A measure of two columns** (`times` on a base measure that is not a count): reads `column` times the `times` column on each row, then aggregates, such as units on order times a unit cost. A rollup's column for such a measure already holds the product, so the rollup is read as it is. `measureAvailability` hides the measure from a role that lacks either column.
94
94
 
package/dist/index.js CHANGED
@@ -1189,7 +1189,14 @@ function compileMode(model, view, ctx) {
1189
1189
  if (!VIEW_MODES.includes(view.mode)) fail("mode_unsupported", `mode "${String(view.mode)}" is not compiled yet`);
1190
1190
  if (view.mode === "transaction") return compileTransactions(model, view, ctx);
1191
1191
  if (view.mode === "stream") return compileStreams(model, view, ctx);
1192
- if (view.mode === "matrix") return compileMatrix(model, view, ctx);
1192
+ if (view.mode === "matrix") {
1193
+ try {
1194
+ return compileMatrix(model, view, ctx);
1195
+ } catch (err) {
1196
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream") throw err;
1197
+ return compileMatrix(model, view, ctx, false, true);
1198
+ }
1199
+ }
1193
1200
  if (view.mode === "custom") return compileCustom(model, view, ctx);
1194
1201
  const direct = view.mode === "total" || view.mode === "period_variance";
1195
1202
  try {
@@ -1943,20 +1950,24 @@ function compileCustom(model, view, ctx) {
1943
1950
  }
1944
1951
  return found;
1945
1952
  };
1946
- const streamOf = (measure, depth = 0) => {
1947
- if (!isFormulaMeasure(measure)) return measure.stream;
1948
- const first = depth > 20 ? void 0 : formulaRefs(parseFormula(measure.formula)).map((ref) => measureByKey.get(ref)).find((m) => m !== void 0);
1949
- return first === void 0 ? stream.key : streamOf(first, depth + 1);
1953
+ const streamsOf = (measure, depth = 0) => {
1954
+ if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
1955
+ const found = /* @__PURE__ */ new Set();
1956
+ if (depth <= 20) {
1957
+ formulaRefs(parseFormula(measure.formula)).forEach((ref) => {
1958
+ const named = measureByKey.get(ref);
1959
+ if (named) streamsOf(named, depth + 1).forEach((key) => found.add(key));
1960
+ });
1961
+ }
1962
+ return found.size > 0 ? found : /* @__PURE__ */ new Set([stream.key]);
1950
1963
  };
1951
1964
  const points = [];
1952
1965
  const pointOf = (point, what) => {
1953
1966
  if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1954
1967
  const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
1955
1968
  const { window, number } = windowOf(point.period);
1956
- if (point.where !== void 0 && (typeof point.where !== "object" || point.where === null || "measure" in point.where)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
1957
- const src = readsOf(streamOf(measure));
1958
- src.windows.add(number);
1959
- const rule = point.where === void 0 ? "" : ` AND ${src.scope.dimensionRule(point.where)}`;
1969
+ const where2 = point.where;
1970
+ if (where2 !== void 0 && (typeof where2 !== "object" || where2 === null || "measure" in where2)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
1960
1971
  const bucket = {
1961
1972
  key: `w${number}`,
1962
1973
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1964,11 +1975,25 @@ function compileCustom(model, view, ctx) {
1964
1975
  to: window.to,
1965
1976
  days: daysBetween(window.from, window.to)
1966
1977
  };
1967
- const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1968
- const sql2 = `CAST(${measureOver(src.reads, measure.key, slice)} AS DOUBLE)`;
1969
- const key = src.scope.stream.key;
1970
- const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1971
- return { name: `p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`, measure, bucket };
1978
+ const read = (m, depth) => {
1979
+ const streams = streamsOf(m);
1980
+ if (streams.size > 1 && isFormulaMeasure(m)) {
1981
+ if (depth > 20) fail("formula_cycle", `"${m.key}" refers back to itself`);
1982
+ return emitFormulaSql(parseFormula(m.formula), {
1983
+ measure: (ref) => read(measureByKey.get(ref) ?? fail("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
1984
+ days: bucket.days
1985
+ });
1986
+ }
1987
+ const src = readsOf([...streams][0] ?? stream.key);
1988
+ src.windows.add(number);
1989
+ const rule = where2 === void 0 ? "" : ` AND ${src.scope.dimensionRule(where2)}`;
1990
+ const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1991
+ const sql2 = `CAST(${measureOver(src.reads, m.key, slice)} AS DOUBLE)`;
1992
+ const key = src.scope.stream.key;
1993
+ const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1994
+ return quoteIdent(`p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`);
1995
+ };
1996
+ return { ref: read(measure, 0), measure, bucket };
1972
1997
  };
1973
1998
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
1974
1999
  const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
@@ -1994,13 +2019,13 @@ function compileCustom(model, view, ctx) {
1994
2019
  const cur = pointOf(column.point, `"${key}"`);
1995
2020
  if (column.against === void 0) {
1996
2021
  if (column.show !== void 0) fail("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
1997
- expr = quoteIdent(cur.name);
2022
+ expr = cur.ref;
1998
2023
  about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
1999
2024
  } else {
2000
2025
  const prev = pointOf(column.against, `"${key}"`);
2001
2026
  const show = column.show ?? "difference";
2002
2027
  if (show !== "difference" && show !== "percent") fail("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
2003
- expr = show === "difference" ? `COALESCE(${quoteIdent(cur.name)}, 0) - COALESCE(${quoteIdent(prev.name)}, 0)` : `(COALESCE(${quoteIdent(cur.name)}, 0) - ${quoteIdent(prev.name)}) / NULLIF(abs(${quoteIdent(prev.name)}), 0)`;
2028
+ expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
2004
2029
  about = {
2005
2030
  label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
2006
2031
  measure: cur.measure.key,
@@ -2015,7 +2040,7 @@ function compileCustom(model, view, ctx) {
2015
2040
  expr = emitFormulaSql(parseFormula(String(column.expression)), {
2016
2041
  measure: (ref) => {
2017
2042
  if (!Object.prototype.hasOwnProperty.call(named, ref)) fail("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2018
- return quoteIdent(pointOf(named[ref], `point "${ref}" of "${key}"`).name);
2043
+ return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
2019
2044
  },
2020
2045
  days: reads.days
2021
2046
  });
@@ -2030,7 +2055,6 @@ function compileCustom(model, view, ctx) {
2030
2055
  if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
2031
2056
  if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
2032
2057
  const multi = reading.size > 1;
2033
- if (multi && nest) fail("option_unsupported", "nested rows are not compiled for a custom view of more than one stream yet");
2034
2058
  points.forEach(({ sql: sql2 }, i) => {
2035
2059
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
2036
2060
  left.push(`p${i + 1}`);
@@ -2057,31 +2081,38 @@ function compileCustom(model, view, ctx) {
2057
2081
  const stages = !multi ? [] : streamKeys.map((key) => {
2058
2082
  const { scope: s, reads: r, windows: used } = readsOf(key);
2059
2083
  const grouped = `GROUPING(${s.codeExpr})`;
2060
- const parts2 = [`${s.codeExpr} AS "code"`];
2084
+ const levels = nest ? nestOf(view, s) : null;
2085
+ const parts2 = [...levels?.select ?? [], `${s.codeExpr} AS "code"`];
2061
2086
  shownProperties(view).forEach((property) => {
2062
2087
  const expr = `any_value(${s.propertyOf(groupDim.key, property)})`;
2063
- parts2.push(`${totalRow ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2088
+ parts2.push(`${totalRow || levels ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2064
2089
  });
2065
2090
  points.forEach((p, i) => {
2066
2091
  if (p.stream === key) parts2.push(`${p.sql} AS ${quoteIdent(`p${i + 1}`)}`);
2067
2092
  });
2068
- parts2.push(`${totalRow ? `CAST(${grouped} AS INTEGER)` : "0"} AS "__total"`);
2093
+ parts2.push(`${totalRow ? `CAST(${levels ? levels.total : grouped} AS INTEGER)` : "0"} AS "__total"`);
2094
+ if (levels) parts2.push(levels.level);
2069
2095
  const mine = [...used].sort((a, b) => a - b);
2070
2096
  const sDate = quoteIdent(s.stream.date);
2071
2097
  const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
2072
2098
  const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
2073
2099
  const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
2074
2100
  const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(quoteIdent(s.stream.table), sDate, `, ${sFlags}`, sAny, mine.map((n) => ({ where: sIn(windows[n - 1]), flag: `__l${n}` }))) : `(SELECT *, ${sFlags} FROM ${quoteIdent(s.stream.table)} WHERE ${sAny}) AS ${FACT}`;
2075
- return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy: totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}` };
2101
+ const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
2102
+ return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
2076
2103
  });
2104
+ const anyOf = (name) => `any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`;
2077
2105
  const fold = [
2106
+ ...(nest?.columns ?? []).map((c) => c.property === "name" ? anyOf(c.name) : quoteIdent(c.name)),
2078
2107
  '"code"',
2079
- ...shownProperties(view).map((property) => `any_value(${quoteIdent(`prop__${property}`)}) AS ${quoteIdent(`prop__${property}`)}`),
2080
- ...points.map((_, i) => `any_value(${quoteIdent(`p${i + 1}`)}) AS ${quoteIdent(`p${i + 1}`)}`),
2081
- '"__total"'
2108
+ ...shownProperties(view).map((property) => anyOf(`prop__${property}`)),
2109
+ ...points.map((_, i) => anyOf(`p${i + 1}`)),
2110
+ '"__total"',
2111
+ ...nest ? ['"__level"'] : []
2082
2112
  ];
2113
+ const foldKeys = [...nest ? Array.from({ length: nest.count }, (_, i) => quoteIdent(`lv${i + 1}`)) : [], '"code"', '"__total"', ...nest ? ['"__level"'] : []];
2083
2114
  const sql = [
2084
- ...multi ? foldStreams(stages, fold) : [
2115
+ ...multi ? foldStreams(stages, fold, foldKeys) : [
2085
2116
  "WITH g AS (",
2086
2117
  `SELECT ${select.join(", ")}`,
2087
2118
  `FROM ${fact}`,
@@ -2187,7 +2218,7 @@ function compileTransactions(model, view, ctx) {
2187
2218
  checkLength(sql, ctx);
2188
2219
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2189
2220
  }
2190
- function foldStreams(stages, fold, levels = []) {
2221
+ function foldStreams(stages, fold, keys) {
2191
2222
  return [
2192
2223
  ...stages.flatMap((stage, i) => [
2193
2224
  `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
@@ -2201,9 +2232,39 @@ function foldStreams(stages, fold, levels = []) {
2201
2232
  `SELECT ${fold.join(", ")}`,
2202
2233
  // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2203
2234
  `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2204
- `GROUP BY ${[...levels.map(quoteIdent), '"code"', '"__total"', ...levels.length > 0 ? ['"__level"'] : []].join(", ")}`
2235
+ `GROUP BY ${keys.join(", ")}`
2205
2236
  ];
2206
2237
  }
2238
+ function foldedMeasures(measureByKey, periodCount) {
2239
+ const needed = /* @__PURE__ */ new Map();
2240
+ const parsed = /* @__PURE__ */ new Map();
2241
+ const exprOf = (key, part, depth) => {
2242
+ if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2243
+ const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2244
+ if (isFormulaMeasure(measure)) {
2245
+ let node = parsed.get(key);
2246
+ if (!node) {
2247
+ node = parseFormula(measure.formula);
2248
+ parsed.set(key, node);
2249
+ }
2250
+ return emitFormulaSql(node, {
2251
+ measure: (ref) => exprOf(ref, part, depth + 1),
2252
+ days: part.days,
2253
+ ...periodCount > 0 ? { periodCount } : {}
2254
+ });
2255
+ }
2256
+ const list2 = needed.get(measure.stream) ?? [];
2257
+ if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2258
+ needed.set(measure.stream, list2);
2259
+ return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2260
+ };
2261
+ return { needed, exprOf };
2262
+ }
2263
+ function streamSum(measure, over) {
2264
+ const call = aggregateOf(measure, "COUNT(*)");
2265
+ const sum = measure.snapshot ? `${call} FILTER (WHERE ${over.last})` : over.filter === null ? call : measure.agg === "count" && measure.rolled ? `COALESCE(${call} FILTER (WHERE ${over.filter}), 0)` : `${call} FILTER (WHERE ${over.filter})`;
2266
+ return `${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`;
2267
+ }
2207
2268
  function compileStreams(model, view, ctx) {
2208
2269
  const options = view.options ?? {};
2209
2270
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
@@ -2244,28 +2305,7 @@ function compileStreams(model, view, ctx) {
2244
2305
  before: back ? { bucket: back, part: { prefix: `p${i + 1}`, days: back.days, filter: `${FACT}."__pb" = ${i + 1}`, last: `${FACT}."__pb" = ${i + 1} AND ${FACT}."__plast"` } } : null
2245
2306
  };
2246
2307
  });
2247
- const needed = /* @__PURE__ */ new Map();
2248
- const parsed = /* @__PURE__ */ new Map();
2249
- const exprOf = (key, part, depth) => {
2250
- if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2251
- const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2252
- if (isFormulaMeasure(measure)) {
2253
- let node = parsed.get(key);
2254
- if (!node) {
2255
- node = parseFormula(measure.formula);
2256
- parsed.set(key, node);
2257
- }
2258
- return emitFormulaSql(node, {
2259
- measure: (ref) => exprOf(ref, part, depth + 1),
2260
- days: part.days,
2261
- ...buckets.length > 0 ? { periodCount: buckets.length } : {}
2262
- });
2263
- }
2264
- const list2 = needed.get(measure.stream) ?? [];
2265
- if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2266
- needed.set(measure.stream, list2);
2267
- return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2268
- };
2308
+ const { needed, exprOf } = foldedMeasures(measureByKey, buckets.length);
2269
2309
  const properties = shownProperties(view);
2270
2310
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
2271
2311
  const select = [
@@ -2386,11 +2426,7 @@ function compileStreams(model, view, ctx) {
2386
2426
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2387
2427
  part.push(`${totalRow || levels ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2388
2428
  });
2389
- mine.forEach(({ measure, part: over }) => {
2390
- const call = aggregateOf(measure, "COUNT(*)");
2391
- const sum = measure.snapshot ? `${call} FILTER (WHERE ${over.last})` : over.filter === null ? call : measure.agg === "count" && measure.rolled ? `COALESCE(${call} FILTER (WHERE ${over.filter}), 0)` : `${call} FILTER (WHERE ${over.filter})`;
2392
- part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2393
- });
2429
+ mine.forEach(({ measure, part: over }) => part.push(streamSum(measure, over)));
2394
2430
  part.push(`${totalRow ? `CAST(${levels ? levels.total : grouping} AS INTEGER)` : "0"} AS "__total"`);
2395
2431
  if (levels) part.push(levels.level);
2396
2432
  return {
@@ -2403,7 +2439,13 @@ function compileStreams(model, view, ctx) {
2403
2439
  };
2404
2440
  });
2405
2441
  const sql = [
2406
- ...foldStreams(stages, select, nest ? Array.from({ length: nest.count }, (_, i) => `lv${i + 1}`) : []),
2442
+ // Nested: each level's row folds apart from the members beneath it, by its level columns.
2443
+ ...foldStreams(stages, select, [
2444
+ ...nest ? Array.from({ length: nest.count }, (_, i) => quoteIdent(`lv${i + 1}`)) : [],
2445
+ '"code"',
2446
+ '"__total"',
2447
+ ...nest ? ['"__level"'] : []
2448
+ ]),
2407
2449
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2408
2450
  ...rankAndPage(source, sortName, sort, keepRows(lead.having, options, figures), left, offset, limit, {
2409
2451
  others: false,
@@ -2419,7 +2461,7 @@ function compileStreams(model, view, ctx) {
2419
2461
  } : range;
2420
2462
  return { ok: true, sql, columns, window: range, ...two ? { comparison: two.comparison } : {}, buckets, months: monthsRange(read), streams: streamKeys };
2421
2463
  }
2422
- function compileMatrix(model, view, ctx, byPeriod = false) {
2464
+ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2423
2465
  const options = view.options ?? {};
2424
2466
  const what = byPeriod ? "the long shape of a period view" : "matrix mode";
2425
2467
  if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
@@ -2438,6 +2480,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2438
2480
  const days = daysBetween(range.from, range.to);
2439
2481
  const uses = /* @__PURE__ */ new Set();
2440
2482
  const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days, uses };
2483
+ const folded = streams ? foldedMeasures(measureByKey, 0) : null;
2484
+ const whole = { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
2441
2485
  const rowCode = scope.codeExpr;
2442
2486
  let colCode = `${FACT}."__b"`;
2443
2487
  let keep = buckets.length;
@@ -2477,22 +2521,24 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2477
2521
  if (!Number.isInteger(offset) || offset < 0) fail("bad_paging", "offset must be a whole number, 0 or more");
2478
2522
  const limit = Math.min(asked, room);
2479
2523
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2480
- const select = [`${rowCode} AS "code"`];
2481
- shownProperties(view).forEach((property) => {
2524
+ const properties = shownProperties(view);
2525
+ const anyOf = (name) => `any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`;
2526
+ const select = [folded ? '"code"' : `${rowCode} AS "code"`];
2527
+ properties.forEach((property) => {
2482
2528
  const name = `prop__${property}`;
2483
- select.push(`CASE WHEN GROUPING(${rowCode}) = 0 THEN any_value(${scope.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(name)}`);
2529
+ select.push(folded ? anyOf(name) : `CASE WHEN GROUPING(${rowCode}) = 0 THEN any_value(${scope.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(name)}`);
2484
2530
  columns.push({ name, kind: "property", label: propertyLabel(groupDim, property), property });
2485
2531
  });
2486
- select.push(`${colCode} AS "across"`);
2532
+ select.push(folded ? '"across"' : `${colCode} AS "across"`);
2487
2533
  columns.push(acrossColumn);
2488
2534
  if (acrossName && acrossColumn.dimension !== void 0) {
2489
- select.push(`CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${scope.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2535
+ select.push(folded ? anyOf("across__name") : `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${scope.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2490
2536
  columns.push(acrossName);
2491
2537
  }
2492
2538
  const hidden = [];
2493
2539
  const addMeasure = (measure, seen) => {
2494
2540
  const name = `m__${measure.key}`;
2495
- select.push(`CAST(${measureOver(reads, measure.key, null)} AS DOUBLE) AS ${quoteIdent(name)}`);
2541
+ select.push(`CAST(${folded ? folded.exprOf(measure.key, whole, 0) : measureOver(reads, measure.key, null)} AS DOUBLE) AS ${quoteIdent(name)}`);
2496
2542
  if (seen) columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2497
2543
  else hidden.push(name);
2498
2544
  };
@@ -2512,7 +2558,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2512
2558
  } else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
2513
2559
  fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2514
2560
  }
2515
- select.push(`CAST(GROUPING(${rowCode}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${colCode}) AS INTEGER) AS "__across_total"`);
2561
+ const flags = (row, col) => [`CAST(GROUPING(${row}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${col}) AS INTEGER) AS "__across_total"`];
2562
+ select.push(...folded ? ['"__total"', '"__across_total"'] : flags(rowCode, colCode));
2516
2563
  columns.push(
2517
2564
  { name: "__total", kind: "meta", label: "Total row" },
2518
2565
  { name: "__across_total", kind: "meta", label: "Row total" },
@@ -2533,14 +2580,41 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2533
2580
  const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
2534
2581
  const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
2535
2582
  const kept = keepRows(scope.having, options, shown.map((m) => `m__${m.key}`));
2583
+ const sets = (row, col) => `GROUP BY GROUPING SETS ((${row}, ${col}), (${row}), (${col}), ())`;
2584
+ const streamKeys = folded ? [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && folded.needed.has(key))] : [];
2585
+ const stages = streamKeys.map((key, i) => {
2586
+ const own = i === 0 ? scope : scopeOf(model, { ...view, stream: key }, ctx);
2587
+ const row = own.codeExpr;
2588
+ const col = own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
2589
+ const mine = folded?.needed.get(key) ?? [];
2590
+ const part = [`${row} AS "code"`];
2591
+ properties.forEach((property) => {
2592
+ part.push(`CASE WHEN GROUPING(${row}) = 0 THEN any_value(${own.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(`prop__${property}`)}`);
2593
+ });
2594
+ part.push(`${col} AS "across"`);
2595
+ if (acrossName && acrossColumn.dimension !== void 0) {
2596
+ part.push(`CASE WHEN GROUPING(${col}) = 0 THEN any_value(${own.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2597
+ }
2598
+ mine.forEach(({ measure, part: over }) => part.push(streamSum(measure, over)));
2599
+ part.push(...flags(row, col));
2600
+ return {
2601
+ select: part,
2602
+ from: factAcross(own.stream, range, [], null, mine.some(({ measure }) => measure.snapshot)),
2603
+ joins: [...own.joins.values()],
2604
+ where: own.where,
2605
+ groupBy: sets(row, col)
2606
+ };
2607
+ });
2536
2608
  const sql = [
2537
2609
  // Every stage opens as `name AS (`. The route takes any other opening, such as AS MATERIALIZED, for a table it does not hold.
2538
- "WITH g AS (",
2539
- `SELECT ${select.join(", ")}`,
2540
- `FROM ${fact}`,
2541
- ...scope.joins.values(),
2542
- ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2543
- `GROUP BY GROUPING SETS ((${rowCode}, ${colCode}), (${rowCode}), (${colCode}), ())`,
2610
+ ...folded ? foldStreams(stages, select, ['"code"', '"across"', '"__total"', '"__across_total"']) : [
2611
+ "WITH g AS (",
2612
+ `SELECT ${select.join(", ")}`,
2613
+ `FROM ${fact}`,
2614
+ ...scope.joins.values(),
2615
+ ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2616
+ sets(rowCode, colCode)
2617
+ ],
2544
2618
  // Rows are ranked, and filtered on a measure, by their totals across every column.
2545
2619
  "), rw AS (",
2546
2620
  `SELECT "code", row_number() OVER (ORDER BY ${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST, "code" ASC) AS "__row"`,
@@ -2571,7 +2645,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2571
2645
  shape: "long",
2572
2646
  ...byPeriod && options.reverse_periods ? { reversed: true } : {},
2573
2647
  limit,
2574
- ...acrossColumn.dimension !== void 0 ? { across: { dimension: acrossColumn.dimension, limit: keep } } : {}
2648
+ ...acrossColumn.dimension !== void 0 ? { across: { dimension: acrossColumn.dimension, limit: keep } } : {},
2649
+ ...folded ? { streams: streamKeys } : {}
2575
2650
  };
2576
2651
  }
2577
2652
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "Pure reporting core: a model of dimensions and measures, a formula parser, a period engine, and a compiler from a saved view to one DuckDB statement.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",