@sprigr/apps-reporting-core 0.0.10 → 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 CHANGED
@@ -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") {
@@ -1286,30 +1352,30 @@ function memberWindows(model, view, ctx) {
1286
1352
  return found;
1287
1353
  }
1288
1354
  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)}"`);
1355
+ const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
1290
1356
  const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
1291
1357
  const measureByKey = new Map(model.measures.map((m) => [m.key, m]));
1292
1358
  const joins = /* @__PURE__ */ new Map();
1293
1359
  const alias = (dim) => quoteIdent(`d_${dim.key}`);
1294
- const dimension = (key) => dimByKey.get(key) ?? fail("unknown_dimension", `no dimension "${String(key)}"`);
1360
+ const dimension = (key) => dimByKey.get(key) ?? fail2("unknown_dimension", `no dimension "${String(key)}"`);
1295
1361
  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`);
1362
+ if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1297
1363
  const a = alias(dim);
1298
1364
  if (!into.has(a)) into.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${codeExpr2}`);
1299
1365
  return a;
1300
1366
  };
1301
1367
  const codeOf = (key, depth = 0, into = joins) => {
1302
- if (depth > 20) fail("unknown_dimension", `the via chain of "${key}" does not end`);
1368
+ if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
1303
1369
  const dim = dimension(key);
1304
1370
  const direct = stream.dimension_keys[key];
1305
1371
  if (direct !== void 0) return `${FACT}.${quoteIdent(direct)}`;
1306
- if (!dim.via) fail("dimension_not_on_stream", `stream "${stream.key}" has no "${key}"`);
1372
+ if (!dim.via) fail2("dimension_not_on_stream", `stream "${stream.key}" has no "${key}"`);
1307
1373
  const parent = dimension(dim.via.dimension);
1308
1374
  return `${join(parent, codeOf(parent.key, depth + 1, into), into)}.${quoteIdent(dim.via.column)}`;
1309
1375
  };
1310
1376
  const columnOf = (dim, property) => {
1311
1377
  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)}"`);
1378
+ return column ?? fail2("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
1313
1379
  };
1314
1380
  const propertyOf = (dimKey, property) => {
1315
1381
  const code = codeOf(dimKey);
@@ -1323,7 +1389,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1323
1389
  const membersOf = () => {
1324
1390
  const table = groupDim.table;
1325
1391
  const codeColumn = groupDim.code;
1326
- if (!table || !codeColumn) fail("dimension_has_no_table", `"${groupDim.key}" has no table to list its members from`);
1392
+ if (!table || !codeColumn) fail2("dimension_has_no_table", `"${groupDim.key}" has no table to list its members from`);
1327
1393
  const root = quoteIdent("mb");
1328
1394
  const joinsHere = /* @__PURE__ */ new Map();
1329
1395
  const reaches = (key, depth = 0) => {
@@ -1333,7 +1399,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1333
1399
  };
1334
1400
  const tableOf = (dim, code) => {
1335
1401
  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`);
1402
+ if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1337
1403
  const a = quoteIdent(`mb_${dim.key}`);
1338
1404
  if (!joinsHere.has(a)) joinsHere.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${code}`);
1339
1405
  return a;
@@ -1341,7 +1407,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1341
1407
  const codeHere = (key) => {
1342
1408
  const dim = dimension(key);
1343
1409
  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}"`);
1410
+ const via = dim.via ?? fail2("dimension_not_on_stream", `"${key}" is not above "${groupDim.key}"`);
1345
1411
  const parent = dimension(via.dimension);
1346
1412
  return `${tableOf(parent, codeHere(parent.key))}.${quoteIdent(via.column)}`;
1347
1413
  };
@@ -1367,8 +1433,8 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1367
1433
  });
1368
1434
  const filterMeasures = [];
1369
1435
  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)}"`);
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)}"`);
1372
1438
  const window = memberWindow(model, view, ctx, rule);
1373
1439
  const own = /* @__PURE__ */ new Map();
1374
1440
  const member = codeOf(rule.dimension, 0, own);
@@ -1384,9 +1450,9 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1384
1450
  };
