@sprigr/apps-reporting-core 0.0.9 → 0.0.11
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 +4 -1
- package/dist/index.d.ts +41 -2
- package/dist/index.js +216 -124
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -78,7 +78,7 @@ 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
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.
|
|
@@ -89,6 +89,9 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
|
|
|
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
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
|
+
- **Calculations of the view** (`calculations`, every mode): measures a saved view defines for itself, each a `key` no model measure holds, a `formula` over model measures and the calculations listed before it, an optional `label` (the key when left out) and `format` (`number` when left out). A view lists one in `measures`, sorts on it and a custom column reads it like a measure of the model, and it compiles as the same formula measure in the model would. A key already in the model or listed twice, or a format that is not a measure format, refuses with `bad_calculation`; a formula naming a later calculation or itself refuses with `formula_unknown_measure`.
|
|
93
|
+
- **Hidden columns** (`hidden_columns`, every mode): measure columns of the result, by name such as `m__qty` or `prev__sales`, left out of `columns`, so a grid, `pivotLong` and an export never show them. The statement is unchanged, so a sort still reads a hidden column. A name that is not a measure column of the view refuses with `unknown_column`, and hiding every one with `no_measures`. Custom mode also has `hidden` on a column.
|
|
94
|
+
- **Number formats** (`formats`, every mode): per measure column of the result, by name, `format` (a measure format, the same names as a custom column's), `decimals` (0 to 6) and `thousands` (true or false). Each one set lands on that column in `columns`; one left out keeps the model's. The statement is unchanged. A column that is not a measure column refuses with `unknown_column`, anything else with `bad_format`.
|
|
92
95
|
- **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
96
|
- **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
97
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Every way this package refuses. A caller can switch on `reason`. */
|
|
2
|
-
declare const REPORTING_REASONS: readonly ["bad_identifier", "bad_number", "bad_date", "bad_params", "formula_empty", "formula_too_long", "formula_syntax", "formula_unknown_function", "formula_arity", "formula_type", "formula_function_unsupported", "formula_unknown_measure", "formula_cycle", "unknown_period", "period_range_inverted", "too_many_periods", "bad_grain", "mode_unsupported", "unknown_stream", "unknown_dimension", "unknown_measure", "unknown_property", "no_measures", "duplicate_measure", "measure_not_on_stream", "snapshot_measure_unsupported", "dimension_not_on_stream", "dimension_has_no_table", "empty_selection", "filter_too_deep", "empty_filter", "measure_filter_unsupported", "option_unsupported", "keyword_too_long", "unknown_column", "bad_across", "bad_levels", "bad_custom_column", "bad_sort", "bad_paging", "sql_too_long", "no_rollup", "result_not_long"];
|
|
2
|
+
declare const REPORTING_REASONS: readonly ["bad_identifier", "bad_number", "bad_date", "bad_params", "formula_empty", "formula_too_long", "formula_syntax", "formula_unknown_function", "formula_arity", "formula_type", "formula_function_unsupported", "formula_unknown_measure", "formula_cycle", "unknown_period", "period_range_inverted", "too_many_periods", "bad_grain", "mode_unsupported", "unknown_stream", "unknown_dimension", "unknown_measure", "unknown_property", "no_measures", "duplicate_measure", "measure_not_on_stream", "snapshot_measure_unsupported", "dimension_not_on_stream", "dimension_has_no_table", "empty_selection", "filter_too_deep", "empty_filter", "measure_filter_unsupported", "option_unsupported", "keyword_too_long", "unknown_column", "bad_across", "bad_levels", "bad_custom_column", "bad_calculation", "bad_format", "bad_sort", "bad_paging", "sql_too_long", "no_rollup", "result_not_long"];
|
|
3
3
|
type ReportingReason = (typeof REPORTING_REASONS)[number];
|
|
4
4
|
declare class ReportingError extends Error {
|
|
5
5
|
readonly reason: ReportingReason;
|
|
@@ -293,6 +293,35 @@ declare function validateModel(input: unknown): ModelValidation;
|
|
|
293
293
|
*/
|
|
294
294
|
declare function measureAvailability(model: ReportingModel, schema: Record<string, readonly string[]>): Record<string, boolean>;
|
|
295
295
|
|
|
296
|
+
/**
|
|
297
|
+
* What a view adds on top of the model: calculations of its own, columns it hides and the number
|
|
298
|
+
* format of a column. Each is optional, and a view without them compiles exactly as it would anyway.
|
|
299
|
+
*/
|
|
300
|
+
|
|
301
|
+
/** A calculated measure the view defines for itself. It is listed in `measures` like a measure of the model. */
|
|
302
|
+
interface ViewCalculation {
|
|
303
|
+
/** A key no measure of the model holds. The result names its column `m__<key>` as for any measure. */
|
|
304
|
+
key: string;
|
|
305
|
+
label?: string;
|
|
306
|
+
/** A formula over measures of the model and the calculations listed before this one. */
|
|
307
|
+
formula: string;
|
|
308
|
+
/** `number` when absent. */
|
|
309
|
+
format?: string;
|
|
310
|
+
}
|
|
311
|
+
/** How one result column shows its figures. A field left out keeps what the model gives. */
|
|
312
|
+
interface ViewNumberFormat {
|
|
313
|
+
/** A measure format, as in the model and on a custom column: `number`, `integer`, `currency` or `percent`. */
|
|
314
|
+
format?: string;
|
|
315
|
+
/** Digits after the point, 0 to 6. */
|
|
316
|
+
decimals?: number;
|
|
317
|
+
/** Separate thousands. */
|
|
318
|
+
thousands?: boolean;
|
|
319
|
+
}
|
|
320
|
+
/** The model with the view's calculations added as formula measures, or the model itself when it has none. */
|
|
321
|
+
declare function withCalculations(model: ReportingModel, view: ViewState): ReportingModel;
|
|
322
|
+
/** The columns as the view shows them: hidden ones left out and formats applied. The statement is not changed. */
|
|
323
|
+
declare function shownColumns(view: ViewState, columns: CompiledColumn[]): CompiledColumn[];
|
|
324
|
+
|
|
296
325
|
/** The query route refuses longer SQL (`ANALYTICS_QUERY_MAX_SQL_CHARS` in sprigr-team). */
|
|
297
326
|
declare const ROUTE_MAX_SQL_CHARS = 24000;
|
|
298
327
|
/** The query route's row cap (`ANALYTICS_QUERY_MAX_ROWS` in sprigr-team). */
|
|
@@ -453,6 +482,12 @@ interface ViewState {
|
|
|
453
482
|
limit?: number;
|
|
454
483
|
offset?: number;
|
|
455
484
|
options?: ViewOptions;
|
|
485
|
+
/** Calculated measures of this view alone. Each is listed in `measures`, or read by a custom column, like a measure of the model. */
|
|
486
|
+
calculations?: ViewCalculation[];
|
|
487
|
+
/** Measure columns of the result, by name such as `prev__sales`, left out of `columns`. The statement still works them out, so a sort reads them. */
|
|
488
|
+
hidden_columns?: string[];
|
|
489
|
+
/** The number format of a measure column of the result, by name. */
|
|
490
|
+
formats?: Record<string, ViewNumberFormat>;
|
|
456
491
|
}
|
|
457
492
|
interface CompileContext {
|
|
458
493
|
/** Today in the tenant's time zone, `YYYY-MM-DD`. */
|
|
@@ -477,6 +512,10 @@ interface CompiledColumn {
|
|
|
477
512
|
/** For a measure column: the measure key and its format. */
|
|
478
513
|
measure?: string;
|
|
479
514
|
format?: string;
|
|
515
|
+
/** For a measure column the view formats (`formats`): digits after the point. */
|
|
516
|
+
decimals?: number;
|
|
517
|
+
/** For a measure column the view formats (`formats`): whether thousands are separated. */
|
|
518
|
+
thousands?: boolean;
|
|
480
519
|
/** For a measure column: the period it covers, or null for the whole window. */
|
|
481
520
|
period?: PeriodBucket | null;
|
|
482
521
|
/** For a measure column in period mode: true on the mean of the measure's period columns. */
|
|
@@ -609,4 +648,4 @@ interface Grid {
|
|
|
609
648
|
*/
|
|
610
649
|
declare function pivotLong(compiled: CompiledView, rows: ResultRow[]): Grid;
|
|
611
650
|
|
|
612
|
-
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 ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, 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, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, writtenLength };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -42,6 +42,8 @@ var REPORTING_REASONS = [
|
|
|
42
42
|
"bad_across",
|
|
43
43
|
"bad_levels",
|
|
44
44
|
"bad_custom_column",
|
|
45
|
+
"bad_calculation",
|
|
46
|
+
"bad_format",
|
|
45
47
|
"bad_sort",
|
|
46
48
|
"bad_paging",
|
|
47
49
|
"sql_too_long",
|
|
@@ -1144,6 +1146,68 @@ function measureAvailability(model, schema) {
|
|
|
1144
1146
|
return Object.fromEntries(model.measures.map((m) => [m.key, available(m.key, 0)]));
|
|
1145
1147
|
}
|
|
1146
1148
|
|
|
1149
|
+
// src/view-extras.ts
|
|
1150
|
+
var KEY_RX2 = /^[a-z][a-z0-9_]{0,62}$/;
|
|
1151
|
+
var MAX_DECIMALS = 6;
|
|
1152
|
+
function fail(reason, detail) {
|
|
1153
|
+
throw new ReportingError(reason, detail);
|
|
1154
|
+
}
|
|
1155
|
+
function isRecord(value) {
|
|
1156
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1157
|
+
}
|
|
1158
|
+
function withCalculations(model, view) {
|
|
1159
|
+
const listed = view.calculations;
|
|
1160
|
+
if (listed === void 0) return model;
|
|
1161
|
+
if (!Array.isArray(listed)) fail("bad_calculation", "calculations must be a list");
|
|
1162
|
+
if (listed.length === 0) return model;
|
|
1163
|
+
const known = new Set(model.measures.map((m) => m.key));
|
|
1164
|
+
const added = listed.map((raw, i) => {
|
|
1165
|
+
if (!isRecord(raw)) fail("bad_calculation", `calculation ${i + 1} is not an object`);
|
|
1166
|
+
const { key, label, formula, format } = raw;
|
|
1167
|
+
if (typeof key !== "string" || !KEY_RX2.test(key)) fail("bad_calculation", `calculation ${i + 1} needs a key of lower case letters, digits and _`);
|
|
1168
|
+
if (known.has(key)) fail("bad_calculation", `"${key}" is already a measure`);
|
|
1169
|
+
if (typeof formula !== "string") fail("bad_calculation", `calculation "${key}" needs a formula`);
|
|
1170
|
+
if (label !== void 0 && typeof label !== "string") fail("bad_calculation", `the label of calculation "${key}" must be text`);
|
|
1171
|
+
if (format !== void 0 && !MEASURE_FORMATS.includes(format)) fail("bad_calculation", `"${String(format)}" is not a format`);
|
|
1172
|
+
for (const ref of formulaRefs(parseFormula(formula))) {
|
|
1173
|
+
if (!known.has(ref)) throw new ReportingError("formula_unknown_measure", `calculation "${key}" reads "${ref}", which is not a measure or an earlier calculation`);
|
|
1174
|
+
}
|
|
1175
|
+
known.add(key);
|
|
1176
|
+
return { key, label: label === void 0 || label === "" ? key : label, formula, format: format ?? "number" };
|
|
1177
|
+
});
|
|
1178
|
+
return { ...model, measures: [...model.measures, ...added] };
|
|
1179
|
+
}
|
|
1180
|
+
function shownColumns(view, columns) {
|
|
1181
|
+
const { hidden_columns: hidden, formats } = view;
|
|
1182
|
+
if (hidden === void 0 && formats === void 0) return columns;
|
|
1183
|
+
const measureNames = new Set(columns.filter((c) => c.kind === "measure").map((c) => c.name));
|
|
1184
|
+
if (hidden !== void 0 && !Array.isArray(hidden)) fail("unknown_column", "hidden_columns must be a list of result columns");
|
|
1185
|
+
const hide = /* @__PURE__ */ new Set();
|
|
1186
|
+
for (const name of hidden ?? []) {
|
|
1187
|
+
if (typeof name !== "string" || !measureNames.has(name)) fail("unknown_column", `"${String(name)}" is not a measure column of this view`);
|
|
1188
|
+
hide.add(name);
|
|
1189
|
+
}
|
|
1190
|
+
if (hide.size > 0 && [...measureNames].every((name) => hide.has(name))) fail("no_measures", "every measure column of the view is hidden");
|
|
1191
|
+
if (formats !== void 0 && !isRecord(formats)) fail("bad_format", "formats must map result columns to a format");
|
|
1192
|
+
const shape = /* @__PURE__ */ new Map();
|
|
1193
|
+
for (const [name, raw] of Object.entries(formats ?? {})) {
|
|
1194
|
+
if (!measureNames.has(name)) fail("unknown_column", `"${name}" is not a measure column of this view`);
|
|
1195
|
+
if (!isRecord(raw)) fail("bad_format", `the format of "${name}" must be an object`);
|
|
1196
|
+
const { format, decimals, thousands } = raw;
|
|
1197
|
+
if (format !== void 0 && !MEASURE_FORMATS.includes(format)) fail("bad_format", `"${String(format)}" is not a format`);
|
|
1198
|
+
if (decimals !== void 0 && (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > MAX_DECIMALS)) {
|
|
1199
|
+
fail("bad_format", `decimals of "${name}" must be a whole number from 0 to ${MAX_DECIMALS}`);
|
|
1200
|
+
}
|
|
1201
|
+
if (thousands !== void 0 && typeof thousands !== "boolean") fail("bad_format", `thousands of "${name}" must be true or false`);
|
|
1202
|
+
shape.set(name, {
|
|
1203
|
+
...format !== void 0 ? { format } : {},
|
|
1204
|
+
...decimals !== void 0 ? { decimals } : {},
|
|
1205
|
+
...thousands !== void 0 ? { thousands } : {}
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
return columns.filter((c) => !hide.has(c.name)).map((c) => shape.has(c.name) ? { ...c, ...shape.get(c.name) } : c);
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1147
1211
|
// src/compile.ts
|
|
1148
1212
|
var ROUTE_MAX_SQL_CHARS = 24e3;
|
|
1149
1213
|
var ROUTE_MAX_ROWS = 2e3;
|
|
@@ -1157,22 +1221,24 @@ var MEASURE_CMPS = ["=", "<>", "<", "<=", ">", ">="];
|
|
|
1157
1221
|
var VARIANCE_PARTS = ["current", "previous", "variance", "variance_pct"];
|
|
1158
1222
|
var PART_PREFIX = { current: "m__", previous: "prev__", variance: "var__", variance_pct: "varp__" };
|
|
1159
1223
|
var FACT = "f";
|
|
1160
|
-
function
|
|
1224
|
+
function fail2(reason, detail) {
|
|
1161
1225
|
throw new ReportingError(reason, detail);
|
|
1162
1226
|
}
|
|
1163
1227
|
function isGroup(rule) {
|
|
1164
1228
|
return typeof rule === "object" && rule !== null && "rules" in rule;
|
|
1165
1229
|
}
|
|
1166
1230
|
function stringList(values, what) {
|
|
1167
|
-
if (!Array.isArray(values) || values.length === 0)
|
|
1231
|
+
if (!Array.isArray(values) || values.length === 0) fail2("empty_selection", `${what} has nothing selected`);
|
|
1168
1232
|
return values.map((v) => {
|
|
1169
|
-
if (typeof v !== "string" && typeof v !== "number")
|
|
1233
|
+
if (typeof v !== "string" && typeof v !== "number") fail2("empty_selection", `${what} holds a value that is not text`);
|
|
1170
1234
|
return String(v);
|
|
1171
1235
|
});
|
|
1172
1236
|
}
|
|
1173
1237
|
function compileView(model, view, ctx) {
|
|
1174
1238
|
try {
|
|
1175
|
-
const
|
|
1239
|
+
const full = withCalculations(model, view);
|
|
1240
|
+
const compiled = compileMode(full, view, ctx);
|
|
1241
|
+
const out = { ...compiled, columns: shownColumns(view, compiled.columns) };
|
|
1176
1242
|
const { sql, params } = bindValues(out.sql);
|
|
1177
1243
|
const known = /* @__PURE__ */ new Set([...model.streams.map((s) => s.table), ...model.dimensions.flatMap((d) => d.table ? [d.table] : [])]);
|
|
1178
1244
|
const ruleWindows = memberWindows(model, view, ctx);
|
|
@@ -1186,7 +1252,7 @@ function compileView(model, view, ctx) {
|
|
|
1186
1252
|
}
|
|
1187
1253
|
}
|
|
1188
1254
|
function compileMode(model, view, ctx) {
|
|
1189
|
-
if (!VIEW_MODES.includes(view.mode))
|
|
1255
|
+
if (!VIEW_MODES.includes(view.mode)) fail2("mode_unsupported", `mode "${String(view.mode)}" is not compiled yet`);
|
|
1190
1256
|
if (view.mode === "transaction") return compileTransactions(model, view, ctx);
|
|
1191
1257
|
if (view.mode === "stream") return compileStreams(model, view, ctx);
|
|
1192
1258
|
if (view.mode === "matrix") {
|
|
@@ -1202,8 +1268,23 @@ function compileMode(model, view, ctx) {
|
|
|
1202
1268
|
try {
|
|
1203
1269
|
return direct ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
|
|
1204
1270
|
} catch (err) {
|
|
1205
|
-
if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream"
|
|
1206
|
-
|
|
1271
|
+
if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream") throw err;
|
|
1272
|
+
if (direct || view.mode !== "period" || ctx.periodShape === "wide") {
|
|
1273
|
+
if (!direct && ctx.periodShape === "long") throw err;
|
|
1274
|
+
return compileStreams(model, view, ctx);
|
|
1275
|
+
}
|
|
1276
|
+
if (ctx.periodShape === "long") return compileMatrix(model, view, ctx, true, true);
|
|
1277
|
+
try {
|
|
1278
|
+
return compileStreams(model, view, ctx);
|
|
1279
|
+
} catch (tooLong) {
|
|
1280
|
+
if (!(tooLong instanceof ReportingError) || tooLong.reason !== "sql_too_long") throw tooLong;
|
|
1281
|
+
try {
|
|
1282
|
+
return compileMatrix(model, view, ctx, true, true);
|
|
1283
|
+
} catch (longErr) {
|
|
1284
|
+
if (longErr instanceof ReportingError) throw tooLong;
|
|
1285
|
+
throw longErr;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1207
1288
|
}
|
|
1208
1289
|
}
|
|
1209
1290
|
function compileOneStream(model, view, ctx) {
|
|
@@ -1271,30 +1352,30 @@ function memberWindows(model, view, ctx) {
|
|
|
1271
1352
|
return found;
|
|
1272
1353
|
}
|
|
1273
1354
|
function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
1274
|
-
const stream = model.streams.find((s) => s.key === view.stream) ??
|
|
1355
|
+
const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
|
|
1275
1356
|
const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
|
|
1276
1357
|
const measureByKey = new Map(model.measures.map((m) => [m.key, m]));
|
|
1277
1358
|
const joins = /* @__PURE__ */ new Map();
|
|
1278
1359
|
const alias = (dim) => quoteIdent(`d_${dim.key}`);
|
|
1279
|
-
const dimension = (key) => dimByKey.get(key) ??
|
|
1360
|
+
const dimension = (key) => dimByKey.get(key) ?? fail2("unknown_dimension", `no dimension "${String(key)}"`);
|
|
1280
1361
|
const join = (dim, codeExpr2, into = joins) => {
|
|
1281
|
-
if (!dim.table || !dim.code)
|
|
1362
|
+
if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
|
|
1282
1363
|
const a = alias(dim);
|
|
1283
1364
|
if (!into.has(a)) into.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${codeExpr2}`);
|
|
1284
1365
|
return a;
|
|
1285
1366
|
};
|
|
1286
1367
|
const codeOf = (key, depth = 0, into = joins) => {
|
|
1287
|
-
if (depth > 20)
|
|
1368
|
+
if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
|
|
1288
1369
|
const dim = dimension(key);
|
|
1289
1370
|
const direct = stream.dimension_keys[key];
|
|
1290
1371
|
if (direct !== void 0) return `${FACT}.${quoteIdent(direct)}`;
|
|
1291
|
-
if (!dim.via)
|
|
1372
|
+
if (!dim.via) fail2("dimension_not_on_stream", `stream "${stream.key}" has no "${key}"`);
|
|
1292
1373
|
const parent = dimension(dim.via.dimension);
|
|
1293
1374
|
return `${join(parent, codeOf(parent.key, depth + 1, into), into)}.${quoteIdent(dim.via.column)}`;
|
|
1294
1375
|
};
|
|
1295
1376
|
const columnOf = (dim, property) => {
|
|
1296
1377
|
const column = property === "name" ? dim.name : dim.properties.find((p) => p.key === property)?.column;
|
|
1297
|
-
return column ??
|
|
1378
|
+
return column ?? fail2("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
|
|
1298
1379
|
};
|
|
1299
1380
|
const propertyOf = (dimKey, property) => {
|
|
1300
1381
|
const code = codeOf(dimKey);
|
|
@@ -1308,7 +1389,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1308
1389
|
const membersOf = () => {
|
|
1309
1390
|
const table = groupDim.table;
|
|
1310
1391
|
const codeColumn = groupDim.code;
|
|
1311
|
-
if (!table || !codeColumn)
|
|
1392
|
+
if (!table || !codeColumn) fail2("dimension_has_no_table", `"${groupDim.key}" has no table to list its members from`);
|
|
1312
1393
|
const root = quoteIdent("mb");
|
|
1313
1394
|
const joinsHere = /* @__PURE__ */ new Map();
|
|
1314
1395
|
const reaches = (key, depth = 0) => {
|
|
@@ -1318,7 +1399,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1318
1399
|
};
|
|
1319
1400
|
const tableOf = (dim, code) => {
|
|
1320
1401
|
if (dim.key === groupDim.key) return root;
|
|
1321
|
-
if (!dim.table || !dim.code)
|
|
1402
|
+
if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
|
|
1322
1403
|
const a = quoteIdent(`mb_${dim.key}`);
|
|
1323
1404
|
if (!joinsHere.has(a)) joinsHere.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${code}`);
|
|
1324
1405
|
return a;
|
|
@@ -1326,7 +1407,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1326
1407
|
const codeHere = (key) => {
|
|
1327
1408
|
const dim = dimension(key);
|
|
1328
1409
|
if (dim.key === groupDim.key) return `${root}.${quoteIdent(codeColumn)}`;
|
|
1329
|
-
const via = dim.via ??
|
|
1410
|
+
const via = dim.via ?? fail2("dimension_not_on_stream", `"${key}" is not above "${groupDim.key}"`);
|
|
1330
1411
|
const parent = dimension(via.dimension);
|
|
1331
1412
|
return `${tableOf(parent, codeHere(parent.key))}.${quoteIdent(via.column)}`;
|
|
1332
1413
|
};
|
|
@@ -1352,8 +1433,8 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1352
1433
|
});
|
|
1353
1434
|
const filterMeasures = [];
|
|
1354
1435
|
const memberLeaf = (rule, outer) => {
|
|
1355
|
-
if (!MEASURE_CMPS.includes(rule.cmp))
|
|
1356
|
-
if (!measureByKey.has(rule.measure))
|
|
1436
|
+
if (!MEASURE_CMPS.includes(rule.cmp)) fail2("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
|
|
1437
|
+
if (!measureByKey.has(rule.measure)) fail2("unknown_measure", `no measure "${String(rule.measure)}"`);
|
|
1357
1438
|
const window = memberWindow(model, view, ctx, rule);
|
|
1358
1439
|
const own = /* @__PURE__ */ new Map();
|
|
1359
1440
|
const member = codeOf(rule.dimension, 0, own);
|
|
@@ -1369,9 +1450,9 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1369
1450
|
};
|
|
1370
1451
|
const dimensionLeafWith = (resolve) => (rule) => {
|
|
1371
1452
|
if (isMemberRule(rule)) return memberLeaf(rule, resolve(rule.dimension, "code"));
|
|
1372
|
-
if ("measure" in rule)
|
|
1453
|
+
if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
|
|
1373
1454
|
const whole = rule.cmp === "in" || rule.cmp === "not_in";
|
|
1374
|
-
if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains")
|
|
1455
|
+
if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
|
|
1375
1456
|
const expr = resolve(rule.dimension, rule.property ?? "code");
|
|
1376
1457
|
const what = `the filter on "${String(rule.dimension)}"`;
|
|
1377
1458
|
const values = stringList(rule.values, what);
|
|
@@ -1379,8 +1460,8 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1379
1460
|
return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
|
|
1380
1461
|
}
|
|
1381
1462
|
const found = values.map((text) => {
|
|
1382
|
-
if (text === "")
|
|
1383
|
-
if (text.length > MAX_KEYWORD_CHARS)
|
|
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`);
|
|
1384
1465
|
return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
|
|
1385
1466
|
});
|
|
1386
1467
|
const any = `(${found.join(" OR ")})`;
|
|
@@ -1388,39 +1469,39 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1388
1469
|
};
|
|
1389
1470
|
const dimensionLeaf = dimensionLeafWith(propertyOf);
|
|
1390
1471
|
const measureLeaf = (rule) => {
|
|
1391
|
-
if (!("measure" in rule) || isMemberRule(rule))
|
|
1392
|
-
if (!MEASURE_CMPS.includes(rule.cmp))
|
|
1472
|
+
if (!("measure" in rule) || isMemberRule(rule)) fail2("measure_filter_unsupported", "a dimension rule cannot sit in a group of measure rules");
|
|
1473
|
+
if (!MEASURE_CMPS.includes(rule.cmp)) fail2("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
|
|
1393
1474
|
const part = rule.of ?? "current";
|
|
1394
|
-
if (!VARIANCE_PARTS.includes(part))
|
|
1395
|
-
if (part !== "current" && view.mode !== "variance" && view.mode !== "period_variance")
|
|
1396
|
-
const measure = measureByKey.get(rule.measure) ??
|
|
1475
|
+
if (!VARIANCE_PARTS.includes(part)) fail2("measure_filter_unsupported", `"${String(part)}" is not a variance column`);
|
|
1476
|
+
if (part !== "current" && view.mode !== "variance" && view.mode !== "period_variance") fail2("measure_filter_unsupported", `"${part}" exists in a variance only`);
|
|
1477
|
+
const measure = measureByKey.get(rule.measure) ?? fail2("unknown_measure", `no measure "${String(rule.measure)}"`);
|
|
1397
1478
|
if (!filterMeasures.includes(measure.key)) filterMeasures.push(measure.key);
|
|
1398
1479
|
return `${quoteIdent(`${PART_PREFIX[part]}${measure.key}`)} ${rule.cmp} ${sqlNumber(rule.value)}`;
|
|
1399
1480
|
};
|
|
1400
1481
|
const kindOf = (rule, depth) => {
|
|
1401
1482
|
if (!isGroup(rule)) return "measure" in rule && !isMemberRule(rule) ? "measure" : "dimension";
|
|
1402
|
-
if (depth > MAX_FILTER_DEPTH)
|
|
1483
|
+
if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
|
|
1403
1484
|
const kinds = new Set((Array.isArray(rule.rules) ? rule.rules : []).map((r) => kindOf(r, depth + 1)));
|
|
1404
|
-
if (kinds.size > 1)
|
|
1485
|
+
if (kinds.size > 1) fail2("measure_filter_unsupported", "below the top level a filter group holds dimension rules or measure rules, not both");
|
|
1405
1486
|
return kinds.has("measure") ? "measure" : "dimension";
|
|
1406
1487
|
};
|
|
1407
1488
|
const groupSql = (group, depth, leaf) => {
|
|
1408
|
-
if (depth > MAX_FILTER_DEPTH)
|
|
1409
|
-
if (group.op !== "and" && group.op !== "or")
|
|
1489
|
+
if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
|
|
1490
|
+
if (group.op !== "and" && group.op !== "or") fail2("empty_filter", 'a filter group needs op "and" or "or"');
|
|
1410
1491
|
const rules = Array.isArray(group.rules) ? group.rules : [];
|
|
1411
|
-
if (rules.length === 0)
|
|
1492
|
+
if (rules.length === 0) fail2("empty_filter", "a filter group has no rules");
|
|
1412
1493
|
const parts2 = rules.map((rule) => isGroup(rule) ? groupSql(rule, depth + 1, leaf) : leaf(rule));
|
|
1413
1494
|
return `(${parts2.join(group.op === "and" ? " AND " : " OR ")})`;
|
|
1414
1495
|
};
|
|
1415
1496
|
let having = null;
|
|
1416
1497
|
if (view.filters) {
|
|
1417
1498
|
const top = view.filters;
|
|
1418
|
-
if (top.op !== "and" && top.op !== "or")
|
|
1499
|
+
if (top.op !== "and" && top.op !== "or") fail2("empty_filter", 'a filter group needs op "and" or "or"');
|
|
1419
1500
|
const rules = Array.isArray(top.rules) ? top.rules : [];
|
|
1420
1501
|
const onRows = rules.filter((rule) => kindOf(rule, 1) === "dimension");
|
|
1421
1502
|
const onGroups = rules.filter((rule) => kindOf(rule, 1) === "measure");
|
|
1422
1503
|
if (onRows.length > 0 && onGroups.length > 0 && top.op === "or") {
|
|
1423
|
-
|
|
1504
|
+
fail2("measure_filter_unsupported", 'dimension rules and measure rules combine with "and" only');
|
|
1424
1505
|
}
|
|
1425
1506
|
if (onRows.length > 0) where.push(groupSql({ op: top.op, rules: onRows }, 0, dimensionLeaf));
|
|
1426
1507
|
if (onGroups.length > 0) having = groupSql({ op: top.op, rules: onGroups }, 0, measureLeaf);
|
|
@@ -1433,7 +1514,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1433
1514
|
}
|
|
1434
1515
|
}
|
|
1435
1516
|
const keyword = typeof view.keyword === "string" ? view.keyword.trim() : "";
|
|
1436
|
-
if (keyword.length > MAX_KEYWORD_CHARS)
|
|
1517
|
+
if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
|
|
1437
1518
|
if (keyword !== "") {
|
|
1438
1519
|
const pattern = `${sqlValue(likePattern(keyword))} ESCAPE '\\'`;
|
|
1439
1520
|
const targets = [`CAST(${codeExpr} AS VARCHAR) ILIKE ${pattern}`];
|
|
@@ -1455,25 +1536,25 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
|
|
|
1455
1536
|
return { stream, measureByKey, joins, dimension, propertyOf, groupDim, codeExpr, where, dimensionRule: dimensionLeaf, having, filterMeasures, members, focus };
|
|
1456
1537
|
}
|
|
1457
1538
|
function shownMeasures(view, measureByKey) {
|
|
1458
|
-
if (!Array.isArray(view.measures) || view.measures.length === 0)
|
|
1539
|
+
if (!Array.isArray(view.measures) || view.measures.length === 0) fail2("no_measures", "a view needs at least one measure");
|
|
1459
1540
|
return view.measures.map((key, i) => {
|
|
1460
|
-
if (view.measures.indexOf(key) !== i)
|
|
1461
|
-
return measureByKey.get(key) ??
|
|
1541
|
+
if (view.measures.indexOf(key) !== i) fail2("duplicate_measure", `"${String(key)}" is listed twice`);
|
|
1542
|
+
return measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${String(key)}"`);
|
|
1462
1543
|
});
|
|
1463
1544
|
}
|
|
1464
1545
|
function pageOf(view, ctx, reserved) {
|
|
1465
1546
|
const maxRows = ctx.maxRows ?? ROUTE_MAX_ROWS;
|
|
1466
1547
|
const limit = view.limit ?? DEFAULT_PAGE_ROWS;
|
|
1467
1548
|
const offset = view.offset ?? 0;
|
|
1468
|
-
if (!Number.isInteger(limit) || limit < 1 || limit + reserved > maxRows)
|
|
1469
|
-
if (!Number.isInteger(offset) || offset < 0)
|
|
1549
|
+
if (!Number.isInteger(limit) || limit < 1 || limit + reserved > maxRows) fail2("bad_paging", `limit must be a whole number from 1 to ${maxRows - reserved}`);
|
|
1550
|
+
if (!Number.isInteger(offset) || offset < 0) fail2("bad_paging", "offset must be a whole number, 0 or more");
|
|
1470
1551
|
return { limit, offset };
|
|
1471
1552
|
}
|
|
1472
1553
|
function checkLength(sql, ctx) {
|
|
1473
1554
|
const maxSqlChars = ctx.maxSqlChars ?? ROUTE_MAX_SQL_CHARS;
|
|
1474
1555
|
const length = writtenLength(sql);
|
|
1475
1556
|
if (length > maxSqlChars) {
|
|
1476
|
-
|
|
1557
|
+
fail2("sql_too_long", `the statement is ${length} characters, the limit is ${maxSqlChars}; use fewer periods, measures or selected values`);
|
|
1477
1558
|
}
|
|
1478
1559
|
}
|
|
1479
1560
|
function valueOf(measure) {
|
|
@@ -1541,8 +1622,8 @@ function rankAndPage(source, sortName, sort, having, left, offset, limit, extra
|
|
|
1541
1622
|
];
|
|
1542
1623
|
}
|
|
1543
1624
|
function measureOver(src, key, slice, depth = 0) {
|
|
1544
|
-
if (depth > 20)
|
|
1545
|
-
const measure = src.measureByKey.get(key) ??
|
|
1625
|
+
if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
|
|
1626
|
+
const measure = src.measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
|
|
1546
1627
|
if (isFormulaMeasure(measure)) {
|
|
1547
1628
|
let node = src.parsed.get(key);
|
|
1548
1629
|
if (!node) {
|
|
@@ -1555,7 +1636,7 @@ function measureOver(src, key, slice, depth = 0) {
|
|
|
1555
1636
|
...src.periodCount !== void 0 ? { periodCount: src.periodCount } : {}
|
|
1556
1637
|
});
|
|
1557
1638
|
}
|
|
1558
|
-
if (measure.stream !== src.stream.key)
|
|
1639
|
+
if (measure.stream !== src.stream.key) fail2("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${src.stream.key}"`);
|
|
1559
1640
|
const call = aggregateOf(measure, src.countAll);
|
|
1560
1641
|
if (measure.snapshot) {
|
|
1561
1642
|
src.uses.add("snapshot");
|
|
@@ -1589,10 +1670,10 @@ function comparedWith(model, view, ctx, window) {
|
|
|
1589
1670
|
const compare = view.compare ?? "previous_year";
|
|
1590
1671
|
let comparison;
|
|
1591
1672
|
if (typeof compare === "object" && compare !== null) {
|
|
1592
|
-
if (typeof compare.period !== "object" || compare.period === null)
|
|
1673
|
+
if (typeof compare.period !== "object" || compare.period === null) fail2("option_unsupported", "a comparison given as an object needs a period");
|
|
1593
1674
|
comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
|
|
1594
1675
|
} else {
|
|
1595
|
-
if (compare !== "previous_year" && compare !== "previous_period")
|
|
1676
|
+
if (compare !== "previous_year" && compare !== "previous_period") fail2("option_unsupported", `"${String(compare)}" is not a comparison`);
|
|
1596
1677
|
comparison = comparisonWindow(window, compare);
|
|
1597
1678
|
}
|
|
1598
1679
|
const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
|
|
@@ -1635,15 +1716,15 @@ function propertyLabel(dim, property) {
|
|
|
1635
1716
|
function nestOf(view, scope) {
|
|
1636
1717
|
if (view.levels === void 0) return null;
|
|
1637
1718
|
const keys = view.levels;
|
|
1638
|
-
if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_LEVELS)
|
|
1719
|
+
if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_LEVELS) fail2("bad_levels", `levels lists from 1 to ${MAX_LEVELS} dimensions`);
|
|
1639
1720
|
const codes = [];
|
|
1640
1721
|
const select = [];
|
|
1641
1722
|
const columns = [];
|
|
1642
1723
|
keys.forEach((key, i) => {
|
|
1643
|
-
if (typeof key !== "string")
|
|
1724
|
+
if (typeof key !== "string") fail2("bad_levels", "a level is named by its dimension key");
|
|
1644
1725
|
const dim = scope.dimension(key);
|
|
1645
1726
|
const code = scope.propertyOf(dim.key, "code");
|
|
1646
|
-
if (code === scope.codeExpr || codes.includes(code))
|
|
1727
|
+
if (code === scope.codeExpr || codes.includes(code)) fail2("bad_levels", `"${key}" is the row dimension, or is listed twice`);
|
|
1647
1728
|
codes.push(code);
|
|
1648
1729
|
const level2 = i + 1;
|
|
1649
1730
|
select.push(`${code} AS ${quoteIdent(`lv${level2}`)}`);
|
|
@@ -1667,27 +1748,27 @@ function nestOf(view, scope) {
|
|
|
1667
1748
|
function compileGrouped(model, view, ctx) {
|
|
1668
1749
|
const options = view.options ?? {};
|
|
1669
1750
|
const activity = options.activity ?? "with";
|
|
1670
|
-
if (activity !== "with" && activity !== "without" && activity !== "all")
|
|
1671
|
-
if (options.others_row && activity !== "with")
|
|
1751
|
+
if (activity !== "with" && activity !== "without" && activity !== "all") fail2("option_unsupported", `"${String(activity)}" is not an activity option`);
|
|
1752
|
+
if (options.others_row && activity !== "with") fail2("option_unsupported", "an others row with the activity option is not compiled yet");
|
|
1672
1753
|
const totalRow = options.total_row === true && activity !== "without";
|
|
1673
1754
|
const averageRow = options.average_row === true;
|
|
1674
1755
|
const sumRow = options.sum_row === true;
|
|
1675
|
-
if (options.hide_zero_rows && activity !== "with")
|
|
1756
|
+
if (options.hide_zero_rows && activity !== "with") fail2("option_unsupported", "hiding zero rows with the activity option is not compiled yet");
|
|
1676
1757
|
const averageColumn = options.average_column === true && view.mode === "period";
|
|
1677
1758
|
const scope = scopeOf(model, view, ctx, activity !== "with", options.others_row === true);
|
|
1678
1759
|
const { stream, measureByKey, joins, groupDim, where, members } = scope;
|
|
1679
1760
|
const nest = nestOf(view, scope);
|
|
1680
1761
|
if (nest) {
|
|
1681
1762
|
if (activity !== "with" || options.others_row || averageRow || sumRow || options.hide_zero_rows) {
|
|
1682
|
-
|
|
1763
|
+
fail2("option_unsupported", "the activity option, an others, average or sum row and hiding zero rows are not compiled with nested rows yet");
|
|
1683
1764
|
}
|
|
1684
|
-
if (scope.having !== null)
|
|
1765
|
+
if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
|
|
1685
1766
|
}
|
|
1686
1767
|
const focused = scope.focus.length > 0 ? `COALESCE(${scope.focus.join(" AND ")}, FALSE)` : null;
|
|
1687
1768
|
const othersRow = focused !== null;
|
|
1688
1769
|
const codeExpr = members ? `COALESCE(${members.code}, ${FACT}."__code")` : scope.codeExpr;
|
|
1689
1770
|
const shown = shownMeasures(view, measureByKey);
|
|
1690
|
-
const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ??
|
|
1771
|
+
const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
|
|
1691
1772
|
const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
|
|
1692
1773
|
const periodVariance = view.mode === "period_variance";
|
|
1693
1774
|
const buckets = view.mode === "period" || periodVariance ? period.buckets : [];
|
|
@@ -1716,7 +1797,7 @@ function compileGrouped(model, view, ctx) {
|
|
|
1716
1797
|
if (periodVariance) {
|
|
1717
1798
|
const earlier = splitWindow(comparison, period.grain, model.periods);
|
|
1718
1799
|
if (earlier.length !== buckets.length) {
|
|
1719
|
-
|
|
1800
|
+
fail2("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlier.length}, so they cannot be set side by side`);
|
|
1720
1801
|
}
|
|
1721
1802
|
earlierBuckets = earlier;
|
|
1722
1803
|
earlierSlices = earlier.map((bucket, i) => ({
|
|
@@ -1856,10 +1937,10 @@ function compileGrouped(model, view, ctx) {
|
|
|
1856
1937
|
}
|
|
1857
1938
|
columns.push({ name: "__rows", kind: "meta", label: "Row count" });
|
|
1858
1939
|
const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
|
|
1859
|
-
if (sort.dir !== "asc" && sort.dir !== "desc")
|
|
1940
|
+
if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
|
|
1860
1941
|
const sortName = sortNameOf(sort.by);
|
|
1861
1942
|
const sortColumn = columns.find((c) => c.name === sortName && c.kind !== "meta");
|
|
1862
|
-
if (!sortColumn)
|
|
1943
|
+
if (!sortColumn) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
|
|
1863
1944
|
const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (othersRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
|
|
1864
1945
|
const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
|
|
1865
1946
|
const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
|
|
@@ -1914,20 +1995,20 @@ function compileGrouped(model, view, ctx) {
|
|
|
1914
1995
|
}
|
|
1915
1996
|
function compileCustom(model, view, ctx) {
|
|
1916
1997
|
const options = view.options ?? {};
|
|
1917
|
-
if (options.activity !== void 0 && options.activity !== "with")
|
|
1918
|
-
if (options.others_row)
|
|
1998
|
+
if (options.activity !== void 0 && options.activity !== "with") fail2("option_unsupported", "the activity option in custom mode is not compiled yet");
|
|
1999
|
+
if (options.others_row) fail2("option_unsupported", "an others row in custom mode is not compiled yet");
|
|
1919
2000
|
const totalRow = options.total_row === true;
|
|
1920
2001
|
const averageRow = options.average_row === true;
|
|
1921
2002
|
const sumRow = options.sum_row === true;
|
|
1922
2003
|
const scope = scopeOf(model, view, ctx);
|
|
1923
|
-
if (scope.having !== null)
|
|
2004
|
+
if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure in custom mode is not compiled yet");
|
|
1924
2005
|
const { stream, measureByKey, joins, groupDim, where, codeExpr } = scope;
|
|
1925
2006
|
const nest = nestOf(view, scope);
|
|
1926
2007
|
if (nest && (averageRow || sumRow || options.hide_zero_rows)) {
|
|
1927
|
-
|
|
2008
|
+
fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
|
|
1928
2009
|
}
|
|
1929
2010
|
const listed = Array.isArray(view.custom_columns) ? view.custom_columns : [];
|
|
1930
|
-
if (listed.length === 0)
|
|
2011
|
+
if (listed.length === 0) fail2("bad_custom_column", "a custom view needs at least one column");
|
|
1931
2012
|
const date = quoteIdent(stream.date);
|
|
1932
2013
|
const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
|
|
1933
2014
|
const resolve = (spec) => resolvePeriod(spec, model.periods, ctx.today, { periodToDate: options.period_to_date === true }).window;
|
|
@@ -1963,11 +2044,11 @@ function compileCustom(model, view, ctx) {
|
|
|
1963
2044
|
};
|
|
1964
2045
|
const points = [];
|
|
1965
2046
|
const pointOf = (point, what) => {
|
|
1966
|
-
if (typeof point !== "object" || point === null)
|
|
1967
|
-
const measure = measureByKey.get(point.measure) ??
|
|
2047
|
+
if (typeof point !== "object" || point === null) fail2("bad_custom_column", `${what} has no data point`);
|
|
2048
|
+
const measure = measureByKey.get(point.measure) ?? fail2("unknown_measure", `no measure "${String(point.measure)}"`);
|
|
1968
2049
|
const { window, number } = windowOf(point.period);
|
|
1969
2050
|
const where2 = point.where;
|
|
1970
|
-
if (where2 !== void 0 && (typeof where2 !== "object" || where2 === null || "measure" in where2))
|
|
2051
|
+
if (where2 !== void 0 && (typeof where2 !== "object" || where2 === null || "measure" in where2)) fail2("bad_custom_column", `the rule of ${what} is not a dimension rule`);
|
|
1971
2052
|
const bucket = {
|
|
1972
2053
|
key: `w${number}`,
|
|
1973
2054
|
label: `${window.from} to ${addDays(window.to, -1)}`,
|
|
@@ -1978,9 +2059,9 @@ function compileCustom(model, view, ctx) {
|
|
|
1978
2059
|
const read = (m, depth) => {
|
|
1979
2060
|
const streams = streamsOf(m);
|
|
1980
2061
|
if (streams.size > 1 && isFormulaMeasure(m)) {
|
|
1981
|
-
if (depth > 20)
|
|
2062
|
+
if (depth > 20) fail2("formula_cycle", `"${m.key}" refers back to itself`);
|
|
1982
2063
|
return emitFormulaSql(parseFormula(m.formula), {
|
|
1983
|
-
measure: (ref) => read(measureByKey.get(ref) ??
|
|
2064
|
+
measure: (ref) => read(measureByKey.get(ref) ?? fail2("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
|
|
1984
2065
|
days: bucket.days
|
|
1985
2066
|
});
|
|
1986
2067
|
}
|
|
@@ -2008,23 +2089,23 @@ function compileCustom(model, view, ctx) {
|
|
|
2008
2089
|
const left = ["__rn"];
|
|
2009
2090
|
const keys = /* @__PURE__ */ new Set();
|
|
2010
2091
|
listed.forEach((column, i) => {
|
|
2011
|
-
if (typeof column !== "object" || column === null || !isIdentifier(column.key))
|
|
2092
|
+
if (typeof column !== "object" || column === null || !isIdentifier(column.key)) fail2("bad_custom_column", `column ${i + 1} needs a key that is a plain name`);
|
|
2012
2093
|
const { key } = column;
|
|
2013
|
-
if (keys.has(key))
|
|
2094
|
+
if (keys.has(key)) fail2("bad_custom_column", `"${key}" is the key of two columns`);
|
|
2014
2095
|
keys.add(key);
|
|
2015
|
-
if (column.point === void 0 === (column.expression === void 0))
|
|
2096
|
+
if (column.point === void 0 === (column.expression === void 0)) fail2("bad_custom_column", `"${key}" holds a point or an expression, one of the two`);
|
|
2016
2097
|
let expr;
|
|
2017
2098
|
let about;
|
|
2018
2099
|
if (column.point !== void 0) {
|
|
2019
2100
|
const cur = pointOf(column.point, `"${key}"`);
|
|
2020
2101
|
if (column.against === void 0) {
|
|
2021
|
-
if (column.show !== void 0)
|
|
2102
|
+
if (column.show !== void 0) fail2("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
|
|
2022
2103
|
expr = cur.ref;
|
|
2023
2104
|
about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
|
|
2024
2105
|
} else {
|
|
2025
2106
|
const prev = pointOf(column.against, `"${key}"`);
|
|
2026
2107
|
const show = column.show ?? "difference";
|
|
2027
|
-
if (show !== "difference" && show !== "percent")
|
|
2108
|
+
if (show !== "difference" && show !== "percent") fail2("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
|
|
2028
2109
|
expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
|
|
2029
2110
|
about = {
|
|
2030
2111
|
label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
|
|
@@ -2035,11 +2116,11 @@ function compileCustom(model, view, ctx) {
|
|
|
2035
2116
|
}
|
|
2036
2117
|
} else {
|
|
2037
2118
|
const format = column.format ?? "number";
|
|
2038
|
-
if (!MEASURE_FORMATS.includes(format))
|
|
2119
|
+
if (!MEASURE_FORMATS.includes(format)) fail2("bad_custom_column", `"${String(format)}" is not a format`);
|
|
2039
2120
|
const named = column.points ?? {};
|
|
2040
2121
|
expr = emitFormulaSql(parseFormula(String(column.expression)), {
|
|
2041
2122
|
measure: (ref) => {
|
|
2042
|
-
if (!Object.prototype.hasOwnProperty.call(named, ref))
|
|
2123
|
+
if (!Object.prototype.hasOwnProperty.call(named, ref)) fail2("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
|
|
2043
2124
|
return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
|
|
2044
2125
|
},
|
|
2045
2126
|
days: reads.days
|
|
@@ -2052,8 +2133,8 @@ function compileCustom(model, view, ctx) {
|
|
|
2052
2133
|
else columns.push({ name, kind: "measure", custom: key, ...about });
|
|
2053
2134
|
});
|
|
2054
2135
|
const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
|
|
2055
|
-
if (measured.length === 0)
|
|
2056
|
-
if (points.length === 0)
|
|
2136
|
+
if (measured.length === 0) fail2("bad_custom_column", "every column of the view is hidden");
|
|
2137
|
+
if (points.length === 0) fail2("bad_custom_column", "no column of the view reads a data point");
|
|
2057
2138
|
const multi = reading.size > 1;
|
|
2058
2139
|
points.forEach(({ sql: sql2 }, i) => {
|
|
2059
2140
|
select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
|
|
@@ -2067,11 +2148,11 @@ function compileCustom(model, view, ctx) {
|
|
|
2067
2148
|
}
|
|
2068
2149
|
columns.push({ name: "__rows", kind: "meta", label: "Row count" });
|
|
2069
2150
|
const sort = view.sort ?? { by: `column.${measured[0]?.slice(3) ?? ""}`, dir: "desc" };
|
|
2070
|
-
if (sort.dir !== "asc" && sort.dir !== "desc")
|
|
2151
|
+
if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
|
|
2071
2152
|
const by = String(sort.by).split(".");
|
|
2072
2153
|
const sortName = by[0] === "column" ? by.length === 2 && keys.has(by[1] ?? "") ? `c__${by[1]}` : "" : sortNameOf(sort.by);
|
|
2073
2154
|
if (!sortName.startsWith("c__") && !columns.some((c) => c.name === sortName && (c.kind === "code" || c.kind === "property"))) {
|
|
2074
|
-
|
|
2155
|
+
fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
|
|
2075
2156
|
}
|
|
2076
2157
|
const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
|
|
2077
2158
|
const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
|
|
@@ -2139,19 +2220,19 @@ function compileCustom(model, view, ctx) {
|
|
|
2139
2220
|
}
|
|
2140
2221
|
function compileTransactions(model, view, ctx) {
|
|
2141
2222
|
const options = view.options ?? {};
|
|
2142
|
-
if (view.levels !== void 0)
|
|
2143
|
-
if (options.activity !== void 0 && options.activity !== "with")
|
|
2144
|
-
if (options.total_row || options.others_row || options.average_row || options.sum_row)
|
|
2223
|
+
if (view.levels !== void 0) fail2("option_unsupported", "a transaction list has no nested rows");
|
|
2224
|
+
if (options.activity !== void 0 && options.activity !== "with") fail2("option_unsupported", "a transaction list shows rows that exist; activity does not apply");
|
|
2225
|
+
if (options.total_row || options.others_row || options.average_row || options.sum_row) fail2("option_unsupported", "a transaction list has no total, others, average or sum row");
|
|
2145
2226
|
const scope = scopeOf(model, view, ctx);
|
|
2146
2227
|
const { stream, measureByKey } = scope;
|
|
2147
|
-
if (scope.having !== null)
|
|
2228
|
+
if (scope.having !== null) fail2("measure_filter_unsupported", "a transaction list cannot be filtered on a measure");
|
|
2148
2229
|
const shown = shownMeasures(view, measureByKey);
|
|
2149
2230
|
const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
|
|
2150
2231
|
const windowDays = period.buckets.reduce((sum, b) => sum + b.days, 0);
|
|
2151
2232
|
const parsed = /* @__PURE__ */ new Map();
|
|
2152
2233
|
const rowSql = (key, depth) => {
|
|
2153
|
-
if (depth > 20)
|
|
2154
|
-
const measure = measureByKey.get(key) ??
|
|
2234
|
+
if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
|
|
2235
|
+
const measure = measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
|
|
2155
2236
|
if (isFormulaMeasure(measure)) {
|
|
2156
2237
|
let node = parsed.get(key);
|
|
2157
2238
|
if (!node) {
|
|
@@ -2160,8 +2241,8 @@ function compileTransactions(model, view, ctx) {
|
|
|
2160
2241
|
}
|
|
2161
2242
|
return emitFormulaSql(node, { measure: (ref) => rowSql(ref, depth + 1), days: windowDays });
|
|
2162
2243
|
}
|
|
2163
|
-
if (measure.stream !== stream.key)
|
|
2164
|
-
if (measure.snapshot)
|
|
2244
|
+
if (measure.stream !== stream.key) fail2("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${stream.key}"`);
|
|
2245
|
+
if (measure.snapshot) fail2("snapshot_measure_unsupported", `"${key}" is a snapshot measure, which is not compiled yet`);
|
|
2165
2246
|
const column = valueOf(measure);
|
|
2166
2247
|
if (measure.agg === "count" || measure.agg === "count_distinct") return column === "" ? "1" : `(CASE WHEN ${column} IS NULL THEN 0 ELSE 1 END)`;
|
|
2167
2248
|
return column;
|
|
@@ -2175,10 +2256,10 @@ function compileTransactions(model, view, ctx) {
|
|
|
2175
2256
|
columns.push({ name, kind: "dimension", label: scope.dimension(key).label, dimension: key });
|
|
2176
2257
|
});
|
|
2177
2258
|
const wanted = view.columns ?? stream.columns.map((c) => c.key);
|
|
2178
|
-
if (!Array.isArray(wanted))
|
|
2259
|
+
if (!Array.isArray(wanted)) fail2("unknown_column", "columns must be a list of column keys");
|
|
2179
2260
|
wanted.forEach((key, i) => {
|
|
2180
2261
|
if (wanted.indexOf(key) !== i) return;
|
|
2181
|
-
const extra = stream.columns.find((c) => c.key === key) ??
|
|
2262
|
+
const extra = stream.columns.find((c) => c.key === key) ?? fail2("unknown_column", `stream "${stream.key}" has no column "${String(key)}"`);
|
|
2182
2263
|
const name = `col__${extra.key}`;
|
|
2183
2264
|
select.push(`${FACT}.${quoteIdent(extra.column)} AS ${quoteIdent(name)}`);
|
|
2184
2265
|
columns.push({ name, kind: "column", label: extra.label, column: extra.key });
|
|
@@ -2189,11 +2270,11 @@ function compileTransactions(model, view, ctx) {
|
|
|
2189
2270
|
columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
|
|
2190
2271
|
});
|
|
2191
2272
|
const sort = view.sort ?? { by: "date", dir: "desc" };
|
|
2192
|
-
if (sort.dir !== "asc" && sort.dir !== "desc")
|
|
2273
|
+
if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
|
|
2193
2274
|
const sortParts = String(sort.by).split(".");
|
|
2194
2275
|
const two = sortParts.length === 2;
|
|
2195
2276
|
const sortName = sortParts[0] === "date" && sortParts.length === 1 ? "date" : sortParts[0] === "dimension" && two ? `dim__${sortParts[1]}` : sortParts[0] === "column" && two ? `col__${sortParts[1]}` : sortParts[0] === "total" && two ? `m__${sortParts[1]}` : "";
|
|
2196
|
-
if (!columns.some((c) => c.name === sortName))
|
|
2277
|
+
if (!columns.some((c) => c.name === sortName)) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
|
|
2197
2278
|
const order = [
|
|
2198
2279
|
`${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST`,
|
|
2199
2280
|
...columns.filter((c) => c.name !== sortName).map((c) => `${quoteIdent(c.name)} ASC`)
|
|
@@ -2239,8 +2320,8 @@ function foldedMeasures(measureByKey, periodCount) {
|
|
|
2239
2320
|
const needed = /* @__PURE__ */ new Map();
|
|
2240
2321
|
const parsed = /* @__PURE__ */ new Map();
|
|
2241
2322
|
const exprOf = (key, part, depth) => {
|
|
2242
|
-
if (depth > 20)
|
|
2243
|
-
const measure = measureByKey.get(key) ??
|
|
2323
|
+
if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
|
|
2324
|
+
const measure = measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
|
|
2244
2325
|
if (isFormulaMeasure(measure)) {
|
|
2245
2326
|
let node = parsed.get(key);
|
|
2246
2327
|
if (!node) {
|
|
@@ -2249,7 +2330,7 @@ function foldedMeasures(measureByKey, periodCount) {
|
|
|
2249
2330
|
}
|
|
2250
2331
|
return emitFormulaSql(node, {
|
|
2251
2332
|
measure: (ref) => exprOf(ref, part, depth + 1),
|
|
2252
|
-
days: part.days,
|
|
2333
|
+
...part.daysSql !== void 0 ? { daysSql: part.daysSql } : { days: part.days },
|
|
2253
2334
|
...periodCount > 0 ? { periodCount } : {}
|
|
2254
2335
|
});
|
|
2255
2336
|
}
|
|
@@ -2262,15 +2343,15 @@ function foldedMeasures(measureByKey, periodCount) {
|
|
|
2262
2343
|
}
|
|
2263
2344
|
function streamSum(measure, over) {
|
|
2264
2345
|
const call = aggregateOf(measure, "COUNT(*)");
|
|
2265
|
-
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})`;
|
|
2346
|
+
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})`;
|
|
2266
2347
|
return `${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`;
|
|
2267
2348
|
}
|
|
2268
2349
|
function compileStreams(model, view, ctx) {
|
|
2269
2350
|
const options = view.options ?? {};
|
|
2270
2351
|
const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
|
|
2271
|
-
if ((options.activity ?? "with") !== "with")
|
|
2272
|
-
if (options.others_row)
|
|
2273
|
-
if (options.average_column && view.mode === "period")
|
|
2352
|
+
if ((options.activity ?? "with") !== "with") fail2("option_unsupported", `the activity option is not compiled for ${what} yet`);
|
|
2353
|
+
if (options.others_row) fail2("option_unsupported", `an others row is not compiled for ${what} yet`);
|
|
2354
|
+
if (options.average_column && view.mode === "period") fail2("option_unsupported", `an average column is not compiled for ${what} yet`);
|
|
2274
2355
|
const totalRow = options.total_row === true;
|
|
2275
2356
|
const averageRow = options.average_row === true;
|
|
2276
2357
|
const sumRow = options.sum_row === true;
|
|
@@ -2279,12 +2360,12 @@ function compileStreams(model, view, ctx) {
|
|
|
2279
2360
|
const nest = nestOf(view, lead);
|
|
2280
2361
|
if (nest) {
|
|
2281
2362
|
if (averageRow || sumRow || options.hide_zero_rows) {
|
|
2282
|
-
|
|
2363
|
+
fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
|
|
2283
2364
|
}
|
|
2284
|
-
if (lead.having !== null)
|
|
2365
|
+
if (lead.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
|
|
2285
2366
|
}
|
|
2286
2367
|
const shown = shownMeasures(view, measureByKey);
|
|
2287
|
-
const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ??
|
|
2368
|
+
const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
|
|
2288
2369
|
const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
|
|
2289
2370
|
const range = period.window;
|
|
2290
2371
|
const periodVariance = view.mode === "period_variance";
|
|
@@ -2292,7 +2373,7 @@ function compileStreams(model, view, ctx) {
|
|
|
2292
2373
|
const two = view.mode === "variance" || periodVariance ? comparedWith(model, view, ctx, range) : null;
|
|
2293
2374
|
const earlierBuckets = periodVariance && two ? splitWindow(two.comparison, period.grain, model.periods) : [];
|
|
2294
2375
|
if (periodVariance && earlierBuckets.length !== buckets.length) {
|
|
2295
|
-
|
|
2376
|
+
fail2("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlierBuckets.length}, so they cannot be set side by side`);
|
|
2296
2377
|
}
|
|
2297
2378
|
const whole = two ? { prefix: "a", days: two.current.days, filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` } : { prefix: "a", days: daysBetween(range.from, range.to), filter: null, last: `${FACT}."__lastw"` };
|
|
2298
2379
|
const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
|
|
@@ -2407,9 +2488,9 @@ function compileStreams(model, view, ctx) {
|
|
|
2407
2488
|
}
|
|
2408
2489
|
columns.push({ name: "__rows", kind: "meta", label: "Row count" });
|
|
2409
2490
|
const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
|
|
2410
|
-
if (sort.dir !== "asc" && sort.dir !== "desc")
|
|
2491
|
+
if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
|
|
2411
2492
|
const sortName = sortNameOf(sort.by);
|
|
2412
|
-
if (!columns.some((c) => c.name === sortName && c.kind !== "meta"))
|
|
2493
|
+
if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
|
|
2413
2494
|
const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
|
|
2414
2495
|
const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
|
|
2415
2496
|
const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
|
|
@@ -2464,24 +2545,32 @@ function compileStreams(model, view, ctx) {
|
|
|
2464
2545
|
function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
2465
2546
|
const options = view.options ?? {};
|
|
2466
2547
|
const what = byPeriod ? "the long shape of a period view" : "matrix mode";
|
|
2467
|
-
if (view.levels !== void 0)
|
|
2468
|
-
if (byPeriod && options.average_column)
|
|
2469
|
-
if ((options.activity ?? "with") !== "with")
|
|
2470
|
-
if (options.others_row || options.average_row || options.sum_row)
|
|
2548
|
+
if (view.levels !== void 0) fail2("option_unsupported", `nested rows are not compiled for ${what} yet`);
|
|
2549
|
+
if (byPeriod && options.average_column) fail2("option_unsupported", "the average column is not compiled for the long shape of a period view yet");
|
|
2550
|
+
if ((options.activity ?? "with") !== "with") fail2("option_unsupported", `the activity option is not compiled for ${what} yet`);
|
|
2551
|
+
if (options.others_row || options.average_row || options.sum_row) fail2("option_unsupported", `others, average and sum rows are not compiled for ${what} yet`);
|
|
2471
2552
|
const totalRow = options.total_row === true;
|
|
2472
2553
|
const scope = scopeOf(model, view, ctx);
|
|
2473
2554
|
const { stream, measureByKey, groupDim } = scope;
|
|
2474
2555
|
const shown = shownMeasures(view, measureByKey);
|
|
2475
|
-
const first = shown[0] ??
|
|
2476
|
-
const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ??
|
|
2556
|
+
const first = shown[0] ?? fail2("no_measures", "a view needs at least one measure");
|
|
2557
|
+
const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
|
|
2477
2558
|
const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
|
|
2478
2559
|
const range = period.window;
|
|
2479
2560
|
const buckets = byPeriod ? period.buckets : [];
|
|
2480
2561
|
const days = daysBetween(range.from, range.to);
|
|
2481
2562
|
const uses = /* @__PURE__ */ new Set();
|
|
2482
2563
|
const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days, uses };
|
|
2483
|
-
const folded = streams ? foldedMeasures(measureByKey,
|
|
2484
|
-
const whole =
|
|
2564
|
+
const folded = streams ? foldedMeasures(measureByKey, buckets.length) : null;
|
|
2565
|
+
const whole = byPeriod ? {
|
|
2566
|
+
prefix: "a",
|
|
2567
|
+
days,
|
|
2568
|
+
filter: null,
|
|
2569
|
+
last: `${FACT}."__lastw"`,
|
|
2570
|
+
cellWhen: `GROUPING(${FACT}."__b") = 0`,
|
|
2571
|
+
// A folded row is a cell when it has a period number, and a total over the whole window when it has none.
|
|
2572
|
+
daysSql: `CASE ${buckets.map((b, i) => `WHEN "across" = ${i + 1} THEN ${sqlNumber(b.days)}`).join(" ")} ELSE ${sqlNumber(days)} END`
|
|
2573
|
+
} : { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
|
|
2485
2574
|
const rowCode = scope.codeExpr;
|
|
2486
2575
|
let colCode = `${FACT}."__b"`;
|
|
2487
2576
|
let keep = buckets.length;
|
|
@@ -2495,13 +2584,13 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2495
2584
|
reads.daysSql = `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${FACT}."__days") ELSE ${sqlNumber(days)} END`;
|
|
2496
2585
|
} else {
|
|
2497
2586
|
const across = view.across;
|
|
2498
|
-
if (!across || typeof across.dimension !== "string")
|
|
2587
|
+
if (!across || typeof across.dimension !== "string") fail2("bad_across", 'a matrix needs a second dimension in "across"');
|
|
2499
2588
|
const acrossDim = scope.dimension(across.dimension);
|
|
2500
|
-
if (acrossDim.key === groupDim.key)
|
|
2589
|
+
if (acrossDim.key === groupDim.key) fail2("bad_across", "the second dimension must differ from the first");
|
|
2501
2590
|
const order = across.order ?? "value";
|
|
2502
|
-
if (order !== "value" && order !== "code")
|
|
2591
|
+
if (order !== "value" && order !== "code") fail2("bad_across", `"${String(order)}" is not a column order`);
|
|
2503
2592
|
keep = across.limit ?? DEFAULT_ACROSS_MEMBERS;
|
|
2504
|
-
if (!Number.isInteger(keep) || keep < 1)
|
|
2593
|
+
if (!Number.isInteger(keep) || keep < 1) fail2("bad_across", "across.limit must be a whole number, 1 or more");
|
|
2505
2594
|
colCode = scope.propertyOf(acrossDim.key, "code");
|
|
2506
2595
|
acrossColumn = { name: "across", kind: "across", label: acrossDim.label, dimension: acrossDim.key };
|
|
2507
2596
|
if (acrossDim.table && acrossDim.name) {
|
|
@@ -2514,11 +2603,11 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2514
2603
|
const columnTotals = totalRow || !byPeriod;
|
|
2515
2604
|
const reserved = (columnTotals ? keep : 0) + (totalRow ? 1 : 0);
|
|
2516
2605
|
const room = Math.floor((maxRows - reserved) / (keep + 1));
|
|
2517
|
-
if (room < 1)
|
|
2606
|
+
if (room < 1) fail2("bad_paging", `${keep} columns leave no room for a row in ${maxRows} result rows`);
|
|
2518
2607
|
const asked = view.limit ?? DEFAULT_PAGE_ROWS;
|
|
2519
2608
|
const offset = view.offset ?? 0;
|
|
2520
|
-
if (!Number.isInteger(asked) || asked < 1)
|
|
2521
|
-
if (!Number.isInteger(offset) || offset < 0)
|
|
2609
|
+
if (!Number.isInteger(asked) || asked < 1) fail2("bad_paging", "limit must be a whole number, 1 or more");
|
|
2610
|
+
if (!Number.isInteger(offset) || offset < 0) fail2("bad_paging", "offset must be a whole number, 0 or more");
|
|
2522
2611
|
const limit = Math.min(asked, room);
|
|
2523
2612
|
const columns = [{ name: "code", kind: "code", label: groupDim.label }];
|
|
2524
2613
|
const properties = shownProperties(view);
|
|
@@ -2545,18 +2634,19 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2545
2634
|
shown.forEach((measure) => addMeasure(measure, true));
|
|
2546
2635
|
unseen.forEach((measure) => addMeasure(measure, false));
|
|
2547
2636
|
const sort = view.sort ?? { by: `total.${first.key}`, dir: "desc" };
|
|
2548
|
-
if (sort.dir !== "asc" && sort.dir !== "desc")
|
|
2637
|
+
if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
|
|
2549
2638
|
let sortName = sortNameOf(sort.by);
|
|
2550
2639
|
const byOne = String(sort.by).split(".");
|
|
2551
2640
|
const bucket = byPeriod && byOne[0] === "period" && byOne.length === 3 ? buckets[Number(byOne[1]) - 1] : void 0;
|
|
2552
2641
|
if (bucket && shown.some((measure) => measure.key === byOne[2])) {
|
|
2553
2642
|
const n = buckets.indexOf(bucket) + 1;
|
|
2554
2643
|
const slice = { bucket, filter: `${FACT}."__b" = ${n}`, last: `${FACT}."__b" = ${n} AND ${FACT}."__last"` };
|
|
2555
|
-
|
|
2644
|
+
const part = { prefix: `a${n}`, days: bucket.days, filter: slice.filter, last: slice.last };
|
|
2645
|
+
select.push(`CAST(${folded ? folded.exprOf(String(byOne[2]), part, 0) : measureOver(reads, String(byOne[2]), slice)} AS DOUBLE) AS "__sort"`);
|
|
2556
2646
|
hidden.push("__sort");
|
|
2557
2647
|
sortName = "__sort";
|
|
2558
2648
|
} else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
|
|
2559
|
-
|
|
2649
|
+
fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
|
|
2560
2650
|
}
|
|
2561
2651
|
const flags = (row, col) => [`CAST(GROUPING(${row}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${col}) AS INTEGER) AS "__across_total"`];
|
|
2562
2652
|
select.push(...folded ? ['"__total"', '"__across_total"'] : flags(rowCode, colCode));
|
|
@@ -2585,7 +2675,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2585
2675
|
const stages = streamKeys.map((key, i) => {
|
|
2586
2676
|
const own = i === 0 ? scope : scopeOf(model, { ...view, stream: key }, ctx);
|
|
2587
2677
|
const row = own.codeExpr;
|
|
2588
|
-
const col = own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
|
|
2678
|
+
const col = byPeriod ? `${FACT}."__b"` : own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
|
|
2589
2679
|
const mine = folded?.needed.get(key) ?? [];
|
|
2590
2680
|
const part = [`${row} AS "code"`];
|
|
2591
2681
|
properties.forEach((property) => {
|
|
@@ -2599,7 +2689,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
|
|
|
2599
2689
|
part.push(...flags(row, col));
|
|
2600
2690
|
return {
|
|
2601
2691
|
select: part,
|
|
2602
|
-
from: factAcross(own.stream, range,
|
|
2692
|
+
from: factAcross(own.stream, range, buckets, null, mine.some(({ measure }) => measure.snapshot)),
|
|
2603
2693
|
joins: [...own.joins.values()],
|
|
2604
2694
|
where: own.where,
|
|
2605
2695
|
groupBy: sets(row, col)
|
|
@@ -2755,6 +2845,7 @@ export {
|
|
|
2755
2845
|
quoteIdent,
|
|
2756
2846
|
refusalOf,
|
|
2757
2847
|
resolvePeriod,
|
|
2848
|
+
shownColumns,
|
|
2758
2849
|
splitWindow,
|
|
2759
2850
|
sqlDate,
|
|
2760
2851
|
sqlNumber,
|
|
@@ -2764,5 +2855,6 @@ export {
|
|
|
2764
2855
|
tablesIn,
|
|
2765
2856
|
usesGridOnlyFunction,
|
|
2766
2857
|
validateModel,
|
|
2858
|
+
withCalculations,
|
|
2767
2859
|
writtenLength
|
|
2768
2860
|
};
|
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.11",
|
|
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",
|