@sprigr/apps-reporting-core 0.0.10 → 0.0.12

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 CHANGED
@@ -73,7 +73,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
73
73
  - **Variance** reads the period and a comparison window (`compare`: `previous_year` for the same dates a year earlier, `previous_period` for the period just before, or `{ period }` for a window of its own, which may overlap the period or come after it) in one pass. Each measure gets four columns: current, previous, variance and variance percentage (a fraction).
74
74
  - **Period variance** is a period view where every period is a variance. Each period gets four columns: its own value, the value of the period at the same place in the comparison window, the variance and the variance percentage. The same four over the whole windows follow. `compare` is read as in a variance. The comparison window is cut with the period's grain, and the view is refused when the two windows do not cut into the same number of periods. Columns are named `b<n>__`, `pb<n>__`, `bv<n>__` and `bvp<n>__` before the measure key, `<n>` counted from the oldest period; each carries `bucket: n` and its `part`. `sort.by` and a filter on a measure take what a period view and a variance take. The statement is always one column per period, and a view too wide for the route is refused.
75
75
  - **A filter on a dimension** tests fact rows, on the code or on a property. `in` and `not_in` match whole values. `contains` and `not_contains` look for text anywhere in the value, whatever its case; a rule with several texts passes when any one is found, and a text can be up to 200 characters. A row with no value passes `not_in` and `not_contains`. Rules sit in groups joined by `and` or `or`, up to three deep, so a search over a code or a name is an `or` group of two `contains` rules. A data point of a custom view takes the same rules.
76
- - **A filter on a member's own figure** names a dimension and a measure together: `{ dimension, measure, cmp, value, period? }`. It keeps the fact rows of the members whose figure passes, worked out over the rule's own `period` (the view's when it gives none), so "products that sold more than 100 last year" can filter a view of this month. It sits with the dimension rules, in `and` and `or` groups and in every mode. The figure is over all of the stream's rows in those dates, whatever else the view filters on, and the measure must be the view's stream's own, so a view that reads several streams refuses. The result lists the dates each such rule reads in `ruleWindows`, and `months` covers them. A data point of a custom view does not take one.
76
+ - **A filter on a member's own figure** names a dimension and a measure together: `{ dimension, measure, cmp, value, period? }`. It keeps the fact rows of the members whose figure passes, worked out over the rule's own `period` (the view's when it gives none), so "products that sold more than 100 last year" can filter a view of this month. It sits with the dimension rules, in `and` and `or` groups and in every mode. The figure is over all of the rows of the measure's own stream in those dates, whatever else the view filters on, so "stock on hand over 0" can filter a view of sales. That stream must reach the rule's dimension, and a formula over two streams is refused. Each stream the view reads keeps the same members, and `compileRollupView` reads a rollup of the rule's stream too. A member with no rows on that stream has a sum or count of 0, as Phocas reads it, so "sales under 100" keeps products that sold nothing. Those members are listed from the dimension's table, or from the table of the dimension it hangs off, and a rule that 0 passes is refused on a dimension with neither. A snapshot figure, a formula and the other aggregates stay blank for such a member and pass no comparison. The result lists the dates each such rule reads in `ruleWindows`, and `months` covers them. A data point of a custom view does not take one.
77
77
  - **A filter on a measure** drops rows after grouping. It never drops the total row, which stays the total of every member. A measure the view does not show can be filtered on. Dimension rules and measure rules combine with "and" only.
78
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.
@@ -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 fail(reason, detail) {
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) fail("empty_selection", `${what} has nothing selected`);
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") fail("empty_selection", `${what} holds a value that is not text`);
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 out = compileMode(model, view, ctx);
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)) fail("mode_unsupported", `mode "${String(view.mode)}" is not compiled yet`);
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") {
@@ -1247,7 +1313,8 @@ function compileRollupView(model, view, ctx) {
1247
1313
  }
1248
1314
  let rolled = model;
1249
1315
  const rollups = [];
