@hypequery/datasets 0.32.0 → 0.35.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 (264) 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 +10 -48
  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/client-contract/dataset-fields.d.ts.map +1 -1
  14. package/dist/client-contract/dataset-fields.js +2 -1
  15. package/dist/cloud-publication.d.ts +3 -3
  16. package/dist/cloud-publication.d.ts.map +1 -1
  17. package/dist/cloud-publishing.d.ts +2 -2
  18. package/dist/cloud-publishing.d.ts.map +1 -1
  19. package/dist/codegen/dataset-source.d.ts.map +1 -1
  20. package/dist/codegen/dataset-source.js +10 -1
  21. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  22. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  23. package/dist/contract-3-authoring.fixture.js +40 -0
  24. package/dist/contract.d.ts +5 -1
  25. package/dist/contract.d.ts.map +1 -1
  26. package/dist/contract.js +9 -0
  27. package/dist/dataset-compilation.d.ts +3 -0
  28. package/dist/dataset-compilation.d.ts.map +1 -1
  29. package/dist/dataset-query.d.ts +5 -0
  30. package/dist/dataset-query.d.ts.map +1 -1
  31. package/dist/dataset.d.ts.map +1 -1
  32. package/dist/dataset.js +12 -2
  33. package/dist/event-operations.d.ts +43 -0
  34. package/dist/event-operations.d.ts.map +1 -0
  35. package/dist/event-operations.js +137 -0
  36. package/dist/execution-capabilities.d.ts +16 -3
  37. package/dist/execution-capabilities.d.ts.map +1 -1
  38. package/dist/execution-capabilities.js +5 -3
  39. package/dist/execution-capabilities.json +7 -8
  40. package/dist/executor.d.ts +13 -0
  41. package/dist/executor.d.ts.map +1 -1
  42. package/dist/executor.js +42 -8
  43. package/dist/index.d.ts +7 -3
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +4 -1
  46. package/dist/portable-execution-errors.d.ts +11 -0
  47. package/dist/portable-execution-errors.d.ts.map +1 -1
  48. package/dist/portable-execution-errors.js +14 -0
  49. package/dist/portable-executor.d.ts +22 -5
  50. package/dist/portable-executor.d.ts.map +1 -1
  51. package/dist/portable-executor.js +64 -5
  52. package/dist/protocol-adapter.d.ts +12 -0
  53. package/dist/protocol-adapter.d.ts.map +1 -1
  54. package/dist/protocol-adapter.js +32 -10
  55. package/dist/protocol-deployment-adapter.d.ts +10 -3
  56. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  57. package/dist/protocol-deployment-adapter.js +60 -26
  58. package/dist/protocol-rehydrate.d.ts +3 -16
  59. package/dist/protocol-rehydrate.d.ts.map +1 -1
  60. package/dist/protocol-rehydrate.js +72 -14
  61. package/dist/query-builder-protocol.d.ts +10 -0
  62. package/dist/query-builder-protocol.d.ts.map +1 -1
  63. package/dist/query-planner.d.ts.map +1 -1
  64. package/dist/query-planner.js +3 -1
  65. package/dist/relationship-check.d.ts.map +1 -1
  66. package/dist/relationship-check.js +2 -0
  67. package/dist/semantic-planner.d.ts.map +1 -1
  68. package/dist/semantic-planner.js +17 -4
  69. package/dist/semantic-query-schema.d.ts +18 -0
  70. package/dist/semantic-query-schema.d.ts.map +1 -1
  71. package/dist/semantic-query-schema.js +79 -55
  72. package/dist/tools.d.ts +6 -0
  73. package/dist/tools.d.ts.map +1 -1
  74. package/dist/types.d.ts +121 -10
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/utils/agent-catalog-projection.d.ts +2 -12
  77. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  78. package/dist/utils/agent-catalog-projection.js +39 -2
  79. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  80. package/dist/utils/build-dataset-query-builder.js +4 -8
  81. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  82. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  83. package/dist/utils/calculation-stage-sql.js +98 -0
  84. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  85. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  86. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  87. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  88. package/dist/utils/compile-dataset-query.js +11 -3
  89. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  90. package/dist/utils/dataset-definition-validation.js +94 -7
  91. package/dist/utils/dataset-events.d.ts +19 -0
  92. package/dist/utils/dataset-events.d.ts.map +1 -0
  93. package/dist/utils/dataset-events.js +46 -0
  94. package/dist/utils/dataset-having.d.ts.map +1 -1
  95. package/dist/utils/dataset-having.js +6 -1
  96. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  97. package/dist/utils/dataset-query-result.js +7 -1
  98. package/dist/utils/dataset-query-validation.d.ts +1 -1
  99. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  100. package/dist/utils/dataset-query-validation.js +25 -47
  101. package/dist/utils/dataset-source.d.ts +2 -2
  102. package/dist/utils/dataset-source.d.ts.map +1 -1
  103. package/dist/utils/dataset-source.js +8 -1
  104. package/dist/utils/dataset-validation.d.ts.map +1 -1
  105. package/dist/utils/dataset-validation.js +2 -1
  106. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  107. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  108. package/dist/utils/dimension-selection-overrides.js +22 -0
  109. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  110. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  111. package/dist/utils/event-breakdown-sql.js +17 -0
  112. package/dist/utils/event-condition-sql.d.ts +18 -0
  113. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  114. package/dist/utils/event-condition-sql.js +63 -0
  115. package/dist/utils/event-operation-shape.d.ts +8 -0
  116. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  117. package/dist/utils/event-operation-shape.js +66 -0
  118. package/dist/utils/event-operation-spec.d.ts +43 -0
  119. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  120. package/dist/utils/event-operation-spec.js +68 -0
  121. package/dist/utils/event-range-span.d.ts +4 -0
  122. package/dist/utils/event-range-span.d.ts.map +1 -0
  123. package/dist/utils/event-range-span.js +22 -0
  124. package/dist/utils/event-result-values.d.ts +8 -0
  125. package/dist/utils/event-result-values.d.ts.map +1 -0
  126. package/dist/utils/event-result-values.js +21 -0
  127. package/dist/utils/event-source-sql.d.ts +38 -0
  128. package/dist/utils/event-source-sql.d.ts.map +1 -0
  129. package/dist/utils/event-source-sql.js +71 -0
  130. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  131. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  132. package/dist/utils/filter-predicate-tree.js +80 -0
  133. package/dist/utils/filter-tree.d.ts +42 -0
  134. package/dist/utils/filter-tree.d.ts.map +1 -0
  135. package/dist/utils/filter-tree.js +164 -0
  136. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  137. package/dist/utils/filtered-aggregation-sql.js +22 -1
  138. package/dist/utils/funnel-rows.d.ts +10 -0
  139. package/dist/utils/funnel-rows.d.ts.map +1 -0
  140. package/dist/utils/funnel-rows.js +30 -0
  141. package/dist/utils/funnel-sql.d.ts +18 -0
  142. package/dist/utils/funnel-sql.d.ts.map +1 -0
  143. package/dist/utils/funnel-sql.js +104 -0
  144. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  145. package/dist/utils/metric-derived-query.js +4 -5
  146. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  147. package/dist/utils/metric-query-builder.js +4 -5
  148. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  149. package/dist/utils/metric-query-validation.js +18 -7
  150. package/dist/utils/other-bucket-sql.d.ts +23 -0
  151. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  152. package/dist/utils/other-bucket-sql.js +51 -0
  153. package/dist/utils/portable-aggregations.d.ts +10 -6
  154. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  155. package/dist/utils/portable-aggregations.js +13 -8
  156. package/dist/utils/portable-grains.d.ts +17 -8
  157. package/dist/utils/portable-grains.d.ts.map +1 -1
  158. package/dist/utils/portable-grains.js +26 -11
  159. package/dist/utils/portable-query-calculations.d.ts +14 -0
  160. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  161. package/dist/utils/portable-query-calculations.js +31 -0
  162. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  163. package/dist/utils/portable-semantic-query.js +27 -1
  164. package/dist/utils/protocol-contract-3.d.ts +30 -0
  165. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  166. package/dist/utils/protocol-contract-3.js +93 -0
  167. package/dist/utils/protocol-dataset-query.d.ts +19 -0
  168. package/dist/utils/protocol-dataset-query.d.ts.map +1 -0
  169. package/dist/utils/protocol-dataset-query.js +50 -0
  170. package/dist/utils/protocol-filter-nodes.d.ts +9 -0
  171. package/dist/utils/protocol-filter-nodes.d.ts.map +1 -0
  172. package/dist/utils/protocol-filter-nodes.js +68 -0
  173. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  174. package/dist/utils/protocol-metric-capabilities.js +2 -1
  175. package/dist/utils/protocol-metric-expressions.d.ts +9 -1
  176. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  177. package/dist/utils/protocol-metric-expressions.js +27 -2
  178. package/dist/utils/protocol-rehydrate-filters.d.ts +8 -1
  179. package/dist/utils/protocol-rehydrate-filters.d.ts.map +1 -1
  180. package/dist/utils/protocol-rehydrate-filters.js +20 -1
  181. package/dist/utils/protocol-rehydrate-time-keys.d.ts +6 -0
  182. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  183. package/dist/utils/protocol-rehydrate-time-keys.js +7 -0
  184. package/dist/utils/query-calculation-errors.d.ts +6 -0
  185. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  186. package/dist/utils/query-calculation-errors.js +9 -0
  187. package/dist/utils/query-calculation-formula.d.ts +19 -0
  188. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  189. package/dist/utils/query-calculation-formula.js +77 -0
  190. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  191. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  192. package/dist/utils/query-calculation-outputs.js +72 -0
  193. package/dist/utils/query-calculation-plan.d.ts +67 -0
  194. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  195. package/dist/utils/query-calculation-plan.js +416 -0
  196. package/dist/utils/query-calculation-types.d.ts +97 -0
  197. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  198. package/dist/utils/query-calculation-types.js +8 -0
  199. package/dist/utils/query-field-references.d.ts.map +1 -1
  200. package/dist/utils/query-field-references.js +3 -2
  201. package/dist/utils/query-filter-errors.d.ts +11 -0
  202. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  203. package/dist/utils/query-filter-errors.js +65 -0
  204. package/dist/utils/query-schema-calculations.d.ts +55 -0
  205. package/dist/utils/query-schema-calculations.d.ts.map +1 -0
  206. package/dist/utils/query-schema-calculations.js +150 -0
  207. package/dist/utils/query-schema-filters.d.ts +47 -0
  208. package/dist/utils/query-schema-filters.d.ts.map +1 -0
  209. package/dist/utils/query-schema-filters.js +132 -0
  210. package/dist/utils/query-timezone.d.ts +6 -3
  211. package/dist/utils/query-timezone.d.ts.map +1 -1
  212. package/dist/utils/query-timezone.js +5 -1
  213. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  214. package/dist/utils/relationship-builder-plan.js +2 -1
  215. package/dist/utils/relationship-fields.d.ts.map +1 -1
  216. package/dist/utils/relationship-fields.js +5 -0
  217. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  218. package/dist/utils/relationship-measure-sql.js +4 -1
  219. package/dist/utils/relationship-measures.d.ts.map +1 -1
  220. package/dist/utils/relationship-measures.js +2 -1
  221. package/dist/utils/relationship-validation.d.ts +3 -1
  222. package/dist/utils/relationship-validation.d.ts.map +1 -1
  223. package/dist/utils/relationship-validation.js +8 -4
  224. package/dist/utils/relative-date-filters.d.ts +21 -0
  225. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  226. package/dist/utils/relative-date-filters.js +86 -0
  227. package/dist/utils/relative-date-range.d.ts +20 -0
  228. package/dist/utils/relative-date-range.d.ts.map +1 -0
  229. package/dist/utils/relative-date-range.js +75 -0
  230. package/dist/utils/retention-rows.d.ts +9 -0
  231. package/dist/utils/retention-rows.d.ts.map +1 -0
  232. package/dist/utils/retention-rows.js +30 -0
  233. package/dist/utils/retention-sql.d.ts +16 -0
  234. package/dist/utils/retention-sql.d.ts.map +1 -0
  235. package/dist/utils/retention-sql.js +68 -0
  236. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  237. package/dist/utils/scoped-dataset-source.js +4 -0
  238. package/dist/utils/segments.d.ts +3 -2
  239. package/dist/utils/segments.d.ts.map +1 -1
  240. package/dist/utils/segments.js +5 -4
  241. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  242. package/dist/utils/semantic-query-syntax.js +8 -2
  243. package/dist/utils/sql-dataset-source.d.ts +36 -0
  244. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  245. package/dist/utils/sql-dataset-source.js +126 -0
  246. package/dist/utils/time-axis-bounds.d.ts +11 -4
  247. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  248. package/dist/utils/time-axis-bounds.js +14 -6
  249. package/dist/utils/time-measure-axis.d.ts +2 -2
  250. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  251. package/dist/utils/time-measure-axis.js +13 -3
  252. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  253. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  254. package/dist/utils/time-measure-dataset-sql.js +15 -5
  255. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  256. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  257. package/dist/utils/time-measure-source-sql.js +7 -8
  258. package/dist/utils/time-query-measures.d.ts +5 -0
  259. package/dist/utils/time-query-measures.d.ts.map +1 -1
  260. package/dist/utils/time-query-measures.js +7 -0
  261. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  262. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  263. package/dist/utils/unsupported-contract-reasons.js +5 -1
  264. package/package.json +3 -3