1385
1451
  const dimensionLeafWith = (resolve) => (rule) => {
1386
1452
  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");
1453
+ if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
1388
1454
  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`);
1455
+ if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
1390
1456
  const expr = resolve(rule.dimension, rule.property ?? "code");
1391
1457
  const what = `the filter on "${String(rule.dimension)}"`;
1392
1458
  const values = stringList(rule.values, what);
@@ -1394,8 +1460,8 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1394
1460
  return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
1395
1461
  }
1396
1462
  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`);
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`);
1399
1465
  return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
1400
1466
  });
1401
1467
  const any = `(${found.join(" OR ")})`;
@@ -1403,39 +1469,39 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1403
1469
  };
1404
1470
  const dimensionLeaf = dimensionLeafWith(propertyOf);
1405
1471
  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`);
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`);
1408
1474
  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)}"`);
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)}"`);
1412
1478
  if (!filterMeasures.includes(measure.key)) filterMeasures.push(measure.key);
1413
1479
  return `${quoteIdent(`${PART_PREFIX[part]}${measure.key}`)} ${rule.cmp} ${sqlNumber(rule.value)}`;
1414
1480
  };
1415
1481
  const kindOf = (rule, depth) => {
1416
1482
  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`);
1483
+ if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `filters nest deeper than ${MAX_FILTER_DEPTH} levels`);
1418
1484
  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");
1485
+ if (kinds.size > 1) fail2("measure_filter_unsupported", "below the top level a filter group holds dimension rules or measure rules, not both");
1420
1486
  return kinds.has("measure") ? "measure" : "dimension";
1421
1487
  };
1422
1488
  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"');
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"');
1425
1491
  const rules = Array.isArray(group.rules) ? group.rules : [];
1426
- if (rules.length === 0) fail("empty_filter", "a filter group has no rules");
1492
+ if (rules.length === 0) fail2("empty_filter", "a filter group has no rules");
1427
1493
  const parts2 = rules.map((rule) => isGroup(rule) ? groupSql(rule, depth + 1, leaf) : leaf(rule));
1428
1494
  return `(${parts2.join(group.op === "and" ? " AND " : " OR ")})`;
1429
1495
  };
1430
1496
  let having = null;
1431
1497
  if (view.filters) {
1432
1498
  const top = view.filters;
1433
- if (top.op !== "and" && top.op !== "or") fail("empty_filter", 'a filter group needs op "and" or "or"');
1499
+ if (top.op !== "and" && top.op !== "or") fail2("empty_filter", 'a filter group needs op "and" or "or"');
1434
1500
  const rules = Array.isArray(top.rules) ? top.rules : [];
1435
1501
  const onRows = rules.filter((rule) => kindOf(rule, 1) === "dimension");
1436
1502
  const onGroups = rules.filter((rule) => kindOf(rule, 1) === "measure");
1437
1503
  if (onRows.length > 0 && onGroups.length > 0 && top.op === "or") {
1438
- fail("measure_filter_unsupported", 'dimension rules and measure rules combine with "and" only');
1504
+ fail2("measure_filter_unsupported", 'dimension rules and measure rules combine with "and" only');
1439
1505
  }
1440
1506
  if (onRows.length > 0) where.push(groupSql({ op: top.op, rules: onRows }, 0, dimensionLeaf));
1441
1507
  if (onGroups.length > 0) having = groupSql({ op: top.op, rules: onGroups }, 0, measureLeaf);
@@ -1448,7 +1514,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1448
1514
  }
1449
1515
  }
1450
1516
  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`);
1517
+ if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
1452
1518
  if (keyword !== "") {
1453
1519
  const pattern = `${sqlValue(likePattern(keyword))} ESCAPE '\\'`;
1454
1520
  const targets = [`CAST(${codeExpr} AS VARCHAR) ILIKE ${pattern}`];
@@ -1470,25 +1536,25 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1470
1536
  return { stream, measureByKey, joins, dimension, propertyOf, groupDim, codeExpr, where, dimensionRule: dimensionLeaf, having, filterMeasures, members, focus };
1471
1537
  }
1472
1538
  function shownMeasures(view, measureByKey) {
1473
- if (!Array.isArray(view.measures) || view.measures.length === 0) fail("no_measures", "a view needs at least one measure");
1539
+ if (!Array.isArray(view.measures) || view.measures.length === 0) fail2("no_measures", "a view needs at least one measure");
1474
1540
  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)}"`);
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)}"`);
1477
1543
  });