1250
- for (const key of plain.streams ?? [view.stream]) {
1316
+ const keys = [.../* @__PURE__ */ new Set([...plain.streams ?? [view.stream], ...memberRuleStreams(model, view)])];
1317
+ for (const key of keys) {
1251
1318
  const listed = model.streams.find((s) => s.key === key)?.rollups ?? [];
1252
1319
  const smallestFirst = [...listed].sort((a, b) => Object.keys(a.dimension_keys).length - Object.keys(b.dimension_keys).length);
1253
1320
  const pick = smallestFirst.find((rollup) => compileView(onRollup(model, key, rollup), view, ctx).ok);
@@ -1285,31 +1352,74 @@ function memberWindows(model, view, ctx) {
1285
1352
  if (view.filters) walk(view.filters);
1286
1353
  return found;
1287
1354
  }
1355
+ function measureStreams(measureByKey, key, depth = 0) {
1356
+ const measure = measureByKey.get(key);
1357
+ if (!measure) return /* @__PURE__ */ new Set();
1358
+ if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
1359
+ const found = /* @__PURE__ */ new Set();
1360
+ if (depth <= 20) formulaRefs(parseFormula(measure.formula)).forEach((ref) => measureStreams(measureByKey, ref, depth + 1).forEach((s) => found.add(s)));
1361
+ return found;
1362
+ }
1363
+ function memberRuleStream(model, key, fallback) {
1364
+ const streams = [...measureStreams(new Map(model.measures.map((m) => [m.key, m])), key)];
1365
+ if (streams.length > 1) fail2("measure_not_on_stream", `"${key}" reads streams ${streams.map((s) => `"${s}"`).join(" and ")}; a member rule tests its members on one`);
1366
+ return streams[0] ?? fallback;
1367
+ }
1368
+ function zeroPasses(cmp, value) {
1369
+ switch (cmp) {
1370
+ case "=":
1371
+ return value === 0;
1372
+ case "<>":
1373
+ return value !== 0;
1374
+ case "<":
1375
+ return 0 < value;
1376
+ case "<=":
1377
+ return 0 <= value;
1378
+ case ">":
1379
+ return 0 > value;
1380
+ case ">=":
1381
+ return 0 >= value;
1382
+ default:
1383
+ return false;
1384
+ }
1385
+ }
1386
+ function memberRuleStreams(model, view) {
1387
+ const found = [];
1388
+ const walk = (rule) => {
1389
+ if (isGroup(rule)) (Array.isArray(rule.rules) ? rule.rules : []).forEach(walk);
1390
+ else if (isMemberRule(rule)) {
1391
+ const key = memberRuleStream(model, rule.measure, view.stream);
1392
+ if (!found.includes(key)) found.push(key);
1393
+ }
1394
+ };
1395
+ if (view.filters) walk(view.filters);
1396
+ return found;
1397
+ }
1288
1398
  function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1289
- const stream = model.streams.find((s) => s.key === view.stream) ?? fail("unknown_stream", `no stream "${String(view.stream)}"`);
1399
+ const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
1290
1400
  const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
1291
1401
  const measureByKey = new Map(model.measures.map((m) => [m.key, m]));
1292
1402
  const joins = /* @__PURE__ */ new Map();
1293
1403
  const alias = (dim) => quoteIdent(`d_${dim.key}`);
1294
- const dimension = (key) => dimByKey.get(key) ?? fail("unknown_dimension", `no dimension "${String(key)}"`);
1404
+ const dimension = (key) => dimByKey.get(key) ?? fail2("unknown_dimension", `no dimension "${String(key)}"`);
1295
1405
  const join = (dim, codeExpr2, into = joins) => {
1296
- if (!dim.table || !dim.code) fail("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1406
+ if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1297
1407
  const a = alias(dim);
1298
1408
  if (!into.has(a)) into.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${codeExpr2}`);
1299
1409
  return a;
1300
1410
  };
1301
- const codeOf = (key, depth = 0, into = joins) => {
1302
- if (depth > 20) fail("unknown_dimension", `the via chain of "${key}" does not end`);
1411
+ const codeOf = (key, depth = 0, into = joins, on = stream) => {
1412
+ if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
1303
1413
  const dim = dimension(key);
1304
- const direct = stream.dimension_keys[key];
1414
+ const direct = on.dimension_keys[key];
1305
1415
  if (direct !== void 0) return `${FACT}.${quoteIdent(direct)}`;
1306
- if (!dim.via) fail("dimension_not_on_stream", `stream "${stream.key}" has no "${key}"`);
1416
+ if (!dim.via) fail2("dimension_not_on_stream", `stream "${on.key}" has no "${key}"`);
1307
1417
  const parent = dimension(dim.via.dimension);
1308
- return `${join(parent, codeOf(parent.key, depth + 1, into), into)}.${quoteIdent(dim.via.column)}`;
1418
+ return `${join(parent, codeOf(parent.key, depth + 1, into, on), into)}.${quoteIdent(dim.via.column)}`;
1309
1419
  };
1310
1420
  const columnOf = (dim, property) => {
1311
1421
  const column = property === "name" ? dim.name : dim.properties.find((p) => p.key === property)?.column;
1312
- return column ?? fail("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
1422
+ return column ?? fail2("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
1313
1423
  };
1314
1424
  const propertyOf = (dimKey, property) => {
1315
1425
  const code = codeOf(dimKey);
@@ -1323,7 +1433,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1323
1433
  const membersOf = () => {
1324
1434
  const table = groupDim.table;
1325
1435
  const codeColumn = groupDim.code;
1326
- if (!table || !codeColumn) fail("dimension_has_no_table", `"${groupDim.key}" has no table to list its members from`);
1436
+ if (!table || !codeColumn) fail2("dimension_has_no_table", `"${groupDim.key}" has no table to list its members from`);
1327
1437
  const root = quoteIdent("mb");
1328
1438
  const joinsHere = /* @__PURE__ */ new Map();
1329
1439
  const reaches = (key, depth = 0) => {
@@ -1333,7 +1443,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1333
1443
  };
1334
1444
  const tableOf = (dim, code) => {
1335
1445
  if (dim.key === groupDim.key) return root;
1336
- if (!dim.table || !dim.code) fail("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1446
+ if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1337
1447
  const a = quoteIdent(`mb_${dim.key}`);
1338
1448
  if (!joinsHere.has(a)) joinsHere.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${code}`);
1339
1449
  return a;
@@ -1341,7 +1451,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1341
1451
  const codeHere = (key) => {
1342
1452
  const dim = dimension(key);
1343
1453
  if (dim.key === groupDim.key) return `${root}.${quoteIdent(codeColumn)}`;
1344
- const via = dim.via ?? fail("dimension_not_on_stream", `"${key}" is not above "${groupDim.key}"`);
1454
+ const via = dim.via ?? fail2("dimension_not_on_stream", `"${key}" is not above "${groupDim.key}"`);
1345
1455
  const parent = dimension(via.dimension);
1346
1456
  return `${tableOf(parent, codeHere(parent.key))}.${quoteIdent(via.column)}`;
1347
1457
  };
@@ -1366,27 +1476,37 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1366
1476
  if (mb && mb.reaches(step.dimension)) mb.conds.push(`CAST(${mb.codeHere(step.dimension)} AS VARCHAR) IN ${inList(values)}`);
1367
1477
  });
1368
1478
  const filterMeasures = [];
1479
+ const memberSource = (dim) => {
1480
+ if (dim.table && dim.code) return { table: dim.table, column: dim.code };
1481
+ const parent = dim.via ? dimension(dim.via.dimension) : void 0;
1482
+ if (dim.via && parent?.table) return { table: parent.table, column: dim.via.column };
1483
+ return fail2("dimension_has_no_table", `"${dim.key}" has no table to list its members from`);
1484
+ };
1369
1485
  const memberLeaf = (rule, outer) => {
1370
- if (!MEASURE_CMPS.includes(rule.cmp)) fail("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
1371
- if (!measureByKey.has(rule.measure)) fail("unknown_measure", `no measure "${String(rule.measure)}"`);
1486
+ if (!MEASURE_CMPS.includes(rule.cmp)) fail2("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
1487
+ if (!measureByKey.has(rule.measure)) fail2("unknown_measure", `no measure "${String(rule.measure)}"`);
1488
+ const on = model.streams.find((s) => s.key === memberRuleStream(model, rule.measure, stream.key)) ?? stream;
1372
1489
  const window = memberWindow(model, view, ctx, rule);
1373
1490
  const own = /* @__PURE__ */ new Map();
1374
- const member = codeOf(rule.dimension, 0, own);
1491
+ const member = codeOf(rule.dimension, 0, own, on);
1375
1492
  const uses = /* @__PURE__ */ new Set();
1376
- const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(window.from, window.to), uses };
1493
+ const reads = { stream: on, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(window.from, window.to), uses };
1377
1494
  const figure = measureOver(reads, rule.measure, null);
1378
- const passing = [
1379
- `SELECT CAST(${member} AS VARCHAR) FROM ${factOver(stream, window, uses.has("snapshot"))}`,
1380
- ...own.values(),
1381
- `GROUP BY ${member} HAVING ${figure} ${rule.cmp} ${sqlNumber(rule.value)}`
1382
- ].join(" ");
1383
- return `CAST(${outer} AS VARCHAR) IN (${passing})`;
1495
+ const value = sqlNumber(rule.value);
1496
+ const from = [`FROM ${factOver(on, window, uses.has("snapshot"))}`, ...own.values()].join(" ");
1497
+ const measure = measureByKey.get(rule.measure);
1498
+ const blankIsZero = measure !== void 0 && !isFormulaMeasure(measure) && !measure.snapshot && (measure.agg === "sum" || measure.agg === "count") && zeroPasses(rule.cmp, rule.value);
1499
+ if (!blankIsZero) return `CAST(${outer} AS VARCHAR) IN (SELECT CAST(${member} AS VARCHAR) ${from} GROUP BY ${member} HAVING ${figure} ${rule.cmp} ${value})`;
1500
+ const source = memberSource(dimension(rule.dimension));
1501
+ const listed = `"__mb".${quoteIdent(source.column)}`;
1502
+ const figures = `SELECT CAST(${member} AS VARCHAR) AS "__m", ${figure} AS "__v" ${from} GROUP BY ${member}`;
1503
+ return `CAST(${outer} AS VARCHAR) IN (SELECT CAST(${listed} AS VARCHAR) FROM ${quoteIdent(source.table)} AS "__mb" LEFT JOIN (${figures}) AS "__r" ON "__r"."__m" = CAST(${listed} AS VARCHAR) WHERE COALESCE("__r"."__v", 0) ${rule.cmp} ${value})`;
1384
1504
  };
1385
1505
  const dimensionLeafWith = (resolve) => (rule) => {
1386
1506
  if (isMemberRule(rule)) return memberLeaf(rule, resolve(rule.dimension, "code"));
1387
- if ("measure" in rule) fail("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
1507
+ if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
1388
1508
  const whole = rule.cmp === "in" || rule.cmp === "not_in";
1389
- if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
1509
+ if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
1390
1510
  const expr = resolve(rule.dimension, rule.property ?? "code");
1391
1511
  const what = `the filter on "${String(rule.dimension)}"`;
1392
1512
  const values = stringList(rule.values, what);
@@ -1394,8 +1514,8 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1394
1514
  return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
1395
1515
  }
1396
1516
  const found = values.map((text) => {
1397
- if (text === "") fail("empty_selection", `${what} holds an empty text to look for`);
1398
- if (text.length > MAX_KEYWORD_CHARS) fail("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
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`);
1399
1519
  return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
1400
1520
  });
1401
1521
  const any = `(${found.join(" OR ")})`;
@@ -1403,39 +1523,39 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1403
1523
  };
1404
1524
  const dimensionLeaf = dimensionLeafWith(propertyOf);
1405
1525
  const measureLeaf = (rule) => {
1406
- if (!("measure" in rule) || isMemberRule(rule)) fail("measure_filter_unsupported", "a dimension rule cannot sit in a group of measure rules");
1407
- if (!MEASURE_CMPS.includes(rule.cmp)) fail("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
1526
+ if (!("measure" in rule) || isMemberRule(rule)) fail2("measure_filter_unsupported", "a dimension rule cannot sit in a group of measure rules");
1527
+ if (!MEASURE_CMPS.includes(rule.cmp)) fail2("measure_filter_unsupported", `"${String(rule.cmp)}" is not a comparison`);
1408
1528
  const part = rule.of ?? "current";
1409
- if (!VARIANCE_PARTS.includes(part)) fail("measure_filter_unsupported", `"${String(part)}" is not a variance column`);
1410
- if (part !== "current" && view.mode !== "variance" && view.mode !== "period_variance") fail("measure_filter_unsupported", `"${part}" exists in a variance only`);
1411
- const measure = measureByKey.get(rule.measure) ?? fail("unknown_measure", `no measure "${String(rule.measure)}"`);
1529
+ if (!VARIANCE_PARTS.includes(part)) fail2("measure_filter_unsupported", `"${String(part)}" is not a variance column`);
1530
+ if (part !== "current" && view.mode !== "variance" && view.mode !== "period_variance") fail2("measure_filter_unsupported", `"${part}" exists in a variance only`);
1531
+ const measure = measureByKey.get(rule.measure) ?? fail2("unknown_measure", `no measure "${String(rule.measure)}"`);
1412
1532
  if (!filterMeasures.includes(measure.key)) filterMeasures.push(measure.key);
1413
1533
  return `${quoteIdent(`${PART_PREFIX[part]}${measure.key}`)} ${rule.cmp} ${sqlNumber(rule.value)}`;
1414
1534
  };
1415
1535
  const kindOf = (rule, depth) => {
1416
1536
  if (!isGroup(rule)) return "measure" in rule && !isMemberRule(rule) ? "measure" : "dimension";
1417
- if (depth > MAX_FILTER_DEPTH) fail("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
1537
+ if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
1418
1538
  const kinds = new Set((Array.isArray(rule.rules) ? rule.rules : []).map((r) => kindOf(r, depth + 1)));
1419
- if (kinds.size > 1) fail("measure_filter_unsupported", "below the top level a filter group holds dimension rules or measure rules, not both");
1539
+ if (kinds.size > 1) fail2("measure_filter_unsupported", "below the top level a filter group holds dimension rules or measure rules, not both");
1420
1540
  return kinds.has("measure") ? "measure" : "dimension";
1421
1541
  };
1422
1542
  const groupSql = (group, depth, leaf) => {
1423
- if (depth > MAX_FILTER_DEPTH) fail("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
1424
- if (group.op !== "and" && group.op !== "or") fail("empty_filter", 'a filter group needs op "and" or "or"');
1543
+ if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
1544
+ if (group.op !== "and" && group.op !== "or") fail2("empty_filter", 'a filter group needs op "and" or "or"');
1425
1545
  const rules = Array.isArray(group.rules) ? group.rules : [];
1426
- if (rules.length === 0) fail("empty_filter", "a filter group has no rules");
1546
+ if (rules.length === 0) fail2("empty_filter", "a filter group has no rules");
1427
1547
  const parts2 = rules.map((rule) => isGroup(rule) ? groupSql(rule, depth + 1, leaf) : leaf(rule));
1428
1548
  return `(${parts2.join(group.op === "and" ? " AND " : " OR ")})`;
1429
1549
  };
1430
1550
  let having = null;
1431
1551
  if (view.filters) {
1432
1552
  const top = view.filters;
1433
- if (top.op !== "and" && top.op !== "or") fail("empty_filter", 'a filter group needs op "and" or "or"');
1553
+ if (top.op !== "and" && top.op !== "or") fail2("empty_filter", 'a filter group needs op "and" or "or"');
1434
1554
  const rules = Array.isArray(top.rules) ? top.rules : [];
1435
1555
  const onRows = rules.filter((rule) => kindOf(rule, 1) === "dimension");
1436
1556
  const onGroups = rules.filter((rule) => kindOf(rule, 1) === "measure");
1437
1557
  if (onRows.length > 0 && onGroups.length > 0 && top.op === "or") {
1438
- fail("measure_filter_unsupported", 'dimension rules and measure rules combine with "and" only');
1558
+ fail2("measure_filter_unsupported", 'dimension rules and measure rules combine with "and" only');
1439
1559
  }
1440
1560
  if (onRows.length > 0) where.push(groupSql({ op: top.op, rules: onRows }, 0, dimensionLeaf));
1441
1561
  if (onGroups.length > 0) having = groupSql({ op: top.op, rules: onGroups }, 0, measureLeaf);
@@ -1448,7 +1568,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1448
1568
  }
1449
1569
  }
1450
1570
  const keyword = typeof view.keyword === "string" ? view.keyword.trim() : "";
1451
- if (keyword.length > MAX_KEYWORD_CHARS) fail("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
1571
+ if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
1452
1572
  if (keyword !== "") {
1453
1573
  const pattern = `${sqlValue(likePattern(keyword))} ESCAPE '\\'`;
1454
1574
  const targets = [`CAST(${codeExpr} AS VARCHAR) ILIKE ${pattern}`];
@@ -1470,25 +1590,25 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1470
1590
  return { stream, measureByKey, joins, dimension, propertyOf, groupDim, codeExpr, where, dimensionRule: dimensionLeaf, having, filterMeasures, members, focus };
1471
1591
  }
1472
1592
  function shownMeasures(view, measureByKey) {
1473
- if (!Array.isArray(view.measures) || view.measures.length === 0) fail("no_measures", "a view needs at least one measure");
1593
+ if (!Array.isArray(view.measures) || view.measures.length === 0) fail2("no_measures", "a view needs at least one measure");
1474
1594
  return view.measures.map((key, i) => {
1475
- if (view.measures.indexOf(key) !== i) fail("duplicate_measure", `"${String(key)}" is listed twice`);
1476
- return measureByKey.get(key) ?? fail("unknown_measure", `no measure "${String(key)}"`);
1595
+ if (view.measures.indexOf(key) !== i) fail2("duplicate_measure", `"${String(key)}" is listed twice`);
1596
+ return measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${String(key)}"`);
1477
1597
  });
1478
1598
  }
1479
1599
  function pageOf(view, ctx, reserved) {
1480
1600
  const maxRows = ctx.maxRows ?? ROUTE_MAX_ROWS;
1481
1601
  const limit = view.limit ?? DEFAULT_PAGE_ROWS;
1482
1602
  const offset = view.offset ?? 0;
1483
- if (!Number.isInteger(limit) || limit < 1 || limit + reserved > maxRows) fail("bad_paging", `limit must be a whole number from 1 to ${maxRows - reserved}`);
1484
- if (!Number.isInteger(offset) || offset < 0) fail("bad_paging", "offset must be a whole number, 0 or more");
1603
+ if (!Number.isInteger(limit) || limit < 1 || limit + reserved > maxRows) fail2("bad_paging", `limit must be a whole number from 1 to ${maxRows - reserved}`);
1604
+ if (!Number.isInteger(offset) || offset < 0) fail2("bad_paging", "offset must be a whole number, 0 or more");
1485
1605
  return { limit, offset };
1486
1606
  }
1487
1607
  function checkLength(sql, ctx) {
1488
1608
  const maxSqlChars = ctx.maxSqlChars ?? ROUTE_MAX_SQL_CHARS;
1489
1609
  const length = writtenLength(sql);
1490
1610
  if (length > maxSqlChars) {
1491
- fail("sql_too_long", `the statement is ${length} characters, the limit is ${maxSqlChars}; use fewer periods, measures or selected values`);
1611
+ fail2("sql_too_long", `the statement is ${length} characters, the limit is ${maxSqlChars}; use fewer periods, measures or selected values`);
1492
1612
  }
1493
1613
  }
1494
1614
  function valueOf(measure) {
@@ -1556,8 +1676,8 @@ function rankAndPage(source, sortName, sort, having, left, offset, limit, extra
1556
1676
  ];
1557
1677
  }
1558
1678
  function measureOver(src, key, slice, depth = 0) {
1559
- if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
1560
- const measure = src.measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
1679
+ if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
1680
+ const measure = src.measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
1561
1681
  if (isFormulaMeasure(measure)) {
1562
1682
  let node = src.parsed.get(key);
1563
1683
  if (!node) {
@@ -1570,7 +1690,7 @@ function measureOver(src, key, slice, depth = 0) {
1570
1690
  ...src.periodCount !== void 0 ? { periodCount: src.periodCount } : {}
1571
1691
  });
1572
1692
  }
1573
- if (measure.stream !== src.stream.key) fail("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${src.stream.key}"`);
1693
+ if (measure.stream !== src.stream.key) fail2("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${src.stream.key}"`);
1574
1694
  const call = aggregateOf(measure, src.countAll);
1575
1695
  if (measure.snapshot) {
1576
1696
  src.uses.add("snapshot");
@@ -1604,10 +1724,10 @@ function comparedWith(model, view, ctx, window) {
1604
1724
  const compare = view.compare ?? "previous_year";
1605
1725
  let comparison;
1606
1726
  if (typeof compare === "object" && compare !== null) {
1607
- if (typeof compare.period !== "object" || compare.period === null) fail("option_unsupported", "a comparison given as an object needs a period");
1727
+ if (typeof compare.period !== "object" || compare.period === null) fail2("option_unsupported", "a comparison given as an object needs a period");
1608
1728
  comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
1609
1729
  } else {
1610
- if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1730
+ if (compare !== "previous_year" && compare !== "previous_period") fail2("option_unsupported", `"${String(compare)}" is not a comparison`);
1611
1731
  comparison = comparisonWindow(window, compare);
1612
1732
  }
1613
1733
  const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
@@ -1650,15 +1770,15 @@ function propertyLabel(dim, property) {
1650
1770
  function nestOf(view, scope) {
1651
1771
  if (view.levels === void 0) return null;
1652
1772
  const keys = view.levels;
1653
- if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_LEVELS) fail("bad_levels", `levels lists from 1 to ${MAX_LEVELS} dimensions`);
1773
+ if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_LEVELS) fail2("bad_levels", `levels lists from 1 to ${MAX_LEVELS} dimensions`);
1654
1774
  const codes = [];
1655
1775
  const select = [];
1656
1776
  const columns = [];
1657
1777
  keys.forEach((key, i) => {
1658
- if (typeof key !== "string") fail("bad_levels", "a level is named by its dimension key");
1778
+ if (typeof key !== "string") fail2("bad_levels", "a level is named by its dimension key");
1659
1779
  const dim = scope.dimension(key);
1660
1780
  const code = scope.propertyOf(dim.key, "code");
1661
- if (code === scope.codeExpr || codes.includes(code)) fail("bad_levels", `"${key}" is the row dimension, or is listed twice`);
1781
+ if (code === scope.codeExpr || codes.includes(code)) fail2("bad_levels", `"${key}" is the row dimension, or is listed twice`);
1662
1782
  codes.push(code);
1663
1783
  const level2 = i + 1;
1664
1784
  select.push(`${code} AS ${quoteIdent(`lv${level2}`)}`);
@@ -1682,27 +1802,27 @@ function nestOf(view, scope) {
1682
1802
  function compileGrouped(model, view, ctx) {
1683
1803
  const options = view.options ?? {};
1684
1804
  const activity = options.activity ?? "with";
1685
- if (activity !== "with" && activity !== "without" && activity !== "all") fail("option_unsupported", `"${String(activity)}" is not an activity option`);
1686
- if (options.others_row && activity !== "with") fail("option_unsupported", "an others row with the activity option is not compiled yet");
1805
+ if (activity !== "with" && activity !== "without" && activity !== "all") fail2("option_unsupported", `"${String(activity)}" is not an activity option`);
1806
+ if (options.others_row && activity !== "with") fail2("option_unsupported", "an others row with the activity option is not compiled yet");
1687
1807
  const totalRow = options.total_row === true && activity !== "without";
1688
1808
  const averageRow = options.average_row === true;
1689
1809
  const sumRow = options.sum_row === true;
1690
- if (options.hide_zero_rows && activity !== "with") fail("option_unsupported", "hiding zero rows with the activity option is not compiled yet");
1810
+ if (options.hide_zero_rows && activity !== "with") fail2("option_unsupported", "hiding zero rows with the activity option is not compiled yet");
1691
1811
  const averageColumn = options.average_column === true && view.mode === "period";
1692
1812
  const scope = scopeOf(model, view, ctx, activity !== "with", options.others_row === true);
1693
1813
  const { stream, measureByKey, joins, groupDim, where, members } = scope;
1694
1814
  const nest = nestOf(view, scope);
1695
1815
  if (nest) {
1696
1816
  if (activity !== "with" || options.others_row || averageRow || sumRow || options.hide_zero_rows) {
1697
- fail("option_unsupported", "the activity option, an others, average or sum row and hiding zero rows are not compiled with nested rows yet");
1817
+ fail2("option_unsupported", "the activity option, an others, average or sum row and hiding zero rows are not compiled with nested rows yet");
1698
1818
  }
1699
- if (scope.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
1819
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
1700
1820
  }
1701
1821
  const focused = scope.focus.length > 0 ? `COALESCE(${scope.focus.join(" AND ")}, FALSE)` : null;
1702
1822
  const othersRow = focused !== null;
1703
1823
  const codeExpr = members ? `COALESCE(${members.code}, ${FACT}."__code")` : scope.codeExpr;
1704
1824
  const shown = shownMeasures(view, measureByKey);
1705
- const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
1825
+ const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
1706
1826
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
1707
1827
  const periodVariance = view.mode === "period_variance";
1708
1828
  const buckets = view.mode === "period" || periodVariance ? period.buckets : [];
@@ -1731,7 +1851,7 @@ function compileGrouped(model, view, ctx) {
1731
1851
  if (periodVariance) {
1732
1852
  const earlier = splitWindow(comparison, period.grain, model.periods);
1733
1853
  if (earlier.length !== buckets.length) {
1734
- fail("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlier.length}, so they cannot be set side by side`);
1854
+ fail2("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlier.length}, so they cannot be set side by side`);
1735
1855
  }
1736
1856
  earlierBuckets = earlier;
1737
1857
  earlierSlices = earlier.map((bucket, i) => ({
@@ -1871,10 +1991,10 @@ function compileGrouped(model, view, ctx) {
1871
1991
  }
1872
1992
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
1873
1993
  const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
1874
- if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
1994
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
1875
1995
  const sortName = sortNameOf(sort.by);
1876
1996
  const sortColumn = columns.find((c) => c.name === sortName && c.kind !== "meta");
1877
- if (!sortColumn) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
1997
+ if (!sortColumn) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
1878
1998
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (othersRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
1879
1999
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
1880
2000
  const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
@@ -1929,20 +2049,20 @@ function compileGrouped(model, view, ctx) {
1929
2049
  }
1930
2050
  function compileCustom(model, view, ctx) {
1931
2051
  const options = view.options ?? {};
1932
- if (options.activity !== void 0 && options.activity !== "with") fail("option_unsupported", "the activity option in custom mode is not compiled yet");
1933
- if (options.others_row) fail("option_unsupported", "an others row in custom mode is not compiled yet");
2052
+ if (options.activity !== void 0 && options.activity !== "with") fail2("option_unsupported", "the activity option in custom mode is not compiled yet");
2053
+ if (options.others_row) fail2("option_unsupported", "an others row in custom mode is not compiled yet");
1934
2054
  const totalRow = options.total_row === true;
1935
2055
  const averageRow = options.average_row === true;
1936
2056
  const sumRow = options.sum_row === true;
1937
2057
  const scope = scopeOf(model, view, ctx);
1938
- if (scope.having !== null) fail("measure_filter_unsupported", "a filter on a measure in custom mode is not compiled yet");
2058
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure in custom mode is not compiled yet");
1939
2059
  const { stream, measureByKey, joins, groupDim, where, codeExpr } = scope;
1940
2060
  const nest = nestOf(view, scope);
1941
2061
  if (nest && (averageRow || sumRow || options.hide_zero_rows)) {
1942
- fail("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2062
+ fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
1943
2063
  }
1944
2064
  const listed = Array.isArray(view.custom_columns) ? view.custom_columns : [];
1945
- if (listed.length === 0) fail("bad_custom_column", "a custom view needs at least one column");
2065
+ if (listed.length === 0) fail2("bad_custom_column", "a custom view needs at least one column");
1946
2066
  const date = quoteIdent(stream.date);
1947
2067
  const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1948
2068
  const resolve = (spec) => resolvePeriod(spec, model.periods, ctx.today, { periodToDate: options.period_to_date === true }).window;
@@ -1965,24 +2085,17 @@ function compileCustom(model, view, ctx) {
1965
2085
  }
1966
2086
  return found;
1967
2087
  };
1968
- const streamsOf = (measure, depth = 0) => {
1969
- if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
1970
- const found = /* @__PURE__ */ new Set();
1971
- if (depth <= 20) {
1972
- formulaRefs(parseFormula(measure.formula)).forEach((ref) => {
1973
- const named = measureByKey.get(ref);
1974
- if (named) streamsOf(named, depth + 1).forEach((key) => found.add(key));
1975
- });
1976
- }
2088
+ const streamsOf = (measure) => {
2089
+ const found = measureStreams(measureByKey, measure.key);
1977
2090
  return found.size > 0 ? found : /* @__PURE__ */ new Set([stream.key]);
1978
2091
  };
1979
2092
  const points = [];
1980
2093
  const pointOf = (point, what) => {
1981
- if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1982
- const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
2094
+ if (typeof point !== "object" || point === null) fail2("bad_custom_column", `${what} has no data point`);
2095
+ const measure = measureByKey.get(point.measure) ?? fail2("unknown_measure", `no measure "${String(point.measure)}"`);
1983
2096
  const { window, number } = windowOf(point.period);
1984
2097
  const where2 = point.where;
1985
- if (where2 !== void 0 && (typeof where2 !== "object" || where2 === null || "measure" in where2)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
2098
+ 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`);
1986
2099
  const bucket = {
1987
2100
  key: `w${number}`,
1988
2101
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1993,9 +2106,9 @@ function compileCustom(model, view, ctx) {
1993
2106
  const read = (m, depth) => {
1994
2107
  const streams = streamsOf(m);
1995
2108
  if (streams.size > 1 && isFormulaMeasure(m)) {
1996
- if (depth > 20) fail("formula_cycle", `"${m.key}" refers back to itself`);
2109
+ if (depth > 20) fail2("formula_cycle", `"${m.key}" refers back to itself`);
1997
2110
  return emitFormulaSql(parseFormula(m.formula), {
1998
- measure: (ref) => read(measureByKey.get(ref) ?? fail("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
2111
+ measure: (ref) => read(measureByKey.get(ref) ?? fail2("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
1999
2112
  days: bucket.days
2000
2113
  });
2001
2114
  }
@@ -2023,23 +2136,23 @@ function compileCustom(model, view, ctx) {
2023
2136
  const left = ["__rn"];
2024
2137
  const keys = /* @__PURE__ */ new Set();
2025
2138
  listed.forEach((column, i) => {
2026
- if (typeof column !== "object" || column === null || !isIdentifier(column.key)) fail("bad_custom_column", `column ${i + 1} needs a key that is a plain name`);
2139
+ if (typeof column !== "object" || column === null || !isIdentifier(column.key)) fail2("bad_custom_column", `column ${i + 1} needs a key that is a plain name`);
2027
2140
  const { key } = column;
2028
- if (keys.has(key)) fail("bad_custom_column", `"${key}" is the key of two columns`);
2141
+ if (keys.has(key)) fail2("bad_custom_column", `"${key}" is the key of two columns`);
2029
2142
  keys.add(key);
2030
- if (column.point === void 0 === (column.expression === void 0)) fail("bad_custom_column", `"${key}" holds a point or an expression, one of the two`);
2143
+ if (column.point === void 0 === (column.expression === void 0)) fail2("bad_custom_column", `"${key}" holds a point or an expression, one of the two`);
2031
2144
  let expr;
2032
2145
  let about;
2033
2146
  if (column.point !== void 0) {
2034
2147
  const cur = pointOf(column.point, `"${key}"`);
2035
2148
  if (column.against === void 0) {
2036
- if (column.show !== void 0) fail("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
2149
+ if (column.show !== void 0) fail2("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
2037
2150
  expr = cur.ref;
2038
2151
  about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
2039
2152
  } else {
2040
2153
  const prev = pointOf(column.against, `"${key}"`);
2041
2154
  const show = column.show ?? "difference";
2042
- if (show !== "difference" && show !== "percent") fail("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
2155
+ if (show !== "difference" && show !== "percent") fail2("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
2043
2156
  expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
2044
2157
  about = {
2045
2158
  label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
@@ -2050,11 +2163,11 @@ function compileCustom(model, view, ctx) {
2050
2163
  }
2051
2164
  } else {
2052
2165
  const format = column.format ?? "number";
2053
- if (!MEASURE_FORMATS.includes(format)) fail("bad_custom_column", `"${String(format)}" is not a format`);
2166
+ if (!MEASURE_FORMATS.includes(format)) fail2("bad_custom_column", `"${String(format)}" is not a format`);
2054
2167
  const named = column.points ?? {};
2055
2168
  expr = emitFormulaSql(parseFormula(String(column.expression)), {
2056
2169
  measure: (ref) => {
2057
- if (!Object.prototype.hasOwnProperty.call(named, ref)) fail("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2170
+ if (!Object.prototype.hasOwnProperty.call(named, ref)) fail2("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2058
2171
  return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
2059
2172
  },
2060
2173
  days: reads.days
@@ -2067,8 +2180,8 @@ function compileCustom(model, view, ctx) {
2067
2180
  else columns.push({ name, kind: "measure", custom: key, ...about });
2068
2181
  });
2069
2182
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2070
- if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
2071
- if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
2183
+ if (measured.length === 0) fail2("bad_custom_column", "every column of the view is hidden");
2184
+ if (points.length === 0) fail2("bad_custom_column", "no column of the view reads a data point");
2072
2185
  const multi = reading.size > 1;
2073
2186
  points.forEach(({ sql: sql2 }, i) => {
2074
2187
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
@@ -2082,11 +2195,11 @@ function compileCustom(model, view, ctx) {
2082
2195
  }
2083
2196
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2084
2197
  const sort = view.sort ?? { by: `column.${measured[0]?.slice(3) ?? ""}`, dir: "desc" };
2085
- if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2198
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2086
2199
  const by = String(sort.by).split(".");
2087
2200
  const sortName = by[0] === "column" ? by.length === 2 && keys.has(by[1] ?? "") ? `c__${by[1]}` : "" : sortNameOf(sort.by);
2088
2201
  if (!sortName.startsWith("c__") && !columns.some((c) => c.name === sortName && (c.kind === "code" || c.kind === "property"))) {
2089
- fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2202
+ fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2090
2203
  }
2091
2204
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2092
2205
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
@@ -2154,19 +2267,19 @@ function compileCustom(model, view, ctx) {
2154
2267
  }
2155
2268
  function compileTransactions(model, view, ctx) {
2156
2269
  const options = view.options ?? {};
2157
- if (view.levels !== void 0) fail("option_unsupported", "a transaction list has no nested rows");
2158
- if (options.activity !== void 0 && options.activity !== "with") fail("option_unsupported", "a transaction list shows rows that exist; activity does not apply");
2159
- if (options.total_row || options.others_row || options.average_row || options.sum_row) fail("option_unsupported", "a transaction list has no total, others, average or sum row");
2270
+ if (view.levels !== void 0) fail2("option_unsupported", "a transaction list has no nested rows");
2271
+ if (options.activity !== void 0 && options.activity !== "with") fail2("option_unsupported", "a transaction list shows rows that exist; activity does not apply");
2272
+ 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");
2160
2273
  const scope = scopeOf(model, view, ctx);
2161
2274
  const { stream, measureByKey } = scope;
2162
- if (scope.having !== null) fail("measure_filter_unsupported", "a transaction list cannot be filtered on a measure");
2275
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a transaction list cannot be filtered on a measure");
2163
2276
  const shown = shownMeasures(view, measureByKey);
2164
2277
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2165
2278
  const windowDays = period.buckets.reduce((sum, b) => sum + b.days, 0);
2166
2279
  const parsed = /* @__PURE__ */ new Map();
2167
2280
  const rowSql = (key, depth) => {
2168
- if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2169
- const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2281
+ if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
2282
+ const measure = measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
2170
2283
  if (isFormulaMeasure(measure)) {
2171
2284
  let node = parsed.get(key);
2172
2285
  if (!node) {
@@ -2175,8 +2288,8 @@ function compileTransactions(model, view, ctx) {
2175
2288
  }
2176
2289
  return emitFormulaSql(node, { measure: (ref) => rowSql(ref, depth + 1), days: windowDays });
2177
2290
  }
2178
- if (measure.stream !== stream.key) fail("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${stream.key}"`);
2179
- if (measure.snapshot) fail("snapshot_measure_unsupported", `"${key}" is a snapshot measure, which is not compiled yet`);
2291
+ if (measure.stream !== stream.key) fail2("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${stream.key}"`);
2292
+ if (measure.snapshot) fail2("snapshot_measure_unsupported", `"${key}" is a snapshot measure, which is not compiled yet`);
2180
2293
  const column = valueOf(measure);
2181
2294
  if (measure.agg === "count" || measure.agg === "count_distinct") return column === "" ? "1" : `(CASE WHEN ${column} IS NULL THEN 0 ELSE 1 END)`;
2182
2295
  return column;
@@ -2190,10 +2303,10 @@ function compileTransactions(model, view, ctx) {
2190
2303
  columns.push({ name, kind: "dimension", label: scope.dimension(key).label, dimension: key });
2191
2304
  });
2192
2305
  const wanted = view.columns ?? stream.columns.map((c) => c.key);
2193
- if (!Array.isArray(wanted)) fail("unknown_column", "columns must be a list of column keys");
2306
+ if (!Array.isArray(wanted)) fail2("unknown_column", "columns must be a list of column keys");
2194
2307
  wanted.forEach((key, i) => {
2195
2308
  if (wanted.indexOf(key) !== i) return;
2196
- const extra = stream.columns.find((c) => c.key === key) ?? fail("unknown_column", `stream "${stream.key}" has no column "${String(key)}"`);
2309
+ const extra = stream.columns.find((c) => c.key === key) ?? fail2("unknown_column", `stream "${stream.key}" has no column "${String(key)}"`);
2197
2310
  const name = `col__${extra.key}`;
2198
2311
  select.push(`${FACT}.${quoteIdent(extra.column)} AS ${quoteIdent(name)}`);
2199
2312
  columns.push({ name, kind: "column", label: extra.label, column: extra.key });
@@ -2204,11 +2317,11 @@ function compileTransactions(model, view, ctx) {
2204
2317
  columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2205
2318
  });
2206
2319
  const sort = view.sort ?? { by: "date", dir: "desc" };
2207
- if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2320
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2208
2321
  const sortParts = String(sort.by).split(".");
2209
2322
  const two = sortParts.length === 2;
2210
2323
  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]}` : "";
2211
- if (!columns.some((c) => c.name === sortName)) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2324
+ if (!columns.some((c) => c.name === sortName)) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2212
2325
  const order = [
2213
2326
  `${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST`,
2214
2327
  ...columns.filter((c) => c.name !== sortName).map((c) => `${quoteIdent(c.name)} ASC`)
@@ -2254,8 +2367,8 @@ function foldedMeasures(measureByKey, periodCount) {
2254
2367
  const needed = /* @__PURE__ */ new Map();
2255
2368
  const parsed = /* @__PURE__ */ new Map();
2256
2369
  const exprOf = (key, part, depth) => {
2257
- if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2258
- const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2370
+ if (depth > 20) fail2("formula_cycle", `"${key}" refers back to itself`);
2371
+ const measure = measureByKey.get(key) ?? fail2("formula_unknown_measure", `"${key}" is not a measure`);
2259
2372
  if (isFormulaMeasure(measure)) {
2260
2373
  let node = parsed.get(key);
2261
2374
  if (!node) {
@@ -2283,9 +2396,9 @@ function streamSum(measure, over) {
2283
2396
  function compileStreams(model, view, ctx) {
2284
2397
  const options = view.options ?? {};
2285
2398
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2286
- if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2287
- if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2288
- if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
2399
+ if ((options.activity ?? "with") !== "with") fail2("option_unsupported", `the activity option is not compiled for ${what} yet`);
2400
+ if (options.others_row) fail2("option_unsupported", `an others row is not compiled for ${what} yet`);
2401
+ if (options.average_column && view.mode === "period") fail2("option_unsupported", `an average column is not compiled for ${what} yet`);
2289
2402
  const totalRow = options.total_row === true;
2290
2403
  const averageRow = options.average_row === true;
2291
2404
  const sumRow = options.sum_row === true;
@@ -2294,12 +2407,12 @@ function compileStreams(model, view, ctx) {
2294
2407
  const nest = nestOf(view, lead);
2295
2408
  if (nest) {
2296
2409
  if (averageRow || sumRow || options.hide_zero_rows) {
2297
- fail("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2410
+ fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2298
2411
  }
2299
- if (lead.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2412
+ if (lead.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2300
2413
  }
2301
2414
  const shown = shownMeasures(view, measureByKey);
2302
- const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2415
+ const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
2303
2416
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2304
2417
  const range = period.window;
2305
2418
  const periodVariance = view.mode === "period_variance";
@@ -2307,7 +2420,7 @@ function compileStreams(model, view, ctx) {
2307
2420
  const two = view.mode === "variance" || periodVariance ? comparedWith(model, view, ctx, range) : null;
2308
2421
  const earlierBuckets = periodVariance && two ? splitWindow(two.comparison, period.grain, model.periods) : [];
2309
2422
  if (periodVariance && earlierBuckets.length !== buckets.length) {
2310
- fail("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlierBuckets.length}, so they cannot be set side by side`);
2423
+ fail2("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlierBuckets.length}, so they cannot be set side by side`);
2311
2424
  }
2312
2425
  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"` };
2313
2426
  const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
@@ -2422,9 +2535,9 @@ function compileStreams(model, view, ctx) {
2422
2535
  }
2423
2536
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2424
2537
  const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
2425
- if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2538
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2426
2539
  const sortName = sortNameOf(sort.by);
2427
- if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2540
+ if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2428
2541
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2429
2542
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2430
2543
  const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
@@ -2479,16 +2592,16 @@ function compileStreams(model, view, ctx) {
2479
2592
  function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2480
2593
  const options = view.options ?? {};
2481
2594
  const what = byPeriod ? "the long shape of a period view" : "matrix mode";
2482
- if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2483
- if (byPeriod && options.average_column) fail("option_unsupported", "the average column is not compiled for the long shape of a period view yet");
2484
- if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2485
- if (options.others_row || options.average_row || options.sum_row) fail("option_unsupported", `others, average and sum rows are not compiled for ${what} yet`);
2595
+ if (view.levels !== void 0) fail2("option_unsupported", `nested rows are not compiled for ${what} yet`);
2596
+ if (byPeriod && options.average_column) fail2("option_unsupported", "the average column is not compiled for the long shape of a period view yet");
2597
+ if ((options.activity ?? "with") !== "with") fail2("option_unsupported", `the activity option is not compiled for ${what} yet`);
2598
+ if (options.others_row || options.average_row || options.sum_row) fail2("option_unsupported", `others, average and sum rows are not compiled for ${what} yet`);
2486
2599
  const totalRow = options.total_row === true;
2487
2600
  const scope = scopeOf(model, view, ctx);
2488
2601
  const { stream, measureByKey, groupDim } = scope;
2489
2602
  const shown = shownMeasures(view, measureByKey);
2490
- const first = shown[0] ?? fail("no_measures", "a view needs at least one measure");
2491
- const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2603
+ const first = shown[0] ?? fail2("no_measures", "a view needs at least one measure");
2604
+ const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
2492
2605
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2493
2606
  const range = period.window;
2494
2607
  const buckets = byPeriod ? period.buckets : [];
@@ -2518,13 +2631,13 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2518
2631
  reads.daysSql = `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${FACT}."__days") ELSE ${sqlNumber(days)} END`;
2519
2632
  } else {
2520
2633
  const across = view.across;
2521
- if (!across || typeof across.dimension !== "string") fail("bad_across", 'a matrix needs a second dimension in "across"');
2634
+ if (!across || typeof across.dimension !== "string") fail2("bad_across", 'a matrix needs a second dimension in "across"');
2522
2635
  const acrossDim = scope.dimension(across.dimension);
2523
- if (acrossDim.key === groupDim.key) fail("bad_across", "the second dimension must differ from the first");
2636
+ if (acrossDim.key === groupDim.key) fail2("bad_across", "the second dimension must differ from the first");
2524
2637
  const order = across.order ?? "value";
2525
- if (order !== "value" && order !== "code") fail("bad_across", `"${String(order)}" is not a column order`);
2638
+ if (order !== "value" && order !== "code") fail2("bad_across", `"${String(order)}" is not a column order`);
2526
2639
  keep = across.limit ?? DEFAULT_ACROSS_MEMBERS;
2527
- if (!Number.isInteger(keep) || keep < 1) fail("bad_across", "across.limit must be a whole number, 1 or more");
2640
+ if (!Number.isInteger(keep) || keep < 1) fail2("bad_across", "across.limit must be a whole number, 1 or more");
2528
2641
  colCode = scope.propertyOf(acrossDim.key, "code");
2529
2642
  acrossColumn = { name: "across", kind: "across", label: acrossDim.label, dimension: acrossDim.key };
2530
2643
  if (acrossDim.table && acrossDim.name) {
@@ -2537,11 +2650,11 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2537
2650
  const columnTotals = totalRow || !byPeriod;
2538
2651
  const reserved = (columnTotals ? keep : 0) + (totalRow ? 1 : 0);
2539
2652
  const room = Math.floor((maxRows - reserved) / (keep + 1));
2540
- if (room < 1) fail("bad_paging", `${keep} columns leave no room for a row in ${maxRows} result rows`);
2653
+ if (room < 1) fail2("bad_paging", `${keep} columns leave no room for a row in ${maxRows} result rows`);
2541
2654
  const asked = view.limit ?? DEFAULT_PAGE_ROWS;
2542
2655
  const offset = view.offset ?? 0;
2543
- if (!Number.isInteger(asked) || asked < 1) fail("bad_paging", "limit must be a whole number, 1 or more");
2544
- if (!Number.isInteger(offset) || offset < 0) fail("bad_paging", "offset must be a whole number, 0 or more");
2656
+ if (!Number.isInteger(asked) || asked < 1) fail2("bad_paging", "limit must be a whole number, 1 or more");
2657
+ if (!Number.isInteger(offset) || offset < 0) fail2("bad_paging", "offset must be a whole number, 0 or more");
2545
2658
  const limit = Math.min(asked, room);
2546
2659
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2547
2660
  const properties = shownProperties(view);
@@ -2568,7 +2681,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2568
2681
  shown.forEach((measure) => addMeasure(measure, true));
2569
2682
  unseen.forEach((measure) => addMeasure(measure, false));
2570
2683
  const sort = view.sort ?? { by: `total.${first.key}`, dir: "desc" };
2571
- if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2684
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2572
2685
  let sortName = sortNameOf(sort.by);
2573
2686
  const byOne = String(sort.by).split(".");
2574
2687
  const bucket = byPeriod && byOne[0] === "period" && byOne.length === 3 ? buckets[Number(byOne[1]) - 1] : void 0;
@@ -2580,7 +2693,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2580
2693
  hidden.push("__sort");
2581
2694
  sortName = "__sort";
2582
2695
  } else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
2583
- fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2696
+ fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2584
2697
  }
2585
2698
  const flags = (row, col) => [`CAST(GROUPING(${row}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${col}) AS INTEGER) AS "__across_total"`];
2586
2699
  select.push(...folded ? ['"__total"', '"__across_total"'] : flags(rowCode, colCode));
@@ -2779,6 +2892,7 @@ export {
2779
2892
  quoteIdent,
2780
2893
  refusalOf,
2781
2894
  resolvePeriod,
2895
+ shownColumns,
2782
2896
  splitWindow,
2783
2897
  sqlDate,
2784
2898
  sqlNumber,
@@ -2788,5 +2902,6 @@ export {
2788
2902
  tablesIn,
2789
2903
  usesGridOnlyFunction,
2790
2904
  validateModel,
2905
+ withCalculations,
2791
2906
  writtenLength
2792
2907
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
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",