@@ -0,0 +1,21 @@
1
+ /** A ClickHouse count arrives as a number or, for 64-bit types, a quoted string. */
2
+ export function countValue(value) {
3
+ const count = typeof value === 'string' ? Number(value) : value;
4
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0) {
5
+ throw new Error('The executor returned a count that is not a non-negative integer.');
6
+ }
7
+ return count;
8
+ }
9
+ export function ratio(numerator, denominator) {
10
+ return denominator === 0 ? null : numerator / denominator;
11
+ }
12
+ /** A result cell: scalars pass through; anything else becomes its string form. */
13
+ export function scalar(value) {
14
+ if (value === null || value === undefined)
15
+ return null;
16
+ if (typeof value === 'string' || typeof value === 'boolean')
17
+ return value;
18
+ if (typeof value === 'number')
19
+ return Number.isFinite(value) ? value : null;
20
+ return String(value);
21
+ }
@@ -0,0 +1,38 @@
1
+ import type { AnyDatasetInstance, DatasetFilterNode, MetricFilter } from '../types.js';
2
+ import type { QueryTimePredicate } from './query-timezone.js';
3
+ import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
4
+ import { type RelationshipBuilderContext } from './relationship-builder-plan.js';
5
+ import type { StatementParameters } from './statement-parameters.js';
6
+ /** What an event scan projects, and the aliases later stages read. */
7
+ export interface EventSourceRequest {
8
+ readonly entity: string;
9
+ readonly breakdown: readonly string[];
10
+ /** Filter names that step, start or return conditions test. */
11
+ readonly conditionFields: readonly string[];
12
+ /** Every caller filter, including the time range; groups allowed (RFC 0029). */
13
+ readonly filters: readonly DatasetFilterNode[];
14
+ readonly timezone?: string;
15
+ }
16
+ export interface EventSourceSql {
17
+ /** `_hq_raw` and `_hq_events`. */
18
+ readonly ctes: readonly string[];
19
+ /** `_hq_b0`, `_hq_b1`, … in breakdown order. */
20
+ readonly breakdown: readonly string[];
21
+ /** Condition field name -> its projected alias. */
22
+ readonly conditionColumn: (field: string) => string;
23
+ /** One condition as predicates over its projected alias, as a caller filter on that field. */
24
+ readonly conditionPredicates: (condition: MetricFilter) => readonly QueryTimePredicate[];
25
+ readonly joinCtx: RelationshipBuilderContext | undefined;
26
+ }
27
+ /**
28
+ * The event rows an RFC 0027 operation reads: the dataset's source with every
29
+ * trusted restriction applied (tenancy, row policies, enforced constraints,
30
+ * `FINAL`), the caller's filters, and only the columns the operation needs.
31
+ *
32
+ * Authored expressions stay inside their own SELECT and come out as one
33
+ * positional tuple, so internal aliases can't capture a source column name.
34
+ * `_hq_events` has `_hq_time` (in the query zone), `_hq_entity`, the
35
+ * breakdown aliases and the condition aliases.
36
+ */
37
+ export declare function buildEventSourceSql(ds: AnyDatasetInstance, request: EventSourceRequest, options: DatasetQueryExecutionOptions, statement: StatementParameters): EventSourceSql;
38
+ //# sourceMappingURL=event-source-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-source-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-source-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,EAAmC,KAAK,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAGlH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAErE,sEAAsE;AACtE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,+DAA+D;IAC/D,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,gFAAgF;IAChF,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,cAAc;IAC7B,kCAAkC;IAClC,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,mDAAmD;IACnD,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;IACpD,8FAA8F;IAC9F,QAAQ,CAAC,mBAAmB,EAAE,CAAC,SAAS,EAAE,YAAY,KAAK,SAAS,kBAAkB,EAAE,CAAC;IACzF,QAAQ,CAAC,OAAO,EAAE,0BAA0B,GAAG,SAAS,CAAC;CAC1D;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,kBAAkB,EACtB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,4BAA4B,EACrC,SAAS,EAAE,mBAAmB,GAC7B,cAAc,CA2DhB"}
@@ -0,0 +1,71 @@
1
+ import { applyFilterTree } from './filter-predicate-tree.js';
2
+ import { resolveDimensionExpression, resolveFilterField } from '../query-planner.js';
3
+ import { buildRelationshipBuilderContext } from './relationship-builder-plan.js';
4
+ import { queryTimeFilter, queryTimeSql } from './query-timezone.js';
5
+ import { scopedDatasetSource } from './scoped-dataset-source.js';
6
+ /**
7
+ * The event rows an RFC 0027 operation reads: the dataset's source with every
8
+ * trusted restriction applied (tenancy, row policies, enforced constraints,
9
+ * `FINAL`), the caller's filters, and only the columns the operation needs.
10
+ *
11
+ * Authored expressions stay inside their own SELECT and come out as one
12
+ * positional tuple, so internal aliases can't capture a source column name.
13
+ * `_hq_events` has `_hq_time` (in the query zone), `_hq_entity`, the
14
+ * breakdown aliases and the condition aliases.
15
+ */
16
+ export function buildEventSourceSql(ds, request, options, statement) {
17
+ const { dialect } = statement;
18
+ if (!ds.timeKey)
19
+ throw new Error(`Dataset "${ds.name}" has no time key for events.`);
20
+ const joinCtx = buildRelationshipBuilderContext(ds, {
21
+ dimensions: [request.entity, ...request.breakdown],
22
+ filters: [...request.filters],
23
+ }, options.context, dialect);
24
+ let raw = scopedDatasetSource({
25
+ builderFactory: options.builderFactory, ds, context: options.context, joinCtx, dialect, timezone: request.timezone,
26
+ });
27
+ const parts = [
28
+ resolveDimensionExpression(ds, ds.timeKey, joinCtx),
29
+ resolveDimensionExpression(ds, request.entity, joinCtx),
30
+ ...request.breakdown.map(name => resolveDimensionExpression(ds, name, joinCtx)),
31
+ ...request.conditionFields.map(name => resolveFilterField(ds, name, joinCtx)),
32
+ ];
33
+ const identifiers = [
34
+ ...parts,
35
+ ...Object.keys(ds.dimensions),
36
+ ...Object.values(ds.dimensions).map(dimension => dimension.sql ?? dimension.column ?? ''),
37
+ ...Object.values(ds.filters).map(filter => filter.field ?? ''),
38
+ ds.tenantKey ?? '',
39
+ ];
40
+ let rowAlias = '_hq_row';
41
+ while (identifiers.some(text => text.includes(rowAlias)))
42
+ rowAlias += '_';
43
+ raw = raw.select([`${dialect.packRow(parts)} AS ${rowAlias}`]);
44
+ raw = applyFilterTree(raw, request.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), request.timezone)));
45
+ const breakdown = request.breakdown.map((_, index) => `_hq_b${index}`);
46
+ const conditionAliases = new Map(request.conditionFields.map((name, index) => [name, `_hq_f${index}`]));
47
+ const element = (position) => dialect.rowElement(rowAlias, position);
48
+ const columns = [
49
+ `${queryTimeSql(dialect, dialect.assumeNotNull(element(1)), request.timezone)} AS _hq_time`,
50
+ `${element(2)} AS _hq_entity`,
51
+ ...breakdown.map((alias, index) => `${element(3 + index)} AS ${alias}`),
52
+ ...request.conditionFields.map((name, index) => (`${element(3 + breakdown.length + index)} AS ${conditionAliases.get(name)}`)),
53
+ ];
54
+ const conditionColumn = (field) => {
55
+ const alias = conditionAliases.get(field);
56
+ if (!alias)
57
+ throw new Error(`Condition field "${field}" was not projected.`);
58
+ return alias;
59
+ };
60
+ return {
61
+ ctes: [
62
+ `_hq_raw AS (${statement.embedBuilder(raw)})`,
63
+ // An event with no time or no entity can't be placed in a sequence.
64
+ `_hq_events AS (SELECT ${columns.join(', ')} FROM _hq_raw WHERE ${dialect.isNotNull(element(1))} AND ${dialect.isNotNull(element(2))})`,
65
+ ],
66
+ breakdown,
67
+ conditionColumn,
68
+ conditionPredicates: condition => queryTimeFilter(dialect, ds, condition, conditionColumn(condition.field), request.timezone),
69
+ joinCtx,
70
+ };
71
+ }
@@ -0,0 +1,28 @@
1
+ import type { DatasetFilterNode, MetricFilterOperator } from '../types.js';
2
+ import type { QueryBuilderLike } from '../query-builder-protocol.js';
3
+ /**
4
+ * Operators a planned comparison may carry. `notLike` exists only here: it is
5
+ * how a negated `like` renders, never something a caller writes (RFC 0029).
6
+ */
7
+ export type PlannedFilterOperator = MetricFilterOperator | 'notLike';
8
+ /** A comparison after `not` has been pushed down to it. */
9
+ export interface PlannedFilter {
10
+ readonly field: string;
11
+ readonly operator: PlannedFilterOperator;
12
+ readonly value?: unknown;
13
+ }
14
+ /** One `where` call: the column side, its operator, and the value to bind. */
15
+ export interface PlannedWherePredicate {
16
+ readonly expression: string;
17
+ readonly operator: PlannedFilterOperator;
18
+ readonly value: unknown;
19
+ }
20
+ type Predicates = (filter: PlannedFilter) => readonly PlannedWherePredicate[];
21
+ /**
22
+ * Apply caller filters to `builder`. A flat list makes exactly the `where`
23
+ * calls it always has, so its SQL is unchanged; groups use the builder's
24
+ * group methods and fail loudly on a builder without them.
25
+ */
26
+ export declare function applyFilterTree(builder: QueryBuilderLike, nodes: readonly DatasetFilterNode[] | undefined, predicates: Predicates): QueryBuilderLike;
27
+ export {};
28
+ //# sourceMappingURL=filter-predicate-tree.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter-predicate-tree.d.ts","sourceRoot":"","sources":["../../src/utils/filter-predicate-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAgB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAGrE;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG,oBAAoB,GAAG,SAAS,CAAC;AAErE,2DAA2D;AAC3D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;IACzC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,8EAA8E;AAC9E,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AA2CD,KAAK,UAAU,GAAG,CAAC,MAAM,EAAE,aAAa,KAAK,SAAS,qBAAqB,EAAE,CAAC;AAyC9E;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,EAC/C,UAAU,EAAE,UAAU,GACrB,gBAAgB,CAKlB"}
@@ -0,0 +1,80 @@
1
+ import { isFilterGroup } from './filter-tree.js';
2
+ const NEGATED = {
3
+ eq: 'neq', neq: 'eq', gt: 'lte', gte: 'lt', lt: 'gte', lte: 'gt',
4
+ in: 'notIn', notIn: 'in', isNull: 'isNotNull', isNotNull: 'isNull', like: 'notLike',
5
+ };
6
+ function negateLeaf(filter) {
7
+ if (filter.operator === 'between') {
8
+ const [low, high] = filter.value;
9
+ return {
10
+ kind: 'or',
11
+ items: [
12
+ { kind: 'leaf', filter: { field: filter.field, operator: 'lt', value: low } },
13
+ { kind: 'leaf', filter: { field: filter.field, operator: 'gt', value: high } },
14
+ ],
15
+ };
16
+ }
17
+ const operator = NEGATED[filter.operator];
18
+ if (!operator)
19
+ throw new Error(`Filter operator "${filter.operator}" cannot be negated.`);
20
+ return { kind: 'leaf', filter: { ...filter, operator } };
21
+ }
22
+ /**
23
+ * Negation normal form: `not` pushed to the leaves by De Morgan. Each rewrite
24
+ * is exact under SQL three-valued logic, so the rows are those of the
25
+ * authored tree.
26
+ */
27
+ function normalize(node, negated) {
28
+ if (!isFilterGroup(node))
29
+ return negated ? negateLeaf(node) : { kind: 'leaf', filter: node };
30
+ if ('not' in node && node.not !== undefined)
31
+ return normalize(node.not, !negated);
32
+ const isAnd = 'and' in node && node.and !== undefined;
33
+ const items = (isAnd ? node.and : node.or)
34
+ .map(item => normalize(item, negated));
35
+ if (items.length === 1)
36
+ return items[0];
37
+ // De Morgan: a negated AND is an OR of the negated items, and vice versa.
38
+ return { kind: isAnd !== negated ? 'and' : 'or', items };
39
+ }
40
+ function requireGroups(builder) {
41
+ if (!builder.whereGroup || !builder.orWhere || !builder.orWhereGroup) {
42
+ throw new Error('Filter groups with "or" or "not" need a query builder with whereGroup, orWhere and orWhereGroup.');
43
+ }
44
+ return builder;
45
+ }
46
+ /** AND the node's predicates onto `builder`. */
47
+ function applyAnd(builder, node, predicates) {
48
+ if (node.kind === 'leaf') {
49
+ return predicates(node.filter).reduce((current, predicate) => current.where(predicate.expression, predicate.operator, predicate.value), builder);
50
+ }
51
+ if (node.kind === 'and')
52
+ return node.items.reduce((current, item) => applyAnd(current, item, predicates), builder);
53
+ return requireGroups(builder).whereGroup(group => applyOr(group, node.items, predicates));
54
+ }
55
+ /** OR the items together inside an open group. */
56
+ function applyOr(builder, items, predicates) {
57
+ return items.reduce((current, item, index) => {
58
+ const groups = requireGroups(current);
59
+ const leafPredicates = item.kind === 'leaf' ? predicates(item.filter) : undefined;
60
+ if (leafPredicates?.length === 1) {
61
+ const [predicate] = leafPredicates;
62
+ return index === 0
63
+ ? groups.where(predicate.expression, predicate.operator, predicate.value)
64
+ : groups.orWhere(predicate.expression, predicate.operator, predicate.value);
65
+ }
66
+ // A multi-predicate leaf, or a nested AND/OR, is one parenthesized alternative.
67
+ const nested = (inner) => (item.kind === 'or'
68
+ ? applyOr(inner, item.items, predicates)
69
+ : applyAnd(inner, item, predicates));
70
+ return index === 0 ? groups.whereGroup(nested) : groups.orWhereGroup(nested);
71
+ }, builder);
72
+ }
73
+ /**
74
+ * Apply caller filters to `builder`. A flat list makes exactly the `where`
75
+ * calls it always has, so its SQL is unchanged; groups use the builder's
76
+ * group methods and fail loudly on a builder without them.
77
+ */
78
+ export function applyFilterTree(builder, nodes, predicates) {
79
+ return (nodes ?? []).reduce((current, node) => applyAnd(current, normalize(node, false), predicates), builder);
80
+ }
@@ -0,0 +1,42 @@
1
+ import type { DatasetFilterGroup, DatasetFilterNode, MetricFilter, MetricFilterOperator } from '../types.js';
2
+ /**
3
+ * Nested caller filters (RFC 0029): a query's `filters` list is an implicit
4
+ * AND of comparisons and `{ and }` / `{ or }` / `{ not }` groups.
5
+ */
6
+ /** Deepest group nesting a query may use, so a hostile tree cannot exhaust the stack. */
7
+ export declare const MAX_FILTER_GROUP_DEPTH = 32;
8
+ /** True for a `{ and }`, `{ or }` or `{ not }` node, as opposed to a comparison. */
9
+ export declare function isFilterGroup(node: unknown): node is DatasetFilterGroup;
10
+ /** True when `nodes` holds any group, so the flat, builder-free paths cannot run it. */
11
+ export declare function hasFilterGroups(nodes: readonly DatasetFilterNode[] | undefined): boolean;
12
+ /** Every comparison in the tree, depth first, as authored. */
13
+ export declare function filterLeaves(nodes: readonly DatasetFilterNode[] | undefined): MetricFilter[];
14
+ /** Number of comparisons the query applies: what `maxFilters` bounds. */
15
+ export declare function filterLeafCount(nodes: readonly DatasetFilterNode[] | undefined): number;
16
+ /**
17
+ * The operator a comparison has once `not` is pushed down to it, as the
18
+ * operator allowlist sees it. `between` negates to a pair; `like` has no
19
+ * portable negation and is checked as itself.
20
+ */
21
+ export declare function negatedFilterOperators(operator: MetricFilterOperator): readonly MetricFilterOperator[];
22
+ export interface EffectiveFilterLeaf {
23
+ /** The comparison as authored. */
24
+ readonly filter: MetricFilter;
25
+ /** True under an odd number of `not`s. */
26
+ readonly negated: boolean;
27
+ /** Operators the allowlist must permit for this comparison (RFC 0029). */
28
+ readonly operators: readonly MetricFilterOperator[];
29
+ }
30
+ /** Every comparison with the operators it effectively applies. */
31
+ export declare function effectiveFilterLeaves(nodes: readonly DatasetFilterNode[] | undefined): EffectiveFilterLeaf[];
32
+ /** Structural problems with the groups themselves; leaves are validated separately. */
33
+ export declare function filterTreeErrors(nodes: unknown): string[];
34
+ /**
35
+ * The top-level conjuncts: top-level `and` groups and one-item `or` groups
36
+ * are spliced in, so `[{ and: [a, b] }, c]` reads as `[a, b, c]`. Only these
37
+ * can bound a time axis.
38
+ */
39
+ export declare function topLevelFilterNodes(nodes: readonly DatasetFilterNode[] | undefined): DatasetFilterNode[];
40
+ /** Comparisons nested under an `or` or `not`, which filter rows but bound nothing. */
41
+ export declare function nestedFilterLeaves(nodes: readonly DatasetFilterNode[] | undefined): MetricFilter[];
42
+ //# sourceMappingURL=filter-tree.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter-tree.d.ts","sourceRoot":"","sources":["../../src/utils/filter-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AAEH,yFAAyF;AACzF,eAAO,MAAM,sBAAsB,KAAK,CAAC;AAIzC,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,kBAAkB,CAIvE;AAED,wFAAwF;AACxF,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,OAAO,CAExF;AAOD,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,YAAY,EAAE,CAc5F;AAED,yEAAyE;AACzE,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,MAAM,CAEvF;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,oBAAoB,EAAE,CAiBtG;AAED,MAAM,WAAW,mBAAmB;IAClC,kCAAkC;IAClC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,0CAA0C;IAC1C,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,0EAA0E;IAC1E,QAAQ,CAAC,SAAS,EAAE,SAAS,oBAAoB,EAAE,CAAC;CACrD;AAED,kEAAkE;AAClE,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,mBAAmB,EAAE,CAoB5G;AAMD,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,CAqCzD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,iBAAiB,EAAE,CAcxG;AAED,sFAAsF;AACtF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,YAAY,EAAE,CAElG"}
@@ -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,EAAmC,MAAM,aAAa,CAAC;AAGxG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAExE,KAAK,YAAY,GAAG,kBAAkB,CAAC;AAyEvC,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,3 +1,4 @@
1
+ import { isFilterGroup } from './filter-tree.js';
1
2
  import { resolveFilterField } from '../query-planner.js';
