@sprigr/apps-reporting-core 0.0.8 → 0.0.10
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.
- package/README.md +3 -3
- package/dist/index.js +82 -34
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -78,9 +78,9 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
|
|
|
78
78
|
- **Transaction** lists the fact rows: the date as text, every dimension code of the stream, the stream's extra `columns`, and each measure as that row holds it (a count is 1).
|
|
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
|
-
- **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.
|
|
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. A period view takes the long shape as a view of one stream does: each stream groups by member and period in its own stage, the stages are folded by cell, and a formula, `DAYS()`, a snapshot measure and a sort on one period read the folded sums. A variance or period variance view is always one column per period, and is refused when too wide for the route. A custom view reads one through its points, below.
|
|
82
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
|
|
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,
|
|
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
|
@@ -1202,8 +1202,23 @@ function compileMode(model, view, ctx) {
|
|
|
1202
1202
|
try {
|
|
1203
1203
|
return direct ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
|
|
1204
1204
|
} catch (err) {
|
|
1205
|
-
if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream"
|
|
1206
|
-
|
|
1205
|
+
if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream") throw err;
|
|
1206
|
+
if (direct || view.mode !== "period" || ctx.periodShape === "wide") {
|
|
1207
|
+
if (!direct && ctx.periodShape === "long") throw err;
|
|
1208
|
+
return compileStreams(model, view, ctx);
|
|
1209
|
+
}
|
|
1210
|
+
if (ctx.periodShape === "long") return compileMatrix(model, view, ctx, true, true);
|
|
1211
|
+
try {
|
|
1212
|
+
return compileStreams(model, view, ctx);
|
|
1213
|
+
} catch (tooLong) {
|
|
1214
|
+
if (!(tooLong instanceof ReportingError) || tooLong.reason !== "sql_too_long") throw tooLong;
|
|
1215
|
+
try {
|
|
1216
|
+
return compileMatrix(model, view, ctx, true, true);
|
|
1217
|
+
} catch (longErr) {
|
|
1218
|
+
if (longErr instanceof ReportingError) throw tooLong;
|
|
1219
|
+
throw longErr;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1207
1222
|
}
|
|
1208
1223
|
}
|
|
1209
1224
|
function compileOneStream(model, view, ctx) {
|
|
@@ -1950,20 +1965,24 @@ function compileCustom(model, view, ctx) {
|
|
|
1950
1965
|
}
|
|
1951
1966
|
return found;
|
|
1952
1967
|
};
|
|
1953
|
-
const
|
|
1954
|
-
if (!isFormulaMeasure(measure)) return measure.stream;
|
|
1955
|
-
const
|
|
1956
|
-
|
|
1968
|
+
const streamsOf = (measure, depth = 0) => {
|
|
1969
|
+
if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
|
|
1970
|
+
const found = /* @__PURE__ */ new Set();
|
|
1971
|
+
if (depth <= 20) {
|
|
1972
|
+
formulaRefs(parseFormula(measure.formula)).forEach((ref) => {
|
|
1973
|
+
const named = measureByKey.get(ref);
|
|
1974
|
+
if (named) streamsOf(named, depth + 1).forEach((key) => found.add(key));
|
|
1975
|
+
});
|
|
1976
|
+
}
|
|
1977
|
+
return found.size > 0 ? found : /* @__PURE__ */ new Set([stream.key]);
|
|
1957
1978
|
};
|
|
1958
1979
|
const points = [];
|
|
1959
1980
|
const pointOf = (point, what) => {
|
|
1960
1981
|
if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
|
|
1961
1982
|
const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
|
|
1962
1983
|
const { window, number } = windowOf(point.period);
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
src.windows.add(number);
|
|
1966
|
-
const rule = point.where === void 0 ? "" : ` AND ${src.scope.dimensionRule(point.where)}`;
|
|
1984
|
+
const where2 = point.where;
|
|
1985
|
+
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`);
|
|
1967
1986
|
const bucket = {
|
|
1968
1987
|
key: `w${number}`,
|
|
1969
1988
|
label: `${window.from} to ${addDays(window.to, -1)}`,
|
|
@@ -1971,11 +1990,25 @@ function compileCustom(model, view, ctx) {
|
|
|
1971
1990
|
to: window.to,
|
|
1972
1991
|
days: daysBetween(window.from, window.to)
|
|
1973
1992
|
};
|
|
1974
|
-
const
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1993
|
+
const read = (m, depth) => {
|
|
1994
|
+
const streams = streamsOf(m);
|
|
1995
|
+
if (streams.size > 1 && isFormulaMeasure(m)) {
|
|
1996
|
+
if (depth > 20) fail("formula_cycle", `"${m.key}" refers back to itself`);
|
|
1997
|
+
return emitFormulaSql(parseFormula(m.formula), {
|
|
1998
|
+
measure: (ref) => read(measureByKey.get(ref) ?? fail("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
|
|
1999
|
+
days: bucket.days
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
const src = readsOf([...streams][0] ?? stream.key);
|
|
2003
|
+
src.windows.add(number);
|
|
2004
|
+
const rule = where2 === void 0 ? "" : ` AND ${src.scope.dimensionRule(where2)}`;
|
|
2005
|
+
const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
|
|
2006
|
+
const sql2 = `CAST(${measureOver(src.reads, m.key, slice)} AS DOUBLE)`;
|
|
2007
|
+
const key = src.scope.stream.key;
|
|
2008
|
+
const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
|
|
2009
|
+
return quoteIdent(`p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`);
|
|
2010
|
+
};
|
|
2011
|
+
return { ref: read(measure, 0), measure, bucket };
|
|
1979
2012
|
};
|
|
1980
2013
|
const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
|
|
1981
2014
|
const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
|
|
@@ -2001,13 +2034,13 @@ function compileCustom(model, view, ctx) {
|
|
|
2001
2034
|
const cur = pointOf(column.point, `"${key}"`);
|
|
2002
2035
|
if (column.against === void 0) {
|
|
2003
2036
|
if (column.show !== void 0) fail("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
|
|
2004
|
-
expr =
|
|
2037
|
+
expr = cur.ref;
|
|
2005
2038
|
about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
|
|
2006
2039
|
} else {
|
|
2007
2040
|
const prev = pointOf(column.against, `"${key}"`);
|
|
2008
2041
|
const show = column.show ?? "difference";
|
|
2009
2042
|
if (show !== "difference" && show !== "percent") fail("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
|
|
2010
|
-
expr = show === "difference" ? `COALESCE(${
|
|
2043
|
+
expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
|
|
2011
2044
|
about = {
|
|
2012
2045
|
label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
|
|
2013
2046
|
measure: cur.measure.key,
|
|
@@ -2022,7 +2055,7 @@ function compileCustom(model, view, ctx) {
|
|
|
2022
2055
|
expr = emitFormulaSql(parseFormula(String(column.expression)), {
|
|
2023
2056
|
measure: (ref) => {
|
|
2024
2057
|
if (!Object.prototype.hasOwnProperty.call(named, ref)) fail("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
|
|
2025
|
-
return
|
|
2058
|
+
return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
|
|
2026
2059
|
},
|
|
2027
2060
|
days: reads.days
|
|
2028
2061
|
});
|
|
@@ -2037,7 +2070,6 @@ function compileCustom(model, view, ctx) {
|
|
|
2037
2070
|
if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
|
|
2038
2071
|
if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
|
|
2039
2072
|
const multi = reading.size > 1;
|
|
2040
|
-
if (multi && nest) fail("option_unsupported", "nested rows are not compiled for a custom view of more than one stream yet");
|
|
2041
2073
|
points.forEach(({ sql: sql2 }, i) => {
|
|
2042
2074
|
select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
|
|
2043
2075
|
left.push(`p${i + 1}`);
|
|
@@ -2064,31 +2096,38 @@ function compileCustom(model, view, ctx) {
|
|
|
2064
2096
|
const stages = !multi ? [] : streamKeys.map((key) => {
|
|
2065
2097
|
const { scope: s, reads: r, windows: used } = readsOf(key);
|
|
2066
2098
|
const grouped = `GROUPING(${s.codeExpr})`;
|
|
2067
|
-
const
|
|
2099
|
+
const levels = nest ? nestOf(view, s) : null;
|
|
2100
|
+
const parts2 = [...levels?.select ?? [], `${s.codeExpr} AS "code"`];
|
|
2068
2101
|
shownProperties(view).forEach((property) => {
|
|
2069
2102
|
const expr = `any_value(${s.propertyOf(groupDim.key, property)})`;
|
|
2070
|
-
parts2.push(`${totalRow ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
|
|
2103
|
+
parts2.push(`${totalRow || levels ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
|
|
2071
2104
|
});
|
|
2072
2105
|
points.forEach((p, i) => {
|
|
2073
2106
|
if (p.stream === key) parts2.push(`${p.sql} AS ${quoteIdent(`p${i + 1}`)}`);
|
|
2074
2107
|
});
|
|
2075
|
-
parts2.push(`${totalRow ? `CAST(${grouped} AS INTEGER)` : "0"} AS "__total"`);
|
|
2108
|
+
parts2.push(`${totalRow ? `CAST(${levels ? levels.total : grouped} AS INTEGER)` : "0"} AS "__total"`);
|
|
2109
|
+
if (levels) parts2.push(levels.level);
|
|
2076
2110
|
const mine = [...used].sort((a, b) => a - b);
|
|
2077
2111
|
const sDate = quoteIdent(s.stream.date);
|
|
2078
2112
|
const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
|
|
2079
2113
|
const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
|
|
2080
2114
|
const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
|
|
2081
2115
|
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}`;
|
|
2082
|
-
|
|
2116
|
+
const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
|
|
2117
|
+
return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
|
|
2083
2118
|
});
|
|
2119
|
+
const anyOf = (name) => `any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`;
|
|
2084
2120
|
const fold = [
|
|
2121
|
+
...(nest?.columns ?? []).map((c) => c.property === "name" ? anyOf(c.name) : quoteIdent(c.name)),
|
|
2085
2122
|
'"code"',
|
|
2086
|
-
...shownProperties(view).map((property) =>
|
|
2087
|
-
...points.map((_, i) =>
|
|
2088
|
-
'"__total"'
|
|
2123
|
+
...shownProperties(view).map((property) => anyOf(`prop__${property}`)),
|
|
2124
|
+
...points.map((_, i) => anyOf(`p${i + 1}`)),
|
|
2125
|
+
'"__total"',
|
|
2126
|
+
...nest ? ['"__level"'] : []
|
|
2089
2127
|
];
|
|
2128
|
+
const foldKeys = [...nest ? Array.from({ length: nest.count }, (_, i) => quoteIdent(`lv${i + 1}`)) : [], '"code"', '"__total"', ...nest ? ['"__level"'] : []];
|
|
2090
2129
|
const sql = [
|
|
2091
|
-
...multi ? foldStreams(stages, fold,
|
|
2130
|
+
...multi ? foldStreams(stages, fold, foldKeys) : [
|
|
2092
2131
|
"WITH g AS (",
|
|
2093
2132
|
`SELECT ${select.join(", ")}`,
|
|
2094
2133
|
`FROM ${fact}`,
|
|
@@ -2225,7 +2264,7 @@ function foldedMeasures(measureByKey, periodCount) {
|
|
|
2225
2264
|
}
|
|
2226
2265
|
return emitFormulaSql(node, {
|
|
2227
2266
|
measure: (ref) => exprOf(ref, part, depth + 1),
|
|
2228
|
-
days: part.days,
|
|
2267
|
+
...part.daysSql !== void 0 ? { daysSql: part.daysSql } : { days: part.days },
|
|
2229
2268
|
...periodCount > 0 ? { periodCount } : {}
|
|
2230
2269
|
});
|
|
2231
2270
|
}
|
|
@@ -2238,7 +2277,7 @@ function foldedMeasures(measureByKey, periodCount) {
|
|
|
2238
2277
|
}
|
|
2239
2278
|
function streamSum(measure, over) {
|
|
2240
2279
|
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})`;
|
|
2280
|
+
const sum = measure.snapshot && over.cellWhen !== void 0 ? `CASE WHEN ${over.cellWhen} THEN ${call} FILTER (WHERE ${FACT}."__last") ELSE ${call} FILTER (WHERE ${over.last}) END` : 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
2281
|
return `${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`;
|
|
2243
2282
|
}
|
|
2244
2283
|
function compileStreams(model, view, ctx) {
|
|
@@ -2456,8 +2495,16 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2456
2495
|
const days = daysBetween(range.from, range.to);
|
|
2457
2496
|
const uses = /* @__PURE__ */ new Set();
|
|
2458
2497
|
const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days, uses };
|
|
2459
|
-
const folded = streams ? foldedMeasures(measureByKey,
|
|
2460
|
-
const whole =
|
|
2498
|
+
const folded = streams ? foldedMeasures(measureByKey, buckets.length) : null;
|
|
2499
|
+
const whole = byPeriod ? {
|
|
2500
|
+
prefix: "a",
|
|
2501
|
+
days,
|
|
2502
|
+
filter: null,
|
|
2503
|
+
last: `${FACT}."__lastw"`,
|
|
2504
|
+
cellWhen: `GROUPING(${FACT}."__b") = 0`,
|
|
2505
|
+
// A folded row is a cell when it has a period number, and a total over the whole window when it has none.
|
|
2506
|
+
daysSql: `CASE ${buckets.map((b, i) => `WHEN "across" = ${i + 1} THEN ${sqlNumber(b.days)}`).join(" ")} ELSE ${sqlNumber(days)} END`
|
|
2507
|
+
} : { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
|
|
2461
2508
|
const rowCode = scope.codeExpr;
|
|
2462
2509
|
let colCode = `${FACT}."__b"`;
|
|
2463
2510
|
let keep = buckets.length;
|
|
@@ -2528,7 +2575,8 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2528
2575
|
if (bucket && shown.some((measure) => measure.key === byOne[2])) {
|
|
2529
2576
|
const n = buckets.indexOf(bucket) + 1;
|
|
2530
2577
|
const slice = { bucket, filter: `${FACT}."__b" = ${n}`, last: `${FACT}."__b" = ${n} AND ${FACT}."__last"` };
|
|
2531
|
-
|
|
2578
|
+
const part = { prefix: `a${n}`, days: bucket.days, filter: slice.filter, last: slice.last };
|
|
2579
|
+
select.push(`CAST(${folded ? folded.exprOf(String(byOne[2]), part, 0) : measureOver(reads, String(byOne[2]), slice)} AS DOUBLE) AS "__sort"`);
|
|
2532
2580
|
hidden.push("__sort");
|
|
2533
2581
|
sortName = "__sort";
|
|
2534
2582
|
} else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
|
|
@@ -2561,7 +2609,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2561
2609
|
const stages = streamKeys.map((key, i) => {
|
|
2562
2610
|
const own = i === 0 ? scope : scopeOf(model, { ...view, stream: key }, ctx);
|
|
2563
2611
|
const row = own.codeExpr;
|
|
2564
|
-
const col = own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
|
|
2612
|
+
const col = byPeriod ? `${FACT}."__b"` : own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
|
|
2565
2613
|
const mine = folded?.needed.get(key) ?? [];
|
|
2566
2614
|
const part = [`${row} AS "code"`];
|
|
2567
2615
|
properties.forEach((property) => {
|
|
@@ -2575,7 +2623,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2575
2623
|
part.push(...flags(row, col));
|
|
2576
2624
|
return {
|
|
2577
2625
|
select: part,
|
|
2578
|
-
from: factAcross(own.stream, range,
|
|
2626
|
+
from: factAcross(own.stream, range, buckets, null, mine.some(({ measure }) => measure.snapshot)),
|
|
2579
2627
|
joins: [...own.joins.values()],
|
|
2580
2628
|
where: own.where,
|
|
2581
2629
|
groupBy: sets(row, col)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sprigr/apps-reporting-core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.10",
|
|
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",
|