1478
1544
  }
1479
1545
  function pageOf(view, ctx, reserved) {
1480
1546
  const maxRows = ctx.maxRows ?? ROUTE_MAX_ROWS;
1481
1547
  const limit = view.limit ?? DEFAULT_PAGE_ROWS;
1482
1548
  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");
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");
1485
1551
  return { limit, offset };
1486
1552
  }
1487
1553
  function checkLength(sql, ctx) {
1488
1554
  const maxSqlChars = ctx.maxSqlChars ?? ROUTE_MAX_SQL_CHARS;
1489
1555
  const length = writtenLength(sql);
1490
1556
  if (length > maxSqlChars) {
1491
- fail("sql_too_long", `the statement is ${length} characters, the limit is ${maxSqlChars}; use fewer periods, measures or selected values`);
1557
+ fail2("sql_too_long", `the statement is ${length} characters, the limit is ${maxSqlChars}; use fewer periods, measures or selected values`);
1492
1558
  }
1493
1559
  }
1494
1560
  function valueOf(measure) {
@@ -1556,8 +1622,8 @@ function rankAndPage(source, sortName, sort, having, left, offset, limit, extra
1556
1622
  ];
1557
1623
  }
1558
1624
  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`);
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`);
1561
1627
  if (isFormulaMeasure(measure)) {
1562
1628
  let node = src.parsed.get(key);
1563
1629
  if (!node) {
@@ -1570,7 +1636,7 @@ function measureOver(src, key, slice, depth = 0) {
1570
1636
  ...src.periodCount !== void 0 ? { periodCount: src.periodCount } : {}
1571
1637
  });
1572
1638
  }
1573
- if (measure.stream !== src.stream.key) fail("measure_not_on_stream", `"${key}" belongs to stream "${measure.stream}", not "${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}"`);
1574
1640
  const call = aggregateOf(measure, src.countAll);
