@hypequery/datasets 0.31.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 (239) 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 +37 -0
  14. package/dist/cloud-publication.d.ts.map +1 -0
  15. package/dist/cloud-publication.js +46 -0
  16. package/dist/cloud-publishing.d.ts +2 -2
  17. package/dist/cloud-publishing.d.ts.map +1 -1
  18. package/dist/codegen/dataset-source.d.ts.map +1 -1
  19. package/dist/codegen/dataset-source.js +4 -1
  20. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  21. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  22. package/dist/contract-3-authoring.fixture.js +40 -0
  23. package/dist/contract.d.ts +5 -1
  24. package/dist/contract.d.ts.map +1 -1
  25. package/dist/contract.js +9 -0
  26. package/dist/dataset-compilation.d.ts +3 -0
  27. package/dist/dataset-compilation.d.ts.map +1 -1
  28. package/dist/dataset-query.d.ts +5 -0
  29. package/dist/dataset-query.d.ts.map +1 -1
  30. package/dist/dataset.d.ts.map +1 -1
  31. package/dist/dataset.js +12 -2
  32. package/dist/event-operations.d.ts +43 -0
  33. package/dist/event-operations.d.ts.map +1 -0
  34. package/dist/event-operations.js +137 -0
  35. package/dist/execution-capabilities.d.ts +2 -1
  36. package/dist/execution-capabilities.d.ts.map +1 -1
  37. package/dist/execution-capabilities.js +1 -1
  38. package/dist/execution-capabilities.json +6 -6
  39. package/dist/executor.d.ts +13 -0
  40. package/dist/executor.d.ts.map +1 -1
  41. package/dist/executor.js +42 -8
  42. package/dist/index.d.ts +8 -3
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +4 -1
  45. package/dist/portable-execution-errors.d.ts +11 -0
  46. package/dist/portable-execution-errors.d.ts.map +1 -1
  47. package/dist/portable-execution-errors.js +14 -0
  48. package/dist/portable-executor.d.ts +22 -5
  49. package/dist/portable-executor.d.ts.map +1 -1
  50. package/dist/portable-executor.js +64 -5
  51. package/dist/protocol-adapter.d.ts +12 -0
  52. package/dist/protocol-adapter.d.ts.map +1 -1
  53. package/dist/protocol-adapter.js +30 -8
  54. package/dist/protocol-deployment-adapter.d.ts +10 -3
  55. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  56. package/dist/protocol-deployment-adapter.js +60 -26
  57. package/dist/protocol-rehydrate.d.ts +3 -16
  58. package/dist/protocol-rehydrate.d.ts.map +1 -1
  59. package/dist/protocol-rehydrate.js +71 -11
  60. package/dist/query-builder-protocol.d.ts +10 -0
  61. package/dist/query-builder-protocol.d.ts.map +1 -1
  62. package/dist/query-planner.d.ts.map +1 -1
  63. package/dist/query-planner.js +3 -1
  64. package/dist/relationship-check.d.ts.map +1 -1
  65. package/dist/relationship-check.js +2 -0
  66. package/dist/semantic-planner.d.ts.map +1 -1
  67. package/dist/semantic-planner.js +16 -3
  68. package/dist/types.d.ts +109 -7
  69. package/dist/types.d.ts.map +1 -1
  70. package/dist/utils/agent-catalog-projection.d.ts +11 -2
  71. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  72. package/dist/utils/agent-catalog-projection.js +49 -5
  73. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  74. package/dist/utils/build-dataset-query-builder.js +4 -8
  75. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  76. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  77. package/dist/utils/calculation-stage-sql.js +98 -0
  78. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  79. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  80. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  81. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  82. package/dist/utils/compile-dataset-query.js +11 -3
  83. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  84. package/dist/utils/dataset-definition-validation.js +90 -6
  85. package/dist/utils/dataset-events.d.ts +19 -0
  86. package/dist/utils/dataset-events.d.ts.map +1 -0
  87. package/dist/utils/dataset-events.js +46 -0
  88. package/dist/utils/dataset-having.d.ts.map +1 -1
  89. package/dist/utils/dataset-having.js +6 -1
  90. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  91. package/dist/utils/dataset-query-result.js +7 -1
  92. package/dist/utils/dataset-query-validation.d.ts +1 -1
  93. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  94. package/dist/utils/dataset-query-validation.js +25 -47
  95. package/dist/utils/dataset-source.d.ts +2 -2
  96. package/dist/utils/dataset-source.d.ts.map +1 -1
  97. package/dist/utils/dataset-source.js +8 -1
  98. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  99. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  100. package/dist/utils/dimension-selection-overrides.js +22 -0
  101. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  102. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  103. package/dist/utils/event-breakdown-sql.js +17 -0
  104. package/dist/utils/event-condition-sql.d.ts +18 -0
  105. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  106. package/dist/utils/event-condition-sql.js +63 -0
  107. package/dist/utils/event-operation-shape.d.ts +8 -0
  108. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  109. package/dist/utils/event-operation-shape.js +66 -0
  110. package/dist/utils/event-operation-spec.d.ts +43 -0
  111. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  112. package/dist/utils/event-operation-spec.js +68 -0
  113. package/dist/utils/event-range-span.d.ts +4 -0
  114. package/dist/utils/event-range-span.d.ts.map +1 -0
  115. package/dist/utils/event-range-span.js +22 -0
  116. package/dist/utils/event-result-values.d.ts +8 -0
  117. package/dist/utils/event-result-values.d.ts.map +1 -0
  118. package/dist/utils/event-result-values.js +21 -0
  119. package/dist/utils/event-source-sql.d.ts +38 -0
  120. package/dist/utils/event-source-sql.d.ts.map +1 -0
  121. package/dist/utils/event-source-sql.js +71 -0
  122. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  123. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  124. package/dist/utils/filter-predicate-tree.js +80 -0
  125. package/dist/utils/filter-tree.d.ts +42 -0
  126. package/dist/utils/filter-tree.d.ts.map +1 -0
  127. package/dist/utils/filter-tree.js +164 -0
  128. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  129. package/dist/utils/filtered-aggregation-sql.js +3 -0
  130. package/dist/utils/funnel-rows.d.ts +10 -0
  131. package/dist/utils/funnel-rows.d.ts.map +1 -0
  132. package/dist/utils/funnel-rows.js +30 -0
  133. package/dist/utils/funnel-sql.d.ts +18 -0
  134. package/dist/utils/funnel-sql.d.ts.map +1 -0
  135. package/dist/utils/funnel-sql.js +104 -0
  136. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  137. package/dist/utils/metric-derived-query.js +4 -5
  138. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  139. package/dist/utils/metric-query-builder.js +4 -5
  140. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  141. package/dist/utils/metric-query-validation.js +18 -7
  142. package/dist/utils/other-bucket-sql.d.ts +23 -0
  143. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  144. package/dist/utils/other-bucket-sql.js +51 -0
  145. package/dist/utils/portable-aggregations.d.ts +10 -6
  146. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  147. package/dist/utils/portable-aggregations.js +13 -8
  148. package/dist/utils/portable-grains.d.ts +17 -8
  149. package/dist/utils/portable-grains.d.ts.map +1 -1
  150. package/dist/utils/portable-grains.js +26 -11
  151. package/dist/utils/portable-query-calculations.d.ts +14 -0
  152. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  153. package/dist/utils/portable-query-calculations.js +31 -0
  154. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  155. package/dist/utils/portable-semantic-query.js +27 -1
  156. package/dist/utils/protocol-contract-3.d.ts +30 -0
  157. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  158. package/dist/utils/protocol-contract-3.js +93 -0
  159. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  160. package/dist/utils/protocol-metric-capabilities.js +2 -1
  161. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  162. package/dist/utils/protocol-metric-expressions.js +6 -1
  163. package/dist/utils/protocol-rehydrate-filters.js +2 -1
  164. package/dist/utils/protocol-rehydrate-time-keys.d.ts +5 -0
  165. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  166. package/dist/utils/protocol-rehydrate-time-keys.js +5 -0
  167. package/dist/utils/query-calculation-errors.d.ts +6 -0
  168. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  169. package/dist/utils/query-calculation-errors.js +9 -0
  170. package/dist/utils/query-calculation-formula.d.ts +19 -0
  171. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  172. package/dist/utils/query-calculation-formula.js +77 -0
  173. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  174. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  175. package/dist/utils/query-calculation-outputs.js +72 -0
  176. package/dist/utils/query-calculation-plan.d.ts +67 -0
  177. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  178. package/dist/utils/query-calculation-plan.js +416 -0
  179. package/dist/utils/query-calculation-types.d.ts +97 -0
  180. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  181. package/dist/utils/query-calculation-types.js +8 -0
  182. package/dist/utils/query-field-references.d.ts.map +1 -1
  183. package/dist/utils/query-field-references.js +2 -1
  184. package/dist/utils/query-filter-errors.d.ts +11 -0
  185. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  186. package/dist/utils/query-filter-errors.js +65 -0
  187. package/dist/utils/query-timezone.d.ts +6 -3
  188. package/dist/utils/query-timezone.d.ts.map +1 -1
  189. package/dist/utils/query-timezone.js +5 -1
  190. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  191. package/dist/utils/relationship-builder-plan.js +2 -1
  192. package/dist/utils/relationship-fields.d.ts.map +1 -1
  193. package/dist/utils/relationship-fields.js +5 -0
  194. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  195. package/dist/utils/relationship-measure-sql.js +2 -0
  196. package/dist/utils/relationship-validation.d.ts +3 -1
  197. package/dist/utils/relationship-validation.d.ts.map +1 -1
  198. package/dist/utils/relationship-validation.js +8 -4
  199. package/dist/utils/relative-date-filters.d.ts +21 -0
  200. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  201. package/dist/utils/relative-date-filters.js +86 -0
  202. package/dist/utils/relative-date-range.d.ts +20 -0
  203. package/dist/utils/relative-date-range.d.ts.map +1 -0
  204. package/dist/utils/relative-date-range.js +75 -0
  205. package/dist/utils/retention-rows.d.ts +9 -0
  206. package/dist/utils/retention-rows.d.ts.map +1 -0
  207. package/dist/utils/retention-rows.js +30 -0
  208. package/dist/utils/retention-sql.d.ts +16 -0
  209. package/dist/utils/retention-sql.d.ts.map +1 -0
  210. package/dist/utils/retention-sql.js +68 -0
  211. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  212. package/dist/utils/scoped-dataset-source.js +4 -0
  213. package/dist/utils/segments.d.ts +3 -2
  214. package/dist/utils/segments.d.ts.map +1 -1
  215. package/dist/utils/segments.js +5 -4
  216. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  217. package/dist/utils/semantic-query-syntax.js +8 -2
  218. package/dist/utils/sql-dataset-source.d.ts +36 -0
  219. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  220. package/dist/utils/sql-dataset-source.js +126 -0
  221. package/dist/utils/time-axis-bounds.d.ts +11 -4
  222. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  223. package/dist/utils/time-axis-bounds.js +14 -6
  224. package/dist/utils/time-measure-axis.d.ts +2 -2
  225. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  226. package/dist/utils/time-measure-axis.js +13 -3
  227. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  228. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  229. package/dist/utils/time-measure-dataset-sql.js +15 -5
  230. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  231. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  232. package/dist/utils/time-measure-source-sql.js +7 -8
  233. package/dist/utils/time-query-measures.d.ts +5 -0
  234. package/dist/utils/time-query-measures.d.ts.map +1 -1
  235. package/dist/utils/time-query-measures.js +7 -0
  236. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  237. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  238. package/dist/utils/unsupported-contract-reasons.js +5 -1
  239. package/package.json +3 -3
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Nested caller filters (RFC 0029): a query's `filters` list is an implicit
3
+ * AND of comparisons and `{ and }` / `{ or }` / `{ not }` groups.
4
+ */
5
+ /** Deepest group nesting a query may use, so a hostile tree cannot exhaust the stack. */
6
+ export const MAX_FILTER_GROUP_DEPTH = 32;
7
+ const GROUP_KEYS = ['and', 'or', 'not'];
8
+ /** True for a `{ and }`, `{ or }` or `{ not }` node, as opposed to a comparison. */
9
+ export function isFilterGroup(node) {
10
+ if (typeof node !== 'object' || node === null || Array.isArray(node))
11
+ return false;
12
+ if (Object.hasOwn(node, 'field'))
13
+ return false;
14
+ return GROUP_KEYS.some(key => Object.hasOwn(node, key));
15
+ }
16
+ /** True when `nodes` holds any group, so the flat, builder-free paths cannot run it. */
17
+ export function hasFilterGroups(nodes) {
18
+ return (nodes ?? []).some(isFilterGroup);
19
+ }
20
+ function groupItems(group) {
21
+ if ('not' in group && group.not !== undefined)
22
+ return [group.not];
23
+ return ('and' in group ? group.and : group.or) ?? [];
24
+ }
25
+ /** Every comparison in the tree, depth first, as authored. */
26
+ export function filterLeaves(nodes) {
27
+ const leaves = [];
28
+ const visit = (node, depth) => {
29
+ if (!isFilterGroup(node)) {
30
+ // Malformed entries are reported by filterTreeErrors, not read here.
31
+ if (typeof node === 'object' && node !== null && !Array.isArray(node))
32
+ leaves.push(node);
33
+ return;
34
+ }
35
+ if (depth > MAX_FILTER_GROUP_DEPTH)
36
+ return;
37
+ const items = groupItems(node);
38
+ if (Array.isArray(items))
39
+ items.forEach(item => visit(item, depth + 1));
40
+ };
41
+ (nodes ?? []).forEach(node => visit(node, 1));
42
+ return leaves;
43
+ }
44
+ /** Number of comparisons the query applies: what `maxFilters` bounds. */
45
+ export function filterLeafCount(nodes) {
46
+ return filterLeaves(nodes).length;
47
+ }
48
+ /**
49
+ * The operator a comparison has once `not` is pushed down to it, as the
50
+ * operator allowlist sees it. `between` negates to a pair; `like` has no
51
+ * portable negation and is checked as itself.
52
+ */
53
+ export function negatedFilterOperators(operator) {
54
+ switch (operator) {
55
+ case 'eq': return ['neq'];
56
+ case 'neq': return ['eq'];
57
+ case 'gt': return ['lte'];
58
+ case 'gte': return ['lt'];
59
+ case 'lt': return ['gte'];
60
+ case 'lte': return ['gt'];
61
+ case 'in': return ['notIn'];
62
+ case 'notIn': return ['in'];
63
+ case 'isNull': return ['isNotNull'];
64
+ case 'isNotNull': return ['isNull'];
65
+ case 'between': return ['lt', 'gt'];
66
+ case 'like': return ['like'];
67
+ case 'inDateRange': return ['lt', 'gte'];
68
+ default: return [operator];
69
+ }
70
+ }
71
+ /** Every comparison with the operators it effectively applies. */
72
+ export function effectiveFilterLeaves(nodes) {
73
+ const leaves = [];
74
+ const visit = (node, negated, depth) => {
75
+ if (!isFilterGroup(node)) {
76
+ if (typeof node !== 'object' || node === null || Array.isArray(node))
77
+ return;
78
+ leaves.push({
79
+ filter: node,
80
+ negated,
81
+ operators: negated ? negatedFilterOperators(node.operator) : [node.operator],
82
+ });
83
+ return;
84
+ }
85
+ if (depth > MAX_FILTER_GROUP_DEPTH)
86
+ return;
87
+ const items = groupItems(node);
88
+ if (!Array.isArray(items))
89
+ return;
90
+ const flips = 'not' in group(node);
91
+ items.forEach(item => visit(item, flips ? !negated : negated, depth + 1));
92
+ };
93
+ (nodes ?? []).forEach(node => visit(node, false, 1));
94
+ return leaves;
95
+ }
96
+ function group(node) {
97
+ return node;
98
+ }
99
+ /** Structural problems with the groups themselves; leaves are validated separately. */
100
+ export function filterTreeErrors(nodes) {
101
+ if (nodes === undefined)
102
+ return [];
103
+ if (!Array.isArray(nodes))
104
+ return ['Filters must be an array.'];
105
+ const errors = [];
106
+ const visit = (node, depth) => {
107
+ if (typeof node !== 'object' || node === null || Array.isArray(node)) {
108
+ errors.push('Each filter must be an object: a comparison, or an and/or/not group.');
109
+ return;
110
+ }
111
+ if (!isFilterGroup(node))
112
+ return;
113
+ if (depth > MAX_FILTER_GROUP_DEPTH) {
114
+ errors.push(`Filter groups may nest at most ${MAX_FILTER_GROUP_DEPTH} deep.`);
115
+ return;
116
+ }
117
+ const keys = Object.keys(node);
118
+ if (keys.length !== 1) {
119
+ errors.push('A filter group has exactly one of "and", "or" or "not".');
120
+ return;
121
+ }
122
+ const [key] = keys;
123
+ const value = node[key];
124
+ if (key === 'not') {
125
+ if (Array.isArray(value)) {
126
+ errors.push('A "not" group takes one filter, not an array.');
127
+ return;
128
+ }
129
+ visit(value, depth + 1);
130
+ return;
131
+ }
132
+ if (!Array.isArray(value) || value.length === 0) {
133
+ errors.push(`An "${key}" group needs a non-empty array of filters.`);
134
+ return;
135
+ }
136
+ value.forEach(item => visit(item, depth + 1));
137
+ };
138
+ nodes.forEach(node => visit(node, 1));
139
+ return errors;
140
+ }
141
+ /**
142
+ * The top-level conjuncts: top-level `and` groups and one-item `or` groups
143
+ * are spliced in, so `[{ and: [a, b] }, c]` reads as `[a, b, c]`. Only these
144
+ * can bound a time axis.
145
+ */
146
+ export function topLevelFilterNodes(nodes) {
147
+ const result = [];
148
+ const visit = (node) => {
149
+ if (isFilterGroup(node)) {
150
+ const record = group(node);
151
+ if (Array.isArray(record.and) || (Array.isArray(record.or) && record.or.length === 1)) {
152
+ (groupItems(node)).forEach(visit);
153
+ return;
154
+ }
155
+ }
156
+ result.push(node);
157
+ };
158
+ (nodes ?? []).forEach(visit);
159
+ return result;
160
+ }
161
+ /** Comparisons nested under an `or` or `not`, which filter rows but bound nothing. */
162
+ export function nestedFilterLeaves(nodes) {
163
+ return topLevelFilterNodes(nodes).filter(isFilterGroup).flatMap(node => filterLeaves([node]));
164
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"filtered-aggregation-sql.d.ts","sourceRoot":"","sources":["../../src/utils/filtered-aggregation-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAgB,MAAM,aAAa,CAAC;AAErF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAExE,KAAK,YAAY,GAAG,kBAAkB,CAAC;AAiDvC,wBAAgB,kCAAkC,CAChD,EAAE,EAAE,YAAY,EAChB,IAAI,EAAE,eAAe,EACrB,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,0BAA0B,GAAG,SAAS,EAC/C,OAAO,EAAE,sBAAsB,GAC9B,MAAM,CAmCR"}
1
+ {"version":3,"file":"filtered-aggregation-sql.d.ts","sourceRoot":"","sources":["../../src/utils/filtered-aggregation-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAgB,MAAM,aAAa,CAAC;AAErF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAExE,KAAK,YAAY,GAAG,kBAAkB,CAAC;AAoDvC,wBAAgB,kCAAkC,CAChD,EAAE,EAAE,YAAY,EAChB,IAAI,EAAE,eAAe,EACrB,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,0BAA0B,GAAG,SAAS,EAC/C,OAAO,EAAE,sBAAsB,GAC9B,MAAM,CAmCR"}
@@ -35,6 +35,9 @@ function renderMeasureFilterCondition(ds, filter, joinCtx, dialect) {
35
35
  return `${field} IS NULL`;
36
36
  case 'isNotNull':
37
37
  return `${field} IS NOT NULL`;
38
+ case 'inDateRange':
39
+ // RFC 0029: a measure definition must not change meaning with the calendar.
40
+ throw new Error('"inDateRange" is a query filter; measure filters cannot use it.');
38
41
  }
39
42
  }
40
43
  export function applyFilteredAggregationExpression(ds, spec, fieldOrExpr, joinCtx, dialect) {
@@ -0,0 +1,10 @@
1
+ import type { FunnelSpec } from './event-operation-spec.js';
2
+ import { type EventResultRow } from './event-result-values.js';
3
+ export type { EventResultRow, EventResultValue } from './event-result-values.js';
4
+ /**
5
+ * Expand one row per funnel group (`_hq_r1 … _hq_rN`) into one row per step
6
+ * (RFC 0027): `cohort`, breakdown values, `step`, `step_index`, `entities`,
7
+ * both conversions and `dropoff`.
8
+ */
9
+ export declare function funnelResultRows(spec: FunnelSpec, breakdownAliases: readonly string[], rows: readonly Record<string, unknown>[]): EventResultRow[];
10
+ //# sourceMappingURL=funnel-rows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"funnel-rows.d.ts","sourceRoot":"","sources":["../../src/utils/funnel-rows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAA6B,KAAK,cAAc,EAAyB,MAAM,0BAA0B,CAAC;AAEjH,YAAY,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjF;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,UAAU,EAChB,gBAAgB,EAAE,SAAS,MAAM,EAAE,EACnC,IAAI,EAAE,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GACvC,cAAc,EAAE,CAuBlB"}
@@ -0,0 +1,30 @@
1
+ import { countValue, ratio, scalar } from './event-result-values.js';
2
+ /**
3
+ * Expand one row per funnel group (`_hq_r1 … _hq_rN`) into one row per step
4
+ * (RFC 0027): `cohort`, breakdown values, `step`, `step_index`, `entities`,
5
+ * both conversions and `dropoff`.
6
+ */
7
+ export function funnelResultRows(spec, breakdownAliases, rows) {
8
+ const result = [];
9
+ for (const row of rows) {
10
+ const reached = spec.steps.map((_, index) => countValue(row[`_hq_r${index + 1}`]));
11
+ const group = {
12
+ ...(spec.by === undefined ? {} : { cohort: scalar(row._hq_cohort) }),
13
+ ...Object.fromEntries(spec.breakdown.map((name, index) => [name, scalar(row[breakdownAliases[index]])])),
14
+ };
15
+ spec.steps.forEach((step, index) => {
16
+ const entities = reached[index];
17
+ const previous = index === 0 ? entities : reached[index - 1];
18
+ result.push(Object.freeze({
19
+ ...group,
20
+ step: step.name,
21
+ step_index: index + 1,
22
+ entities,
23
+ conversion_from_previous: index === 0 ? (entities === 0 ? null : 1) : ratio(entities, previous),
24
+ conversion_from_first: ratio(entities, reached[0]),
25
+ dropoff: index === 0 ? 0 : previous - entities,
26
+ }));
27
+ });
28
+ }
29
+ return result;
30
+ }
@@ -0,0 +1,18 @@
1
+ import type { AnyDatasetInstance } from '../types.js';
2
+ import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
3
+ import { type PlannedStatement } from './statement-parameters.js';
4
+ import { buildEventSourceSql } from './event-source-sql.js';
5
+ import type { FunnelSpec } from './event-operation-spec.js';
6
+ /** A planned event operation and what its rows mean. */
7
+ export interface PlannedEventStatement {
8
+ readonly statement: PlannedStatement;
9
+ readonly breakdown: readonly string[];
10
+ readonly readsFinal: boolean;
11
+ }
12
+ /**
13
+ * Plan a funnel (RFC 0027) as one statement: scan → per-entity level →
14
+ * per-group counts of entities reaching each step → ranked breakdown groups.
15
+ * The caller expands each returned row into one row per step.
16
+ */
17
+ export declare function buildFunnelSql(ds: AnyDatasetInstance, spec: FunnelSpec, options: DatasetQueryExecutionOptions, readsFinal: (joinCtx: ReturnType<typeof buildEventSourceSql>['joinCtx']) => boolean): PlannedEventStatement;
18
+ //# sourceMappingURL=funnel-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"funnel-sql.d.ts","sourceRoot":"","sources":["../../src/utils/funnel-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAGxE,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAI5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,wDAAwD;AACxD,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,SAAS,EAAE,gBAAgB,CAAC;IACrC,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B;AA0CD;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,EAAE,EAAE,kBAAkB,EACtB,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,4BAA4B,EACrC,UAAU,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,SAAS,CAAC,KAAK,OAAO,GAClF,qBAAqB,CA2DvB"}
@@ -0,0 +1,104 @@
1
+ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
2
+ import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
3
+ import { StatementParameters } from './statement-parameters.js';
4
+ import { buildEventSourceSql } from './event-source-sql.js';
5
+ import { filterLeaves } from './filter-tree.js';
6
+ import { eventConditionFlagSql } from './event-condition-sql.js';
7
+ import { rankedBreakdownSql } from './event-breakdown-sql.js';
8
+ /**
9
+ * The `strict` level: the deepest step reached by a chain of strictly later
10
+ * events whose last is within the window of its first.
11
+ *
12
+ * `windowFunnel(…, 'strict_increase')` alone is wrong when events share a
13
+ * timestamp: whether a chain survives depends on the order it reads ties in.
14
+ * Each event is therefore split into one row per step it satisfies, the rows
15
+ * are ordered by `time × (N + 1) + (N − step)`, and the window is scaled by
16
+ * `N + 1`. Higher steps at one instant then sort first, so an event can only
17
+ * extend a chain whose previous event is strictly earlier, and the window
18
+ * check is exact because the offset is smaller than one scaled millisecond.
19
+ */
20
+ function strictLevelSql(steps, windowMs) {
21
+ const scale = steps + 1;
22
+ const conditions = Array.from({ length: steps }, (_, index) => `_hq_j = ${index + 1}`).join(', ');
23
+ return {
24
+ arrayJoin: `ARRAY JOIN arrayFilter(_hq_k -> _hq_steps[_hq_k] = 1, range(1, ${steps + 1})) AS _hq_j`,
25
+ level: `windowFunnel(${windowMs * scale}, 'strict_increase')(`
26
+ + `toUInt64(toUnixTimestamp64Milli(_hq_time) * ${scale} + (${steps} - _hq_j)), ${conditions}) AS _hq_level`,
27
+ };
28
+ }
29
+ /**
30
+ * The `any` level: the largest k such that steps 1…k each have a matching
31
+ * event within one span of `window`, in any order. Every matching timestamp
32
+ * is tried as the span's start; the earliest event of a satisfying span is
33
+ * one of them, so the search is exact.
34
+ */
35
+ function anyLevelSql(steps, windowMs) {
36
+ const arrays = Array.from({ length: steps }, (_, index) => (`groupArrayIf(toUnixTimestamp64Milli(_hq_time), _hq_steps[${index + 1}] = 1) AS _hq_s${index + 1}`));
37
+ let prefix = String(steps);
38
+ for (let step = steps; step >= 1; step -= 1) {
39
+ prefix = `if(arrayExists(_hq_x -> _hq_x >= _hq_t AND _hq_x <= _hq_t + ${windowMs}, _hq_s${step}), ${prefix}, ${step - 1})`;
40
+ }
41
+ const anchors = `arrayConcat(${Array.from({ length: steps }, (_, index) => `_hq_s${index + 1}`).join(', ')})`;
42
+ return { arrays, level: `arrayMax(arrayMap(_hq_t -> ${prefix}, ${anchors})) AS _hq_level` };
43
+ }
44
+ /**
45
+ * Plan a funnel (RFC 0027) as one statement: scan → per-entity level →
46
+ * per-group counts of entities reaching each step → ranked breakdown groups.
47
+ * The caller expands each returned row into one row per step.
48
+ */
49
+ export function buildFunnelSql(ds, spec, options, readsFinal) {
50
+ const dialect = resolveDatasetSqlDialect(options.builderFactory);
51
+ if (dialect.name !== 'clickhouse') {
52
+ throw new Error(`Funnels need ClickHouse; the "${dialect.name}" datasets dialect has no equivalent yet.`);
53
+ }
54
+ assertRawSqlForDialect(ds, dialect);
55
+ const statement = new StatementParameters(dialect);
56
+ const conditionFields = [...new Set(spec.steps.flatMap(step => filterLeaves(step.where).map(condition => condition.field)))];
57
+ const source = buildEventSourceSql(ds, {
58
+ entity: spec.entity,
59
+ breakdown: spec.breakdown,
60
+ conditionFields,
61
+ filters: spec.filters,
62
+ ...(spec.timezone === undefined ? {} : { timezone: spec.timezone }),
63
+ }, options, statement);
64
+ const breakdown = source.breakdown;
65
+ const steps = spec.steps.length;
66
+ const flags = spec.steps.map(step => eventConditionFlagSql(step.where, source.conditionPredicates, statement));
67
+ const partition = ['_hq_entity', ...breakdown].join(', ');
68
+ // Only events that satisfy some step can move an entity through the funnel.
69
+ const flagged = `_hq_flagged AS (SELECT _hq_time, ${partition}, [${flags.join(', ')}] AS _hq_steps `
70
+ + 'FROM _hq_events WHERE has(_hq_steps, 1))';
71
+ const cohort = spec.by === undefined ? [] : ['_hq_first'];
72
+ let entities;
73
+ if (spec.order === 'any') {
74
+ const any = anyLevelSql(steps, spec.windowMs);
75
+ const first = spec.by === undefined ? [] : ['minIf(_hq_time, _hq_steps[1] = 1) AS _hq_first'];
76
+ entities = `_hq_entity_arrays AS (SELECT ${partition}, ${[...first, ...any.arrays].join(', ')} `
77
+ + `FROM _hq_flagged GROUP BY ${partition}), `
78
+ + `_hq_entities AS (SELECT ${[partition, ...cohort].join(', ')}, ${any.level} FROM _hq_entity_arrays)`;
79
+ }
80
+ else {
81
+ const strict = strictLevelSql(steps, spec.windowMs);
82
+ const first = spec.by === undefined ? [] : ['minIf(_hq_time, _hq_j = 1) AS _hq_first'];
83
+ entities = `_hq_entities AS (SELECT ${partition}, ${[...first, strict.level].join(', ')} `
84
+ + `FROM _hq_flagged ${strict.arrayJoin} GROUP BY ${partition})`;
85
+ }
86
+ const cohortColumn = spec.by === undefined
87
+ ? []
88
+ : [`formatDateTime(${dialect.truncateTime('_hq_first', spec.by)}, '%Y-%m-%d') AS _hq_cohort`];
89
+ const reached = Array.from({ length: steps }, (_, index) => (`countIf(_hq_level >= ${index + 1}) AS _hq_r${index + 1}`));
90
+ const groupKeys = [...breakdown, ...(spec.by === undefined ? [] : ['_hq_cohort'])];
91
+ // With no grouping key the aggregate returns one row even for no entities,
92
+ // so an empty funnel still reports zero at every step.
93
+ const groups = `_hq_groups AS (SELECT ${[...breakdown.map(alias => alias), ...cohortColumn, ...reached].join(', ')} `
94
+ + `FROM _hq_entities${groupKeys.length ? ` WHERE _hq_level >= 1 GROUP BY ${groupKeys.join(', ')}` : ''})`;
95
+ const orderBy = [
96
+ ...(spec.by === undefined ? [] : ['_hq_cohort ASC']),
97
+ ...(breakdown.length ? ['_hq_rank ASC'] : []),
98
+ ];
99
+ const body = rankedBreakdownSql({
100
+ relation: '_hq_groups', breakdown, sizeColumn: '_hq_r1', limit: spec.breakdownLimit, orderBy,
101
+ });
102
+ const text = `WITH ${[...source.ctes, flagged, entities, groups].join(', ')} ${body}`;
103
+ return { statement: { text, parameters: statement }, breakdown, readsFinal: readsFinal(source.joinCtx) };
104
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"metric-derived-query.d.ts","sourceRoot":"","sources":["../../src/utils/metric-derived-query.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,8BAA8B,CAAC;AAQ9F,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAKvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAMrD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,iBAAiB,EACvB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAmHlB"}
1
+ {"version":3,"file":"metric-derived-query.d.ts","sourceRoot":"","sources":["../../src/utils/metric-derived-query.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,8BAA8B,CAAC;AAU9F,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAKvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAMrD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,iBAAiB,EACvB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAkHlB"}
@@ -5,6 +5,8 @@ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
5
5
  import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
6
6
  import { applyAggregationSpec, buildDimensionSelectionPlan, resolveDimensionExpression, resolveFilterField, } from '../query-planner.js';
7
7
  import { queryTimeFilter } from './query-timezone.js';
8
+ import { applyFilterTree } from './filter-predicate-tree.js';
9
+ import { filterLeaves } from './filter-tree.js';
8
10
  import { StatementParameters } from './statement-parameters.js';
9
11
  import { formulaExpressionSql } from './derived-measure-sql.js';
10
12
  import { isTenantScopedFilter } from './metric-handle.js';
@@ -49,15 +51,12 @@ export function buildDerivedMetricSql(ref, spec, query, grain, builderFactory, c
49
51
  aggregateAliases.push(quoted);
50
52
  }
51
53
  // Filters on CTE
52
- for (const filter of query.filters ?? []) {
54
+ for (const filter of filterLeaves(query.filters)) {
53
55
  if (isTenantScopedFilter(ds, filter, context)) {
54
56
  throw new Error(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
55
57
  }
56
- const resolvedField = resolveFilterField(ds, filter.field, joinCtx);
57
- for (const predicate of queryTimeFilter(dialect, ds, filter, resolvedField, query.timezone)) {
58
- cteBuilder = cteBuilder.where(predicate.expression, predicate.operator, predicate.value);
59
- }
60
58
  }
59
+ cteBuilder = applyFilterTree(cteBuilder, query.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), query.timezone)));
61
60
  for (const filter of segmentFilters(ds, query.segments)) {
62
61
  const predicates = queryTimeFilter(dialect, ds, filter, resolveDimensionExpression(ds, filter.field, joinCtx), query.timezone, { field: 'dimension' });
63
62
  for (const predicate of predicates) {
@@ -1 +1 @@
1
- {"version":3,"file":"metric-query-builder.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAa9F,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEvE,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAsDlB"}
1
+ {"version":3,"file":"metric-query-builder.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAe9F,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEvE,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAqDlB"}
@@ -5,6 +5,8 @@ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
5
5
  import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
6
6
  import { applyAggregationSpec, appendOrderLimitOffset, buildDimensionSelectionPlan, resolveDimensionExpression, resolveFilterField, } from '../query-planner.js';
7
7
  import { queryTimeFilter } from './query-timezone.js';
8
+ import { applyFilterTree } from './filter-predicate-tree.js';
9
+ import { filterLeaves } from './filter-tree.js';
8
10
  import { isTenantScopedFilter } from './metric-handle.js';
9
11
  import { buildRelationshipBuilderContext } from './relationship-builder-plan.js';
10
12
  import { segmentFilters } from './segments.js';
@@ -29,15 +31,12 @@ export function buildMetricQueryBuilder(ref, spec, dataset, query, grain, builde
29
31
  }
30
32
  qb = applyAggregationSpec(qb, ds, spec, ref.name, joinCtx, dialect);
31
33
  // User filters
32
- for (const filter of query.filters ?? []) {
34
+ for (const filter of filterLeaves(query.filters)) {
33
35
  if (isTenantScopedFilter(ds, filter, context)) {
34
36
  throw new Error(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
35
37
  }
36
- const resolvedField = resolveFilterField(ds, filter.field, joinCtx);
37
- for (const predicate of queryTimeFilter(dialect, ds, filter, resolvedField, query.timezone)) {
38
- qb = qb.where(predicate.expression, predicate.operator, predicate.value);
39
- }
40
38
  }
39
+ qb = applyFilterTree(qb, query.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), query.timezone)));
41
40
  // Segments: author-defined, so they resolve dimensions directly rather
42
41
  // than through the caller-facing filter allow-list.
43
42
  for (const filter of segmentFilters(ds, query.segments)) {
@@ -1 +1 @@
1
- {"version":3,"file":"metric-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-validation.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAI9E,OAAO,EAAsD,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAW3G,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,WAAW,EAClB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAwIlB"}
1
+ {"version":3,"file":"metric-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-validation.ts"],"names":[],"mappings":"AAIA,gFAAgF;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAI9E,OAAO,EAAsD,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAW3G,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,WAAW,EAClB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAiJlB"}
@@ -1,3 +1,5 @@
1
+ import { relativeDateFilterError } from './relative-date-filters.js';
2
+ import { effectiveFilterLeaves, filterLeafCount, filterTreeErrors } from './filter-tree.js';
1
3
  import { notGroupableError } from './groupable.js';
2
4
  import { semanticQuerySyntaxErrors } from './semantic-query-syntax.js';
3
5
  import { validateFilterValue } from '../validation.js';
@@ -38,7 +40,7 @@ export function validateMetricQueryInput(metric, query, context) {
38
40
  if (relationshipTenantError) {
39
41
  errors.push(relationshipTenantError);
40
42
  }
41
- errors.push(...enforcedConstraintErrors(ds, context, query.filters?.length ?? 0));
43
+ errors.push(...enforcedConstraintErrors(ds, context, filterLeafCount(query.filters)));
42
44
  if (metric.__type === 'grained_metric_ref' && query.by && query.by !== metric.grain) {
43
45
  errors.push(`Metric "${ref.name}" is already grained by "${metric.grain}" and cannot be queried with by="${query.by}".`);
44
46
  }
@@ -62,9 +64,16 @@ export function validateMetricQueryInput(metric, query, context) {
62
64
  }
63
65
  }
64
66
  // Validate filters
65
- for (const filter of query.filters ?? []) {
67
+ const filterEntries = filterTreeErrors(query.filters).length === 0 ? effectiveFilterLeaves(query.filters) : [];
68
+ for (const { filter, operators } of filterEntries) {
69
+ // The client resolves every valid relative range first (RFC 0029); one
70
+ // still here could not be resolved, and says why.
71
+ if (filter.operator === 'inDateRange') {
72
+ errors.push(relativeDateFilterError(ds, filter) ?? `Filter "${filter.field}": "inDateRange" was not resolved before validation.`);
73
+ continue;
74
+ }
66
75
  if (isQualifiedField(filter.field)) {
67
- const filterError = validateQualifiedFilter(ds, filter, context);
76
+ const filterError = validateQualifiedFilter(ds, filter, context, operators);
68
77
  if (filterError) {
69
78
  errors.push(filterError);
70
79
  }
@@ -75,8 +84,9 @@ export function validateMetricQueryInput(metric, query, context) {
75
84
  continue;
76
85
  }
77
86
  const filterDefinition = filters[filter.field];
78
- if (!filterAllowsOperator(filterDefinition, filter.operator)) {
79
- errors.push(`Filter "${filter.field}" does not allow operator "${filter.operator}". Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
87
+ const refused = operators.find(operator => !filterAllowsOperator(filterDefinition, operator));
88
+ if (refused) {
89
+ errors.push(`Filter "${filter.field}" does not allow operator "${refused}"${refused === filter.operator ? '' : ` (the negation of "${filter.operator}")`}. Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
80
90
  continue;
81
91
  }
82
92
  const resolvedField = filterDefinition.field;
@@ -122,8 +132,9 @@ export function validateMetricQueryInput(metric, query, context) {
122
132
  if (ds.limits.maxMeasures && 1 > ds.limits.maxMeasures) {
123
133
  errors.push(`Too many measures (1). Max: ${ds.limits.maxMeasures}`);
124
134
  }
125
- if (ds.limits.maxFilters && (query.filters?.length ?? 0) > ds.limits.maxFilters) {
126
- errors.push(`Too many filters (${query.filters?.length}). Max: ${ds.limits.maxFilters}`);
135
+ const filterCount = filterLeafCount(query.filters);
136
+ if (ds.limits.maxFilters && filterCount > ds.limits.maxFilters) {
137
+ errors.push(`Too many filters (${filterCount}). Max: ${ds.limits.maxFilters}`);
127
138
  }
128
139
  if (ds.limits.maxResultSize && query.limit != null && query.limit > ds.limits.maxResultSize) {
129
140
  errors.push(`Too many results requested (${query.limit}). Max: ${ds.limits.maxResultSize}`);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * RFC 0026 `other`: the top-N ranking statement, and the dataset view whose
3
+ * selected dimension reads `if(value IN top-N, value, label)`.
4
+ *
5
+ * Every row is regrouped from source, so every measure in the remainder row
6
+ * is exact, `countDistinct` included. The ranking runs over the same filters,
7
+ * segments and tenancy as the query, over its whole range rather than per
8
+ * period, and never counts NULL as a top value.
9
+ */
10
+ import type { DatasetSqlDialectRules } from '../dataset-sql-dialect.js';
11
+ import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
12
+ import type { AnyDatasetInstance } from '../types.js';
13
+ import type { PlannedOther, QueryCalculationPlan } from './query-calculation-plan.js';
14
+ import type { PlannedStatement } from './statement-parameters.js';
15
+ /**
16
+ * Why this dialect cannot run the plan's stage, as one message, or undefined.
17
+ * `limitBy`, `other` and joined share denominators rely on ClickHouse SQL.
18
+ */
19
+ export declare function unsupportedStageMessage(plan: QueryCalculationPlan, dialect: DatasetSqlDialectRules): string | undefined;
20
+ export declare function assertStageSupported(plan: QueryCalculationPlan, dialect: DatasetSqlDialectRules): void;
21
+ export declare function withOtherBucket(ds: AnyDatasetInstance, other: PlannedOther, dialect: DatasetSqlDialectRules): AnyDatasetInstance;
22
+ export declare function otherRankingSql(ds: AnyDatasetInstance, other: PlannedOther, options: DatasetQueryExecutionOptions, dialect: DatasetSqlDialectRules): PlannedStatement;
23
+ //# sourceMappingURL=other-bucket-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"other-bucket-sql.d.ts","sourceRoot":"","sources":["../../src/utils/other-bucket-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKtD,OAAO,KAAK,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAGlE;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,SAAS,CASvH;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAGtG;AAED,wBAAgB,eAAe,CAC7B,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,sBAAsB,GAC9B,kBAAkB,CAIpB;AAED,wBAAgB,eAAe,CAC7B,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,sBAAsB,GAC9B,gBAAgB,CAUlB"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * RFC 0026 `other`: the top-N ranking statement, and the dataset view whose
3
+ * selected dimension reads `if(value IN top-N, value, label)`.
4
+ *
5
+ * Every row is regrouped from source, so every measure in the remainder row
6
+ * is exact, `countDistinct` included. The ranking runs over the same filters,
7
+ * segments and tenancy as the query, over its whole range rather than per
8
+ * period, and never counts NULL as a top value.
9
+ */
10
+ import { buildDatasetQueryBuilder } from './build-dataset-query-builder.js';
11
+ import { buildDerivedDatasetSql } from './dataset-derived-query.js';
12
+ import { withDimensionSelectionRewrite } from './dimension-selection-overrides.js';
13
+ import { OTHER_TOP_CTE } from './calculation-stage-sql.js';
14
+ import { UnsupportedQueryCalculationError } from './query-calculation-errors.js';
15
+ /**
16
+ * Why this dialect cannot run the plan's stage, as one message, or undefined.
17
+ * `limitBy`, `other` and joined share denominators rely on ClickHouse SQL.
18
+ */
19
+ export function unsupportedStageMessage(plan, dialect) {
20
+ if (dialect.name === 'clickhouse')
21
+ return undefined;
22
+ const reasons = [
23
+ ...(plan.limitBy === undefined ? [] : ['"limitBy"']),
24
+ ...(plan.other === undefined ? [] : ['"other"']),
25
+ ...(plan.shares.some(share => share.denominator !== undefined) ? ['a share of a non-additive measure'] : []),
26
+ ];
27
+ if (reasons.length === 0)
28
+ return undefined;
29
+ return `${reasons.join(', ')} ${reasons.length === 1 ? 'is' : 'are'} not supported on the "${dialect.name}" dialect.`;
30
+ }
31
+ export function assertStageSupported(plan, dialect) {
32
+ const message = unsupportedStageMessage(plan, dialect);
33
+ if (message !== undefined)
34
+ throw new UnsupportedQueryCalculationError([message]);
35
+ }
36
+ export function withOtherBucket(ds, other, dialect) {
37
+ const top = `SELECT ${dialect.quoteIdentifier(other.dimension)} FROM ${dialect.quoteIdentifier(OTHER_TOP_CTE)}`;
38
+ const label = dialect.measureFilterLiteral(other.label);
39
+ return withDimensionSelectionRewrite(ds, other.dimension, expression => `if(${expression} IN (${top}), ${expression}, ${label})`);
40
+ }
41
+ export function otherRankingSql(ds, other, options, dialect) {
42
+ const ranked = buildDerivedDatasetSql(ds, other.ranking, options, buildDatasetQueryBuilder);
43
+ const quote = dialect.quoteIdentifier;
44
+ const dimension = quote(other.dimension);
45
+ // Ties break on the value itself, so the list is deterministic.
46
+ return {
47
+ text: `SELECT ${dimension} FROM (${ranked.text}) AS ${quote('_hq_other_ranked')} WHERE ${dimension} IS NOT NULL`
48
+ + ` ORDER BY ${quote(other.measure)} DESC, ${dimension} ASC LIMIT ${other.n}`,
49
+ parameters: ranked.parameters,
50
+ };
51
+ }
@@ -1,17 +1,21 @@
1
1
  /**
2
2
  * Aggregations that the published deployment contract can carry.
3
3
  *
4
- * `approxCountDistinct` runs locally, but it is an expression extension 2 and
5
- * deployment contract 3 feature (RFC 0015). Publishing emits contract 2 until
6
- * it can emit contract 3, so it refuses the measure with an error naming it.
4
+ * `approxCountDistinct` is an expression extension 2 and deployment contract 3
5
+ * feature (RFC 0015). A deployment carries it as a contract 3 measure; the
6
+ * standalone dataset contract and published metrics stay on contract 2 and
7
+ * refuse it with an error naming it.
7
8
  * `merge` is a deployment measure with its state function (RFC 0022), but the
8
9
  * expression grammar has no merge aggregate, so a metric over one is refused.
9
10
  */
10
- import type { ProtocolAggregation, ProtocolDatasetMeasure } from '@hypequery/protocol';
11
+ import type { ProtocolAggregation, ProtocolDatasetMeasureV3 } from '@hypequery/protocol';
11
12
  import type { AggregationType } from '../types.js';
12
13
  type PortableAggregation = Exclude<ProtocolAggregation, 'approxCountDistinct'>;
13
- /** A dataset measure's aggregation as the contract carries it; otherwise throws naming `owner`. */
14
- export declare function requirePublishableMeasureAggregation(aggregation: AggregationType, owner: string): ProtocolDatasetMeasure['aggregation'];
14
+ /**
15
+ * A dataset measure's aggregation as the contract carries it; otherwise throws
16
+ * naming `owner`. Contract 3 carries `approxCountDistinct`; contract 2 does not.
17
+ */
18
+ export declare function requirePublishableMeasureAggregation(aggregation: AggregationType, owner: string, contractVersion?: 2 | 3): ProtocolDatasetMeasureV3['aggregation'];
15
19
  /** Returns `aggregation` when an expression can carry it; otherwise throws naming `owner`. */
16
20
  export declare function requirePortableAggregation(aggregation: AggregationType, owner: string): PortableAggregation;
17
21
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"portable-aggregations.d.ts","sourceRoot":"","sources":["../../src/utils/portable-aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACvF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,KAAK,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,CAAC;AAc/E,mGAAmG;AACnG,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,sBAAsB,CAAC,aAAa,CAAC,CAGvC;AAED,8FAA8F;AAC9F,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,mBAAmB,CASrB"}
1
+ {"version":3,"file":"portable-aggregations.d.ts","sourceRoot":"","sources":["../../src/utils/portable-aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACzF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,KAAK,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,CAAC;AAc/E;;;GAGG;AACH,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,EACb,eAAe,GAAE,CAAC,GAAG,CAAK,GACzB,wBAAwB,CAAC,aAAa,CAAC,CAGzC;AAED,8FAA8F;AAC9F,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,mBAAmB,CASrB"}