@sprigr/apps-reporting-core 0.0.6 → 0.0.8

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 +128 -65
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -79,7 +79,7 @@ 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.
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
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.
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.
@@ -88,11 +88,11 @@ 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` 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, stream and matrix modes, and the long shape of a period view. 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, 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.
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
 
95
- Refused with a named reason until built: an others row in stream mode; nested rows, the activity option and an others row in a total, period or variance view of more than one stream, and the average column in such a period view; others, average and sum rows in matrix mode and in the long shape of a period view; an others row or hidden zero rows with the activity option; the average column in the long shape of a period view; the activity option, period columns and a variance in stream and matrix modes; the activity option in the long shape of a period view; a snapshot measure or a total row on a transaction list; a filter on a measure, an others row and the activity option in custom mode; the grid functions RANK, PERCENTILE and FORECAST.LINEAR.
95
+ Refused with a named reason until built: an others row in stream mode; the activity option and an others row in a total, period or variance view of more than one stream, and the average column in such a period view; others, average and sum rows in matrix mode and in the long shape of a period view; an others row or hidden zero rows with the activity option; the average column in the long shape of a period view; the activity option, period columns and a variance in stream and matrix modes; the activity option in the long shape of a period view; a snapshot measure or a total row on a transaction list; a filter on a measure, an others row and the activity option in custom mode; the grid functions RANK, PERCENTILE and FORECAST.LINEAR.
96
96
 
97
97
  ## To check against the source system at migration
98
98
 
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 {
@@ -2081,7 +2088,7 @@ function compileCustom(model, view, ctx) {
2081
2088
  '"__total"'
2082
2089
  ];
2083
2090
  const sql = [
2084
- ...multi ? foldStreams(stages, fold) : [
2091
+ ...multi ? foldStreams(stages, fold, ['"code"', '"__total"']) : [
2085
2092
  "WITH g AS (",
2086
2093
  `SELECT ${select.join(", ")}`,
2087
2094
  `FROM ${fact}`,
@@ -2187,7 +2194,7 @@ function compileTransactions(model, view, ctx) {
2187
2194
  checkLength(sql, ctx);
2188
2195
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2189
2196
  }
2190
- function foldStreams(stages, fold) {
2197
+ function foldStreams(stages, fold, keys) {
2191
2198
  return [
2192
2199
  ...stages.flatMap((stage, i) => [
2193
2200
  `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