1575
1641
  if (measure.snapshot) {
1576
1642
  src.uses.add("snapshot");
@@ -1604,10 +1670,10 @@ function comparedWith(model, view, ctx, window) {
1604
1670
  const compare = view.compare ?? "previous_year";
1605
1671
  let comparison;
1606
1672
  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");
1673
+ if (typeof compare.period !== "object" || compare.period === null) fail2("option_unsupported", "a comparison given as an object needs a period");
1608
1674
  comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
1609
1675
  } else {
1610
- if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1676
+ if (compare !== "previous_year" && compare !== "previous_period") fail2("option_unsupported", `"${String(compare)}" is not a comparison`);
1611
1677
  comparison = comparisonWindow(window, compare);
1612
1678
  }
1613
1679
  const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
@@ -1650,15 +1716,15 @@ function propertyLabel(dim, property) {
1650
1716
  function nestOf(view, scope) {
1651
1717
  if (view.levels === void 0) return null;
1652
1718
  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`);
1719
+ if (!Array.isArray(keys) || keys.length === 0 || keys.length > MAX_LEVELS) fail2("bad_levels", `levels lists from 1 to ${MAX_LEVELS} dimensions`);
1654
1720
  const codes = [];
1655
1721
  const select = [];
1656
1722
  const columns = [];
1657
1723
  keys.forEach((key, i) => {
1658
- if (typeof key !== "string") fail("bad_levels", "a level is named by its dimension key");
1724
+ if (typeof key !== "string") fail2("bad_levels", "a level is named by its dimension key");
1659
1725
  const dim = scope.dimension(key);
1660
1726
  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`);
1727
+ if (code === scope.codeExpr || codes.includes(code)) fail2("bad_levels", `"${key}" is the row dimension, or is listed twice`);
1662
1728
  codes.push(code);
1663
1729
  const level2 = i + 1;
1664
1730
  select.push(`${code} AS ${quoteIdent(`lv${level2}`)}`);
@@ -1682,27 +1748,27 @@ function nestOf(view, scope) {
1682
1748
  function compileGrouped(model, view, ctx) {
1683
1749
  const options = view.options ?? {};
1684
1750
  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");
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");
1687
1753
  const totalRow = options.total_row === true && activity !== "without";
1688
1754
  const averageRow = options.average_row === true;
1689
1755
  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");
1756
+ if (options.hide_zero_rows && activity !== "with") fail2("option_unsupported", "hiding zero rows with the activity option is not compiled yet");
1691
1757
  const averageColumn = options.average_column === true && view.mode === "period";
1692
1758
  const scope = scopeOf(model, view, ctx, activity !== "with", options.others_row === true);
1693
1759
  const { stream, measureByKey, joins, groupDim, where, members } = scope;
1694
1760
  const nest = nestOf(view, scope);
1695
1761
  if (nest) {
1696
1762
  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");
1763
+ fail2("option_unsupported", "the activity option, an others, average or sum row and hiding zero rows are not compiled with nested rows yet");
1698
1764
  }
1699
- if (scope.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
1765
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
1700
1766
  }
1701
1767
  const focused = scope.focus.length > 0 ? `COALESCE(${scope.focus.join(" AND ")}, FALSE)` : null;
1702
1768
  const othersRow = focused !== null;
1703
1769
  const codeExpr = members ? `COALESCE(${members.code}, ${FACT}."__code")` : scope.codeExpr;
1704
1770
  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}"`));
1771
+ const unseen = scope.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
1706
1772
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
1707
1773
  const periodVariance = view.mode === "period_variance";
1708
1774
  const buckets = view.mode === "period" || periodVariance ? period.buckets : [];
@@ -1731,7 +1797,7 @@ function compileGrouped(model, view, ctx) {
1731
1797
  if (periodVariance) {
1732
1798
  const earlier = splitWindow(comparison, period.grain, model.periods);
1733
1799
  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`);
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`);
1735
1801
  }
1736
1802
  earlierBuckets = earlier;
1737
1803
  earlierSlices = earlier.map((bucket, i) => ({
@@ -1871,10 +1937,10 @@ function compileGrouped(model, view, ctx) {
1871
1937
  }
1872
1938
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
1873
1939
  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");
1940
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
1875
1941
  const sortName = sortNameOf(sort.by);
1876
1942
  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`);
1943
+ if (!sortColumn) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
1878
1944
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (othersRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
1879
1945
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
1880
1946
  const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
@@ -1929,20 +1995,20 @@ function compileGrouped(model, view, ctx) {
1929
1995
  }
1930
1996
  function compileCustom(model, view, ctx) {
1931
1997
  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");
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");
1934
2000
  const totalRow = options.total_row === true;
1935
2001
  const averageRow = options.average_row === true;
1936
2002
  const sumRow = options.sum_row === true;
1937
2003
  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");
2004
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a filter on a measure in custom mode is not compiled yet");
1939
2005
  const { stream, measureByKey, joins, groupDim, where, codeExpr } = scope;
1940
2006
  const nest = nestOf(view, scope);
1941
2007
  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");
2008
+ fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
1943
2009
  }
1944
2010
  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");
2011
+ if (listed.length === 0) fail2("bad_custom_column", "a custom view needs at least one column");
1946
2012
  const date = quoteIdent(stream.date);
1947
2013
  const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1948
2014
  const resolve = (spec) => resolvePeriod(spec, model.periods, ctx.today, { periodToDate: options.period_to_date === true }).window;
@@ -1978,11 +2044,11 @@ function compileCustom(model, view, ctx) {
1978
2044
  };
1979
2045
  const points = [];
1980
2046
  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)}"`);
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)}"`);
1983
2049
  const { window, number } = windowOf(point.period);
1984
2050
  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`);
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`);
1986
2052
  const bucket = {
1987
2053
  key: `w${number}`,
1988
2054
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1993,9 +2059,9 @@ function compileCustom(model, view, ctx) {
1993
2059
  const read = (m, depth) => {
1994
2060
  const streams = streamsOf(m);
1995
2061
  if (streams.size > 1 && isFormulaMeasure(m)) {
1996
- if (depth > 20) fail("formula_cycle", `"${m.key}" refers back to itself`);
2062
+ if (depth > 20) fail2("formula_cycle", `"${m.key}" refers back to itself`);
1997
2063
  return emitFormulaSql(parseFormula(m.formula), {
1998
- measure: (ref) => read(measureByKey.get(ref) ?? fail("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
2064
+ measure: (ref) => read(measureByKey.get(ref) ?? fail2("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
1999
2065
  days: bucket.days
2000
2066
  });
2001
2067
  }
@@ -2023,23 +2089,23 @@ function compileCustom(model, view, ctx) {
2023
2089
  const left = ["__rn"];
2024
2090
  const keys = /* @__PURE__ */ new Set();
2025
2091
  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`);
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`);
2027
2093
  const { key } = column;
2028
- if (keys.has(key)) fail("bad_custom_column", `"${key}" is the key of two columns`);
2094
+ if (keys.has(key)) fail2("bad_custom_column", `"${key}" is the key of two columns`);
2029
2095
  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`);
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`);
2031
2097
  let expr;
2032
2098
  let about;
2033
2099
  if (column.point !== void 0) {
2034
2100
  const cur = pointOf(column.point, `"${key}"`);
2035
2101
  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`);
2102
+ if (column.show !== void 0) fail2("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
2037
2103
  expr = cur.ref;
2038
2104
  about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
2039
2105
  } else {
2040
2106
  const prev = pointOf(column.against, `"${key}"`);
2041
2107
  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`);
2108
+ if (show !== "difference" && show !== "percent") fail2("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
2043
2109
  expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
2044
2110
  about = {
2045
2111
  label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
@@ -2050,11 +2116,11 @@ function compileCustom(model, view, ctx) {
2050
2116
  }
2051
2117
  } else {
2052
2118
  const format = column.format ?? "number";
2053
- if (!MEASURE_FORMATS.includes(format)) fail("bad_custom_column", `"${String(format)}" is not a format`);
2119
+ if (!MEASURE_FORMATS.includes(format)) fail2("bad_custom_column", `"${String(format)}" is not a format`);
2054
2120
  const named = column.points ?? {};
2055
2121
  expr = emitFormulaSql(parseFormula(String(column.expression)), {
2056
2122
  measure: (ref) => {
2057
- if (!Object.prototype.hasOwnProperty.call(named, ref)) fail("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2123
+ if (!Object.prototype.hasOwnProperty.call(named, ref)) fail2("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2058
2124
  return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
2059
2125
  },
2060
2126
  days: reads.days
@@ -2067,8 +2133,8 @@ function compileCustom(model, view, ctx) {
2067
2133
  else columns.push({ name, kind: "measure", custom: key, ...about });
2068
2134
  });
2069
2135
  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");
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");
2072
2138
  const multi = reading.size > 1;
2073
2139
  points.forEach(({ sql: sql2 }, i) => {
2074
2140
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
@@ -2082,11 +2148,11 @@ function compileCustom(model, view, ctx) {
2082
2148
  }
2083
2149
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2084
2150
  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");
2151
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2086
2152
  const by = String(sort.by).split(".");
2087
2153
  const sortName = by[0] === "column" ? by.length === 2 && keys.has(by[1] ?? "") ? `c__${by[1]}` : "" : sortNameOf(sort.by);
2088
2154
  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`);
2155
+ fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2090
2156
  }
2091
2157
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2092
2158
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
@@ -2154,19 +2220,19 @@ function compileCustom(model, view, ctx) {
2154
2220
  }
2155
2221
  function compileTransactions(model, view, ctx) {
2156
2222
  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");
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");
2160
2226
  const scope = scopeOf(model, view, ctx);
2161
2227
  const { stream, measureByKey } = scope;
2162
- if (scope.having !== null) fail("measure_filter_unsupported", "a transaction list cannot be filtered on a measure");
2228
+ if (scope.having !== null) fail2("measure_filter_unsupported", "a transaction list cannot be filtered on a measure");
2163
2229
  const shown = shownMeasures(view, measureByKey);
2164
2230
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2165
2231
  const windowDays = period.buckets.reduce((sum, b) => sum + b.days, 0);
2166
2232
  const parsed = /* @__PURE__ */ new Map();
2167
2233
  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`);
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`);
2170
2236
  if (isFormulaMeasure(measure)) {
2171
2237
  let node = parsed.get(key);
2172
2238
  if (!node) {
@@ -2175,8 +2241,8 @@ function compileTransactions(model, view, ctx) {
2175
2241
  }
2176
2242
  return emitFormulaSql(node, { measure: (ref) => rowSql(ref, depth + 1), days: windowDays });
2177
2243
  }
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`);
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`);
2180
2246
  const column = valueOf(measure);
2181
2247
  if (measure.agg === "count" || measure.agg === "count_distinct") return column === "" ? "1" : `(CASE WHEN ${column} IS NULL THEN 0 ELSE 1 END)`;
2182
2248
  return column;
@@ -2190,10 +2256,10 @@ function compileTransactions(model, view, ctx) {
2190
2256
  columns.push({ name, kind: "dimension", label: scope.dimension(key).label, dimension: key });
2191
2257
  });
2192
2258
  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");
2259
+ if (!Array.isArray(wanted)) fail2("unknown_column", "columns must be a list of column keys");
2194
2260
  wanted.forEach((key, i) => {
2195
2261
  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)}"`);
2262
+ const extra = stream.columns.find((c) => c.key === key) ?? fail2("unknown_column", `stream "${stream.key}" has no column "${String(key)}"`);
2197
2263
  const name = `col__${extra.key}`;
2198
2264
  select.push(`${FACT}.${quoteIdent(extra.column)} AS ${quoteIdent(name)}`);
2199
2265
  columns.push({ name, kind: "column", label: extra.label, column: extra.key });
@@ -2204,11 +2270,11 @@ function compileTransactions(model, view, ctx) {
2204
2270
  columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2205
2271
  });
2206
2272
  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");
2273
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2208
2274
  const sortParts = String(sort.by).split(".");
2209
2275
  const two = sortParts.length === 2;
2210
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]}` : "";
2211
- if (!columns.some((c) => c.name === sortName)) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2277
+ if (!columns.some((c) => c.name === sortName)) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2212
2278
  const order = [
2213
2279
  `${quoteIdent(sortName)} ${sort.dir === "asc" ? "ASC" : "DESC"} NULLS LAST`,
2214
2280
  ...columns.filter((c) => c.name !== sortName).map((c) => `${quoteIdent(c.name)} ASC`)
@@ -2254,8 +2320,8 @@ function foldedMeasures(measureByKey, periodCount) {
2254
2320
  const needed = /* @__PURE__ */ new Map();
2255
2321
  const parsed = /* @__PURE__ */ new Map();
2256
2322
  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`);
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`);
2259
2325
  if (isFormulaMeasure(measure)) {
2260
2326
  let node = parsed.get(key);
2261
2327
  if (!node) {
@@ -2283,9 +2349,9 @@ function streamSum(measure, over) {
2283
2349
  function compileStreams(model, view, ctx) {
2284
2350
  const options = view.options ?? {};
2285
2351
  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`);
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`);
2289
2355
  const totalRow = options.total_row === true;
2290
2356
  const averageRow = options.average_row === true;
2291
2357
  const sumRow = options.sum_row === true;
@@ -2294,12 +2360,12 @@ function compileStreams(model, view, ctx) {
2294
2360
  const nest = nestOf(view, lead);
2295
2361
  if (nest) {
2296
2362
  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");
2363
+ fail2("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2298
2364
  }
2299
- if (lead.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2365
+ if (lead.having !== null) fail2("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2300
2366
  }
2301
2367
  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}"`));
2368
+ const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail2("unknown_measure", `no measure "${key}"`));
2303
2369
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2304
2370
  const range = period.window;
2305
2371
  const periodVariance = view.mode === "period_variance";
@@ -2307,7 +2373,7 @@ function compileStreams(model, view, ctx) {
2307
2373
  const two = view.mode === "variance" || periodVariance ? comparedWith(model, view, ctx, range) : null;
2308
2374
  const earlierBuckets = periodVariance && two ? splitWindow(two.comparison, period.grain, model.periods) : [];
2309
2375
  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`);
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`);
2311
2377
  }
2312
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"` };
2313
2379
  const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
@@ -2422,9 +2488,9 @@ function compileStreams(model, view, ctx) {
2422
2488
  }
2423
2489
  columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2424
2490
  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");
2491
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2426
2492
  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`);
2493
+ if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2428
2494
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2429
2495
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2430
2496
  const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
@@ -2479,16 +2545,16 @@ function compileStreams(model, view, ctx) {
2479
2545
  function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2480
2546
  const options = view.options ?? {};
2481
2547
  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`);
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`);
2486
2552
  const totalRow = options.total_row === true;
2487
2553
  const scope = scopeOf(model, view, ctx);
2488
2554
  const { stream, measureByKey, groupDim } = scope;
2489
2555
  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}"`));
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}"`));
2492
2558
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2493
2559
  const range = period.window;
