@hypequery/datasets 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/dist/agent-catalog.d.ts +3 -3
  2. package/dist/agent-catalog.d.ts.map +1 -1
  3. package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
  4. package/dist/cache/protocol-cache-keys.js +25 -1
  5. package/dist/cache/query-signature.d.ts.map +1 -1
  6. package/dist/cache/query-signature.js +16 -5
  7. package/dist/catalog.d.ts +5 -1
  8. package/dist/catalog.d.ts.map +1 -1
  9. package/dist/catalog.js +9 -0
  10. package/dist/client-contract/build-from-deployment.d.ts +2 -2
  11. package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
  12. package/dist/client-contract/build-from-deployment.js +7 -0
  13. package/dist/cloud-publication.d.ts +3 -3
  14. package/dist/cloud-publication.d.ts.map +1 -1
  15. package/dist/cloud-publishing.d.ts +2 -2
  16. package/dist/cloud-publishing.d.ts.map +1 -1
  17. package/dist/codegen/dataset-source.d.ts.map +1 -1
  18. package/dist/codegen/dataset-source.js +4 -1
  19. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  20. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  21. package/dist/contract-3-authoring.fixture.js +40 -0
  22. package/dist/contract.d.ts +5 -1
  23. package/dist/contract.d.ts.map +1 -1
  24. package/dist/contract.js +9 -0
  25. package/dist/dataset-compilation.d.ts +3 -0
  26. package/dist/dataset-compilation.d.ts.map +1 -1
  27. package/dist/dataset-query.d.ts +5 -0
  28. package/dist/dataset-query.d.ts.map +1 -1
  29. package/dist/dataset.d.ts.map +1 -1
  30. package/dist/dataset.js +12 -2
  31. package/dist/event-operations.d.ts +43 -0
  32. package/dist/event-operations.d.ts.map +1 -0
  33. package/dist/event-operations.js +137 -0
  34. package/dist/execution-capabilities.d.ts +2 -1
  35. package/dist/execution-capabilities.d.ts.map +1 -1
  36. package/dist/execution-capabilities.js +1 -1
  37. package/dist/execution-capabilities.json +6 -6
  38. package/dist/executor.d.ts +13 -0
  39. package/dist/executor.d.ts.map +1 -1
  40. package/dist/executor.js +42 -8
  41. package/dist/index.d.ts +6 -3
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +3 -1
  44. package/dist/portable-execution-errors.d.ts +11 -0
  45. package/dist/portable-execution-errors.d.ts.map +1 -1
  46. package/dist/portable-execution-errors.js +14 -0
  47. package/dist/portable-executor.d.ts +22 -5
  48. package/dist/portable-executor.d.ts.map +1 -1
  49. package/dist/portable-executor.js +64 -5
  50. package/dist/protocol-adapter.d.ts +12 -0
  51. package/dist/protocol-adapter.d.ts.map +1 -1
  52. package/dist/protocol-adapter.js +30 -8
  53. package/dist/protocol-deployment-adapter.d.ts +10 -3
  54. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  55. package/dist/protocol-deployment-adapter.js +60 -26
  56. package/dist/protocol-rehydrate.d.ts +3 -16
  57. package/dist/protocol-rehydrate.d.ts.map +1 -1
  58. package/dist/protocol-rehydrate.js +71 -11
  59. package/dist/query-builder-protocol.d.ts +10 -0
  60. package/dist/query-builder-protocol.d.ts.map +1 -1
  61. package/dist/query-planner.d.ts.map +1 -1
  62. package/dist/query-planner.js +3 -1
  63. package/dist/relationship-check.d.ts.map +1 -1
  64. package/dist/relationship-check.js +2 -0
  65. package/dist/semantic-planner.d.ts.map +1 -1
  66. package/dist/semantic-planner.js +16 -3
  67. package/dist/types.d.ts +109 -7
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/utils/agent-catalog-projection.d.ts +2 -2
  70. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  71. package/dist/utils/agent-catalog-projection.js +31 -2
  72. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  73. package/dist/utils/build-dataset-query-builder.js +4 -8
  74. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  75. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  76. package/dist/utils/calculation-stage-sql.js +98 -0
  77. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  78. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  79. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  80. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  81. package/dist/utils/compile-dataset-query.js +11 -3
  82. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  83. package/dist/utils/dataset-definition-validation.js +90 -6
  84. package/dist/utils/dataset-events.d.ts +19 -0
  85. package/dist/utils/dataset-events.d.ts.map +1 -0
  86. package/dist/utils/dataset-events.js +46 -0
  87. package/dist/utils/dataset-having.d.ts.map +1 -1
  88. package/dist/utils/dataset-having.js +6 -1
  89. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  90. package/dist/utils/dataset-query-result.js +7 -1
  91. package/dist/utils/dataset-query-validation.d.ts +1 -1
  92. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  93. package/dist/utils/dataset-query-validation.js +25 -47
  94. package/dist/utils/dataset-source.d.ts +2 -2
  95. package/dist/utils/dataset-source.d.ts.map +1 -1
  96. package/dist/utils/dataset-source.js +8 -1
  97. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  98. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  99. package/dist/utils/dimension-selection-overrides.js +22 -0
  100. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  101. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  102. package/dist/utils/event-breakdown-sql.js +17 -0
  103. package/dist/utils/event-condition-sql.d.ts +18 -0
  104. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  105. package/dist/utils/event-condition-sql.js +63 -0
  106. package/dist/utils/event-operation-shape.d.ts +8 -0
  107. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  108. package/dist/utils/event-operation-shape.js +66 -0
  109. package/dist/utils/event-operation-spec.d.ts +43 -0
  110. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  111. package/dist/utils/event-operation-spec.js +68 -0
  112. package/dist/utils/event-range-span.d.ts +4 -0
  113. package/dist/utils/event-range-span.d.ts.map +1 -0
  114. package/dist/utils/event-range-span.js +22 -0
  115. package/dist/utils/event-result-values.d.ts +8 -0
  116. package/dist/utils/event-result-values.d.ts.map +1 -0
  117. package/dist/utils/event-result-values.js +21 -0
  118. package/dist/utils/event-source-sql.d.ts +38 -0
  119. package/dist/utils/event-source-sql.d.ts.map +1 -0
  120. package/dist/utils/event-source-sql.js +71 -0
  121. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  122. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  123. package/dist/utils/filter-predicate-tree.js +80 -0
  124. package/dist/utils/filter-tree.d.ts +42 -0
  125. package/dist/utils/filter-tree.d.ts.map +1 -0
  126. package/dist/utils/filter-tree.js +164 -0
  127. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  128. package/dist/utils/filtered-aggregation-sql.js +3 -0
  129. package/dist/utils/funnel-rows.d.ts +10 -0
  130. package/dist/utils/funnel-rows.d.ts.map +1 -0
  131. package/dist/utils/funnel-rows.js +30 -0
  132. package/dist/utils/funnel-sql.d.ts +18 -0
  133. package/dist/utils/funnel-sql.d.ts.map +1 -0
  134. package/dist/utils/funnel-sql.js +104 -0
  135. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  136. package/dist/utils/metric-derived-query.js +4 -5
  137. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  138. package/dist/utils/metric-query-builder.js +4 -5
  139. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  140. package/dist/utils/metric-query-validation.js +18 -7
  141. package/dist/utils/other-bucket-sql.d.ts +23 -0
  142. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  143. package/dist/utils/other-bucket-sql.js +51 -0
  144. package/dist/utils/portable-aggregations.d.ts +10 -6
  145. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  146. package/dist/utils/portable-aggregations.js +13 -8
  147. package/dist/utils/portable-grains.d.ts +17 -8
  148. package/dist/utils/portable-grains.d.ts.map +1 -1
  149. package/dist/utils/portable-grains.js +26 -11
  150. package/dist/utils/portable-query-calculations.d.ts +14 -0
  151. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  152. package/dist/utils/portable-query-calculations.js +31 -0
  153. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  154. package/dist/utils/portable-semantic-query.js +27 -1
  155. package/dist/utils/protocol-contract-3.d.ts +30 -0
  156. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  157. package/dist/utils/protocol-contract-3.js +93 -0
  158. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  159. package/dist/utils/protocol-metric-capabilities.js +2 -1
  160. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  161. package/dist/utils/protocol-metric-expressions.js +6 -1
  162. package/dist/utils/protocol-rehydrate-filters.js +2 -1
  163. package/dist/utils/protocol-rehydrate-time-keys.d.ts +5 -0
  164. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  165. package/dist/utils/protocol-rehydrate-time-keys.js +5 -0
  166. package/dist/utils/query-calculation-errors.d.ts +6 -0
  167. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  168. package/dist/utils/query-calculation-errors.js +9 -0
  169. package/dist/utils/query-calculation-formula.d.ts +19 -0
  170. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  171. package/dist/utils/query-calculation-formula.js +77 -0
  172. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  173. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  174. package/dist/utils/query-calculation-outputs.js +72 -0
  175. package/dist/utils/query-calculation-plan.d.ts +67 -0
  176. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  177. package/dist/utils/query-calculation-plan.js +416 -0
  178. package/dist/utils/query-calculation-types.d.ts +97 -0
  179. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  180. package/dist/utils/query-calculation-types.js +8 -0
  181. package/dist/utils/query-field-references.d.ts.map +1 -1
  182. package/dist/utils/query-field-references.js +2 -1
  183. package/dist/utils/query-filter-errors.d.ts +11 -0
  184. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  185. package/dist/utils/query-filter-errors.js +65 -0
  186. package/dist/utils/query-timezone.d.ts +6 -3
  187. package/dist/utils/query-timezone.d.ts.map +1 -1
  188. package/dist/utils/query-timezone.js +5 -1
  189. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  190. package/dist/utils/relationship-builder-plan.js +2 -1
  191. package/dist/utils/relationship-fields.d.ts.map +1 -1
  192. package/dist/utils/relationship-fields.js +5 -0
  193. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  194. package/dist/utils/relationship-measure-sql.js +2 -0
  195. package/dist/utils/relationship-validation.d.ts +3 -1
  196. package/dist/utils/relationship-validation.d.ts.map +1 -1
  197. package/dist/utils/relationship-validation.js +8 -4
  198. package/dist/utils/relative-date-filters.d.ts +21 -0
  199. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  200. package/dist/utils/relative-date-filters.js +86 -0
  201. package/dist/utils/relative-date-range.d.ts +20 -0
  202. package/dist/utils/relative-date-range.d.ts.map +1 -0
  203. package/dist/utils/relative-date-range.js +75 -0
  204. package/dist/utils/retention-rows.d.ts +9 -0
  205. package/dist/utils/retention-rows.d.ts.map +1 -0
  206. package/dist/utils/retention-rows.js +30 -0
  207. package/dist/utils/retention-sql.d.ts +16 -0
  208. package/dist/utils/retention-sql.d.ts.map +1 -0
  209. package/dist/utils/retention-sql.js +68 -0
  210. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  211. package/dist/utils/scoped-dataset-source.js +4 -0
  212. package/dist/utils/segments.d.ts +3 -2
  213. package/dist/utils/segments.d.ts.map +1 -1
  214. package/dist/utils/segments.js +5 -4
  215. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  216. package/dist/utils/semantic-query-syntax.js +8 -2
  217. package/dist/utils/sql-dataset-source.d.ts +36 -0
  218. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  219. package/dist/utils/sql-dataset-source.js +126 -0
  220. package/dist/utils/time-axis-bounds.d.ts +11 -4
  221. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  222. package/dist/utils/time-axis-bounds.js +14 -6
  223. package/dist/utils/time-measure-axis.d.ts +2 -2
  224. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  225. package/dist/utils/time-measure-axis.js +13 -3
  226. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  227. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  228. package/dist/utils/time-measure-dataset-sql.js +15 -5
  229. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  230. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  231. package/dist/utils/time-measure-source-sql.js +7 -8
  232. package/dist/utils/time-query-measures.d.ts +5 -0
  233. package/dist/utils/time-query-measures.d.ts.map +1 -1
  234. package/dist/utils/time-query-measures.js +7 -0
  235. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  236. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  237. package/dist/utils/unsupported-contract-reasons.js +5 -1
  238. package/package.json +3 -3