@@ -2201,13 +2208,42 @@ function foldStreams(stages, fold) {
2201
2208
  `SELECT ${fold.join(", ")}`,
2202
2209
  // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2203
2210
  `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2204
- 'GROUP BY "code", "__total"'
2211
+ `GROUP BY ${keys.join(", ")}`
2205
2212
  ];
2206
2213
  }
2214
+ function foldedMeasures(measureByKey, periodCount) {
2215
+ const needed = /* @__PURE__ */ new Map();
2216
+ const parsed = /* @__PURE__ */ new Map();
2217
+ const exprOf = (key, part, depth) => {
2218
+ if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2219
+ const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2220
+ if (isFormulaMeasure(measure)) {
2221
+ let node = parsed.get(key);
2222
+ if (!node) {
2223
+ node = parseFormula(measure.formula);
2224
+ parsed.set(key, node);
2225
+ }
2226
+ return emitFormulaSql(node, {
2227
+ measure: (ref) => exprOf(ref, part, depth + 1),
2228
+ days: part.days,
2229
+ ...periodCount > 0 ? { periodCount } : {}
2230
+ });
2231
+ }
2232
+ const list2 = needed.get(measure.stream) ?? [];
2233
+ if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2234
+ needed.set(measure.stream, list2);
2235
+ return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2236
+ };
2237
+ return { needed, exprOf };
2238
+ }
2239
+ function streamSum(measure, over) {
2240
+ const call = aggregateOf(measure, "COUNT(*)");
2241
+ 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})`;
2242
+ return `${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`;
2243
+ }
2207
2244
  function compileStreams(model, view, ctx) {
2208
2245
  const options = view.options ?? {};
2209
2246
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2210
- if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2211
2247
  if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2212
2248
  if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2213
2249
  if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
@@ -2216,6 +2252,13 @@ function compileStreams(model, view, ctx) {
2216
2252
  const sumRow = options.sum_row === true;
2217
2253
  const lead = scopeOf(model, view, ctx);
2218
2254
  const { measureByKey, groupDim } = lead;
2255
+ const nest = nestOf(view, lead);
2256
+ if (nest) {
2257
+ if (averageRow || sumRow || options.hide_zero_rows) {
2258
+ fail("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2259
+ }
2260
+ if (lead.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2261
+ }
2219
2262
  const shown = shownMeasures(view, measureByKey);
2220
2263
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2221
2264
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
@@ -2238,31 +2281,13 @@ function compileStreams(model, view, ctx) {
2238
2281
  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
2239
2282
  };
2240
2283
  });
2241
- const needed = /* @__PURE__ */ new Map();
2242
- const parsed = /* @__PURE__ */ new Map();
2243
- const exprOf = (key, part, depth) => {
2244
- if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2245
- const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2246
- if (isFormulaMeasure(measure)) {
2247
- let node = parsed.get(key);
2248
- if (!node) {
2249
- node = parseFormula(measure.formula);
2250
- parsed.set(key, node);
2251
- }
2252
- return emitFormulaSql(node, {
2253
- measure: (ref) => exprOf(ref, part, depth + 1),
2254
- days: part.days,
2255
- ...buckets.length > 0 ? { periodCount: buckets.length } : {}
2256
- });
2257
- }
2258
- const list2 = needed.get(measure.stream) ?? [];
2259
- if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2260
- needed.set(measure.stream, list2);
2261
- return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2262
- };
2284
+ const { needed, exprOf } = foldedMeasures(measureByKey, buckets.length);
2263
2285
  const properties = shownProperties(view);
2264
- const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2265
- const select = ['"code"'];
2286
+ const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
2287
+ const select = [
2288
+ ...(nest?.columns ?? []).map((c) => c.property === "name" ? `any_value(${quoteIdent(c.name)}) AS ${quoteIdent(c.name)}` : quoteIdent(c.name)),
2289
+ '"code"'
2290
+ ];
2266
2291
  properties.forEach((property) => {
2267
2292
  const name = `prop__${property}`;
2268
2293
  select.push(`any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`);
@@ -2351,7 +2376,12 @@ function compileStreams(model, view, ctx) {
2351
2376
  shown.forEach((measure) => addMeasure(measure, true));
2352
2377
  unseen.forEach((measure) => addMeasure(measure, false));
2353
2378
  select.push('"__total"');
2354
- columns.push({ name: "__total", kind: "meta", label: "Total row" }, { name: "__rows", kind: "meta", label: "Row count" });
2379
+ columns.push({ name: "__total", kind: "meta", label: "Total row" });
2380
+ if (nest) {
2381
+ select.push('"__level"');
2382
+ columns.push({ name: "__level", kind: "meta", label: "Level" });
2383
+ }
2384
+ columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2355
2385
  const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
2356
2386
  if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2357
2387
  const sortName = sortNameOf(sort.by);
@@ -2366,39 +2396,39 @@ function compileStreams(model, view, ctx) {
2366
2396
  const { stream, codeExpr } = scope;
2367
2397
  const mine = needed.get(key) ?? [];
2368
2398
  const grouping = `GROUPING(${codeExpr})`;
2369
- const part = [`${codeExpr} AS "code"`];
2399
+ const levels = nest ? nestOf(view, scope) : null;
2400
+ const part = [...levels?.select ?? [], `${codeExpr} AS "code"`];
2370
2401
  properties.forEach((property) => {
2371
2402
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2372
- part.push(`${totalRow ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2373
- });
2374
- mine.forEach(({ measure, part: over }) => {
2375
- const call = aggregateOf(measure, "COUNT(*)");
2376
- 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})`;
2377
- part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2403
+ part.push(`${totalRow || levels ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2378
2404
  });
2379
- part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2405
+ mine.forEach(({ measure, part: over }) => part.push(streamSum(measure, over)));
2406
+ part.push(`${totalRow ? `CAST(${levels ? levels.total : grouping} AS INTEGER)` : "0"} AS "__total"`);
2407
+ if (levels) part.push(levels.level);
2380
2408
  return {
2381
2409
  select: part,
2382
2410
  // A snapshot measure reads its own stream's latest day in each set of dates.
2383
2411
  from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot), earlierBuckets),
2384
2412
  joins: [...scope.joins.values()],
2385
2413
  where: scope.where,
2386
- groupBy: totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2414
+ groupBy: levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2387
2415
  };
2388
2416
  });
2389
2417
  const sql = [
2390
- ...foldStreams(stages, select),
2418
+ // Nested: each level's row folds apart from the members beneath it, by its level columns.
2419
+ ...foldStreams(stages, select, [
2420
+ ...nest ? Array.from({ length: nest.count }, (_, i) => quoteIdent(`lv${i + 1}`)) : [],
2421
+ '"code"',
2422
+ '"__total"',
2423
+ ...nest ? ['"__level"'] : []
2424
+ ]),
2391
2425
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2392
- ...rankAndPage(
2393
- source,
2394
- sortName,
2395
- sort,
2396
- keepRows(lead.having, options, figures),
2397
- left,
2398
- offset,
2399
- limit,
2400
- { others: false, average: averageRow ? measured : [], sum: sumRow ? measured : [] }
2401
- )
2426
+ ...rankAndPage(source, sortName, sort, keepRows(lead.having, options, figures), left, offset, limit, {
2427
+ others: false,
2428
+ average: averageRow ? measured : [],
2429
+ sum: sumRow ? measured : [],
2430
+ ...nest ? { nest: { levels: nest.count, byMeasure: columns.find((c) => c.name === sortName)?.kind === "measure" } } : {}
2431
+ })
2402
2432
  ].join("\n");
2403
2433
  checkLength(sql, ctx);
2404
2434
  const read = two ? {
@@ -2407,7 +2437,7 @@ function compileStreams(model, view, ctx) {
2407
2437
  } : range;
2408
2438
  return { ok: true, sql, columns, window: range, ...two ? { comparison: two.comparison } : {}, buckets, months: monthsRange(read), streams: streamKeys };
2409
2439
  }
2410
- function compileMatrix(model, view, ctx, byPeriod = false) {
2440
+ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2411
2441
  const options = view.options ?? {};
2412
2442
  const what = byPeriod ? "the long shape of a period view" : "matrix mode";
2413
2443
  if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
@@ -2426,6 +2456,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2426
2456
  const days = daysBetween(range.from, range.to);
2427
2457
  const uses = /* @__PURE__ */ new Set();
2428
2458
  const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days, uses };
2459
+ const folded = streams ? foldedMeasures(measureByKey, 0) : null;
2460
+ const whole = { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
2429
2461
  const rowCode = scope.codeExpr;
2430
2462
  let colCode = `${FACT}."__b"`;
2431
2463
  let keep = buckets.length;
@@ -2465,22 +2497,24 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2465
2497
  if (!Number.isInteger(offset) || offset < 0) fail("bad_paging", "offset must be a whole number, 0 or more");
2466
2498
  const limit = Math.min(asked, room);
2467
2499
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2468
- const select = [`${rowCode} AS "code"`];
2469
- shownProperties(view).forEach((property) => {
2500
+ const properties = shownProperties(view);
2501
+ const anyOf = (name) => `any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`;
2502
+ const select = [folded ? '"code"' : `${rowCode} AS "code"`];
2503
+ properties.forEach((property) => {
2470
2504
  const name = `prop__${property}`;
2471
- select.push(`CASE WHEN GROUPING(${rowCode}) = 0 THEN any_value(${scope.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(name)}`);
2505
+ select.push(folded ? anyOf(name) : `CASE WHEN GROUPING(${rowCode}) = 0 THEN any_value(${scope.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(name)}`);
2472
2506
  columns.push({ name, kind: "property", label: propertyLabel(groupDim, property), property });
2473
2507
  });
2474
- select.push(`${colCode} AS "across"`);
2508
+ select.push(folded ? '"across"' : `${colCode} AS "across"`);
2475
2509
  columns.push(acrossColumn);
2476
2510
  if (acrossName && acrossColumn.dimension !== void 0) {
2477
- select.push(`CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${scope.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2511
+ select.push(folded ? anyOf("across__name") : `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${scope.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2478
2512
  columns.push(acrossName);
2479
2513
  }
2480
2514
  const hidden = [];
2481
2515
  const addMeasure = (measure, seen) => {
2482
2516
  const name = `m__${measure.key}`;
2483
- select.push(`CAST(${measureOver(reads, measure.key, null)} AS DOUBLE) AS ${quoteIdent(name)}`);
2517
+ select.push(`CAST(${folded ? folded.exprOf(measure.key, whole, 0) : measureOver(reads, measure.key, null)} AS DOUBLE) AS ${quoteIdent(name)}`);
2484
2518
  if (seen) columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2485
2519
  else hidden.push(name);
2486
2520
  };
@@ -2500,7 +2534,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2500
2534
  } else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
2501
2535
  fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2502
2536
  }
2503
- select.push(`CAST(GROUPING(${rowCode}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${colCode}) AS INTEGER) AS "__across_total"`);
2537
+ const flags = (row, col) => [`CAST(GROUPING(${row}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${col}) AS INTEGER) AS "__across_total"`];
2538
+ select.push(...folded ? ['"__total"', '"__across_total"'] : flags(rowCode, colCode));
2504
2539
  columns.push(
2505
2540
  { name: "__total", kind: "meta", label: "Total row" },
2506
2541
  { name: "__across_total", kind: "meta", label: "Row total" },
@@ -2521,14 +2556,41 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2521
2556
  const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
2522
2557
  const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
2523
2558
  const kept = keepRows(scope.having, options, shown.map((m) => `m__${m.key}`));
2559
+ const sets = (row, col) => `GROUP BY GROUPING SETS ((${row}, ${col}), (${row}), (${col}), ())`;
2560
+ const streamKeys = folded ? [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && folded.needed.has(key))] : [];
2561
+ const stages = streamKeys.map((key, i) => {
2562
+ const own = i === 0 ? scope : scopeOf(model, { ...view, stream: key }, ctx);
2563
+ const row = own.codeExpr;
2564
+ const col = own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
2565
+ const mine = folded?.needed.get(key) ?? [];
2566
+ const part = [`${row} AS "code"`];
2567
+ properties.forEach((property) => {
2568
+ part.push(`CASE WHEN GROUPING(${row}) = 0 THEN any_value(${own.propertyOf(groupDim.key, property)}) END AS ${quoteIdent(`prop__${property}`)}`);
2569
+ });
2570
+ part.push(`${col} AS "across"`);
2571
+ if (acrossName && acrossColumn.dimension !== void 0) {
2572
+ part.push(`CASE WHEN GROUPING(${col}) = 0 THEN any_value(${own.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2573
+ }
2574
+ mine.forEach(({ measure, part: over }) => part.push(streamSum(measure, over)));
2575
+ part.push(...flags(row, col));
2576
+ return {
2577
+ select: part,
2578
+ from: factAcross(own.stream, range, [], null, mine.some(({ measure }) => measure.snapshot)),
2579
+ joins: [...own.joins.values()],
2580
+ where: own.where,
2581
+ groupBy: sets(row, col)
2582
+ };
2583
+ });
2524
2584
  const sql = [
2525
2585
  // Every stage opens as `name AS (`. The route takes any other opening, such as AS MATERIALIZED, for a table it does not hold.
2526
- "WITH g AS (",
2527
- `SELECT ${select.join(", ")}`,
2528
- `FROM ${fact}`,
2529
- ...scope.joins.values(),
2530
- ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2531
- `GROUP BY GROUPING SETS ((${rowCode}, ${colCode}), (${rowCode}), (${colCode}), ())`,
2586
+ ...folded ? foldStreams(stages, select, ['"code"', '"across"', '"__total"', '"__across_total"']) : [
2587
+ "WITH g AS (",
2588
+ `SELECT ${select.join(", ")}`,
2589
+ `FROM ${fact}`,
2590
+ ...scope.joins.values(),
2591
+ ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2592
+ sets(rowCode, colCode)
2593
+ ],
2532
2594
  // Rows are ranked, and filtered on a measure, by their totals across every column.
2533
2595
  "), rw AS (",
2534
2596
  `SELECT "code", row_number() OVER (ORDER BY ${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST, "code" ASC) AS "__row"`,
@@ -2559,7 +2621,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2559
2621
  shape: "long",
2560
2622
  ...byPeriod && options.reverse_periods ? { reversed: true } : {},
2561
2623
  limit,
2562
- ...acrossColumn.dimension !== void 0 ? { across: { dimension: acrossColumn.dimension, limit: keep } } : {}
2624
+ ...acrossColumn.dimension !== void 0 ? { across: { dimension: acrossColumn.dimension, limit: keep } } : {},
2625
+ ...folded ? { streams: streamKeys } : {}
2563
2626
  };
2564
2627
  }
2565
2628
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
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",