2494
2560
  const buckets = byPeriod ? period.buckets : [];
@@ -2518,13 +2584,13 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2518
2584
  reads.daysSql = `CASE WHEN GROUPING(${colCode}) = 0 THEN any_value(${FACT}."__days") ELSE ${sqlNumber(days)} END`;
2519
2585
  } else {
2520
2586
  const across = view.across;
2521
- if (!across || typeof across.dimension !== "string") fail("bad_across", 'a matrix needs a second dimension in "across"');
2587
+ if (!across || typeof across.dimension !== "string") fail2("bad_across", 'a matrix needs a second dimension in "across"');
2522
2588
  const acrossDim = scope.dimension(across.dimension);
2523
- if (acrossDim.key === groupDim.key) fail("bad_across", "the second dimension must differ from the first");
2589
+ if (acrossDim.key === groupDim.key) fail2("bad_across", "the second dimension must differ from the first");
2524
2590
  const order = across.order ?? "value";
2525
- if (order !== "value" && order !== "code") fail("bad_across", `"${String(order)}" is not a column order`);
2591
+ if (order !== "value" && order !== "code") fail2("bad_across", `"${String(order)}" is not a column order`);
2526
2592
  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");
2593
+ if (!Number.isInteger(keep) || keep < 1) fail2("bad_across", "across.limit must be a whole number, 1 or more");
2528
2594
  colCode = scope.propertyOf(acrossDim.key, "code");
2529
2595
  acrossColumn = { name: "across", kind: "across", label: acrossDim.label, dimension: acrossDim.key };
2530
2596
  if (acrossDim.table && acrossDim.name) {
@@ -2537,11 +2603,11 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2537
2603
  const columnTotals = totalRow || !byPeriod;
2538
2604
  const reserved = (columnTotals ? keep : 0) + (totalRow ? 1 : 0);
2539
2605
  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`);
2606
+ if (room < 1) fail2("bad_paging", `${keep} columns leave no room for a row in ${maxRows} result rows`);
2541
2607
  const asked = view.limit ?? DEFAULT_PAGE_ROWS;
2542
2608
  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");
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");
2545
2611
  const limit = Math.min(asked, room);
2546
2612
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2547
2613
  const properties = shownProperties(view);
@@ -2568,7 +2634,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2568
2634
  shown.forEach((measure) => addMeasure(measure, true));
2569
2635
  unseen.forEach((measure) => addMeasure(measure, false));
2570
2636
  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");
2637
+ if (sort.dir !== "asc" && sort.dir !== "desc") fail2("bad_sort", "sort.dir must be asc or desc");
2572
2638
  let sortName = sortNameOf(sort.by);
2573
2639
  const byOne = String(sort.by).split(".");
2574
2640
  const bucket = byPeriod && byOne[0] === "period" && byOne.length === 3 ? buckets[Number(byOne[1]) - 1] : void 0;
@@ -2580,7 +2646,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2580
2646
  hidden.push("__sort");
2581
2647
  sortName = "__sort";
2582
2648
  } 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`);
2649
+ fail2("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2584
2650
  }
2585
2651
  const flags = (row, col) => [`CAST(GROUPING(${row}) AS INTEGER) AS "__total"`, `CAST(GROUPING(${col}) AS INTEGER) AS "__across_total"`];
2586
2652
  select.push(...folded ? ['"__total"', '"__across_total"'] : flags(rowCode, colCode));
@@ -2779,6 +2845,7 @@ export {
2779
2845
  quoteIdent,
2780
2846
  refusalOf,
2781
2847
  resolvePeriod,
2848
+ shownColumns,
2782
2849
  splitWindow,
2783
2850
  sqlDate,
2784
2851
  sqlNumber,
@@ -2788,5 +2855,6 @@ export {
2788
2855
  tablesIn,
2789
2856
  usesGridOnlyFunction,
2790
2857
  validateModel,
2858
+ withCalculations,
2791
2859
  writtenLength
2792
2860
  };
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.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",