@hypequery/datasets 0.32.0 → 0.34.0

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.
Files changed (238) hide show
  1. package/dist/agent-catalog.d.ts +3 -3
  2. package/dist/agent-catalog.d.ts.map +1 -1
  3. package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
  4. package/dist/cache/protocol-cache-keys.js +25 -1
  5. package/dist/cache/query-signature.d.ts.map +1 -1
  6. package/dist/cache/query-signature.js +16 -5
  7. package/dist/catalog.d.ts +5 -1
  8. package/dist/catalog.d.ts.map +1 -1
  9. package/dist/catalog.js +9 -0
  10. package/dist/client-contract/build-from-deployment.d.ts +2 -2
  11. package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
  12. package/dist/client-contract/build-from-deployment.js +7 -0
  13. package/dist/cloud-publication.d.ts +3 -3
  14. package/dist/cloud-publication.d.ts.map +1 -1
  15. package/dist/cloud-publishing.d.ts +2 -2
  16. package/dist/cloud-publishing.d.ts.map +1 -1
  17. package/dist/codegen/dataset-source.d.ts.map +1 -1
  18. package/dist/codegen/dataset-source.js +4 -1
  19. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  20. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  21. package/dist/contract-3-authoring.fixture.js +40 -0
  22. package/dist/contract.d.ts +5 -1
  23. package/dist/contract.d.ts.map +1 -1
  24. package/dist/contract.js +9 -0
  25. package/dist/dataset-compilation.d.ts +3 -0
  26. package/dist/dataset-compilation.d.ts.map +1 -1
  27. package/dist/dataset-query.d.ts +5 -0
  28. package/dist/dataset-query.d.ts.map +1 -1
  29. package/dist/dataset.d.ts.map +1 -1
  30. package/dist/dataset.js +12 -2
  31. package/dist/event-operations.d.ts +43 -0
  32. package/dist/event-operations.d.ts.map +1 -0
  33. package/dist/event-operations.js +137 -0
  34. package/dist/execution-capabilities.d.ts +2 -1
  35. package/dist/execution-capabilities.d.ts.map +1 -1
  36. package/dist/execution-capabilities.js +1 -1
  37. package/dist/execution-capabilities.json +6 -6
  38. package/dist/executor.d.ts +13 -0
  39. package/dist/executor.d.ts.map +1 -1
  40. package/dist/executor.js +42 -8
  41. package/dist/index.d.ts +6 -3
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +3 -1
  44. package/dist/portable-execution-errors.d.ts +11 -0
  45. package/dist/portable-execution-errors.d.ts.map +1 -1
  46. package/dist/portable-execution-errors.js +14 -0
  47. package/dist/portable-executor.d.ts +22 -5
  48. package/dist/portable-executor.d.ts.map +1 -1
  49. package/dist/portable-executor.js +64 -5
  50. package/dist/protocol-adapter.d.ts +12 -0
  51. package/dist/protocol-adapter.d.ts.map +1 -1
  52. package/dist/protocol-adapter.js +30 -8
  53. package/dist/protocol-deployment-adapter.d.ts +10 -3
  54. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  55. package/dist/protocol-deployment-adapter.js +60 -26
  56. package/dist/protocol-rehydrate.d.ts +3 -16
  57. package/dist/protocol-rehydrate.d.ts.map +1 -1
  58. package/dist/protocol-rehydrate.js +71 -11
  59. package/dist/query-builder-protocol.d.ts +10 -0
  60. package/dist/query-builder-protocol.d.ts.map +1 -1
  61. package/dist/query-planner.d.ts.map +1 -1
  62. package/dist/query-planner.js +3 -1
  63. package/dist/relationship-check.d.ts.map +1 -1
  64. package/dist/relationship-check.js +2 -0
  65. package/dist/semantic-planner.d.ts.map +1 -1
  66. package/dist/semantic-planner.js +16 -3
  67. package/dist/types.d.ts +109 -7
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/utils/agent-catalog-projection.d.ts +2 -2
  70. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  71. package/dist/utils/agent-catalog-projection.js +31 -2
  72. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  73. package/dist/utils/build-dataset-query-builder.js +4 -8
  74. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  75. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  76. package/dist/utils/calculation-stage-sql.js +98 -0
  77. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  78. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  79. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  80. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  81. package/dist/utils/compile-dataset-query.js +11 -3
  82. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  83. package/dist/utils/dataset-definition-validation.js +90 -6
  84. package/dist/utils/dataset-events.d.ts +19 -0
  85. package/dist/utils/dataset-events.d.ts.map +1 -0
  86. package/dist/utils/dataset-events.js +46 -0
  87. package/dist/utils/dataset-having.d.ts.map +1 -1
  88. package/dist/utils/dataset-having.js +6 -1
  89. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  90. package/dist/utils/dataset-query-result.js +7 -1
  91. package/dist/utils/dataset-query-validation.d.ts +1 -1
  92. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  93. package/dist/utils/dataset-query-validation.js +25 -47
  94. package/dist/utils/dataset-source.d.ts +2 -2
  95. package/dist/utils/dataset-source.d.ts.map +1 -1
  96. package/dist/utils/dataset-source.js +8 -1
  97. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  98. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  99. package/dist/utils/dimension-selection-overrides.js +22 -0
  100. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  101. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  102. package/dist/utils/event-breakdown-sql.js +17 -0
  103. package/dist/utils/event-condition-sql.d.ts +18 -0
  104. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  105. package/dist/utils/event-condition-sql.js +63 -0
  106. package/dist/utils/event-operation-shape.d.ts +8 -0
  107. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  108. package/dist/utils/event-operation-shape.js +66 -0
  109. package/dist/utils/event-operation-spec.d.ts +43 -0
  110. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  111. package/dist/utils/event-operation-spec.js +68 -0
  112. package/dist/utils/event-range-span.d.ts +4 -0
  113. package/dist/utils/event-range-span.d.ts.map +1 -0
  114. package/dist/utils/event-range-span.js +22 -0
  115. package/dist/utils/event-result-values.d.ts +8 -0
  116. package/dist/utils/event-result-values.d.ts.map +1 -0
  117. package/dist/utils/event-result-values.js +21 -0
  118. package/dist/utils/event-source-sql.d.ts +38 -0
  119. package/dist/utils/event-source-sql.d.ts.map +1 -0
  120. package/dist/utils/event-source-sql.js +71 -0
  121. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  122. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  123. package/dist/utils/filter-predicate-tree.js +80 -0
  124. package/dist/utils/filter-tree.d.ts +42 -0
  125. package/dist/utils/filter-tree.d.ts.map +1 -0
  126. package/dist/utils/filter-tree.js +164 -0
  127. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  128. package/dist/utils/filtered-aggregation-sql.js +3 -0
  129. package/dist/utils/funnel-rows.d.ts +10 -0
  130. package/dist/utils/funnel-rows.d.ts.map +1 -0
  131. package/dist/utils/funnel-rows.js +30 -0
  132. package/dist/utils/funnel-sql.d.ts +18 -0
  133. package/dist/utils/funnel-sql.d.ts.map +1 -0
  134. package/dist/utils/funnel-sql.js +104 -0
  135. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  136. package/dist/utils/metric-derived-query.js +4 -5
  137. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  138. package/dist/utils/metric-query-builder.js +4 -5
  139. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  140. package/dist/utils/metric-query-validation.js +18 -7
  141. package/dist/utils/other-bucket-sql.d.ts +23 -0
  142. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  143. package/dist/utils/other-bucket-sql.js +51 -0
  144. package/dist/utils/portable-aggregations.d.ts +10 -6
  145. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  146. package/dist/utils/portable-aggregations.js +13 -8
  147. package/dist/utils/portable-grains.d.ts +17 -8
  148. package/dist/utils/portable-grains.d.ts.map +1 -1
  149. package/dist/utils/portable-grains.js +26 -11
  150. package/dist/utils/portable-query-calculations.d.ts +14 -0
  151. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  152. package/dist/utils/portable-query-calculations.js +31 -0
  153. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  154. package/dist/utils/portable-semantic-query.js +27 -1
  155. package/dist/utils/protocol-contract-3.d.ts +30 -0
  156. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  157. package/dist/utils/protocol-contract-3.js +93 -0
  158. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  159. package/dist/utils/protocol-metric-capabilities.js +2 -1
  160. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  161. package/dist/utils/protocol-metric-expressions.js +6 -1
  162. package/dist/utils/protocol-rehydrate-filters.js +2 -1
  163. package/dist/utils/protocol-rehydrate-time-keys.d.ts +5 -0
  164. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  165. package/dist/utils/protocol-rehydrate-time-keys.js +5 -0
  166. package/dist/utils/query-calculation-errors.d.ts +6 -0
  167. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  168. package/dist/utils/query-calculation-errors.js +9 -0
  169. package/dist/utils/query-calculation-formula.d.ts +19 -0
  170. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  171. package/dist/utils/query-calculation-formula.js +77 -0
  172. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  173. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  174. package/dist/utils/query-calculation-outputs.js +72 -0
  175. package/dist/utils/query-calculation-plan.d.ts +67 -0
  176. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  177. package/dist/utils/query-calculation-plan.js +416 -0
  178. package/dist/utils/query-calculation-types.d.ts +97 -0
  179. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  180. package/dist/utils/query-calculation-types.js +8 -0
  181. package/dist/utils/query-field-references.d.ts.map +1 -1
  182. package/dist/utils/query-field-references.js +2 -1
  183. package/dist/utils/query-filter-errors.d.ts +11 -0
  184. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  185. package/dist/utils/query-filter-errors.js +65 -0
  186. package/dist/utils/query-timezone.d.ts +6 -3
  187. package/dist/utils/query-timezone.d.ts.map +1 -1
  188. package/dist/utils/query-timezone.js +5 -1
  189. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  190. package/dist/utils/relationship-builder-plan.js +2 -1
  191. package/dist/utils/relationship-fields.d.ts.map +1 -1
  192. package/dist/utils/relationship-fields.js +5 -0
  193. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  194. package/dist/utils/relationship-measure-sql.js +2 -0
  195. package/dist/utils/relationship-validation.d.ts +3 -1
  196. package/dist/utils/relationship-validation.d.ts.map +1 -1
  197. package/dist/utils/relationship-validation.js +8 -4
  198. package/dist/utils/relative-date-filters.d.ts +21 -0
  199. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  200. package/dist/utils/relative-date-filters.js +86 -0
  201. package/dist/utils/relative-date-range.d.ts +20 -0
  202. package/dist/utils/relative-date-range.d.ts.map +1 -0
  203. package/dist/utils/relative-date-range.js +75 -0
  204. package/dist/utils/retention-rows.d.ts +9 -0
  205. package/dist/utils/retention-rows.d.ts.map +1 -0
  206. package/dist/utils/retention-rows.js +30 -0
  207. package/dist/utils/retention-sql.d.ts +16 -0
  208. package/dist/utils/retention-sql.d.ts.map +1 -0
  209. package/dist/utils/retention-sql.js +68 -0
  210. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  211. package/dist/utils/scoped-dataset-source.js +4 -0
  212. package/dist/utils/segments.d.ts +3 -2
  213. package/dist/utils/segments.d.ts.map +1 -1
  214. package/dist/utils/segments.js +5 -4
  215. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  216. package/dist/utils/semantic-query-syntax.js +8 -2
  217. package/dist/utils/sql-dataset-source.d.ts +36 -0
  218. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  219. package/dist/utils/sql-dataset-source.js +126 -0
  220. package/dist/utils/time-axis-bounds.d.ts +11 -4
  221. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  222. package/dist/utils/time-axis-bounds.js +14 -6
  223. package/dist/utils/time-measure-axis.d.ts +2 -2
  224. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  225. package/dist/utils/time-measure-axis.js +13 -3
  226. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  227. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  228. package/dist/utils/time-measure-dataset-sql.js +15 -5
  229. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  230. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  231. package/dist/utils/time-measure-source-sql.js +7 -8
  232. package/dist/utils/time-query-measures.d.ts +5 -0
  233. package/dist/utils/time-query-measures.d.ts.map +1 -1
  234. package/dist/utils/time-query-measures.js +7 -0
  235. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  236. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  237. package/dist/utils/unsupported-contract-reasons.js +5 -1
  238. package/package.json +3 -3
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The output columns RFC 0026 calculations add to a result, decided from the
3
+ * query alone: names, internal planner names, kinds and types.
4
+ */
5
+ /**
6
+ * Calculation measures are planned under reserved names, so a caller's output
7
+ * name never collides with, shadows or reveals a field of the model.
8
+ */
9
+ export const CALCULATION_INTERNAL_PREFIX = '_hq_calc_';
10
+ /** True when the query needs the calculation planner. */
11
+ export function hasQueryCalculations(query) {
12
+ return (Array.isArray(query.calculations) && query.calculations.length > 0)
13
+ || query.limitBy !== undefined
14
+ || query.other !== undefined;
15
+ }
16
+ /** The single kind member of an entry, or undefined when it has none or several. */
17
+ export function calculationKind(entry) {
18
+ const kinds = ['filter', 'shift', 'window', 'formula', 'compare', 'rank', 'share']
19
+ .filter(kind => Object.hasOwn(entry, kind));
20
+ return kinds.length === 1 ? kinds[0] : undefined;
21
+ }
22
+ /** Every output column in output order. Entries without exactly one kind add none. */
23
+ export function calculationOutputs(query) {
24
+ const outputs = [];
25
+ (query.calculations ?? []).forEach((entry, index) => {
26
+ const internal = `${CALCULATION_INTERNAL_PREFIX}${index}`;
27
+ const calculation = entry.name;
28
+ const kind = calculationKind(entry);
29
+ switch (kind) {
30
+ case 'filter':
31
+ case 'shift':
32
+ case 'window': {
33
+ const { measure } = entry[kind];
34
+ outputs.push({ name: entry.name, internal, kind, calculation, measure, type: 'number' });
35
+ return;
36
+ }
37
+ case 'formula': {
38
+ const { formula } = entry;
39
+ outputs.push({
40
+ name: entry.name, internal, kind, calculation, type: 'number',
41
+ ...(formula.op === 'percentChange' ? { format: 'ratio' } : {}),
42
+ });
43
+ return;
44
+ }
45
+ case 'compare': {
46
+ const { compare } = entry;
47
+ compare.measures.forEach((measure, at) => {
48
+ const base = `${internal}_${at}`;
49
+ outputs.push({ name: `${measure}_previous`, internal: `${base}_previous`, kind: 'shift', calculation, measure, type: 'number' }, { name: `${measure}_change`, internal: `${base}_change`, kind: 'formula', calculation, type: 'number' }, { name: `${measure}_change_pct`, internal: `${base}_change_pct`, kind: 'formula', calculation, type: 'number', format: 'ratio' });
50
+ });
51
+ return;
52
+ }
53
+ case 'rank': {
54
+ const { rank } = entry;
55
+ outputs.push({ name: entry.name, internal, kind, calculation, measure: rank.measure, type: 'integer' });
56
+ return;
57
+ }
58
+ case 'share': {
59
+ const { share } = entry;
60
+ outputs.push({ name: entry.name, internal, kind, calculation, measure: share.measure, type: 'number', format: 'ratio' });
61
+ return;
62
+ }
63
+ default:
64
+ return;
65
+ }
66
+ });
67
+ return outputs;
68
+ }
69
+ /** The public metadata for each output column. */
70
+ export function calculationColumns(query) {
71
+ return calculationOutputs(query).map(({ internal: _internal, ...column }) => column);
72
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Plans RFC 0026 query-scoped calculations.
3
+ *
4
+ * `filter`, `shift`, `window` and `formula` entries (and `compare`, which
5
+ * expands into a shift and two formulas per measure) become measures of a
6
+ * query-scoped view of the dataset, under reserved internal names. The
7
+ * existing planners then compile the view exactly as they compile model-level
8
+ * filtered, shift, window and derived measures, so every constraint they
9
+ * enforce applies unchanged. The caller-facing names, `having`, ordering and
10
+ * pagination are applied by an outer stage over the planned statement.
11
+ */
12
+ import type { AnyDatasetInstance, DatasetHavingCondition, DatasetQuery, ExecutionContext, MetricOrderBy } from '../types.js';
13
+ import { type CalculationOutput } from './query-calculation-outputs.js';
14
+ /** The remainder label `other` uses when the query names none. */
15
+ export declare const DEFAULT_OTHER_LABEL = "Other";
16
+ /** `rank()` over the grouped rows. */
17
+ export interface PlannedRank {
18
+ readonly internal: string;
19
+ /** The inner column ranked. */
20
+ readonly column: string;
21
+ readonly within: readonly string[];
22
+ readonly direction: 'asc' | 'desc';
23
+ }
24
+ /** A share of total; `denominator` is set when the input is not additive. */
25
+ export interface PlannedShare {
26
+ readonly internal: string;
27
+ readonly column: string;
28
+ readonly of: readonly string[];
29
+ /** Re-aggregates the input from source rows at the `of` grain. */
30
+ readonly denominator?: DatasetQuery;
31
+ }
32
+ export interface PlannedOther {
33
+ readonly dimension: string;
34
+ readonly n: number;
35
+ readonly measure: string;
36
+ readonly label: string;
37
+ /** The top-N query, before ordering and limiting, against the dataset without the rewrite. */
38
+ readonly ranking: DatasetQuery;
39
+ }
40
+ export interface QueryCalculationPlan {
41
+ /** The dataset with every calculation measure added under its internal name. */
42
+ readonly dataset: AnyDatasetInstance;
43
+ /** What the inner planners compile: no calculations, `having`, order or page. */
44
+ readonly inner: DatasetQuery;
45
+ readonly selectedMeasures: readonly string[];
46
+ readonly outputs: readonly CalculationOutput[];
47
+ readonly having: readonly DatasetHavingCondition[];
48
+ readonly orderBy: readonly MetricOrderBy[];
49
+ readonly limit?: number;
50
+ readonly offset?: number;
51
+ readonly ranks: readonly PlannedRank[];
52
+ readonly shares: readonly PlannedShare[];
53
+ readonly limitBy?: {
54
+ readonly n: number;
55
+ readonly by: readonly string[];
56
+ };
57
+ readonly other?: PlannedOther;
58
+ }
59
+ export interface QueryCalculationPlanResult {
60
+ readonly plan?: QueryCalculationPlan;
61
+ readonly errors: readonly string[];
62
+ }
63
+ /** Plans a dataset query that carries calculations, `limitBy` or `other`. */
64
+ export declare function planQueryCalculations(ds: AnyDatasetInstance, query: DatasetQuery, context?: ExecutionContext): QueryCalculationPlanResult;
65
+ /** Maps internal names in planner errors back to the caller's names. */
66
+ export declare function publicCalculationErrors(errors: readonly string[], outputs: readonly CalculationOutput[]): string[];
67
+ //# sourceMappingURL=query-calculation-plan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-calculation-plan.d.ts","sourceRoot":"","sources":["../../src/utils/query-calculation-plan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EACV,kBAAkB,EAClB,sBAAsB,EAEtB,YAAY,EACZ,gBAAgB,EAEhB,aAAa,EAGd,MAAM,aAAa,CAAC;AAUrB,OAAO,EAIL,KAAK,iBAAiB,EACvB,MAAM,gCAAgC,CAAC;AAOxC,kEAAkE;AAClE,eAAO,MAAM,mBAAmB,UAAU,CAAC;AAE3C,sCAAsC;AACtC,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,+BAA+B;IAC/B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,KAAK,GAAG,MAAM,CAAC;CACpC;AAED,6EAA6E;AAC7E,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,kEAAkE;IAClE,QAAQ,CAAC,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wUD,6EAA6E;AAC7E,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB,0BAA0B,CA4D5B;AAsCD,wEAAwE;AACxE,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,SAAS,iBAAiB,EAAE,GAAG,MAAM,EAAE,CAElH"}
@@ -0,0 +1,416 @@
1
+ /**
2
+ * Plans RFC 0026 query-scoped calculations.
3
+ *
4
+ * `filter`, `shift`, `window` and `formula` entries (and `compare`, which
5
+ * expands into a shift and two formulas per measure) become measures of a
6
+ * query-scoped view of the dataset, under reserved internal names. The
7
+ * existing planners then compile the view exactly as they compile model-level
8
+ * filtered, shift, window and derived measures, so every constraint they
9
+ * enforce applies unchanged. The caller-facing names, `having`, ordering and
10
+ * pagination are applied by an outer stage over the planned statement.
11
+ */
12
+ import { ProtocolExpressionError, validateProtocolSemanticQuery } from '@hypequery/protocol';
13
+ import { baseMeasureNames, derivedMeasuresView, getBaseMeasure, isShiftMeasure, isWindowMeasure } from './dataset-measures.js';
14
+ import { validateShiftMeasures } from './shift-measure-validation.js';
15
+ import { validateWindowMeasures } from './window-measure-validation.js';
16
+ import { queryFilterErrors } from './query-filter-errors.js';
17
+ import { effectiveFilters } from './effective-filters.js';
18
+ import { filterLeafCount, filterLeaves } from './filter-tree.js';
19
+ import { datasetHavingErrors } from './dataset-having.js';
20
+ import { measureDependencyNames } from './measure-dependencies.js';
21
+ import { formulaMeasure, formulaReferences } from './query-calculation-formula.js';
22
+ import { CALCULATION_INTERNAL_PREFIX, calculationKind, calculationOutputs, } from './query-calculation-outputs.js';
23
+ /** Base aggregations a filter calculation cannot condition, as for model-level filtered measures. */
24
+ const UNFILTERABLE = new Set(['argMax', 'argMin', 'merge']);
25
+ /** Base aggregations whose per-group values sum to the coarser group's value. */
26
+ const ADDITIVE = new Set(['sum', 'count']);
27
+ /** The remainder label `other` uses when the query names none. */
28
+ export const DEFAULT_OTHER_LABEL = 'Other';
29
+ /** Whether a measure's per-group values sum to the coarser group's value. */
30
+ function isAdditive(measures, name) {
31
+ const definition = Object.hasOwn(measures, name) ? measures[name] : undefined;
32
+ if (isShiftMeasure(definition))
33
+ return isAdditive(measures, definition.measure);
34
+ if (isWindowMeasure(definition))
35
+ return ADDITIVE.has(getBaseMeasure(measures, definition.measure)?.aggregation ?? '');
36
+ const base = getBaseMeasure(measures, name);
37
+ return base !== undefined && ADDITIVE.has(base.aggregation);
38
+ }
39
+ function entryLabel(entry, index) {
40
+ return `Calculation "${String(entry.name)}" (calculations[${index}])`;
41
+ }
42
+ /**
43
+ * The structural rules RFC 0026 makes decidable from the query, via the
44
+ * protocol validator. It sees the measures the query actually selects, so an
45
+ * omitted `measures` is checked as the default selection it runs as.
46
+ */
47
+ function envelopeErrors(query, selectedMeasures) {
48
+ const probe = {
49
+ kind: 'dataset',
50
+ dataset: 'dataset',
51
+ ...(query.dimensions === undefined ? {} : { dimensions: query.dimensions }),
52
+ measures: selectedMeasures,
53
+ ...(query.by === undefined ? {} : { by: 'day' }),
54
+ ...(query.orderBy === undefined
55
+ ? {}
56
+ : { orderBy: query.orderBy.map(order => ({ field: order.field, direction: 'asc' })) }),
57
+ ...(query.calculations === undefined ? {} : {
58
+ calculations: query.calculations.map(entry => (entry !== null && typeof entry === 'object' && 'filter' in entry
59
+ && entry.filter !== null && typeof entry.filter === 'object' && Array.isArray(entry.filter.where)
60
+ ? {
61
+ ...entry,
62
+ filter: {
63
+ ...entry.filter,
64
+ // Values are checked against each field's type below; the
65
+ // envelope only needs the shape and the field name.
66
+ where: entry.filter.where.map(filter => ({
67
+ kind: 'comparison', operator: 'isNull', left: { kind: 'reference', name: filter?.field },
68
+ })),
69
+ },
70
+ }
71
+ : entry)),
72
+ }),
73
+ ...(query.limitBy === undefined ? {} : { limitBy: query.limitBy }),
74
+ ...(query.other === undefined ? {} : { other: query.other }),
75
+ };
76
+ try {
77
+ validateProtocolSemanticQuery(probe, { extension: 2 });
78
+ return [];
79
+ }
80
+ catch (error) {
81
+ if (error instanceof ProtocolExpressionError) {
82
+ return [`Invalid query calculations at ${error.path} (${error.code})${envelopeHint(error.path, query)}.`];
83
+ }
84
+ throw error;
85
+ }
86
+ }
87
+ /** A plain-language reason for the envelope failures a caller most often hits. */
88
+ function envelopeHint(path, query) {
89
+ if (query.by === undefined && /^\$\.calculations\[\d+\]\.(shift|window|compare)$/.test(path)) {
90
+ return ': shift, window and compare calculations require "by"';
91
+ }
92
+ if (path === '$.limitBy' && (query.orderBy?.length ?? 0) === 0)
93
+ return ': limitBy requires a non-empty orderBy';
94
+ if (/\.(measure|args\[\d+\]|measures\[\d+\])$/.test(path)) {
95
+ return ': the input must be a selected measure or an earlier calculation of a kind this one accepts';
96
+ }
97
+ return '';
98
+ }
99
+ class CalculationPlanner {
100
+ ds;
101
+ query;
102
+ context;
103
+ errors = [];
104
+ available = new Map();
105
+ added = {};
106
+ ranks = [];
107
+ shares = [];
108
+ constructor(ds, query, context) {
109
+ this.ds = ds;
110
+ this.query = query;
111
+ this.context = context;
112
+ }
113
+ /** The measures of the view: the dataset's, plus every calculation measure. */
114
+ get measures() {
115
+ return { ...this.ds.measures, ...this.added };
116
+ }
117
+ /**
118
+ * A reference to an earlier output, or to a measure the dataset publishes.
119
+ * The envelope has already refused forward references, earlier outputs of a
120
+ * kind this entry does not accept, relationship measures, and unselected
121
+ * measures where an entry reads selected ones; what is left is the contract.
122
+ */
123
+ input(name, label) {
124
+ const earlier = this.available.get(name);
125
+ if (earlier !== undefined)
126
+ return { internal: earlier.internal, timed: earlier.timed, additive: earlier.additive };
127
+ if (!Object.hasOwn(this.ds.measures, name)) {
128
+ this.errors.push(`${label} reads unknown measure "${name}".`);
129
+ return undefined;
130
+ }
131
+ const timed = measureDependencyNames(this.ds.measures, [name])
132
+ .some(dependency => isShiftMeasure(this.ds.measures[dependency]) || isWindowMeasure(this.ds.measures[dependency]));
133
+ return { internal: name, timed, additive: isAdditive(this.ds.measures, name) };
134
+ }
135
+ add(internal, definition, publicName, kind, timed, additive = isAdditive({ ...this.measures, [internal]: definition }, internal)) {
136
+ this.added[internal] = definition;
137
+ this.available.set(publicName, { internal, kind, timed, additive });
138
+ }
139
+ plan(entry, index) {
140
+ const label = entryLabel(entry, index);
141
+ const kind = calculationKind(entry);
142
+ const internal = `${CALCULATION_INTERNAL_PREFIX}${index}`;
143
+ switch (kind) {
144
+ case 'filter': return this.filter(entry, internal, label);
145
+ case 'shift': return this.shift(entry, internal, label);
146
+ case 'window': return this.window(entry, internal, label);
147
+ case 'formula': return this.formula(entry, internal, label);
148
+ case 'compare': return this.compare(entry, internal, label);
149
+ case 'rank': return this.rank(entry, internal, label);
150
+ case 'share': return this.share(entry, internal, label);
151
+ }
152
+ }
153
+ filter(entry, internal, label) {
154
+ const { measure, where } = entry.filter;
155
+ const input = this.input(measure, label);
156
+ if (input === undefined)
157
+ return;
158
+ const base = getBaseMeasure(this.ds.measures, measure);
159
+ if (base === undefined) {
160
+ this.errors.push(`${label} must filter a base measure; "${measure}" is not one.`);
161
+ return;
162
+ }
163
+ if (UNFILTERABLE.has(base.aggregation)) {
164
+ this.errors.push(`${label} cannot filter "${measure}": ${base.aggregation} measures do not accept filters.`);
165
+ return;
166
+ }
167
+ const filters = effectiveFilters(this.ds);
168
+ for (const filter of where) {
169
+ const field = Object.hasOwn(filters, filter.field) ? filters[filter.field].field : undefined;
170
+ if (field !== undefined && this.ds.dimensions[field]?.fieldType === 'timestamp') {
171
+ this.errors.push(`${label} cannot compare time field "${filter.field}"; bound time with the query's filters.`);
172
+ }
173
+ }
174
+ this.errors.push(...queryFilterErrors(this.ds, where, this.context).map(error => `${label}: ${error}`));
175
+ const definition = { ...base, filters: [...(base.filters ?? []), ...where.map(filter => ({ ...filter }))] };
176
+ this.add(internal, definition, entry.name, 'filter', false);
177
+ }
178
+ shift(entry, internal, label) {
179
+ const { measure, amount, unit } = entry.shift;
180
+ const input = this.input(measure, label);
181
+ if (input === undefined)
182
+ return;
183
+ if (input.timed) {
184
+ this.errors.push(`${label} cannot shift "${measure}", which already depends on a shift or window.`);
185
+ return;
186
+ }
187
+ const definition = {
188
+ __type: 'shift_measure_definition', measure: input.internal, interval: { amount, unit },
189
+ };
190
+ this.add(internal, definition, entry.name, 'shift', true);
191
+ }
192
+ window(entry, internal, label) {
193
+ const { measure } = entry.window;
194
+ const input = this.input(measure, label);
195
+ if (input === undefined)
196
+ return;
197
+ if (getBaseMeasure(this.measures, input.internal) === undefined) {
198
+ this.errors.push(`${label} must window a base measure; "${measure}" is not one.`);
199
+ return;
200
+ }
201
+ const mode = entry.window.trailing !== undefined
202
+ ? { trailing: { ...entry.window.trailing } }
203
+ : entry.window.toDate !== undefined ? { toDate: entry.window.toDate } : { cumulative: true };
204
+ const definition = { __type: 'window_measure_definition', measure: input.internal, ...mode };
205
+ this.add(internal, definition, entry.name, 'window', true);
206
+ }
207
+ formula(entry, internal, label) {
208
+ const resolved = new Map();
209
+ let timed = false;
210
+ for (const name of formulaReferences(entry.formula)) {
211
+ const input = this.input(name, label);
212
+ if (input === undefined)
213
+ return;
214
+ resolved.set(name, input.internal);
215
+ timed ||= input.timed;
216
+ }
217
+ this.add(internal, formulaMeasure(entry.formula, name => resolved.get(name) ?? name), entry.name, 'formula', timed, false);
218
+ }
219
+ compare(entry, internal, label) {
220
+ const { to, measures } = entry.compare;
221
+ // The envelope requires `by` for every compare.
222
+ const unit = to === 'previousYear' ? 'year' : this.query.by;
223
+ measures.forEach((measure, at) => {
224
+ const input = this.input(measure, label);
225
+ if (input === undefined)
226
+ return;
227
+ if (input.timed) {
228
+ this.errors.push(`${label} cannot compare "${measure}", which already depends on a shift or window.`);
229
+ return;
230
+ }
231
+ const base = `${internal}_${at}`;
232
+ const previous = `${base}_previous`;
233
+ this.add(previous, { __type: 'shift_measure_definition', measure: input.internal, interval: { amount: 1, unit } }, `${measure}_previous`, 'compare', true);
234
+ const read = (name) => (name === 'previous' ? previous : input.internal);
235
+ // A difference of additive values is additive; a ratio never is.
236
+ this.add(`${base}_change`, formulaMeasure({ op: 'subtract', args: ['current', 'previous'] }, read), `${measure}_change`, 'compare', true, input.additive);
237
+ this.add(`${base}_change_pct`, formulaMeasure({ op: 'percentChange', args: ['current', 'previous'] }, read), `${measure}_change_pct`, 'compare', true, false);
238
+ });
239
+ }
240
+ rank(entry, internal, label) {
241
+ const input = this.input(entry.rank.measure, label);
242
+ if (input === undefined)
243
+ return;
244
+ this.ranks.push({
245
+ internal, column: input.internal, within: [...(entry.rank.within ?? [])], direction: entry.rank.direction ?? 'desc',
246
+ });
247
+ this.available.set(entry.name, { internal, kind: 'rank', timed: input.timed, additive: false });
248
+ }
249
+ share(entry, internal, label) {
250
+ const input = this.input(entry.share.measure, label);
251
+ if (input === undefined)
252
+ return;
253
+ const of = [...(entry.share.of ?? [])];
254
+ this.available.set(entry.name, { internal, kind: 'share', timed: input.timed, additive: false });
255
+ if (input.additive) {
256
+ this.shares.push({ internal, column: input.internal, of });
257
+ return;
258
+ }
259
+ // Never approximate: a non-additive input is re-aggregated from source
260
+ // rows at the coarser grain, which a shift or window has no form for here.
261
+ if (input.timed) {
262
+ this.errors.push(`${label} cannot share "${entry.share.measure}": it is not additive and depends on a shift or window, `
263
+ + 'so its total at a coarser grain cannot be computed exactly.');
264
+ return;
265
+ }
266
+ // The denominator reads the same rows, but is never a filled series: a
267
+ // filled period has no source rows to total, and is joined as NULL.
268
+ const { calculations: _c, limitBy: _l, other: _o, having: _h, orderBy: _ob, limit: _li, offset: _of, by: _by, dimensions: _d, fill: _fill, ...rest } = this.query;
269
+ // `period` is the time bucket only when `by` makes one; otherwise it is an
270
+ // ordinary dimension and the denominator groups by it like any other.
271
+ const bucketed = this.query.by !== undefined && of.includes('period');
272
+ this.shares.push({
273
+ internal,
274
+ column: input.internal,
275
+ of,
276
+ denominator: {
277
+ ...rest,
278
+ dimensions: bucketed ? of.filter(name => name !== 'period') : of,
279
+ ...(bucketed ? { by: this.query.by } : {}),
280
+ measures: [input.internal],
281
+ },
282
+ });
283
+ }
284
+ other() {
285
+ const other = this.query.other;
286
+ if (other === undefined)
287
+ return undefined;
288
+ const label = '"other"';
289
+ const fields = [
290
+ ...(this.query.dimensions ?? []), ...(this.query.measures ?? []),
291
+ // Every comparison of a filter tree (RFC 0029), however deeply grouped.
292
+ ...filterLeaves(this.query.filters).map(filter => filter.field), ...(this.query.orderBy ?? []).map(order => order.field),
293
+ ];
294
+ if (fields.some(field => field.includes('.'))) {
295
+ this.errors.push(`${label} cannot be combined with relationship fields; it regroups a local dimension.`);
296
+ return undefined;
297
+ }
298
+ if (this.ds.dimensions[other.dimension]?.fieldType !== 'string') {
299
+ this.errors.push(`${label} groups a string dimension; "${other.dimension}" is not one.`);
300
+ return undefined;
301
+ }
302
+ const definition = Object.hasOwn(this.ds.measures, other.measure) ? this.ds.measures[other.measure] : undefined;
303
+ if (definition === undefined) {
304
+ this.errors.push(`${label} ranks by unknown measure "${other.measure}".`);
305
+ return undefined;
306
+ }
307
+ const timed = measureDependencyNames(this.ds.measures, [other.measure])
308
+ .some(name => isShiftMeasure(this.ds.measures[name]) || isWindowMeasure(this.ds.measures[name]));
309
+ if (timed) {
310
+ this.errors.push(`${label} cannot rank by "${other.measure}", which depends on a shift or window.`);
311
+ return undefined;
312
+ }
313
+ // The ranking spans the whole range, unbucketed and unfilled.
314
+ const { calculations: _c, limitBy: _l, other: _o, having: _h, orderBy: _ob, limit: _li, offset: _of, by: _by, dimensions: _d, measures: _m, fill: _fill, ...rest } = this.query;
315
+ return {
316
+ dimension: other.dimension,
317
+ n: other.n,
318
+ measure: other.measure,
319
+ label: other.label ?? DEFAULT_OTHER_LABEL,
320
+ ranking: { ...rest, dimensions: [other.dimension], measures: [other.measure] },
321
+ };
322
+ }
323
+ }
324
+ /** Replaces internal names in planner messages with the names the caller wrote. */
325
+ function publicMessage(message, outputs) {
326
+ return [...outputs]
327
+ .sort((left, right) => right.internal.length - left.internal.length)
328
+ .reduce((text, output) => text.split(output.internal).join(output.name), message);
329
+ }
330
+ /** Plans a dataset query that carries calculations, `limitBy` or `other`. */
331
+ export function planQueryCalculations(ds, query, context) {
332
+ const selectedMeasures = query.measures ?? baseMeasureNames(ds.measures);
333
+ const errors = envelopeErrors(query, selectedMeasures);
334
+ if (errors.length > 0)
335
+ return { errors };
336
+ const reserved = [...Object.keys(ds.measures), ...Object.keys(ds.dimensions)]
337
+ .filter(name => name.startsWith(CALCULATION_INTERNAL_PREFIX));
338
+ if (reserved.length > 0) {
339
+ return {
340
+ errors: [`Dataset "${ds.name}" declares ${reserved.map(name => `"${name}"`).join(', ')}; `
341
+ + `the "${CALCULATION_INTERNAL_PREFIX}" prefix is reserved for query calculations.`],
342
+ };
343
+ }
344
+ const planner = new CalculationPlanner(ds, query, context);
345
+ (query.calculations ?? []).forEach((entry, index) => planner.plan(entry, index));
346
+ const other = planner.other();
347
+ if (planner.errors.length > 0) {
348
+ return { errors: planner.errors };
349
+ }
350
+ const outputs = calculationOutputs(query);
351
+ const measures = planner.measures;
352
+ const view = { ...ds, measures, derivedMeasures: derivedMeasuresView(measures) };
353
+ try {
354
+ validateShiftMeasures(ds.name, view.timeKey, measures);
355
+ validateWindowMeasures(ds.name, view.timeKey, measures);
356
+ }
357
+ catch (error) {
358
+ return { errors: [publicMessage(error.message, outputs)] };
359
+ }
360
+ const { calculations: _calculations, limitBy: _limitBy, other: _other, having: _having, orderBy: _orderBy, limit: _limit, offset: _offset, ...rest } = query;
361
+ // Rank and share are computed over the inner rows, not by the planners.
362
+ const planned = outputs.filter(output => output.kind !== 'rank' && output.kind !== 'share');
363
+ const inner = { ...rest, measures: [...selectedMeasures, ...planned.map(output => output.internal)] };
364
+ const outerErrors = outerStageErrors(ds, query, selectedMeasures, outputs);
365
+ if (outerErrors.length > 0)
366
+ return { errors: outerErrors };
367
+ return {
368
+ errors: [],
369
+ plan: {
370
+ dataset: view,
371
+ inner,
372
+ selectedMeasures,
373
+ outputs,
374
+ having: query.having ?? [],
375
+ orderBy: query.orderBy ?? [],
376
+ ...(query.limit === undefined ? {} : { limit: query.limit }),
377
+ ...(query.offset === undefined ? {} : { offset: query.offset }),
378
+ ranks: planner.ranks,
379
+ shares: planner.shares,
380
+ ...(query.limitBy === undefined ? {} : { limitBy: { n: query.limitBy.n, by: [...query.limitBy.by] } }),
381
+ ...(other === undefined ? {} : { other }),
382
+ },
383
+ };
384
+ }
385
+ /** `having`, `orderBy` and the limits that span calculation outputs. */
386
+ function outerStageErrors(ds, query, selectedMeasures, outputs) {
387
+ const errors = [];
388
+ const outputNames = outputs.map(output => output.name);
389
+ const values = [...selectedMeasures, ...outputNames];
390
+ // Validated as if every output were a selected measure of the base dataset,
391
+ // which is what an outer-stage condition reads.
392
+ // The outer stage runs after every planner, so time-measure queries accept
393
+ // `having` here even though the grouped planners refuse it.
394
+ errors.push(...datasetHavingErrors(ds, { ...query, measures: [] }, values));
395
+ const orderable = new Set([...(query.dimensions ?? []), ...values, ...(query.by ? ['period'] : [])]);
396
+ const unknown = (query.orderBy ?? []).map(order => order.field).filter(field => !orderable.has(field));
397
+ if (unknown.length > 0) {
398
+ errors.push(`Unknown orderBy fields: ${unknown.join(', ')}. Available: ${[...orderable].join(', ')}`);
399
+ }
400
+ const maxMeasures = ds.limits?.maxMeasures;
401
+ if (maxMeasures && values.length > maxMeasures) {
402
+ errors.push(`Too many measures and calculation outputs: ${values.length} (max ${maxMeasures})`);
403
+ }
404
+ const maxFilters = ds.limits?.maxFilters;
405
+ // RFC 0029: a filter tree costs its comparisons; and/or/not groups cost nothing.
406
+ const predicates = filterLeafCount(query.filters) + (query.having?.length ?? 0)
407
+ + (query.calculations ?? []).reduce((count, entry) => (count + ('filter' in entry && Array.isArray(entry.filter?.where) ? entry.filter.where.length : 0)), 0);
408
+ if (maxFilters && predicates > maxFilters) {
409
+ errors.push(`Too many filters, having conditions and filter-calculation conditions: ${predicates} (max ${maxFilters})`);
410
+ }
411
+ return errors;
412
+ }
413
+ /** Maps internal names in planner errors back to the caller's names. */
414
+ export function publicCalculationErrors(errors, outputs) {
415
+ return errors.map(error => publicMessage(error, outputs));
416
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Query-scoped calculations (RFC 0026) as the dataset client accepts them.
3
+ *
4
+ * The shapes mirror the portable query envelope, except that a `filter`
5
+ * calculation's `where` uses the client's `{ field, operator, value }`
6
+ * filters, exactly as `DatasetQuery.filters` does.
7
+ */
8
+ import type { MetricFilter, TimeGrain } from '../types.js';
9
+ export type QueryCalculationKind = 'filter' | 'shift' | 'window' | 'formula' | 'compare' | 'rank' | 'share';
10
+ export type QueryFormulaOperator = 'add' | 'subtract' | 'multiply' | 'divide' | 'nullIfZero' | 'coalesce' | 'round' | 'floor' | 'ceil' | 'percentChange';
11
+ /** A formula operand: an input reference, a finite number, or a nested node. */
12
+ export type QueryFormulaArgument = string | number | QueryFormulaNode;
13
+ export interface QueryFormulaNode {
14
+ readonly op: QueryFormulaOperator;
15
+ readonly args: readonly QueryFormulaArgument[];
16
+ }
17
+ export interface QueryCalculationInterval {
18
+ readonly amount: number;
19
+ readonly unit: TimeGrain;
20
+ }
21
+ export type QueryWindowCalculation = {
22
+ readonly measure: string;
23
+ readonly trailing: QueryCalculationInterval;
24
+ readonly toDate?: never;
25
+ readonly cumulative?: never;
26
+ } | {
27
+ readonly measure: string;
28
+ readonly toDate: Exclude<TimeGrain, 'minute'>;
29
+ readonly trailing?: never;
30
+ readonly cumulative?: never;
31
+ } | {
32
+ readonly measure: string;
33
+ readonly cumulative: true;
34
+ readonly trailing?: never;
35
+ readonly toDate?: never;
36
+ };
37
+ export type DatasetQueryCalculation = {
38
+ readonly name: string;
39
+ readonly filter: {
40
+ readonly measure: string;
41
+ readonly where: readonly MetricFilter[];
42
+ };
43
+ } | {
44
+ readonly name: string;
45
+ readonly shift: {
46
+ readonly measure: string;
47
+ } & QueryCalculationInterval;
48
+ } | {
49
+ readonly name: string;
50
+ readonly window: QueryWindowCalculation;
51
+ } | {
52
+ readonly name: string;
53
+ readonly formula: QueryFormulaNode;
54
+ } | {
55
+ readonly name: string;
56
+ readonly compare: {
57
+ readonly to: 'previousPeriod' | 'previousYear';
58
+ readonly measures: readonly string[];
59
+ };
60
+ } | {
61
+ readonly name: string;
62
+ readonly rank: {
63
+ readonly measure: string;
64
+ readonly within?: readonly string[];
65
+ readonly direction?: 'asc' | 'desc';
66
+ };
67
+ } | {
68
+ readonly name: string;
69
+ readonly share: {
70
+ readonly measure: string;
71
+ readonly of?: readonly string[];
72
+ };
73
+ };
74
+ /** Keep the first `n` rows of each `by` group in `orderBy` order. */
75
+ export interface DatasetQueryLimitBy {
76
+ readonly n: number;
77
+ readonly by: readonly string[];
78
+ }
79
+ /** Group `dimension` as itself for its top `n` values of `measure`, else as `label`. */
80
+ export interface DatasetQueryOtherBucket {
81
+ readonly dimension: string;
82
+ readonly n: number;
83
+ readonly measure: string;
84
+ readonly label?: string;
85
+ }
86
+ /** One output column a calculation adds to a result. */
87
+ export interface DatasetCalculationColumn {
88
+ readonly name: string;
89
+ readonly kind: Exclude<QueryCalculationKind, 'compare'>;
90
+ /** The calculation entry that produced the column. */
91
+ readonly calculation: string;
92
+ /** The input the column varies, for filter, shift, window, rank and share. */
93
+ readonly measure?: string;
94
+ readonly type: 'number' | 'integer';
95
+ readonly format?: 'ratio';
96
+ }
97
+ //# sourceMappingURL=query-calculation-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-calculation-types.d.ts","sourceRoot":"","sources":["../../src/utils/query-calculation-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE3D,MAAM,MAAM,oBAAoB,GAAG,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;AAE5G,MAAM,MAAM,oBAAoB,GAC5B,KAAK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