@@ -9,10 +9,13 @@ import { measureDependencyNames } from './measure-dependencies.js';
9
9
  import { overfetchLimit } from './pagination.js';
10
10
  import { resolveResultLimit } from './result-limits.js';
11
11
  import { buildTimeMeasureDatasetSql } from './time-measure-dataset-sql.js';
12
- import { selectedTimeMeasures } from './time-query-measures.js';
12
+ import { usesTimeSeriesPlan } from './time-query-measures.js';
13
+ import { filterLeaves } from './filter-tree.js';
13
14
  import { renderStatement } from './statement-parameters.js';
14
15
  import { datasetOnTimeKey, selectedTimeKeyError } from './dataset-time-keys.js';
15
16
  import { statementRunner } from './statement-runner.js';
17
+ import { hasQueryCalculations } from './query-calculation-outputs.js';
18
+ import { prepareCalculatedDatasetQuery } from './compile-calculated-dataset-query.js';
16
19
  /** The one dispatch point for dataset preview and query-builder execution. */
17
20
  export function prepareDatasetQuery(source, input, options, mode = 'execution') {
18
21
  // Every planner below compiles against the selected time axis. An unknown
@@ -22,6 +25,9 @@ export function prepareDatasetQuery(source, input, options, mode = 'execution')
22
25
  ...input,
23
26
  limit: mode === 'logical' ? input.limit : resolveResultLimit(input.limit, dataset.limits).limit,
24
27
  });