2
3
  function renderMeasureFilterCondition(ds, filter, joinCtx, dialect) {
3
4
  const field = resolveFilterField(ds, filter.field, joinCtx);
@@ -35,14 +36,34 @@ function renderMeasureFilterCondition(ds, filter, joinCtx, dialect) {
35
36
  return `${field} IS NULL`;
36
37
  case 'isNotNull':
37
38
  return `${field} IS NOT NULL`;
39
+ case 'inDateRange':
40
+ // RFC 0029: a measure definition must not change meaning with the calendar.
41
+ throw new Error('"inDateRange" is a query filter; measure filters cannot use it.');
38
42
  }
39
43
  }
44
+ /** A comparison, or an `and` / `or` / `not` group of them, as one SQL condition. */
45
+ function renderMeasureFilterNode(ds, node, joinCtx, dialect) {
46
+ if (!isFilterGroup(node))
47
+ return renderMeasureFilterCondition(ds, node, joinCtx, dialect);
48
+ if ('not' in node && node.not !== undefined) {
49
+ return `NOT (${renderMeasureFilterNode(ds, node.not, joinCtx, dialect)})`;
50
+ }
51
+ const or = 'or' in node && node.or !== undefined;
52
+ const items = (or ? node.or : node.and) ?? [];
53
+ // A one-item group is its item, exactly as it publishes, so an authored and
54
+ // a rehydrated measure render the same SQL.
55
+ if (items.length === 1)
56
+ return renderMeasureFilterNode(ds, items[0], joinCtx, dialect);
57
+ return items
58
+ .map(item => `(${renderMeasureFilterNode(ds, item, joinCtx, dialect)})`)
59
+ .join(or ? ' OR ' : ' AND ');
60
+ }
40
61
  export function applyFilteredAggregationExpression(ds, spec, fieldOrExpr, joinCtx, dialect) {
41
62
  if (!spec.filters?.length) {
42
63
  return fieldOrExpr;
43
64
  }
44
65
  const combinedCondition = spec.filters
45
- .map(filter => renderMeasureFilterCondition(ds, filter, joinCtx, dialect))
66
+ .map(filter => renderMeasureFilterNode(ds, filter, joinCtx, dialect))
46
67
  .map(condition => `(${condition})`)
47
68
  .join(' AND ');
48
69
  switch (spec.aggregation) {
@@ -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"}