@sprigr/apps-reporting-core 0.0.7 → 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 +1 -1
  2. package/dist/index.js +98 -47
  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.
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, levels = []) {
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,9 +2208,39 @@ function foldStreams(stages, fold, levels = []) {
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 ${[...levels.map(quoteIdent), '"code"', '"__total"', ...levels.length > 0 ? ['"__level"'] : []].join(", ")}`
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";
@@ -2244,28 +2281,7 @@ function compileStreams(model, view, ctx) {
2244
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
2245
2282
  };
2246
2283
  });
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
- };
2284
+ const { needed, exprOf } = foldedMeasures(measureByKey, buckets.length);
2269
2285
  const properties = shownProperties(view);
2270
2286
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
2271
2287
  const select = [
@@ -2386,11 +2402,7 @@ function compileStreams(model, view, ctx) {
2386
2402
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2387
2403
  part.push(`${totalRow || levels ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2388
2404
  });
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
- });
2405
+ mine.forEach(({ measure, part: over }) => part.push(streamSum(measure, over)));
2394
2406
  part.push(`${totalRow ? `CAST(${levels ? levels.total : grouping} AS INTEGER)` : "0"} AS "__total"`);
2395
2407
  if (levels) part.push(levels.level);
2396
2408
  return {
@@ -2403,7 +2415,13 @@ function compileStreams(model, view, ctx) {
2403
2415
  };
2404
2416
  });
2405
2417
  const sql = [
2406
- ...foldStreams(stages, select, nest ? Array.from({ length: nest.count }, (_, i) => `lv${i + 1}`) : []),
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
+ ]),
2407
2425
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2408
2426
  ...rankAndPage(source, sortName, sort, keepRows(lead.having, options, figures), left, offset, limit, {
2409
2427
  others: false,
@@ -2419,7 +2437,7 @@ function compileStreams(model, view, ctx) {
2419
2437
  } : range;
2420
2438
  return { ok: true, sql, columns, window: range, ...two ? { comparison: two.comparison } : {}, buckets, months: monthsRange(read), streams: streamKeys };
2421
2439
  }
2422
- function compileMatrix(model, view, ctx, byPeriod = false) {
2440
+ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2423
2441
  const options = view.options ?? {};
2424
2442
  const what = byPeriod ? "the long shape of a period view" : "matrix mode";
2425
2443
  if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
@@ -2438,6 +2456,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2438
2456
  const days = daysBetween(range.from, range.to);
2439
2457
  const uses = /* @__PURE__ */ new Set();
2440
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"` };
2441
2461
  const rowCode = scope.codeExpr;
2442
2462
  let colCode = `${FACT}."__b"`;
2443
2463
  let keep = buckets.length;
@@ -2477,22 +2497,24 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2477
2497
  if (!Number.isInteger(offset) || offset < 0) fail("bad_paging", "offset must be a whole number, 0 or more");
2478
2498
  const limit = Math.min(asked, room);
2479
2499
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2480
- const select = [`${rowCode} AS "code"`];
2481
- 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) => {
2482
2504
  const name = `prop__${property}`;
2483
- 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)}`);
2484
2506
  columns.push({ name, kind: "property", label: propertyLabel(groupDim, property), property });
2485
2507
  });
2486
- select.push(`${colCode} AS "across"`);
2508
+ select.push(folded ? '"across"' : `${colCode} AS "across"`);
2487
2509
  columns.push(acrossColumn);
2488
2510
  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"`);
2511
+ select.push(folded ? anyOf("across__name") : `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${scope.propertyOf(acrossColumn.dimension, "name")}) END AS "across__name"`);
2490
2512
  columns.push(acrossName);
2491
2513
  }
2492
2514
  const hidden = [];
2493
2515
  const addMeasure = (measure, seen) => {
2494
2516
  const name = `m__${measure.key}`;
2495
- 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)}`);
2496
2518
  if (seen) columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2497
2519
  else hidden.push(name);
2498
2520
  };
@@ -2512,7 +2534,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2512
2534
  } else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
2513
2535
  fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2514
2536
  }
2515
- 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));
2516
2539
  columns.push(
2517
2540
  { name: "__total", kind: "meta", label: "Total row" },
2518
2541
  { name: "__across_total", kind: "meta", label: "Row total" },
@@ -2533,14 +2556,41 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2533
2556
  const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
2534
2557
  const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
2535
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
+ });
2536
2584
  const sql = [
2537
2585
  // 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}), ())`,
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
+ ],
2544
2594
  // Rows are ranked, and filtered on a measure, by their totals across every column.
2545
2595
  "), rw AS (",
2546
2596
  `SELECT "code", row_number() OVER (ORDER BY ${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST, "code" ASC) AS "__row"`,
@@ -2571,7 +2621,8 @@ function compileMatrix(model, view, ctx, byPeriod = false) {
2571
2621
  shape: "long",
2572
2622
  ...byPeriod && options.reverse_periods ? { reversed: true } : {},
2573
2623
  limit,
2574
- ...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 } : {}
2575
2626
  };
2576
2627
  }
2577
2628
 
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.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",