28
+ // RFC 0026: calculations plan against a view of the dataset, under an outer stage.
29
+ if (hasQueryCalculations(query))
30
+ return prepareCalculatedDatasetQuery(dataset, query, options, mode);
25
31
  // Preserve omission while validating/planning: maxMeasures constrains an
26
32
  // explicit selection, not the dataset's default set of base measures.
27
33
  const measures = query.measures ?? baseMeasureNames(dataset.measures);
@@ -35,8 +41,10 @@ export function prepareDatasetQuery(source, input, options, mode = 'execution')
35
41
  // Raw-SQL plans lose builder settings, so they carry the FINAL pin in their SQL.
36
42
  // Called after planning, which validates the query and its enforced constraints.
37
43
  const readsFinal = () => queryReadsFinal(dataset, buildRelationshipBuilderContext(dataset, query, options.context, resolveDatasetSqlDialect(options.builderFactory)));
38
- if (selectedTimeMeasures(dataset, query).size) {
44
+ if (usesTimeSeriesPlan(dataset, query)) {
39
45
  plan = 'time';
46
+ // The planner validates the selection as written, then fills the default
47
+ // measures itself when they were omitted.
40
48
  const planned = buildTimeMeasureDatasetSql(dataset, query, executionOptions);
41
49
  const main = withFinalSafety(readsFinal(), renderStatement(planned.statement));
42
50
  const preflight = withFinalSafety(readsFinal(), renderStatement(planned.preflight));
@@ -62,7 +70,7 @@ export function prepareDatasetQuery(source, input, options, mode = 'execution')
62
70
  dimensions: Object.freeze([...(query.dimensions ?? [])]),
63
71
  measures: Object.freeze([...measures]),
64
72
  measureDependencies: Object.freeze(measureDependencyNames(queryMeasureDefinitions(dataset, measures), measures)),
65
- filters: Object.freeze((query.filters ?? []).map(({ field, operator }) => Object.freeze({ field, operator }))),
73
+ filters: Object.freeze(filterLeaves(query.filters).map(({ field, operator }) => Object.freeze({ field, operator }))),
66
74
  having: Object.freeze((query.having ?? []).map(({ measure, operator }) => Object.freeze({ measure, operator }))),
67
75
  segments: Object.freeze([...(query.segments ?? [])]),
68
76
  by: query.by, timeKey: query.timeKey, timezone: query.timezone,
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-definition-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-definition-validation.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,wBAAwB,EACxB,mBAAmB,EAGnB,sBAAsB,EAEvB,MAAM,aAAa,CAAC;AAWrB,KAAK,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AACzD,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;AAC5D,KAAK,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;AA2R/D;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,aAAa,CAAC,aAAa,EAAE,WAAW,EAAE,gBAAgB,CAAC,GAClE,IAAI,CAmFN"}
1
+ {"version":3,"file":"dataset-definition-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-definition-validation.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAEV,aAAa,EACb,wBAAwB,EACxB,mBAAmB,EAGnB,sBAAsB,EAEvB,MAAM,aAAa,CAAC;AAYrB,KAAK,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AACzD,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;AAC5D,KAAK,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;AAqW/D;;;;;GAKG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,aAAa,CAAC,aAAa,EAAE,WAAW,EAAE,gBAAgB,CAAC,GAClE,IAAI,CA+FN"}
@@ -1,5 +1,6 @@
1
1
  import { validateShiftMeasures } from './shift-measure-validation.js';
2
2
  import { escapeRegExp, isSafeSQLIdentifier, stripSqlLiterals } from '../sql-utils.js';
3
+ import { isDatasetSqlSource, resolveDatasetSqlSource } from './sql-dataset-source.js';
3
4
  import { clickhouseDatasetSqlDialect } from './clickhouse-dataset-sql-dialect.js';
4
5
  import { rawSqlErrorMessage } from './raw-sql-dialect-check.js';
5
6
  import { SEMANTIC_FILTER_OPERATORS, SEMANTIC_NULL_CHECK_OPERATORS, isSemanticFilterOperator } from '../constants.js';
@@ -198,6 +199,79 @@ function validateMergeMeasure(datasetName, name, definition) {
198
199
  fail(datasetName, `measure "${name}" cannot use sql: merge measures read a stored state column.`);
199
200
  }
200
201
  }
202
+ /**
203
+ * RFC 0028: a SQL source's declared columns are the only ones its dataset can
204
+ * address, so every column reference must name one, bare or qualified with
205
+ * the source's alias. References qualified with a relationship name belong to that relationship's target and aren't checked.
206
+ */
207
+ function validateSqlSourceReferences(datasetName, config, alias, columns) {
208
+ const dimensions = config.dimensions ?? {};
209
+ const relationships = config.relationships ?? {};
210
+ const declared = (reference) => {
211
+ const bare = reference.startsWith(`${alias}.`) ? reference.slice(alias.length + 1) : reference;
212
+ return Object.hasOwn(columns, bare) ? bare : undefined;
213
+ };
214
+ const viaRelationship = (reference) => {
215
+ const [head, ...rest] = reference.split(QUALIFIED_SEPARATOR);
216
+ return rest.length > 0 && head !== undefined && Object.hasOwn(relationships, head);
217
+ };
218
+ const requireColumn = (reference, context) => {
219
+ if (declared(reference) === undefined) {
220
+ fail(datasetName, `${context} "${reference}" is not a column of the SQL source. Declare it in source.columns ` +
221
+ `(declared: ${Object.keys(columns).join(', ')}).`);
222
+ }
223
+ };
224
+ const fieldOrColumn = (reference, context) => {
225
+ if (!Object.hasOwn(dimensions, reference) && !viaRelationship(reference))
226
+ requireColumn(reference, context);
227
+ };
228
+ for (const [name, definition] of Object.entries(dimensions)) {
229
+ if (definition.sql !== undefined) {
230
+ for (const dependency of definition.dependencies ?? [])
231
+ requireColumn(dependency, `dimension "${name}" dependency`);
232
+ continue;
233
+ }
234
+ const column = definition.column ?? name;
235
+ requireColumn(column, `dimension "${name}" column`);
236
+ const type = columns[declared(column)];
237
+ if (type !== definition.fieldType) {
238
+ fail(datasetName, `dimension "${name}" is ${definition.fieldType}, but source column "${column}" is declared ${type}.`);
239
+ }
240
+ }
241
+ if (config.tenantKey !== undefined)
242
+ requireColumn(config.tenantKey, 'tenantKey');
243
+ for (const timeKey of [config.timeKey, ...(config.timeKeys ?? [])]) {
244
+ if (timeKey !== undefined)
245
+ fieldOrColumn(timeKey, 'time key');
246
+ }
247
+ for (const [name, definition] of Object.entries(config.filters ?? {})) {
248
+ fieldOrColumn(definition.field, `filter "${name}" field`);
249
+ }
250
+ for (const [name, definition] of Object.entries(config.measures ?? {})) {
251
+ if (isDerivedMeasure(definition) || isWindowMeasure(definition) || isShiftMeasure(definition))
252
+ continue;
253
+ if (definition.sql !== undefined) {
254
+ for (const dependency of definition.dependencies ?? [])
255
+ requireColumn(dependency, `measure "${name}" dependency`);
256
+ }
257
+ else {
258
+ for (const field of [definition.field, definition.argField]) {
259
+ if (field !== undefined)
260
+ fieldOrColumn(field, `measure "${name}" field`);
261
+ }
262
+ }
263
+ for (const filter of definition.filters ?? []) {
264
+ if (Object.hasOwn(config.filters ?? {}, filter.field))
265
+ continue;
266
+ fieldOrColumn(filter.field, `measure "${name}" filter field`);
267
+ }
268
+ }
269
+ for (const [name, relationship] of Object.entries(relationships)) {
270
+ for (const key of relationship.keys ?? [{ from: relationship.from, to: relationship.to }]) {
271
+ requireColumn(key.from, `relationship "${name}" key`);
272
+ }
273
+ }
274
+ }
201
275
  function validateLimits(datasetName, limits) {
202
276
  if (!limits) {
203
277
  return;
@@ -225,13 +299,23 @@ export function validateDatasetDefinition(name, config) {
225
299
  fail(name, 'dataset names must contain only letters, numbers and underscores, and start with a letter ' +
226
300
  'or underscore, so they remain valid identifiers in generated artifacts.');
227
301
  }
228
- if (typeof config.source !== 'string' || config.source.trim().length === 0) {
229
- fail(name, 'a non-empty source table is required.');
302
+ if (isDatasetSqlSource(config.source)) {
303
+ const source = resolveDatasetSqlSource(name, config.source);
304
+ if (config.rowResolution !== undefined || config.final) {
305
+ fail(name, 'rowResolution and final apply to a table, not a SQL source. Write FROM <table> FINAL ' +
306
+ '(and any deletion filter) inside the SQL instead.');
307
+ }
308
+ validateSqlSourceReferences(name, config, source.alias, source.columns);
230
309
  }
231
- // `database.table` is the deepest qualification ClickHouse addresses.
232
- if (!isSafeQualifiedName(config.source, 2)) {
233
- fail(name, `source "${config.source}" is not a safe table identifier. Expected "table" or ` +
234
- '"database.table", each segment containing only letters, numbers and underscores.');
310
+ else {
311
+ if (typeof config.source !== 'string' || config.source.trim().length === 0) {
312
+ fail(name, 'a non-empty source table is required.');
313
+ }
314
+ // `database.table` is the deepest qualification ClickHouse addresses.
315
+ if (!isSafeQualifiedName(config.source, 2)) {
316
+ fail(name, `source "${config.source}" is not a safe table identifier. Expected "table" or ` +
317
+ '"database.table", each segment containing only letters, numbers and underscores.');
318
+ }
235
319
  }
236
320
  if (config.final !== undefined && typeof config.final !== 'boolean') {
237
321
  fail(name, 'final must be true or false.');
@@ -0,0 +1,19 @@
1
+ import type { DatasetEvents, DimensionDefinition } from '../types.js';
2
+ interface EventDatasetShape {
3
+ readonly timeKey?: string;
4
+ readonly dimensions: Readonly<Record<string, DimensionDefinition>>;
5
+ readonly events?: DatasetEvents;
6
+ }
7
+ /**
8
+ * RFC 0027: `entity` names who acted and must be a groupable string or number
9
+ * dimension; `event` optionally names what happened and must be a filterable
10
+ * string dimension; the event timestamp is the dataset's timestamp `timeKey`.
11
+ * The deployment contract applies the same rules, so a dataset that defines
12
+ * also publishes.
13
+ */
14
+ export declare function datasetEventsErrors(config: EventDatasetShape): string[];
15
+ export declare function snapshotDatasetEvents(events: DatasetEvents | undefined): {
16
+ events?: DatasetEvents;
17
+ };
18
+ export {};
19
+ //# sourceMappingURL=dataset-events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataset-events.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEtE,UAAU,iBAAiB;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC,CAAC;IACnE,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,EAAE,CA6BvE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,GAAG;IAAE,MAAM,CAAC,EAAE,aAAa,CAAA;CAAE,CAGnG"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * RFC 0027: `entity` names who acted and must be a groupable string or number
3
+ * dimension; `event` optionally names what happened and must be a filterable
4
+ * string dimension; the event timestamp is the dataset's timestamp `timeKey`.
5
+ * The deployment contract applies the same rules, so a dataset that defines
6
+ * also publishes.
7
+ */
8
+ export function datasetEventsErrors(config) {
9
+ const { events } = config;
10
+ if (events === undefined)
11
+ return [];
12
+ if (typeof events !== 'object' || events === null || Array.isArray(events)) {
13
+ return ['events must be an object with an entity dimension.'];
14
+ }
15
+ const errors = [];
16
+ for (const key of Object.keys(events)) {
17
+ if (key !== 'entity' && key !== 'event')
18
+ errors.push(`events.${key} is not supported; use entity and event.`);
19
+ }
20
+ const entity = config.dimensions[events.entity];
21
+ if (typeof events.entity !== 'string' || !Object.hasOwn(config.dimensions, events.entity) || !entity) {
22
+ errors.push(`events.entity "${String(events.entity)}" must name a dimension.`);
23
+ }
24
+ else if (entity.groupable === false || (entity.fieldType !== 'string' && entity.fieldType !== 'number')) {
25
+ errors.push(`events.entity "${events.entity}" must be a groupable string or number dimension.`);
26
+ }
27
+ if (events.event !== undefined) {
28
+ const event = config.dimensions[events.event];
29
+ if (typeof events.event !== 'string' || !Object.hasOwn(config.dimensions, events.event) || !event) {
30
+ errors.push(`events.event "${String(events.event)}" must name a dimension.`);
31
+ }
32
+ else if (event.filterable === false || event.fieldType !== 'string') {
33
+ errors.push(`events.event "${events.event}" must be a filterable string dimension.`);
34
+ }
35
+ }
36
+ const timeKey = config.timeKey;
37
+ if (timeKey === undefined || config.dimensions[timeKey]?.fieldType !== 'timestamp') {
38
+ errors.push('events requires a timeKey naming a timestamp dimension: the event timestamp.');
39
+ }
40
+ return errors;
41
+ }
42
+ export function snapshotDatasetEvents(events) {
43
+ if (events === undefined)
44
+ return {};
45
+ return { events: Object.freeze({ entity: events.entity, ...(events.event === undefined ? {} : { event: events.event }) }) };
46
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-having.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-having.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE5F,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAkCrE;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAClC,MAAM,EAAE,CA0CV;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,SAAS,sBAAsB,EAAE,EAC7C,UAAU,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,EACvC,SAAS,EAAE,mBAAmB,GAC7B,MAAM,CAgBR"}
1
+ {"version":3,"file":"dataset-having.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-having.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE5F,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAkCrE;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAClC,MAAM,EAAE,CA6CV;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,SAAS,sBAAsB,EAAE,EAC7C,UAAU,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,EACvC,SAAS,EAAE,mBAAmB,GAC7B,MAAM,CAgBR"}
@@ -1,3 +1,4 @@
1
+ import { filterLeafCount } from './filter-tree.js';
1
2
  import { SEMANTIC_HAVING_OPERATORS } from '../constants.js';
2
3
  import { selectedTimeMeasures } from './time-query-measures.js';
3
4
  const HAVING_OPERATORS = new Set(SEMANTIC_HAVING_OPERATORS);
@@ -46,10 +47,14 @@ export function datasetHavingErrors(ds, query, selectedMeasures) {
46
47
  if (selectedTimeMeasures(ds, query).size > 0) {
47
48
  errors.push('Having is not supported on queries that select window or shift measures.');
48
49
  }
50
+ else if (query.fill === true) {
51
+ // It would delete the rows fill adds (RFC 0029).
52
+ errors.push('Having is not supported on filled queries.');
53
+ }
49
54
  // `maxFilters` bounds every predicate the query adds, before and after
50
55
  // aggregation alike. Filters alone over the limit are reported separately.
51
56
  const maxFilters = ds.limits?.maxFilters;
52
- const filterCount = Array.isArray(query.filters) ? query.filters.length : 0;
57
+ const filterCount = Array.isArray(query.filters) ? filterLeafCount(query.filters) : 0;
53
58
  const conditionCount = filterCount + query.having.length;
54
59
  if (maxFilters && conditionCount > maxFilters && filterCount <= maxFilters) {
55
60
  errors.push(`Too many filters and having conditions: ${conditionCount} (max ${maxFilters})`);
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-query-result.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-query-result.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAKrB,oFAAoF;AACpF,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,OAAO,EAAE;IACP,OAAO,EAAE,kBAAkB,CAAC;IAC5B,KAAK,EAAE,YAAY,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,gBAAgB,CAAC;CAC5B,GACA,kBAAkB,CAgBpB"}
1
+ {"version":3,"file":"dataset-query-result.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-query-result.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAKrB,oFAAoF;AACpF,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,OAAO,EAAE;IACP,OAAO,EAAE,kBAAkB,CAAC;IAC5B,KAAK,EAAE,YAAY,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,gBAAgB,CAAC;CAC5B,GACA,kBAAkB,CAqBpB"}
@@ -1,3 +1,4 @@
1
+ import { calculationColumns } from './query-calculation-outputs.js';
1
2
  import { baseMeasureNames } from './dataset-measures.js';
2
3
  import { applyPagination } from './pagination.js';
3
4
  import { serializeSemanticMeasureValues } from './semantic-result-serialization.js';
@@ -7,7 +8,11 @@ export function toDatasetQueryResult(rows, options) {
7
8
  const { dataset, query, sql, timingMs, context } = options;
8
9
  const selectedMeasures = query.measures ?? baseMeasureNames(dataset.measures);
9
10
  const { data, pagination } = applyPagination(rows, query.limit, query.offset);
10
- const serializedData = serializeSemanticMeasureValues(data, selectedMeasures);
11
+ // RFC 0026 outputs are measure values too, serialized the same way.
12
+ const calculations = calculationColumns(query);
13
+ const serializedData = serializeSemanticMeasureValues(data, [
14
+ ...selectedMeasures, ...calculations.map(column => column.name),
15
+ ]);
11
16
  return {
12
17
  data: serializedData,
13
18
  meta: {
@@ -16,6 +21,7 @@ export function toDatasetQueryResult(rows, options) {
16
21
  tenant: getRuntimeTenantId(context),
17
22
  rowCount: serializedData.length,
18
23
  pagination,
24
+ ...(calculations.length === 0 ? {} : { calculations }),
19
25
  },
20
26
  };
21
27
  }
@@ -1,4 +1,4 @@
1
1
  import type { AnyDatasetInstance, DatasetQuery, ExecutionContext } from '../types.js';
2
- import { type ValidationResult } from '../validation.js';
2
+ import type { ValidationResult } from '../validation.js';
3
3
  export declare function validateDatasetQueryInput(dataset: AnyDatasetInstance, query: DatasetQuery, context?: ExecutionContext): ValidationResult;
4
4
  //# sourceMappingURL=dataset-query-validation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-query-validation.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,gBAAgB,EACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAuB9E,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAsLlB"}
1
+ {"version":3,"file":"dataset-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-query-validation.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,gBAAgB,EACjB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAkBzD,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAuJlB"}
@@ -3,20 +3,25 @@ import { resolveRelationshipMeasure } from './relationship-measures.js';
3
3
  import { semanticQuerySyntaxErrors } from './semantic-query-syntax.js';
4
4
  import { queryTimezoneErrors } from './query-timezone.js';
5
5
  import { baseMeasureNames } from './dataset-measures.js';
6
- import { validateFilterValue } from '../validation.js';
7
6
  import { unsupportedTimeGrainError } from './dataset-time-grains.js';
8
- import { getRuntimeTenantPredicate, validateTenantRuntime, } from './tenant-runtime.js';
7
+ import { validateTenantRuntime } from './tenant-runtime.js';
9
8
  import { isQualifiedField, resolveQualifiedField, } from './relationship-fields.js';
10
- import { validateQualifiedFilter, validateRelationshipTenantRuntime, } from './relationship-validation.js';
9
+ import { validateRelationshipTenantRuntime } from './relationship-validation.js';
11
10
  import { segmentSelectionErrors } from './segments.js';
12
- import { filterAllowsOperator } from './filter-operator-policy.js';
13
- import { SEMANTIC_FILTER_OPERATORS } from '../constants.js';
14
11
  import { enforcedConstraintErrors } from './enforced-constraints.js';
15
12
  import { analyzeTimeMeasureAxis } from './time-measure-axis.js';
16
13
  import { datasetHavingErrors } from './dataset-having.js';
17
14
  import { datasetOnTimeKey, selectedTimeKeyError } from './dataset-time-keys.js';
18
- import { effectiveFilters } from './effective-filters.js';
15
+ import { queryFilterErrors } from './query-filter-errors.js';
16
+ import { hasQueryCalculations } from './query-calculation-outputs.js';
17
+ import { calculatedDatasetQueryErrors } from './compile-calculated-dataset-query.js';
18
+ import { filterLeafCount, filterTreeErrors } from './filter-tree.js';
19
19
  export function validateDatasetQueryInput(dataset, query, context) {
20
+ // RFC 0026: a calculated query validates as the view and inner query it plans to.
21
+ if (hasQueryCalculations(query)) {
22
+ const { errors } = calculatedDatasetQueryErrors(dataset, query, context);
23
+ return { valid: errors.length === 0, errors };
24
+ }
20
25
  // Validate against the selected time axis, so grain and window checks see it.
21
26
  const timeKeyError = selectedTimeKeyError(dataset, query.timeKey);
22
27
  const ds = timeKeyError ? dataset : datasetOnTimeKey(dataset, query.timeKey);
@@ -34,8 +39,6 @@ export function validateDatasetQueryInput(dataset, query, context) {
34
39
  errors.push(`Output "${name}" cannot be selected as both a dimension and a measure. Select one or give the definitions distinct names.`);
35
40
  }
36
41
  }
37
- const filters = effectiveFilters(ds);
38
- const filterNames = Object.keys(filters);
39
42
  const orderableFields = new Set([
40
43
  ...selectedDimensions,
41
44
  ...selectedMeasures,
@@ -49,7 +52,7 @@ export function validateDatasetQueryInput(dataset, query, context) {
49
52
  if (relationshipTenantError) {
50
53
  errors.push(relationshipTenantError);
51
54
  }
52
- errors.push(...enforcedConstraintErrors(ds, context, query.filters?.length ?? 0));
55
+ errors.push(...enforcedConstraintErrors(ds, context, filterLeafCount(query.filters)));
53
56
  if (selectedDimensions.length === 0 && selectedMeasures.length === 0) {
54
57
  errors.push(`Dataset "${ds.name}" query must select at least one dimension or measure.`);
55
58
  }
@@ -89,42 +92,9 @@ export function validateDatasetQueryInput(dataset, query, context) {
89
92
  }
90
93
  }
91
94
  }
92
- if (query.filters) {
93
- for (const filter of query.filters) {
94
- if (isQualifiedField(filter.field)) {
95
- const filterError = validateQualifiedFilter(ds, filter, context);
96
- if (filterError) {
97
- errors.push(filterError);
98
- }
99
- continue;
100
- }
101
- if (!filterNames.includes(filter.field)) {
102
- errors.push(`Unknown filter fields: ${filter.field}. Available: ${filterNames.join(', ')}`);
103
- continue;
104
- }
105
- const filterDefinition = filters[filter.field];
106
- if (!filterAllowsOperator(filterDefinition, filter.operator)) {
107
- errors.push(`Filter "${filter.field}" does not allow operator "${filter.operator}". Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
108
- continue;
109
- }
110
- const resolvedField = filterDefinition.field;
111
- const resolvedDimension = ds.dimensions[resolvedField];
112
- const resolvedColumn = resolvedDimension?.sql
113
- ? undefined
114
- : resolvedDimension?.column ?? resolvedField;
115
- if (getRuntimeTenantPredicate(context) && ds.tenantKey && resolvedColumn === ds.tenantKey) {
116
- errors.push(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
117
- continue;
118
- }
119
- const fieldType = resolvedDimension?.fieldType;
120
- if (!fieldType) {
121
- continue;
122
- }
123
- const filterError = validateFilterValue(filter, fieldType);
124
- if (filterError) {
125
- errors.push(filterError);
126
- }
127
- }
95
+ // A malformed tree is reported once, by the syntax check; its leaves are not read.
96
+ if (query.filters && filterTreeErrors(query.filters).length === 0) {
97
+ errors.push(...queryFilterErrors(ds, query.filters, context));
128
98
  }
129
99
  if (query.orderBy) {
130
100
  const invalid = [];
@@ -148,6 +118,12 @@ export function validateDatasetQueryInput(dataset, query, context) {
148
118
  errors.push(`Unknown orderBy fields: ${invalid.join(', ')}. Available: ${Array.from(orderableFields).join(', ')}`);
149
119
  }
150
120
  }
121
+ if (query.fill !== undefined && typeof query.fill !== 'boolean') {
122
+ errors.push('Invalid fill: expected true or false.');
123
+ }
124
+ else if (query.fill === true && !query.by) {
125
+ errors.push('"fill" needs a "by" grain: it fills the periods of the time series.');
126
+ }
151
127
  if (query.by && !ds.timeKey) {
152
128
  errors.push(`Cannot use "by" grain — dataset "${ds.name}" has no timeKey.`);
153
129
  }
@@ -170,8 +146,10 @@ export function validateDatasetQueryInput(dataset, query, context) {
170
146
  errors.push(`Too many measures: ${query.measures.length} (max ${ds.limits.maxMeasures})`);
171
147
  }
172
148
  errors.push(...datasetHavingErrors(ds, query, selectedMeasures));
173
- if (ds.limits?.maxFilters && query.filters && query.filters.length > ds.limits.maxFilters) {
174
- errors.push(`Too many filters: ${query.filters.length} (max ${ds.limits.maxFilters})`);
149
+ // RFC 0029: the budget counts comparisons; and/or/not groups cost nothing.
150
+ const filterCount = filterLeafCount(query.filters);
151
+ if (ds.limits?.maxFilters && filterCount > ds.limits.maxFilters) {
152
+ errors.push(`Too many filters: ${filterCount} (max ${ds.limits.maxFilters})`);
175
153
  }
176
154
  if (ds.limits?.maxResultSize && query.limit != null && query.limit > ds.limits.maxResultSize) {
177
155
  errors.push(`Too many results requested: ${query.limit} (max ${ds.limits.maxResultSize})`);
@@ -6,7 +6,7 @@ import type { RelationshipBuilderContext } from './relationship-builder-plan.js'
6
6
  * declares `rowResolution`. Every builder-path read of a dataset source goes
7
7
  * through here so no query can skip row-version resolution.
8
8
  */
9
- export declare function datasetSourceBuilder(builderFactory: Pick<QueryBuilderFactoryLike, 'table'>, ds: Pick<AnyDatasetInstance, 'name' | 'source' | 'rowResolution'>): QueryBuilderLike;
9
+ export declare function datasetSourceBuilder(builderFactory: Pick<QueryBuilderFactoryLike, 'table'>, ds: Pick<AnyDatasetInstance, 'name' | 'source' | 'rowResolution' | 'sqlSource'>): QueryBuilderLike;
10
10
  /**
11
11
  * A filter moved to PREWHERE runs before `FINAL` and can match an older version
12
12
  * of a row. The server default forbids that; pinning it also covers profiles
@@ -21,7 +21,7 @@ export declare const FINAL_SAFETY_SETTINGS: {
21
21
  * relationship target it actually joins. Unused relationships don't count, so
22
22
  * a plain query never carries the pin.
23
23
  */
24
- export declare function queryReadsFinal(ds: Pick<AnyDatasetInstance, 'rowResolution'>, joinCtx: Pick<RelationshipBuilderContext, 'joins'> | undefined): boolean;
24
+ export declare function queryReadsFinal(ds: Pick<AnyDatasetInstance, 'rowResolution' | 'sqlSource'>, joinCtx: Pick<RelationshipBuilderContext, 'joins'> | undefined): boolean;
25
25
  /**
26
26
  * The statement with `FINAL_SAFETY_SETTINGS` in its own SQL, for paths that run
27
27
  * rendered SQL (`rawQuery`), where builder settings don't travel.
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-source.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAC9F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAEjF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,IAAI,CAAC,uBAAuB,EAAE,OAAO,CAAC,EACtD,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,QAAQ,GAAG,eAAe,CAAC,GAChE,gBAAgB,CAgBlB;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB;;CAAqD,CAAC;AAExF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,EAC7C,OAAO,EAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAC,GAAG,SAAS,GAC7D,OAAO,CAET;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAI/F;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,GAC5C;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,GAAG,SAAS,CAM9C"}
1
+ {"version":3,"file":"dataset-source.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAC9F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAGjF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,IAAI,CAAC,uBAAuB,EAAE,OAAO,CAAC,EACtD,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,QAAQ,GAAG,eAAe,GAAG,WAAW,CAAC,GAC9E,gBAAgB,CAqBlB;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB;;CAAqD,CAAC;AAExF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,GAAG,WAAW,CAAC,EAC3D,OAAO,EAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAC,GAAG,SAAS,GAC7D,OAAO,CAGT;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAI/F;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,GAC5C;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,GAAG,SAAS,CAM9C"}
@@ -1,9 +1,15 @@
1
+ import { sqlSourceRelation } from './sql-dataset-source.js';
1
2
  /**
2
3
  * The dataset's source table as a builder, read with `FINAL` when the dataset
3
4
  * declares `rowResolution`. Every builder-path read of a dataset source goes
4
5
  * through here so no query can skip row-version resolution.
5
6
  */
6
7
  export function datasetSourceBuilder(builderFactory, ds) {
8
+ // RFC 0028: a SQL source is a derived table; FINAL, if any, is inside it.
9
+ if (ds.sqlSource) {
10
+ const derived = builderFactory.table(sqlSourceRelation(ds));
11
+ return ds.sqlSource.readsFinal && derived.settings ? derived.settings(FINAL_SAFETY_SETTINGS) : derived;
12
+ }
7
13
  const qb = builderFactory.table(ds.source);
8
14
  if (!ds.rowResolution) {
9
15
  return qb;
@@ -31,7 +37,8 @@ export const FINAL_SAFETY_SETTINGS = { optimize_move_to_prewhere_if_final: 0 };
31
37
  * a plain query never carries the pin.
32
38
  */
33
39
  export function queryReadsFinal(ds, joinCtx) {
34
- return Boolean(ds.rowResolution) || Boolean(joinCtx?.joins.some(join => join.final));
40
+ return Boolean(ds.rowResolution) || Boolean(ds.sqlSource?.readsFinal)
41
+ || Boolean(joinCtx?.joins.some(join => join.final));
35
42
  }
36
43
  /**
37
44
  * The statement with `FINAL_SAFETY_SETTINGS` in its own SQL, for paths that run
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Selection-only dimension rewrites for RFC 0026 `other`.
3
+ *
4
+ * `other` regroups one dimension as itself or a remainder label. Only the
5
+ * grouped output reads the rewritten expression: filters, segments, measure
6
+ * filters and measures over the same column keep reading source values,
7
+ * because they resolve the dimension through `resolveDimensionExpression`.
8
+ *
9
+ * The rewrite travels on the dataset view under a symbol key, which object
10
+ * spread copies, so views derived from it (a time-key rebase) keep it.
11
+ */
12
+ import type { AnyDatasetInstance } from '../types.js';
13
+ type SelectionRewrite = (expression: string) => string;
14
+ /** A view of `ds` whose `dimension`, when selected, reads `rewrite(expression)`. */
15
+ export declare function withDimensionSelectionRewrite<TDataset extends AnyDatasetInstance>(ds: TDataset, dimension: string, rewrite: SelectionRewrite): TDataset;
16
+ /** The expression a selected (grouped) dimension reads, given its source expression. */
17
+ export declare function rewriteSelectedDimension(ds: AnyDatasetInstance, dimension: string, expression: string): string;
18
+ export {};
19
+ //# sourceMappingURL=dimension-selection-overrides.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dimension-selection-overrides.d.ts","sourceRoot":"","sources":["../../src/utils/dimension-selection-overrides.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAItD,KAAK,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,CAAC;AAGvD,oFAAoF;AACpF,wBAAgB,6BAA6B,CAAC,QAAQ,SAAS,kBAAkB,EAC/E,EAAE,EAAE,QAAQ,EACZ,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,gBAAgB,GACxB,QAAQ,CAGV;AAED,wFAAwF;AACxF,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAG9G"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Selection-only dimension rewrites for RFC 0026 `other`.
3
+ *
4
+ * `other` regroups one dimension as itself or a remainder label. Only the
5
+ * grouped output reads the rewritten expression: filters, segments, measure
6
+ * filters and measures over the same column keep reading source values,
7
+ * because they resolve the dimension through `resolveDimensionExpression`.
8
+ *
9
+ * The rewrite travels on the dataset view under a symbol key, which object
10
+ * spread copies, so views derived from it (a time-key rebase) keep it.
11
+ */
12
+ const SELECTION_OVERRIDES = Symbol('hypequery.datasets.selectionOverrides');
13
+ /** A view of `ds` whose `dimension`, when selected, reads `rewrite(expression)`. */
14
+ export function withDimensionSelectionRewrite(ds, dimension, rewrite) {
15
+ const current = ds[SELECTION_OVERRIDES] ?? {};
16
+ return { ...ds, [SELECTION_OVERRIDES]: Object.freeze({ ...current, [dimension]: rewrite }) };
17
+ }
18
+ /** The expression a selected (grouped) dimension reads, given its source expression. */
19
+ export function rewriteSelectedDimension(ds, dimension, expression) {
20
+ const rewrite = ds[SELECTION_OVERRIDES]?.[dimension];
21
+ return rewrite === undefined ? expression : rewrite(expression);
22
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Keep the first `limit` breakdown groups of an aggregated relation (RFC
3
+ * 0027): ranked by `sizeColumn` summed over the group's rows (descending),
4
+ * then by the breakdown values (ascending, nulls last). Without a breakdown
5
+ * the relation is returned in `orderBy` order.
6
+ */
7
+ export declare function rankedBreakdownSql(options: {
8
+ readonly relation: string;
9
+ readonly breakdown: readonly string[];
10
+ readonly sizeColumn: string;
11
+ readonly limit: number;
12
+ /** Final ordering terms; `_hq_rank` is available to them. */
13
+ readonly orderBy: readonly string[];
14
+ }): string;
15
+ //# sourceMappingURL=event-breakdown-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-breakdown-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-breakdown-sql.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE;IAC1C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC,GAAG,MAAM,CAUT"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Keep the first `limit` breakdown groups of an aggregated relation (RFC
3
+ * 0027): ranked by `sizeColumn` summed over the group's rows (descending),
4
+ * then by the breakdown values (ascending, nulls last). Without a breakdown
5
+ * the relation is returned in `orderBy` order.
6
+ */
7
+ export function rankedBreakdownSql(options) {
8
+ const { relation, breakdown, sizeColumn, limit, orderBy } = options;
9
+ if (breakdown.length === 0) {
10
+ return `SELECT * FROM ${relation}${orderBy.length ? ` ORDER BY ${orderBy.join(', ')}` : ''}`;
11
+ }
12
+ const partition = breakdown.join(', ');
13
+ const valueOrder = breakdown.map(alias => `${alias} ASC NULLS LAST`).join(', ');
14
+ const sized = `SELECT *, sum(${sizeColumn}) OVER (PARTITION BY ${partition}) AS _hq_group_size FROM ${relation}`;
15
+ const ranked = `SELECT *, dense_rank() OVER (ORDER BY _hq_group_size DESC, ${valueOrder}) AS _hq_rank FROM (${sized})`;
16
+ return `SELECT * FROM (${ranked}) WHERE _hq_rank <= ${limit} ORDER BY ${orderBy.join(', ')}`;
17
+ }
@@ -0,0 +1,18 @@
1
+ import type { DatasetFilterNode, MetricFilter } from '../types.js';
2
+ import type { QueryTimePredicate } from './query-timezone.js';
3
+ import type { StatementParameters } from './statement-parameters.js';
4
+ /**
5
+ * One RFC 0027 condition as a SQL boolean over an already-projected column.
6
+ * Every caller value is bound as a parameter, never inlined.
7
+ */
8
+ export declare function eventConditionSql(column: string, filter: MetricFilter, statement: StatementParameters): string;
9
+ /**
10
+ * AND-combined conditions as a non-null 0/1 flag: a NULL comparison is a
11
+ * non-match, so array and aggregate functions never see a Nullable flag.
12
+ *
13
+ * `predicatesFor` turns one condition into the predicates that test it, the
14
+ * way a caller filter on the same field is applied: a timestamp instant is
15
+ * compared in UTC, and a mixed range splits into one predicate per kind.
16
+ */
17
+ export declare function eventConditionFlagSql(conditions: readonly DatasetFilterNode[], predicatesFor: (condition: MetricFilter) => readonly QueryTimePredicate[], statement: StatementParameters): string;
18
+ //# sourceMappingURL=event-condition-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-condition-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-condition-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAErE;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,mBAAmB,GAAG,MAAM,CA8B9G;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,SAAS,iBAAiB,EAAE,EACxC,aAAa,EAAE,CAAC,SAAS,EAAE,YAAY,KAAK,SAAS,kBAAkB,EAAE,EACzE,SAAS,EAAE,mBAAmB,GAC7B,MAAM,CAgBR"}