@sprigr/apps-reporting-core 0.0.11 → 0.0.13
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 +16 -2
- package/dist/index.d.ts +25 -2
- package/dist/index.js +218 -49
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,6 +30,19 @@ run(out.sql, { params: out.params, months: out.months });
|
|
|
30
30
|
- A dimension's lookup table must hold one row per code, or sums multiply.
|
|
31
31
|
- "Today" is passed in, in the tenant's time zone.
|
|
32
32
|
|
|
33
|
+
## A stream's own filter
|
|
34
|
+
|
|
35
|
+
A stream can leave rows of its table out of every figure read from it:
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{ "key": "orders", "table": "order_lines", "date": "order_date", "dimension_keys": { "item": "item_code" },
|
|
39
|
+
"where": { "dimension": "item", "cmp": "not_in", "values": ["X1", "X2"] } }
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`where` takes the shape of a view's dimension filter: a rule (`dimension`, optional `property`, `cmp` of `in`, `not_in`, `contains` or `not_contains`, `values`) or a group (`op` of `and` or `or`, `rules`), nested at most three deep. It works as that filter does: a row with no value passes the two "not" rules, and a dimension can be reached through a parent. `validateModel` refuses a `where` whose dimension the stream does not reach, with `stream_filter_not_on_stream`, and a bad shape, comparison, property or value list with `stream_filter_invalid`, each with its path.
|
|
43
|
+
|
|
44
|
+
Every read of the stream goes through the filter: fact rows, the latest day a snapshot is read on, a member rule's own pass, a transaction list, and each window and stream of a view. A member list under `activity` drops the members the filter leaves out when the member's table can answer it. A rollup is read only when it keeps every dimension the filter names, and it is filtered the same way. `streams_filtered` in the result names each stream the statement read through its filter, so a reader can say the figures leave rows out.
|
|
45
|
+
|
|
33
46
|
## Rollups
|
|
34
47
|
|
|
35
48
|
The fact table is too big to hand to a browser; a rollup of it by month is not. A stream lists its rollups in the model:
|
|
@@ -46,7 +59,8 @@ The fact table is too big to hand to a browser; a rollup of it by month is not.
|
|
|
46
59
|
|
|
47
60
|
- a stream the view reads has no rollup holding every dimension and measure the view needs (a dimension reached through a parent needs the parent, and a formula needs every measure it reads);
|
|
48
61
|
- a window or period of the view does not start and end on the first of a month, such as a period to date, a week or a custom range of days;
|
|
49
|
-
- the view is a transaction list or reads a snapshot measure
|
|
62
|
+
- the view is a transaction list or reads a snapshot measure;
|
|
63
|
+
- a stream's `where` names a dimension the rollup does not keep, directly or through a parent.
|
|
50
64
|
|
|
51
65
|
Of the rollups that can answer, the one with the fewest dimensions is read, then the first listed. A view that does not compile at all refuses with its own reason. The statement still joins the dimension tables for names, properties and parent dimensions, so the caller loads those beside the rollup. `tables` in the result lists every table the statement reads, rollups and dimension tables alike, in the order it first reads them.
|
|
52
66
|
|
|
@@ -73,7 +87,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
|
|
|
73
87
|
- **Variance** reads the period and a comparison window (`compare`: `previous_year` for the same dates a year earlier, `previous_period` for the period just before, or `{ period }` for a window of its own, which may overlap the period or come after it) in one pass. Each measure gets four columns: current, previous, variance and variance percentage (a fraction).
|
|
74
88
|
- **Period variance** is a period view where every period is a variance. Each period gets four columns: its own value, the value of the period at the same place in the comparison window, the variance and the variance percentage. The same four over the whole windows follow. `compare` is read as in a variance. The comparison window is cut with the period's grain, and the view is refused when the two windows do not cut into the same number of periods. Columns are named `b<n>__`, `pb<n>__`, `bv<n>__` and `bvp<n>__` before the measure key, `<n>` counted from the oldest period; each carries `bucket: n` and its `part`. `sort.by` and a filter on a measure take what a period view and a variance take. The statement is always one column per period, and a view too wide for the route is refused.
|
|
75
89
|
- **A filter on a dimension** tests fact rows, on the code or on a property. `in` and `not_in` match whole values. `contains` and `not_contains` look for text anywhere in the value, whatever its case; a rule with several texts passes when any one is found, and a text can be up to 200 characters. A row with no value passes `not_in` and `not_contains`. Rules sit in groups joined by `and` or `or`, up to three deep, so a search over a code or a name is an `or` group of two `contains` rules. A data point of a custom view takes the same rules.
|
|
76
|
-
- **A filter on a member's own figure** names a dimension and a measure together: `{ dimension, measure, cmp, value, period? }`. It keeps the fact rows of the members whose figure passes, worked out over the rule's own `period` (the view's when it gives none), so "products that sold more than 100 last year" can filter a view of this month. It sits with the dimension rules, in `and` and `or` groups and in every mode. The figure is over all of the
|
|
90
|
+
- **A filter on a member's own figure** names a dimension and a measure together: `{ dimension, measure, cmp, value, period? }`. It keeps the fact rows of the members whose figure passes, worked out over the rule's own `period` (the view's when it gives none), so "products that sold more than 100 last year" can filter a view of this month. It sits with the dimension rules, in `and` and `or` groups and in every mode. The figure is over all of the rows of the measure's own stream in those dates, whatever else the view filters on, so "stock on hand over 0" can filter a view of sales. That stream must reach the rule's dimension, and a formula over two streams is refused. Each stream the view reads keeps the same members, and `compileRollupView` reads a rollup of the rule's stream too. A member with no rows on that stream has a sum or count of 0, as Phocas reads it, so "sales under 100" keeps products that sold nothing. Those members are listed from the dimension's table, or from the table of the dimension it hangs off, and a rule that 0 passes is refused on a dimension with neither. A snapshot figure, a formula and the other aggregates stay blank for such a member and pass no comparison. The result lists the dates each such rule reads in `ruleWindows`, and `months` covers them. A data point of a custom view does not take one.
|
|
77
91
|
- **A filter on a measure** drops rows after grouping. It never drops the total row, which stays the total of every member. A measure the view does not show can be filtered on. Dimension rules and measure rules combine with "and" only.
|
|
78
92
|
- **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
93
|
- **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.
|
package/dist/index.d.ts
CHANGED
|
@@ -199,7 +199,28 @@ interface ModelStream {
|
|
|
199
199
|
columns: ModelStreamColumn[];
|
|
200
200
|
/** Tables that hold this stream already added up by month. A view one of them covers can be answered from it. */
|
|
201
201
|
rollups: ModelRollup[];
|
|
202
|
+
/**
|
|
203
|
+
* Rows of the table the stream leaves out, in the shape a view's dimension filter takes. Every read of
|
|
204
|
+
* the stream keeps only the rows that pass, so the figures leave out those rows wherever they are read.
|
|
205
|
+
*/
|
|
206
|
+
where?: StreamFilter;
|
|
207
|
+
}
|
|
208
|
+
/** Keeps the rows whose code, or `property`, of a dimension passes, as a view's dimension rule does. */
|
|
209
|
+
interface StreamFilterRule {
|
|
210
|
+
dimension: string;
|
|
211
|
+
property?: string;
|
|
212
|
+
cmp: StreamFilterCmp;
|
|
213
|
+
values: string[];
|
|
214
|
+
}
|
|
215
|
+
interface StreamFilterGroup {
|
|
216
|
+
op: 'and' | 'or';
|
|
217
|
+
rules: StreamFilter[];
|
|
202
218
|
}
|
|
219
|
+
type StreamFilter = StreamFilterRule | StreamFilterGroup;
|
|
220
|
+
declare const STREAM_FILTER_CMPS: readonly ["in", "not_in", "contains", "not_contains"];
|
|
221
|
+
type StreamFilterCmp = (typeof STREAM_FILTER_CMPS)[number];
|
|
222
|
+
/** How deep a stream filter's groups may nest, as a view's filters may. */
|
|
223
|
+
declare const MAX_STREAM_FILTER_DEPTH = 3;
|
|
203
224
|
/**
|
|
204
225
|
* One rollup of a stream: its figures added up by month and by some of the stream's dimensions.
|
|
205
226
|
* It is small enough to hand to a browser, where the fact table is not.
|
|
@@ -271,7 +292,7 @@ interface ReportingModel {
|
|
|
271
292
|
measures: ModelMeasure[];
|
|
272
293
|
periods: PeriodCalendar;
|
|
273
294
|
}
|
|
274
|
-
declare const MODEL_PROBLEMS: readonly ["not_an_object", "unsupported_model_version", "no_streams", "missing_field", "bad_key", "bad_identifier", "duplicate_key", "unknown_stream", "unknown_dimension", "dimension_table_incomplete", "via_parent_has_no_table", "dimension_cycle", "measure_shape", "unknown_agg", "unknown_format", "formula_invalid", "formula_unknown_measure", "formula_cycle", "bad_fiscal_month", "bad_week_start", "bad_date", "period_range_inverted", "rollup_dimension_not_on_stream", "rollup_measure_unknown", "rollup_measure_not_additive", "reserved_table_name", "reserved_name"];
|
|
295
|
+
declare const MODEL_PROBLEMS: readonly ["not_an_object", "unsupported_model_version", "no_streams", "missing_field", "bad_key", "bad_identifier", "duplicate_key", "unknown_stream", "unknown_dimension", "dimension_table_incomplete", "via_parent_has_no_table", "dimension_cycle", "measure_shape", "unknown_agg", "unknown_format", "formula_invalid", "formula_unknown_measure", "formula_cycle", "bad_fiscal_month", "bad_week_start", "bad_date", "period_range_inverted", "rollup_dimension_not_on_stream", "rollup_measure_unknown", "rollup_measure_not_additive", "reserved_table_name", "reserved_name", "stream_filter_invalid", "stream_filter_not_on_stream"];
|
|
275
296
|
type ModelProblemReason = (typeof MODEL_PROBLEMS)[number];
|
|
276
297
|
interface ModelProblem {
|
|
277
298
|
reason: ModelProblemReason;
|
|
@@ -576,6 +597,8 @@ interface CompiledView {
|
|
|
576
597
|
limit?: number;
|
|
577
598
|
/** From `compileRollupView`: the rollup each stream is read from, in the order the statement reads them. */
|
|
578
599
|
rollups?: CompiledRollup[];
|
|
600
|
+
/** The streams the statement reads through their own `where`, so the figures leave rows of those tables out. */
|
|
601
|
+
streams_filtered?: string[];
|
|
579
602
|
}
|
|
580
603
|
interface CompiledRollup {
|
|
581
604
|
stream: string;
|
|
@@ -648,4 +671,4 @@ interface Grid {
|
|
|
648
671
|
*/
|
|
649
672
|
declare function pivotLong(compiled: CompiledView, rows: ResultRow[]): Grid;
|
|
650
673
|
|
|
651
|
-
export { type CompileContext, type CompiledColumn, type CompiledRollup, type CompiledView, DEFAULT_ACROSS_MEMBERS, DEFAULT_PAGE_ROWS, FORMULA_FUNCTIONS, FORMULA_MAX_CHARS, type FormulaBinaryOp, type FormulaEmitContext, type FormulaFunction, type FormulaNode, type Grid, type GridColumn, type GridFigures, type GridRow, MAX_PERIOD_BUCKETS, MEASURE_AGGS, MEASURE_CMPS, MEASURE_FORMATS, MODEL_PROBLEMS, MODEL_VERSION, type MeasureAgg, type MeasureFormat, type ModelBaseMeasure, type ModelDimension, type ModelFormulaMeasure, type ModelMeasure, type ModelProblem, type ModelProblemReason, type ModelProperty, type ModelRollup, type ModelStream, type ModelStreamColumn, type ModelValidation, type NamedPeriod, PERIOD_GRAINS, PERIOD_PRESETS, type PeriodBucket, type PeriodCalendar, type PeriodGrain, type PeriodPreset, type PeriodSpec, type PeriodWindow, RELATIVE_UNITS, REPORTING_REASONS, ROUTE_MAX_ROWS, ROUTE_MAX_SQL_CHARS, type Refusal, type RelativeUnit, ReportingError, type ReportingModel, type ReportingReason, type ResolvePeriodOptions, type ResolvedPeriod, type ResultRow, VARIANCE_PARTS, VIEW_MODES, type VariancePart, type ViewAcross, type ViewCalculation, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewNumberFormat, type ViewOptions, type ViewPathStep, type ViewSort, type ViewState, type WeekStart, addDays, addMonths, bindValues, comparisonWindow, compileRollupView, compileView, daysBetween, emitFormulaSql, fiscalYearStart, formulaRefs, inlineParams, isFormulaMeasure, isIdentifier, isIsoDate, isRouteWord, isStageName, likePattern, measureAvailability, monthsRange, parseFormula, pivotLong, quoteIdent, refusalOf, resolvePeriod, shownColumns, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, withCalculations, writtenLength };
|
|
674
|
+
export { type CompileContext, type CompiledColumn, type CompiledRollup, type CompiledView, DEFAULT_ACROSS_MEMBERS, DEFAULT_PAGE_ROWS, FORMULA_FUNCTIONS, FORMULA_MAX_CHARS, type FormulaBinaryOp, type FormulaEmitContext, type FormulaFunction, type FormulaNode, type Grid, type GridColumn, type GridFigures, type GridRow, MAX_PERIOD_BUCKETS, MAX_STREAM_FILTER_DEPTH, MEASURE_AGGS, MEASURE_CMPS, MEASURE_FORMATS, MODEL_PROBLEMS, MODEL_VERSION, type MeasureAgg, type MeasureFormat, type ModelBaseMeasure, type ModelDimension, type ModelFormulaMeasure, type ModelMeasure, type ModelProblem, type ModelProblemReason, type ModelProperty, type ModelRollup, type ModelStream, type ModelStreamColumn, type ModelValidation, type NamedPeriod, PERIOD_GRAINS, PERIOD_PRESETS, type PeriodBucket, type PeriodCalendar, type PeriodGrain, type PeriodPreset, type PeriodSpec, type PeriodWindow, RELATIVE_UNITS, REPORTING_REASONS, ROUTE_MAX_ROWS, ROUTE_MAX_SQL_CHARS, type Refusal, type RelativeUnit, ReportingError, type ReportingModel, type ReportingReason, type ResolvePeriodOptions, type ResolvedPeriod, type ResultRow, STREAM_FILTER_CMPS, type StreamFilter, type StreamFilterCmp, type StreamFilterGroup, type StreamFilterRule, VARIANCE_PARTS, VIEW_MODES, type VariancePart, type ViewAcross, type ViewCalculation, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewNumberFormat, type ViewOptions, type ViewPathStep, type ViewSort, type ViewState, type WeekStart, addDays, addMonths, bindValues, comparisonWindow, compileRollupView, compileView, daysBetween, emitFormulaSql, fiscalYearStart, formulaRefs, inlineParams, isFormulaMeasure, isIdentifier, isIsoDate, isRouteWord, isStageName, likePattern, measureAvailability, monthsRange, parseFormula, pivotLong, quoteIdent, refusalOf, resolvePeriod, shownColumns, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, withCalculations, writtenLength };
|
package/dist/index.js
CHANGED
|
@@ -767,6 +767,8 @@ function monthsRange(window) {
|
|
|
767
767
|
var MODEL_VERSION = 1;
|
|
768
768
|
var MEASURE_AGGS = ["sum", "count", "count_distinct", "min", "max", "avg"];
|
|
769
769
|
var MEASURE_FORMATS = ["number", "integer", "currency", "percent"];
|
|
770
|
+
var STREAM_FILTER_CMPS = ["in", "not_in", "contains", "not_contains"];
|
|
771
|
+
var MAX_STREAM_FILTER_DEPTH = 3;
|
|
770
772
|
var MODEL_PROBLEMS = [
|
|
771
773
|
"not_an_object",
|
|
772
774
|
"unsupported_model_version",
|
|
@@ -794,7 +796,9 @@ var MODEL_PROBLEMS = [
|
|
|
794
796
|
"rollup_measure_unknown",
|
|
795
797
|
"rollup_measure_not_additive",
|
|
796
798
|
"reserved_table_name",
|
|
797
|
-
"reserved_name"
|
|
799
|
+
"reserved_name",
|
|
800
|
+
"stream_filter_invalid",
|
|
801
|
+
"stream_filter_not_on_stream"
|
|
798
802
|
];
|
|
799
803
|
var KEY_RX = /^[a-z][a-z0-9_]{0,62}$/;
|
|
800
804
|
function isRec(v) {
|
|
@@ -915,6 +919,53 @@ function validateModel(input) {
|
|
|
915
919
|
cursor = cursor.via ? dimByKey.get(cursor.via.dimension) : void 0;
|
|
916
920
|
}
|
|
917
921
|
});
|
|
922
|
+
const onStream = (dimKey, keys, depth = 0) => {
|
|
923
|
+
if (has(keys, dimKey)) return true;
|
|
924
|
+
const via = dimByKey.get(dimKey)?.via;
|
|
925
|
+
return via !== void 0 && depth < 20 && onStream(via.dimension, keys, depth + 1);
|
|
926
|
+
};
|
|
927
|
+
const streamFilter = (raw, path, depth, keys) => {
|
|
928
|
+
const invalid = (detail) => {
|
|
929
|
+
bad("stream_filter_invalid", path, detail);
|
|
930
|
+
return null;
|
|
931
|
+
};
|
|
932
|
+
if (!isRec(raw)) return invalid("a stream filter is a rule or a group of rules");
|
|
933
|
+
if (raw.rules !== void 0 || raw.op !== void 0) {
|
|
934
|
+
if (depth > MAX_STREAM_FILTER_DEPTH) return invalid(`groups nest deeper than ${MAX_STREAM_FILTER_DEPTH} levels`);
|
|
935
|
+
const op = raw.op;
|
|
936
|
+
if (op !== "and" && op !== "or") return invalid('a group needs op "and" or "or"');
|
|
937
|
+
const rules = list(raw.rules);
|
|
938
|
+
if (rules.length === 0) return invalid("a group has no rules");
|
|
939
|
+
const kept = rules.map((rule, i) => streamFilter(rule, `${path}.rules[${i}]`, depth + 1, keys));
|
|
940
|
+
return kept.every((r) => r !== null) ? { op, rules: kept } : null;
|
|
941
|
+
}
|
|
942
|
+
if (raw.measure !== void 0) return invalid("a stream filter tests dimensions, not measures");
|
|
943
|
+
if (typeof raw.dimension !== "string") return invalid("a rule names a dimension");
|
|
944
|
+
const dim = dimByKey.get(raw.dimension);
|
|
945
|
+
if (!dim) {
|
|
946
|
+
bad("unknown_dimension", path, `no dimension "${raw.dimension}"`);
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
if (!onStream(dim.key, keys)) {
|
|
950
|
+
bad("stream_filter_not_on_stream", path, `the stream has no "${dim.key}", directly or through a parent`);
|
|
951
|
+
return null;
|
|
952
|
+
}
|
|
953
|
+
const property = raw.property === void 0 || raw.property === "code" ? void 0 : raw.property;
|
|
954
|
+
if (property !== void 0) {
|
|
955
|
+
const known = property === "name" && dim.name !== void 0 || dim.properties.some((p) => p.key === property);
|
|
956
|
+
if (!known) return invalid(`"${dim.key}" has no property "${String(property)}"`);
|
|
957
|
+
}
|
|
958
|
+
if (!STREAM_FILTER_CMPS.includes(raw.cmp)) return invalid(`cmp must be one of ${STREAM_FILTER_CMPS.join(", ")}`);
|
|
959
|
+
const cmp = raw.cmp;
|
|
960
|
+
const values = list(raw.values);
|
|
961
|
+
if (values.length === 0) return invalid("a rule needs at least one value");
|
|
962
|
+
if (!values.every((v) => typeof v === "string" || typeof v === "number")) return invalid("a value is text or a number");
|
|
963
|
+
const texts = values.map(String);
|
|
964
|
+
if ((cmp === "contains" || cmp === "not_contains") && texts.some((t) => t === "" || t.length > 200)) {
|
|
965
|
+
return invalid("a text to look for is 1 to 200 characters");
|
|
966
|
+
}
|
|
967
|
+
return { dimension: dim.key, ...typeof property === "string" ? { property } : {}, cmp, values: texts };
|
|
968
|
+
};
|
|
918
969
|
const streams = [];
|
|
919
970
|
const streamKeys = /* @__PURE__ */ new Set();
|
|
920
971
|
list(input.streams).forEach((raw, i) => {
|
|
@@ -979,7 +1030,12 @@ function validateModel(input) {
|
|
|
979
1030
|
});
|
|
980
1031
|
rollups.push({ key: rk, table: rollupTable, date: rollupDate, dimension_keys: kept, measure_columns });
|
|
981
1032
|
});
|
|
982
|
-
|
|
1033
|
+
const stream = { key: k, label: label(raw.label, k), table, date, dimension_keys, columns, rollups };
|
|
1034
|
+
if (raw.where !== void 0 && raw.where !== null) {
|
|
1035
|
+
const where = streamFilter(raw.where, `${path}.where`, 0, dimension_keys);
|
|
1036
|
+
if (where !== null) stream.where = where;
|
|
1037
|
+
}
|
|
1038
|
+
streams.push(stream);
|
|
983
1039
|
});
|
|
984
1040
|
if (streams.length === 0 && problems.length === 0) bad("no_streams", "streams", "a model needs at least one stream");
|
|
985
1041
|
const defaultStream = streams[0]?.key;
|
|
@@ -1236,7 +1292,7 @@ function stringList(values, what) {
|
|
|
1236
1292
|
}
|
|
1237
1293
|
function compileView(model, view, ctx) {
|
|
1238
1294
|
try {
|
|
1239
|
-
const full = withCalculations(model, view);
|
|
1295
|
+
const full = withStreamDimensions(withCalculations(model, view));
|
|
1240
1296
|
const compiled = compileMode(full, view, ctx);
|
|
1241
1297
|
const out = { ...compiled, columns: shownColumns(view, compiled.columns) };
|
|
1242
1298
|
const { sql, params } = bindValues(out.sql);
|
|
@@ -1246,7 +1302,16 @@ function compileView(model, view, ctx) {
|
|
|
1246
1302
|
(all, m) => ({ from: m.from < all.from ? m.from : all.from, to: m.to > all.to ? m.to : all.to }),
|
|
1247
1303
|
out.months
|
|
1248
1304
|
);
|
|
1249
|
-
|
|
1305
|
+
const filtered = model.streams.filter((s) => s.where !== void 0 && sql.includes(`AS ${filteredAlias(s)}`)).sort((a, b) => sql.indexOf(`AS ${filteredAlias(a)}`) - sql.indexOf(`AS ${filteredAlias(b)}`)).map((s) => s.key);
|
|
1306
|
+
return {
|
|
1307
|
+
...out,
|
|
1308
|
+
sql,
|
|
1309
|
+
params,
|
|
1310
|
+
months,
|
|
1311
|
+
...ruleWindows.length > 0 ? { ruleWindows } : {},
|
|
1312
|
+
tables: tablesIn(sql).filter((table) => known.has(table)),
|
|
1313
|
+
...filtered.length > 0 ? { streams_filtered: filtered } : {}
|
|
1314
|
+
};
|
|
1250
1315
|
} catch (err) {
|
|
1251
1316
|
return refusalOf(err);
|
|
1252
1317
|
}
|
|
@@ -1313,7 +1378,8 @@ function compileRollupView(model, view, ctx) {
|
|
|
1313
1378
|
}
|
|
1314
1379
|
let rolled = model;
|
|
1315
1380
|
const rollups = [];
|
|
1316
|
-
|
|
1381
|
+
const keys = [.../* @__PURE__ */ new Set([...plain.streams ?? [view.stream], ...memberRuleStreams(model, view)])];
|
|
1382
|
+
for (const key of keys) {
|
|
1317
1383
|
const listed = model.streams.find((s) => s.key === key)?.rollups ?? [];
|
|
1318
1384
|
const smallestFirst = [...listed].sort((a, b) => Object.keys(a.dimension_keys).length - Object.keys(b.dimension_keys).length);
|
|
1319
1385
|
const pick = smallestFirst.find((rollup) => compileView(onRollup(model, key, rollup), view, ctx).ok);
|
|
@@ -1351,6 +1417,113 @@ function memberWindows(model, view, ctx) {
|
|
|
1351
1417
|
if (view.filters) walk(view.filters);
|
|
1352
1418
|
return found;
|
|
1353
1419
|
}
|
|
1420
|
+
function measureStreams(measureByKey, key, depth = 0) {
|
|
1421
|
+
const measure = measureByKey.get(key);
|
|
1422
|
+
if (!measure) return /* @__PURE__ */ new Set();
|
|
1423
|
+
if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
|
|
1424
|
+
const found = /* @__PURE__ */ new Set();
|
|
1425
|
+
if (depth <= 20) formulaRefs(parseFormula(measure.formula)).forEach((ref) => measureStreams(measureByKey, ref, depth + 1).forEach((s) => found.add(s)));
|
|
1426
|
+
return found;
|
|
1427
|
+
}
|
|
1428
|
+
function memberRuleStream(model, key, fallback) {
|
|
1429
|
+
const streams = [...measureStreams(new Map(model.measures.map((m) => [m.key, m])), key)];
|
|
1430
|
+
if (streams.length > 1) fail2("measure_not_on_stream", `"${key}" reads streams ${streams.map((s) => `"${s}"`).join(" and ")}; a member rule tests its members on one`);
|
|
1431
|
+
return streams[0] ?? fallback;
|
|
1432
|
+
}
|
|
1433
|
+
function zeroPasses(cmp, value) {
|
|
1434
|
+
switch (cmp) {
|
|
1435
|
+
case "=":
|
|
1436
|
+
return value === 0;
|
|
1437
|
+
case "<>":
|
|
1438
|
+
return value !== 0;
|
|
1439
|
+
case "<":
|
|
1440
|
+
return 0 < value;
|
|
1441
|
+
case "<=":
|
|
1442
|
+
return 0 <= value;
|
|
1443
|
+
case ">":
|
|
1444
|
+
return 0 > value;
|
|
1445
|
+
case ">=":
|
|
1446
|
+
return 0 >= value;
|
|
1447
|
+
default:
|
|
1448
|
+
return false;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
function memberRuleStreams(model, view) {
|
|
1452
|
+
const found = [];
|
|
1453
|
+
const walk = (rule) => {
|
|
1454
|
+
if (isGroup(rule)) (Array.isArray(rule.rules) ? rule.rules : []).forEach(walk);
|
|
1455
|
+
else if (isMemberRule(rule)) {
|
|
1456
|
+
const key = memberRuleStream(model, rule.measure, view.stream);
|
|
1457
|
+
if (!found.includes(key)) found.push(key);
|
|
1458
|
+
}
|
|
1459
|
+
};
|
|
1460
|
+
if (view.filters) walk(view.filters);
|
|
1461
|
+
return found;
|
|
1462
|
+
}
|
|
1463
|
+
var inList = (values) => `(${values.map(sqlValue).join(", ")})`;
|
|
1464
|
+
function dimensionRuleSql(rule, resolve) {
|
|
1465
|
+
const whole = rule.cmp === "in" || rule.cmp === "not_in";
|
|
1466
|
+
if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
|
|
1467
|
+
const expr = resolve(rule.dimension, rule.property ?? "code");
|
|
1468
|
+
const what = `the filter on "${String(rule.dimension)}"`;
|
|
1469
|
+
const values = stringList(rule.values, what);
|
|
1470
|
+
if (whole) {
|
|
1471
|
+
return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
|
|
1472
|
+
}
|
|
1473
|
+
const found = values.map((text) => {
|
|
1474
|
+
if (text === "") fail2("empty_selection", `${what} holds an empty text to look for`);
|
|
1475
|
+
if (text.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1476
|
+
return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
|
|
1477
|
+
});
|
|
1478
|
+
const any = `(${found.join(" OR ")})`;
|
|
1479
|
+
return rule.cmp === "contains" ? any : `(${expr} IS NULL OR NOT ${any})`;
|
|
1480
|
+
}
|
|
1481
|
+
function streamFilterSql(filter, leaf, depth = 0) {
|
|
1482
|
+
if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `a stream filter nests deeper than ${MAX_FILTER_DEPTH} levels`);
|
|
1483
|
+
if (!("rules" in filter)) return leaf(filter);
|
|
1484
|
+
if (filter.rules.length === 0) fail2("empty_filter", "a stream filter group has no rules");
|
|
1485
|
+
return `(${filter.rules.map((rule) => streamFilterSql(rule, leaf, depth + 1)).join(filter.op === "and" ? " AND " : " OR ")})`;
|
|
1486
|
+
}
|
|
1487
|
+
var DIMENSIONS = /* @__PURE__ */ Symbol("model dimensions");
|
|
1488
|
+
function withStreamDimensions(model) {
|
|
1489
|
+
const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
|
|
1490
|
+
return { ...model, streams: model.streams.map((s) => ({ ...s, [DIMENSIONS]: dimByKey })) };
|
|
1491
|
+
}
|
|
1492
|
+
function filteredAlias(stream) {
|
|
1493
|
+
return quoteIdent(`w__${stream.key}`);
|
|
1494
|
+
}
|
|
1495
|
+
function sourceOf(stream) {
|
|
1496
|
+
if (!stream.where) return quoteIdent(stream.table);
|
|
1497
|
+
const dims = stream[DIMENSIONS] ?? fail2("unknown_dimension", `stream "${stream.key}" was read without its model`);
|
|
1498
|
+
const row = quoteIdent("__w");
|
|
1499
|
+
const joins = /* @__PURE__ */ new Map();
|
|
1500
|
+
const dimension = (key) => dims.get(key) ?? fail2("unknown_dimension", `no dimension "${String(key)}"`);
|
|
1501
|
+
const codeOf = (key, depth = 0) => {
|
|
1502
|
+
if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
|
|
1503
|
+
const direct = stream.dimension_keys[key];
|
|
1504
|
+
if (direct !== void 0) return `${row}.${quoteIdent(direct)}`;
|
|
1505
|
+
const dim = dimension(key);
|
|
1506
|
+
if (!dim.via) fail2("dimension_not_on_stream", `stream "${stream.key}" has no "${key}" for its filter`);
|
|
1507
|
+
const parent = dimension(dim.via.dimension);
|
|
1508
|
+
return `${joined(parent, codeOf(parent.key, depth + 1))}.${quoteIdent(dim.via.column)}`;
|
|
1509
|
+
};
|
|
1510
|
+
const joined = (dim, code) => {
|
|
1511
|
+
if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
|
|
1512
|
+
const a = quoteIdent(`__w_${dim.key}`);
|
|
1513
|
+
if (!joins.has(a)) joins.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${code}`);
|
|
1514
|
+
return a;
|
|
1515
|
+
};
|
|
1516
|
+
const resolve = (dimKey, property) => {
|
|
1517
|
+
const code = codeOf(dimKey);
|
|
1518
|
+
if (property === "code") return code;
|
|
1519
|
+
const dim = dimension(dimKey);
|
|
1520
|
+
const column = property === "name" ? dim.name : dim.properties.find((p) => p.key === property)?.column;
|
|
1521
|
+
if (column === void 0) fail2("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
|
|
1522
|
+
return `${joined(dim, code)}.${quoteIdent(column)}`;
|
|
1523
|
+
};
|
|
1524
|
+
const cond = streamFilterSql(stream.where, (rule) => dimensionRuleSql(rule, resolve));
|
|
1525
|
+
return `(${[`SELECT ${row}.* FROM ${quoteIdent(stream.table)} AS ${row}`, ...joins.values(), `WHERE ${cond}`].join(" ")}) AS ${filteredAlias(stream)}`;
|
|
1526
|
+
}
|
|
1354
1527
|
function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
1355
1528
|
const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
|
|
1356
1529
|
const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
|
|
@@ -1364,14 +1537,14 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1364
1537
|
if (!into.has(a)) into.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${codeExpr2}`);
|
|
1365
1538
|
return a;
|
|
1366
1539
|
};
|
|
1367
|
-
const codeOf = (key, depth = 0, into = joins) => {
|
|
1540
|
+
const codeOf = (key, depth = 0, into = joins, on = stream) => {
|
|
1368
1541
|
if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
|
|
1369
1542
|
const dim = dimension(key);
|
|
1370
|
-
const direct =
|
|
1543
|
+
const direct = on.dimension_keys[key];
|
|
1371
1544
|
if (direct !== void 0) return `${FACT}.${quoteIdent(direct)}`;
|
|
1372
|
-
if (!dim.via) fail2("dimension_not_on_stream", `stream "${
|
|
1545
|
+
if (!dim.via) fail2("dimension_not_on_stream", `stream "${on.key}" has no "${key}"`);
|
|
1373
1546
|
const parent = dimension(dim.via.dimension);
|
|
1374
|
-
return `${join(parent, codeOf(parent.key, depth + 1, into), into)}.${quoteIdent(dim.via.column)}`;
|
|
1547
|
+
return `${join(parent, codeOf(parent.key, depth + 1, into, on), into)}.${quoteIdent(dim.via.column)}`;
|
|
1375
1548
|
};
|
|
1376
1549
|
const columnOf = (dim, property) => {
|
|
1377
1550
|
const column = property === "name" ? dim.name : dim.properties.find((p) => p.key === property)?.column;
|
|
@@ -1424,7 +1597,6 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1424
1597
|
const mb = withMembers ? membersOf() : null;
|
|
1425
1598
|
const where = [];
|
|
1426
1599
|
const focus = [];
|
|
1427
|
-
const inList = (values) => `(${values.map(sqlValue).join(", ")})`;
|
|
1428
1600
|
(view.path ?? []).forEach((step) => {
|
|
1429
1601
|
const values = stringList(step?.selected, `the drill step on "${String(step?.dimension)}"`);
|
|
1430
1602
|
const kept = `CAST(${codeOf(step.dimension)} AS VARCHAR) IN ${inList(values)}`;
|
|
@@ -1432,40 +1604,36 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1432
1604
|
if (mb && mb.reaches(step.dimension)) mb.conds.push(`CAST(${mb.codeHere(step.dimension)} AS VARCHAR) IN ${inList(values)}`);
|
|
1433
1605
|
});
|
|
1434
1606
|
const filterMeasures = [];
|
|
1607
|
+
const memberSource = (dim) => {
|
|
1608
|
+
if (dim.table && dim.code) return { table: dim.table, column: dim.code };
|
|
1609
|
+
const parent = dim.via ? dimension(dim.via.dimension) : void 0;
|
|
1610
|
+
if (dim.via && parent?.table) return { table: parent.table, column: dim.via.column };
|
|
1611
|
+
return fail2("dimension_has_no_table", `"${dim.key}" has no table to list its members from`);
|
|
1612
|
+
};
|
|
1435
1613
|
const memberLeaf = (rule, outer) => {
|
|
1436
1614
|
if (!MEASURE_CMPS.includes(rule.cmp)) fail2("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
|
|
1437
1615
|
if (!measureByKey.has(rule.measure)) fail2("unknown_measure", `no measure "${String(rule.measure)}"`);
|
|
1616
|
+
const on = model.streams.find((s) => s.key === memberRuleStream(model, rule.measure, stream.key)) ?? stream;
|
|
1438
1617
|
const window = memberWindow(model, view, ctx, rule);
|
|
1439
1618
|
const own = /* @__PURE__ */ new Map();
|
|
1440
|
-
const member = codeOf(rule.dimension, 0, own);
|
|
1619
|
+
const member = codeOf(rule.dimension, 0, own, on);
|
|
1441
1620
|
const uses = /* @__PURE__ */ new Set();
|
|
1442
|
-
const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(window.from, window.to), uses };
|
|
1621
|
+
const reads = { stream: on, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(window.from, window.to), uses };
|
|
1443
1622
|
const figure = measureOver(reads, rule.measure, null);
|
|
1444
|
-
const
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1623
|
+
const value = sqlNumber(rule.value);
|
|
1624
|
+
const from = [`FROM ${factOver(on, window, uses.has("snapshot"))}`, ...own.values()].join(" ");
|
|
1625
|
+
const measure = measureByKey.get(rule.measure);
|
|
1626
|
+
const blankIsZero = measure !== void 0 && !isFormulaMeasure(measure) && !measure.snapshot && (measure.agg === "sum" || measure.agg === "count") && zeroPasses(rule.cmp, rule.value);
|
|
1627
|
+
if (!blankIsZero) return `CAST(${outer} AS VARCHAR) IN (SELECT CAST(${member} AS VARCHAR) ${from} GROUP BY ${member} HAVING ${figure} ${rule.cmp} ${value})`;
|
|
1628
|
+
const source = memberSource(dimension(rule.dimension));
|
|
1629
|
+
const listed = `"__mb".${quoteIdent(source.column)}`;
|
|
1630
|
+
const figures = `SELECT CAST(${member} AS VARCHAR) AS "__m", ${figure} AS "__v" ${from} GROUP BY ${member}`;
|
|
1631
|
+
return `CAST(${outer} AS VARCHAR) IN (SELECT CAST(${listed} AS VARCHAR) FROM ${quoteIdent(source.table)} AS "__mb" LEFT JOIN (${figures}) AS "__r" ON "__r"."__m" = CAST(${listed} AS VARCHAR) WHERE COALESCE("__r"."__v", 0) ${rule.cmp} ${value})`;
|
|
1450
1632
|
};
|
|
1451
1633
|
const dimensionLeafWith = (resolve) => (rule) => {
|
|
1452
1634
|
if (isMemberRule(rule)) return memberLeaf(rule, resolve(rule.dimension, "code"));
|
|
1453
1635
|
if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
|
|
1454
|
-
|
|
1455
|
-
if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
|
|
1456
|
-
const expr = resolve(rule.dimension, rule.property ?? "code");
|
|
1457
|
-
const what = `the filter on "${String(rule.dimension)}"`;
|
|
1458
|
-
const values = stringList(rule.values, what);
|
|
1459
|
-
if (whole) {
|
|
1460
|
-
return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
|
|
1461
|
-
}
|
|
1462
|
-
const found = values.map((text) => {
|
|
1463
|
-
if (text === "") fail2("empty_selection", `${what} holds an empty text to look for`);
|
|
1464
|
-
if (text.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1465
|
-
return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
|
|
1466
|
-
});
|
|
1467
|
-
const any = `(${found.join(" OR ")})`;
|
|
1468
|
-
return rule.cmp === "contains" ? any : `(${expr} IS NULL OR NOT ${any})`;
|
|
1636
|
+
return dimensionRuleSql(rule, resolve);
|
|
1469
1637
|
};
|
|
1470
1638
|
const dimensionLeaf = dimensionLeafWith(propertyOf);
|
|
1471
1639
|
const measureLeaf = (rule) => {
|
|
@@ -1513,6 +1681,12 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1513
1681
|
}
|
|
1514
1682
|
}
|
|
1515
1683
|
}
|
|
1684
|
+
const streamWhere = stream.where;
|
|
1685
|
+
if (mb && streamWhere) {
|
|
1686
|
+
const answerable = (f) => "rules" in f ? f.rules.every(answerable) : mb.reaches(f.dimension);
|
|
1687
|
+
const parts2 = "rules" in streamWhere && streamWhere.op === "and" ? streamWhere.rules.filter(answerable) : answerable(streamWhere) ? [streamWhere] : [];
|
|
1688
|
+
parts2.forEach((part) => mb.conds.push(streamFilterSql(part, (rule) => dimensionRuleSql(rule, mb.propertyHere))));
|
|
1689
|
+
}
|
|
1516
1690
|
const keyword = typeof view.keyword === "string" ? view.keyword.trim() : "";
|
|
1517
1691
|
if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1518
1692
|
if (keyword !== "") {
|
|
@@ -1650,7 +1824,7 @@ function measureOver(src, key, slice, depth = 0) {
|
|
|
1650
1824
|
function factOver(stream, range, latest) {
|
|
1651
1825
|
const date = quoteIdent(stream.date);
|
|
1652
1826
|
const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
|
|
1653
|
-
return latest ? withLatestDay(
|
|
1827
|
+
return latest ? withLatestDay(sourceOf(stream), date, "", within) : `(SELECT * FROM ${sourceOf(stream)} WHERE ${within}) AS ${FACT}`;
|
|
1654
1828
|
}
|
|
1655
1829
|
function withLatestDay(table, date, columns, where) {
|
|
1656
1830
|
return `(SELECT *${columns}, (${date} = (SELECT MAX(${date}) FROM ${table} WHERE ${where})) AS "__lastw" FROM ${table} WHERE ${where}) AS ${FACT}`;
|
|
@@ -1685,7 +1859,7 @@ function comparedWith(model, view, ctx, window) {
|
|
|
1685
1859
|
}
|
|
1686
1860
|
function factAcross(stream, range, buckets, comparison, latest, earlier = []) {
|
|
1687
1861
|
if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
|
|
1688
|
-
const table =
|
|
1862
|
+
const table = sourceOf(stream);
|
|
1689
1863
|
const date = quoteIdent(stream.date);
|
|
1690
1864
|
const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
|
|
1691
1865
|
if (!comparison) {
|
|
@@ -1945,7 +2119,7 @@ function compileGrouped(model, view, ctx) {
|
|
|
1945
2119
|
const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
|
|
1946
2120
|
const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
|
|
1947
2121
|
const periodOf = (parts2) => perBucket(date, parts2, (_, i) => i + 1);
|
|
1948
|
-
const fact = !uses.has("snapshot") ? `(SELECT *${factColumns} FROM ${
|
|
2122
|
+
const fact = !uses.has("snapshot") ? `(SELECT *${factColumns} FROM ${sourceOf(stream)} WHERE ${factWhere}) AS ${FACT}` : buckets.length === 0 && !comparison ? withLatestDay(sourceOf(stream), date, factColumns, factWhere) : !comparison ? withLatestDays(sourceOf(stream), date, periodOf(buckets), factColumns, factWhere) : withLatestDayOfEach(sourceOf(stream), date, factColumns, factWhere, [
|
|
1949
2123
|
{ where: inWindow(period.window), flag: "__lastc", ...periodVariance ? { periods: { by: periodOf(buckets), flag: "__last" } } : {} },
|
|
1950
2124
|
{ where: inWindow(comparison), flag: "__lastp", ...periodVariance ? { periods: { by: periodOf(earlierBuckets), flag: "__plast" } } : {} }
|
|
1951
2125
|
]);
|
|
@@ -2031,15 +2205,8 @@ function compileCustom(model, view, ctx) {
|
|
|
2031
2205
|
}
|
|
2032
2206
|
return found;
|
|
2033
2207
|
};
|
|
2034
|
-
const streamsOf = (measure
|
|
2035
|
-
|
|
2036
|
-
const found = /* @__PURE__ */ new Set();
|
|
2037
|
-
if (depth <= 20) {
|
|
2038
|
-
formulaRefs(parseFormula(measure.formula)).forEach((ref) => {
|
|
2039
|
-
const named = measureByKey.get(ref);
|
|
2040
|
-
if (named) streamsOf(named, depth + 1).forEach((key) => found.add(key));
|
|
2041
|
-
});
|
|
2042
|
-
}
|
|
2208
|
+
const streamsOf = (measure) => {
|
|
2209
|
+
const found = measureStreams(measureByKey, measure.key);
|
|
2043
2210
|
return found.size > 0 ? found : /* @__PURE__ */ new Set([stream.key]);
|
|
2044
2211
|
};
|
|
2045
2212
|
const points = [];
|
|
@@ -2157,7 +2324,7 @@ function compileCustom(model, view, ctx) {
|
|
|
2157
2324
|
const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
|
|
2158
2325
|
const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
|
|
2159
2326
|
const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
|
|
2160
|
-
const fact = uses.has("snapshot") ? withLatestDayOfEach(
|
|
2327
|
+
const fact = uses.has("snapshot") ? withLatestDayOfEach(sourceOf(stream), date, flags, anyWindow, windows.map((w, i) => ({ where: inWindow(w), flag: `__l${i + 1}` }))) : `(SELECT *${flags} FROM ${sourceOf(stream)} WHERE ${anyWindow}) AS ${FACT}`;
|
|
2161
2328
|
const streamKeys = [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && reading.has(key))];
|
|
2162
2329
|
const stages = !multi ? [] : streamKeys.map((key) => {
|
|
2163
2330
|
const { scope: s, reads: r, windows: used } = readsOf(key);
|
|
@@ -2178,7 +2345,7 @@ function compileCustom(model, view, ctx) {
|
|
|
2178
2345
|
const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
|
|
2179
2346
|
const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
|
|
2180
2347
|
const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
|
|
2181
|
-
const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(
|
|
2348
|
+
const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(sourceOf(s.stream), sDate, `, ${sFlags}`, sAny, mine.map((n) => ({ where: sIn(windows[n - 1]), flag: `__l${n}` }))) : `(SELECT *, ${sFlags} FROM ${sourceOf(s.stream)} WHERE ${sAny}) AS ${FACT}`;
|
|
2182
2349
|
const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
|
|
2183
2350
|
return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
|
|
2184
2351
|
});
|
|
@@ -2284,7 +2451,7 @@ function compileTransactions(model, view, ctx) {
|
|
|
2284
2451
|
const sql = [
|
|
2285
2452
|
"WITH g AS (",
|
|
2286
2453
|
`SELECT ${select.join(", ")}`,
|
|
2287
|
-
`FROM (SELECT * FROM ${
|
|
2454
|
+
`FROM (SELECT * FROM ${sourceOf(stream)} WHERE ${date} >= ${sqlDate(period.window.from)} AND ${date} < ${sqlDate(period.window.to)}) AS ${FACT}`,
|
|
2288
2455
|
...scope.joins.values(),
|
|
2289
2456
|
...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
|
|
2290
2457
|
"), r AS (",
|
|
@@ -2665,7 +2832,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2665
2832
|
const numbered = perBucket(date, buckets, (_, i) => i + 1);
|
|
2666
2833
|
const added = `, ${numbered} AS "__b"${perDay}`;
|
|
2667
2834
|
const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
|
|
2668
|
-
fact = uses.has("snapshot") ? withLatestDays(
|
|
2835
|
+
fact = uses.has("snapshot") ? withLatestDays(sourceOf(stream), date, numbered, added, within) : `(SELECT *${added} FROM ${sourceOf(stream)} WHERE ${within}) AS ${FACT}`;
|
|
2669
2836
|
}
|
|
2670
2837
|
const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
|
|
2671
2838
|
const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
|
|
@@ -2807,6 +2974,7 @@ export {
|
|
|
2807
2974
|
FORMULA_FUNCTIONS,
|
|
2808
2975
|
FORMULA_MAX_CHARS,
|
|
2809
2976
|
MAX_PERIOD_BUCKETS,
|
|
2977
|
+
MAX_STREAM_FILTER_DEPTH,
|
|
2810
2978
|
MEASURE_AGGS,
|
|
2811
2979
|
MEASURE_CMPS,
|
|
2812
2980
|
MEASURE_FORMATS,
|
|
@@ -2819,6 +2987,7 @@ export {
|
|
|
2819
2987
|
ROUTE_MAX_ROWS,
|
|
2820
2988
|
ROUTE_MAX_SQL_CHARS,
|
|
2821
2989
|
ReportingError,
|
|
2990
|
+
STREAM_FILTER_CMPS,
|
|
2822
2991
|
VARIANCE_PARTS,
|
|
2823
2992
|
VIEW_MODES,
|
|
2824
2993
|
addDays,
|
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.13",
|
|
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",
|