@sprigr/apps-reporting-core 0.0.12 → 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 +15 -1
- package/dist/index.d.ts +25 -2
- package/dist/index.js +149 -27
- 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
|
|
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
|
}
|
|
@@ -1395,6 +1460,70 @@ function memberRuleStreams(model, view) {
|
|
|
1395
1460
|
if (view.filters) walk(view.filters);
|
|
1396
1461
|
return found;
|
|
1397
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
|
+
}
|
|
1398
1527
|
function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
1399
1528
|
const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
|
|
1400
1529
|
const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
|
|
@@ -1468,7 +1597,6 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1468
1597
|
const mb = withMembers ? membersOf() : null;
|
|
1469
1598
|
const where = [];
|
|
1470
1599
|
const focus = [];
|
|
1471
|
-
const inList = (values) => `(${values.map(sqlValue).join(", ")})`;
|
|
1472
1600
|
(view.path ?? []).forEach((step) => {
|
|
1473
1601
|
const values = stringList(step?.selected, `the drill step on "${String(step?.dimension)}"`);
|
|
1474
1602
|
const kept = `CAST(${codeOf(step.dimension)} AS VARCHAR) IN ${inList(values)}`;
|
|
@@ -1505,21 +1633,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1505
1633
|
const dimensionLeafWith = (resolve) => (rule) => {
|
|
1506
1634
|
if (isMemberRule(rule)) return memberLeaf(rule, resolve(rule.dimension, "code"));
|
|
1507
1635
|
if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
|
|
1508
|
-
|
|
1509
|
-
if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
|
|
1510
|
-
const expr = resolve(rule.dimension, rule.property ?? "code");
|
|
1511
|
-
const what = `the filter on "${String(rule.dimension)}"`;
|
|
1512
|
-
const values = stringList(rule.values, what);
|
|
1513
|
-
if (whole) {
|
|
1514
|
-
return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
|
|
1515
|
-
}
|
|
1516
|
-
const found = values.map((text) => {
|
|
1517
|
-
if (text === "") fail2("empty_selection", `${what} holds an empty text to look for`);
|
|
1518
|
-
if (text.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1519
|
-
return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
|
|
1520
|
-
});
|
|
1521
|
-
const any = `(${found.join(" OR ")})`;
|
|
1522
|
-
return rule.cmp === "contains" ? any : `(${expr} IS NULL OR NOT ${any})`;
|
|
1636
|
+
return dimensionRuleSql(rule, resolve);
|
|
1523
1637
|
};
|
|
1524
1638
|
const dimensionLeaf = dimensionLeafWith(propertyOf);
|
|
1525
1639
|
const measureLeaf = (rule) => {
|
|
@@ -1567,6 +1681,12 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1567
1681
|
}
|
|
1568
1682
|
}
|
|
1569
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
|
+
}
|
|
1570
1690
|
const keyword = typeof view.keyword === "string" ? view.keyword.trim() : "";
|
|
1571
1691
|
if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1572
1692
|
if (keyword !== "") {
|
|
@@ -1704,7 +1824,7 @@ function measureOver(src, key, slice, depth = 0) {
|
|
|
1704
1824
|
function factOver(stream, range, latest) {
|
|
1705
1825
|
const date = quoteIdent(stream.date);
|
|
1706
1826
|
const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
|
|
1707
|
-
return latest ? withLatestDay(
|
|
1827
|
+
return latest ? withLatestDay(sourceOf(stream), date, "", within) : `(SELECT * FROM ${sourceOf(stream)} WHERE ${within}) AS ${FACT}`;
|
|
1708
1828
|
}
|
|
1709
1829
|
function withLatestDay(table, date, columns, where) {
|
|
1710
1830
|
return `(SELECT *${columns}, (${date} = (SELECT MAX(${date}) FROM ${table} WHERE ${where})) AS "__lastw" FROM ${table} WHERE ${where}) AS ${FACT}`;
|
|
@@ -1739,7 +1859,7 @@ function comparedWith(model, view, ctx, window) {
|
|
|
1739
1859
|
}
|
|
1740
1860
|
function factAcross(stream, range, buckets, comparison, latest, earlier = []) {
|
|
1741
1861
|
if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
|
|
1742
|
-
const table =
|
|
1862
|
+
const table = sourceOf(stream);
|
|
1743
1863
|
const date = quoteIdent(stream.date);
|
|
1744
1864
|
const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
|
|
1745
1865
|
if (!comparison) {
|
|
@@ -1999,7 +2119,7 @@ function compileGrouped(model, view, ctx) {
|
|
|
1999
2119
|
const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
|
|
2000
2120
|
const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
|
|
2001
2121
|
const periodOf = (parts2) => perBucket(date, parts2, (_, i) => i + 1);
|
|
2002
|
-
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, [
|
|
2003
2123
|
{ where: inWindow(period.window), flag: "__lastc", ...periodVariance ? { periods: { by: periodOf(buckets), flag: "__last" } } : {} },
|
|
2004
2124
|
{ where: inWindow(comparison), flag: "__lastp", ...periodVariance ? { periods: { by: periodOf(earlierBuckets), flag: "__plast" } } : {} }
|
|
2005
2125
|
]);
|
|
@@ -2204,7 +2324,7 @@ function compileCustom(model, view, ctx) {
|
|
|
2204
2324
|
const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
|
|
2205
2325
|
const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
|
|
2206
2326
|
const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
|
|
2207
|
-
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}`;
|
|
2208
2328
|
const streamKeys = [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && reading.has(key))];
|
|
2209
2329
|
const stages = !multi ? [] : streamKeys.map((key) => {
|
|
2210
2330
|
const { scope: s, reads: r, windows: used } = readsOf(key);
|
|
@@ -2225,7 +2345,7 @@ function compileCustom(model, view, ctx) {
|
|
|
2225
2345
|
const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
|
|
2226
2346
|
const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
|
|
2227
2347
|
const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
|
|
2228
|
-
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}`;
|
|
2229
2349
|
const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
|
|
2230
2350
|
return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
|
|
2231
2351
|
});
|
|
@@ -2331,7 +2451,7 @@ function compileTransactions(model, view, ctx) {
|
|
|
2331
2451
|
const sql = [
|
|
2332
2452
|
"WITH g AS (",
|
|
2333
2453
|
`SELECT ${select.join(", ")}`,
|
|
2334
|
-
`FROM (SELECT * FROM ${
|
|
2454
|
+
`FROM (SELECT * FROM ${sourceOf(stream)} WHERE ${date} >= ${sqlDate(period.window.from)} AND ${date} < ${sqlDate(period.window.to)}) AS ${FACT}`,
|
|
2335
2455
|
...scope.joins.values(),
|
|
2336
2456
|
...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
|
|
2337
2457
|
"), r AS (",
|
|
@@ -2712,7 +2832,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2712
2832
|
const numbered = perBucket(date, buckets, (_, i) => i + 1);
|
|
2713
2833
|
const added = `, ${numbered} AS "__b"${perDay}`;
|
|
2714
2834
|
const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
|
|
2715
|
-
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}`;
|
|
2716
2836
|
}
|
|
2717
2837
|
const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
|
|
2718
2838
|
const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
|
|
@@ -2854,6 +2974,7 @@ export {
|
|
|
2854
2974
|
FORMULA_FUNCTIONS,
|
|
2855
2975
|
FORMULA_MAX_CHARS,
|
|
2856
2976
|
MAX_PERIOD_BUCKETS,
|
|
2977
|
+
MAX_STREAM_FILTER_DEPTH,
|
|
2857
2978
|
MEASURE_AGGS,
|
|
2858
2979
|
MEASURE_CMPS,
|
|
2859
2980
|
MEASURE_FORMATS,
|
|
@@ -2866,6 +2987,7 @@ export {
|
|
|
2866
2987
|
ROUTE_MAX_ROWS,
|
|
2867
2988
|
ROUTE_MAX_SQL_CHARS,
|
|
2868
2989
|
ReportingError,
|
|
2990
|
+
STREAM_FILTER_CMPS,
|
|
2869
2991
|
VARIANCE_PARTS,
|
|
2870
2992
|
VIEW_MODES,
|
|
2871
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",
|