@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,98 @@
1
+ /**
2
+ * The RFC 0026 outer stage over a planned statement.
3
+ *
4
+ * 1. Window layer: `rank` and `share` over the grouped rows, before anything
5
+ * filters them, so a rank or share is of every group the filters select.
6
+ * A non-additive share joins its denominator, re-aggregated from source
7
+ * rows at the coarser grain (NULL keys match).
8
+ * 2. Output layer: names every calculation output as the caller wrote it,
9
+ * then `having`, ordering, `limitBy` and pagination.
10
+ * 3. `other`'s top-N list, as a CTE every inner statement can read.
11
+ */
12
+ import { datasetHavingSql } from './dataset-having.js';
13
+ import { semanticOrderDirection } from './semantic-query-syntax.js';
14
+ /** The CTE `other` reads its top-N values from. */
15
+ export const OTHER_TOP_CTE = '_hq_other_top';
16
+ const INNER = '_hq_calc';
17
+ const WINDOWED = '_hq_calc_windowed';
18
+ const TOTAL = '_hq_total';
19
+ function windowLayer(plan, inner, dialect, statements) {
20
+ if (plan.ranks.length === 0 && plan.shares.length === 0)
21
+ return inner.text;
22
+ const quote = dialect.quoteIdentifier;
23
+ const column = (name) => `${quote(INNER)}.${quote(name)}`;
24
+ const partition = (names) => (names.length === 0 ? '' : `PARTITION BY ${names.map(column).join(', ')} `);
25
+ const nullIfZero = (sql) => dialect.formulaFunction('nullIfZero', [sql]);
26
+ // Through the dialect, so an engine that truncates integer division can fix it in one place.
27
+ const divide = (left, right) => dialect.formulaBinary('divide', left, right);
28
+ const projections = [`${quote(INNER)}.*`];
29
+ const joins = [];
30
+ for (const rank of plan.ranks) {
31
+ const order = `${column(rank.column)} ${rank.direction === 'asc' ? 'ASC' : 'DESC'} NULLS LAST`;
32
+ projections.push(`rank() OVER (${partition(rank.within)}ORDER BY ${order}) AS ${quote(rank.internal)}`);
33
+ }
34
+ for (const share of plan.shares) {
35
+ const denominator = statements.denominators.get(share.internal);
36
+ if (denominator === undefined) {
37
+ projections.push(`${divide(column(share.column), nullIfZero(`sum(${column(share.column)}) OVER (${partition(share.of).trimEnd()})`))} AS ${quote(share.internal)}`);
38
+ continue;
39
+ }
40
+ const alias = quote(`_hq_share_${share.internal}`);
41
+ const marker = inner.parameters.embed(denominator);
42
+ const keys = share.of.map(name => quote(name));
43
+ const select = `SELECT ${[...keys, `${quote(share.column)} AS ${quote(TOTAL)}`].join(', ')} FROM (${marker}) AS ${quote('_hq_share_source')}`;
44
+ joins.push(share.of.length === 0
45
+ ? ` CROSS JOIN (${select}) AS ${alias}`
46
+ : ` LEFT JOIN (${select}) AS ${alias} ON ${share.of.map(name => (`isNotDistinctFrom(${column(name)}, ${alias}.${quote(name)})`)).join(' AND ')}`);
47
+ projections.push(`${divide(column(share.column), nullIfZero(`${alias}.${quote(TOTAL)}`))} AS ${quote(share.internal)}`);
48
+ }
49
+ return `SELECT ${projections.join(', ')} FROM (${inner.text}) AS ${quote(INNER)}${joins.join('')}`;
50
+ }
51
+ export function buildCalculationStageSql(query, plan, inner, dialect, executionLimit, statements = { denominators: new Map() }) {
52
+ const quote = dialect.quoteIdentifier;
53
+ const internal = new Map(plan.outputs.map(output => [output.name, output.internal]));
54
+ const column = (name) => quote(internal.get(name) ?? name);
55
+ const projections = [
56
+ ...(query.by ? [quote('period')] : []),
57
+ ...(query.dimensions ?? []).map(dimension => quote(dimension)),
58
+ ...plan.selectedMeasures.map(measure => quote(measure)),
59
+ ...plan.outputs.map(output => `${quote(output.internal)} AS ${quote(output.name)}`),
60
+ ];
61
+ const source = windowLayer(plan, inner, dialect, statements);
62
+ const from = source === inner.text ? INNER : WINDOWED;
63
+ let text = `SELECT ${projections.join(', ')} FROM (${source}) AS ${quote(from)}`;
64
+ // Conditions read the inner columns rather than output aliases, so they
65
+ // stay valid on dialects that do not resolve aliases in WHERE.
66
+ if (plan.having.length > 0) {
67
+ text += ` WHERE ${datasetHavingSql([...plan.having], column, inner.parameters)}`;
68
+ }
69
+ const order = plan.orderBy.length > 0
70
+ ? plan.orderBy
71
+ : query.by ? [{ field: 'period', direction: 'asc' }] : [];
72
+ if (order.length > 0) {
73
+ text += ` ORDER BY ${order.map(item => dialect.orderTerm(column(item.field), semanticOrderDirection(item.direction))).join(', ')}`;
74
+ }
75
+ if (plan.limitBy !== undefined) {
76
+ text += ` LIMIT ${plan.limitBy.n} BY ${plan.limitBy.by.map(name => quote(name)).join(', ')}`;
77
+ }
78
+ text += dialect.paginate(executionLimit ?? plan.limit, plan.offset);
79
+ return withOtherTop({ text, parameters: inner.parameters }, statements.otherTop, dialect);
80
+ }
81
+ /**
82
+ * Gives a statement `other`'s top-N list as a CTE every nested statement can
83
+ * read. Each statement of the family that reads the rewritten dimension needs
84
+ * it: the outer stage and the time planner's axis preflight alike.
85
+ */
86
+ export function withOtherTop(statement, otherTop, dialect) {
87
+ if (otherTop === undefined)
88
+ return statement;
89
+ const quote = dialect.quoteIdentifier;
90
+ // A statement with its own WITH list is read as a subquery under ours.
91
+ const body = /^WITH\s/.test(statement.text)
92
+ ? `SELECT * FROM (${statement.text}) AS ${quote('_hq_with_other')}`
93
+ : statement.text;
94
+ return {
95
+ text: `WITH ${quote(OTHER_TOP_CTE)} AS (${statement.parameters.embed(otherTop)}) ${body}`,
96
+ parameters: statement.parameters,
97
+ };
98
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Compilation of a dataset query that carries RFC 0026 calculations.
3
+ *
4
+ * The query is planned against a view of the dataset that holds each
5
+ * calculation as a measure; the inner statement comes from the same derived
6
+ * or time-measure planner a model-level query would use, and the outer stage
7
+ * names, filters, orders and pages its rows.
8
+ */
9
+ import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
10
+ import type { AnyDatasetInstance, DatasetQuery, ExecutionContext } from '../types.js';
11
+ import { type QueryCalculationPlan } from './query-calculation-plan.js';
12
+ import type { PreparedDatasetQuery, DatasetQueryMode } from './compile-dataset-query.js';
13
+ /**
14
+ * Every reason a calculated query cannot run, with the caller's names. The
15
+ * inner query is validated with the outer limit and offset, so the
16
+ * time-measure series bound sees the page the caller asked for and an invalid
17
+ * page is refused before any SQL is built.
18
+ */
19
+ export declare function calculatedDatasetQueryErrors(ds: AnyDatasetInstance, query: DatasetQuery, context?: ExecutionContext): {
20
+ errors: string[];
21
+ plan?: QueryCalculationPlan;
22
+ };
23
+ export declare function prepareCalculatedDatasetQuery(dataset: AnyDatasetInstance, query: DatasetQuery, options: DatasetQueryExecutionOptions, mode: DatasetQueryMode): PreparedDatasetQuery;
24
+ //# sourceMappingURL=compile-calculated-dataset-query.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-calculated-dataset-query.d.ts","sourceRoot":"","sources":["../../src/utils/compile-calculated-dataset-query.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AActF,OAAO,EAAkD,KAAK,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAExH,OAAO,KAAK,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAGzF;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACzB;IAAE,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,CAAC,EAAE,oBAAoB,CAAA;CAAE,CAmBnD;AAQD,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,4BAA4B,EACrC,IAAI,EAAE,gBAAgB,GACrB,oBAAoB,CA4EtB"}
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Compilation of a dataset query that carries RFC 0026 calculations.
3
+ *
4
+ * The query is planned against a view of the dataset that holds each
5
+ * calculation as a measure; the inner statement comes from the same derived
6
+ * or time-measure planner a model-level query would use, and the outer stage
7
+ * names, filters, orders and pages its rows.
8
+ */
9
+ import { queryReadsFinal, withFinalSafety } from './dataset-source.js';
10
+ import { buildRelationshipBuilderContext } from './relationship-builder-plan.js';
11
+ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
12
+ import { buildDatasetQueryBuilder } from './build-dataset-query-builder.js';
13
+ import { buildDerivedDatasetSql } from './dataset-derived-query.js';
14
+ import { measureDependencyNames } from './measure-dependencies.js';
15
+ import { queryMeasureDefinitions } from './relationship-measures.js';
16
+ import { overfetchLimit } from './pagination.js';
17
+ import { buildTimeMeasureDatasetSql } from './time-measure-dataset-sql.js';
18
+ import { usesTimeSeriesPlan } from './time-query-measures.js';
19
+ import { filterLeaves } from './filter-tree.js';
20
+ import { renderStatement } from './statement-parameters.js';
21
+ import { statementRunner } from './statement-runner.js';
22
+ import { validateDatasetQueryInput } from './dataset-query-validation.js';
23
+ import { semanticQuerySyntaxErrors } from './semantic-query-syntax.js';
24
+ import { datasetOnTimeKey, selectedTimeKeyError } from './dataset-time-keys.js';
25
+ import { buildCalculationStageSql, withOtherTop } from './calculation-stage-sql.js';
26
+ import { planQueryCalculations, publicCalculationErrors } from './query-calculation-plan.js';
27
+ import { assertStageSupported, otherRankingSql, withOtherBucket } from './other-bucket-sql.js';
28
+ /**
29
+ * Every reason a calculated query cannot run, with the caller's names. The
30
+ * inner query is validated with the outer limit and offset, so the
31
+ * time-measure series bound sees the page the caller asked for and an invalid
32
+ * page is refused before any SQL is built.
33
+ */
34
+ export function calculatedDatasetQueryErrors(ds, query, context) {
35
+ // The syntax every dataset query gets, before the planner rewrites `orderBy`
36
+ // and drops it from the inner query.
37
+ const syntax = semanticQuerySyntaxErrors(query);
38
+ if (syntax.length > 0)
39
+ return { errors: syntax };
40
+ // Plan on the selected time axis, as every inner planner will.
41
+ const axis = selectedTimeKeyError(ds, query.timeKey) ? ds : datasetOnTimeKey(ds, query.timeKey);
42
+ const result = planQueryCalculations(axis, query, context);
43
+ if (result.plan === undefined)
44
+ return { errors: [...result.errors] };
45
+ const { plan } = result;
46
+ const validation = validateDatasetQueryInput(plan.dataset, {
47
+ ...plan.inner,
48
+ ...(query.limit === undefined ? {} : { limit: query.limit }),
49
+ ...(query.offset === undefined ? {} : { offset: query.offset }),
50
+ }, context);
51
+ return {
52
+ errors: publicCalculationErrors(validation.errors, plan.outputs),
53
+ plan,
54
+ };
55
+ }
56
+ function planOrThrow(ds, query, context) {
57
+ const { errors, plan } = calculatedDatasetQueryErrors(ds, query, context);
58
+ if (errors.length > 0 || plan === undefined)
59
+ throw new Error(`Invalid dataset query: ${errors.join('; ')}`);
60
+ return plan;
61
+ }
62
+ export function prepareCalculatedDatasetQuery(dataset, query, options, mode) {
63
+ const plan = planOrThrow(dataset, query, options.context);
64
+ const dialect = resolveDatasetSqlDialect(options.builderFactory);
65
+ assertStageSupported(plan, dialect);
66
+ const view = plan.other === undefined ? plan.dataset : withOtherBucket(plan.dataset, plan.other, dialect);
67
+ const executionLimit = mode === 'execution' ? overfetchLimit(query.limit) : query.limit;
68
+ // The inner statement is unpaged (the outer stage pages it), but the time
69
+ // planner keeps the caller's limit as its exact series budget.
70
+ const innerOptions = {
71
+ ...options, executionLimit: undefined, seriesLimit: query.limit,
72
+ };
73
+ const readsFinal = queryReadsFinal(view, buildRelationshipBuilderContext(view, plan.inner, options.context, dialect));
74
+ let planned;
75
+ let preflight;
76
+ let innerPlan;
77
+ // A time measure or a filled series (RFC 0029) runs on the time-series planner.
78
+ if (usesTimeSeriesPlan(view, plan.inner)) {
79
+ innerPlan = 'time';
80
+ const time = buildTimeMeasureDatasetSql(view, plan.inner, innerOptions);
81
+ planned = time.statement;
82
+ preflight = time.preflight;
83
+ }
84
+ else {
85
+ innerPlan = 'derived';
86
+ planned = buildDerivedDatasetSql(view, plan.inner, innerOptions, buildDatasetQueryBuilder);
87
+ }
88
+ // Each statement the stage embeds is planned and rendered on its own, with
89
+ // the same tenancy, filters and segments as the inner one.
90
+ const denominators = new Map(plan.shares.flatMap(share => (share.denominator === undefined ? [] : [[
91
+ share.internal,
92
+ renderStatement(buildDerivedDatasetSql(view, share.denominator, innerOptions, buildDatasetQueryBuilder)),
93
+ ]])));
94
+ const otherTop = plan.other === undefined
95
+ ? undefined
96
+ : renderStatement(otherRankingSql(plan.dataset, plan.other, innerOptions, dialect));
97
+ const outer = buildCalculationStageSql(query, plan, planned, dialect, executionLimit, {
98
+ denominators, ...(otherTop === undefined ? {} : { otherTop }),
99
+ });
100
+ const statement = withFinalSafety(readsFinal, renderStatement(outer));
101
+ const preflightStatements = preflight === undefined
102
+ ? []
103
+ : [withFinalSafety(readsFinal, renderStatement(withOtherTop(preflight, otherTop, dialect)))];
104
+ const description = Object.freeze({
105
+ kind: 'dataset-compilation', version: 1, dataset: dataset.name, plan: innerPlan,
106
+ dimensions: Object.freeze([...(query.dimensions ?? [])]),
107
+ measures: Object.freeze([...plan.selectedMeasures]),
108
+ measureDependencies: Object.freeze(measureDependencyNames(queryMeasureDefinitions(dataset, [...plan.selectedMeasures]), [...plan.selectedMeasures])),
109
+ filters: Object.freeze(filterLeaves(query.filters).map(({ field, operator }) => Object.freeze({ field, operator }))),
110
+ having: Object.freeze((query.having ?? []).map(({ measure, operator }) => Object.freeze({ measure, operator }))),
111
+ segments: Object.freeze([...(query.segments ?? [])]),
112
+ by: query.by, timeKey: query.timeKey, timezone: query.timezone,
113
+ effectiveLimit: query.limit, executionLimit, offset: query.offset ?? 0,
114
+ parameterCount: statement.parameters.length,
115
+ preflightStatementCount: preflightStatements.length,
116
+ calculations: Object.freeze(plan.outputs.map(output => output.name)),
117
+ });
118
+ const compilation = Object.freeze({
119
+ sql: statement.sql,
120
+ parameters: Object.freeze(structuredClone(statement.parameters)),
121
+ query: Object.freeze(structuredClone({ ...query, measures: [...plan.selectedMeasures] })),
122
+ preflightStatements: Object.freeze(preflightStatements.map(entry => Object.freeze({
123
+ sql: entry.sql, parameters: Object.freeze(structuredClone(entry.parameters)),
124
+ }))),
125
+ describe: () => description,
126
+ toJSON: () => description,
127
+ });
128
+ const runner = statementRunner(options.builderFactory, { kind: 'raw', statement }, {
129
+ abortSignal: options.context?.abortSignal,
130
+ preflight: preflightStatements,
131
+ });
132
+ return { compilation, ...runner };
133
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"compile-dataset-query.d.ts","sourceRoot":"","sources":["../../src/utils/compile-dataset-query.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAA2D,MAAM,2BAA2B,CAAC;AAC7H,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAUpE,OAAO,EAAmB,KAAK,eAAe,EAAwB,MAAM,uBAAuB,CAAC;AAEpG,MAAM,WAAW,oBAAqB,SAAQ,eAAe;IAC3D,QAAQ,CAAC,WAAW,EAAE,kBAAkB,CAAC;CAC1C;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,QAAQ,GAAG,SAAS,CAAC;AAElE,8EAA8E;AAC9E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,kBAAkB,EAC1B,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,4BAA4B,EACrC,IAAI,GAAE,gBAA8B,GACnC,oBAAoB,CA0EtB"}
1
+ {"version":3,"file":"compile-dataset-query.d.ts","sourceRoot":"","sources":["../../src/utils/compile-dataset-query.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAA2D,MAAM,2BAA2B,CAAC;AAC7H,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAWpE,OAAO,EAAmB,KAAK,eAAe,EAAwB,MAAM,uBAAuB,CAAC;AAIpG,MAAM,WAAW,oBAAqB,SAAQ,eAAe;IAC3D,QAAQ,CAAC,WAAW,EAAE,kBAAkB,CAAC;CAC1C;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,QAAQ,GAAG,SAAS,CAAC;AAElE,8EAA8E;AAC9E,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,kBAAkB,EAC1B,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,4BAA4B,EACrC,IAAI,GAAE,gBAA8B,GACnC,oBAAoB,CA8EtB"}
@@ -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":"AAEA;;;;;;;;;;;;;;;;;;;;;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;AAsW/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,7 @@
1
+ import { filterLeaves, filterTreeErrors } from './filter-tree.js';
1
2
  import { validateShiftMeasures } from './shift-measure-validation.js';
2
3
  import { escapeRegExp, isSafeSQLIdentifier, stripSqlLiterals } from '../sql-utils.js';
4
+ import { isDatasetSqlSource, resolveDatasetSqlSource } from './sql-dataset-source.js';
3
5
  import { clickhouseDatasetSqlDialect } from './clickhouse-dataset-sql-dialect.js';
4
6
  import { rawSqlErrorMessage } from './raw-sql-dialect-check.js';
5
7
  import { SEMANTIC_FILTER_OPERATORS, SEMANTIC_NULL_CHECK_OPERATORS, isSemanticFilterOperator } from '../constants.js';
@@ -133,7 +135,9 @@ function validateFilters(datasetName, filters, dimensions) {
133
135
  * identifier, and the operator must be one the renderer knows.
134
136
  */
135
137
  function validateMeasureFilters(datasetName, measureName, filters, dimensions, declaredFilters) {
136
- for (const filter of filters) {
138
+ for (const error of filterTreeErrors(filters))
139
+ fail(datasetName, `measure "${measureName}" filters: ${error}`);
140
+ for (const filter of filterLeaves(filters)) {
137
141
  const context = `measure "${measureName}" filter on "${String(filter.field)}"`;
138
142
  if (typeof filter.field !== 'string') {
139
143
  fail(datasetName, `${context} must name a field.`);
@@ -198,6 +202,79 @@ function validateMergeMeasure(datasetName, name, definition) {
198
202
  fail(datasetName, `measure "${name}" cannot use sql: merge measures read a stored state column.`);
199
203
  }
200
204
  }
205
+ /**
206
+ * RFC 0028: a SQL source's declared columns are the only ones its dataset can
207
+ * address, so every column reference must name one, bare or qualified with
208
+ * the source's alias. References qualified with a relationship name belong to that relationship's target and aren't checked.
209
+ */
210
+ function validateSqlSourceReferences(datasetName, config, alias, columns) {
211
+ const dimensions = config.dimensions ?? {};
212
+ const relationships = config.relationships ?? {};
213
+ const declared = (reference) => {
214
+ const bare = reference.startsWith(`${alias}.`) ? reference.slice(alias.length + 1) : reference;
215
+ return Object.hasOwn(columns, bare) ? bare : undefined;
216
+ };
217
+ const viaRelationship = (reference) => {
218
+ const [head, ...rest] = reference.split(QUALIFIED_SEPARATOR);
219
+ return rest.length > 0 && head !== undefined && Object.hasOwn(relationships, head);
220
+ };
221
+ const requireColumn = (reference, context) => {
222
+ if (declared(reference) === undefined) {
223
+ fail(datasetName, `${context} "${reference}" is not a column of the SQL source. Declare it in source.columns ` +
224
+ `(declared: ${Object.keys(columns).join(', ')}).`);
225
+ }
226
+ };
227
+ const fieldOrColumn = (reference, context) => {
228
+ if (!Object.hasOwn(dimensions, reference) && !viaRelationship(reference))
229
+ requireColumn(reference, context);
230
+ };
231
+ for (const [name, definition] of Object.entries(dimensions)) {
232
+ if (definition.sql !== undefined) {
233
+ for (const dependency of definition.dependencies ?? [])
234
+ requireColumn(dependency, `dimension "${name}" dependency`);
235
+ continue;
236
+ }
237
+ const column = definition.column ?? name;
238
+ requireColumn(column, `dimension "${name}" column`);
239
+ const type = columns[declared(column)];
240
+ if (type !== definition.fieldType) {
241
+ fail(datasetName, `dimension "${name}" is ${definition.fieldType}, but source column "${column}" is declared ${type}.`);
242
+ }
243
+ }
244
+ if (config.tenantKey !== undefined)
245
+ requireColumn(config.tenantKey, 'tenantKey');
246
+ for (const timeKey of [config.timeKey, ...(config.timeKeys ?? [])]) {
247
+ if (timeKey !== undefined)
248
+ fieldOrColumn(timeKey, 'time key');
249
+ }
250
+ for (const [name, definition] of Object.entries(config.filters ?? {})) {
251
+ fieldOrColumn(definition.field, `filter "${name}" field`);
252
+ }
253
+ for (const [name, definition] of Object.entries(config.measures ?? {})) {
254
+ if (isDerivedMeasure(definition) || isWindowMeasure(definition) || isShiftMeasure(definition))
255
+ continue;
256
+ if (definition.sql !== undefined) {
257
+ for (const dependency of definition.dependencies ?? [])
258
+ requireColumn(dependency, `measure "${name}" dependency`);
259
+ }
260
+ else {
261
+ for (const field of [definition.field, definition.argField]) {
262
+ if (field !== undefined)
263
+ fieldOrColumn(field, `measure "${name}" field`);
264
+ }
265
+ }
266
+ for (const filter of filterLeaves(definition.filters)) {
267
+ if (Object.hasOwn(config.filters ?? {}, filter.field))
268
+ continue;
269
+ fieldOrColumn(filter.field, `measure "${name}" filter field`);
270
+ }
271
+ }
272
+ for (const [name, relationship] of Object.entries(relationships)) {
273
+ for (const key of relationship.keys ?? [{ from: relationship.from, to: relationship.to }]) {
274
+ requireColumn(key.from, `relationship "${name}" key`);
275
+ }
276
+ }
277
+ }
201
278
  function validateLimits(datasetName, limits) {
202
279
  if (!limits) {
203
280
  return;
@@ -225,13 +302,23 @@ export function validateDatasetDefinition(name, config) {
225
302
  fail(name, 'dataset names must contain only letters, numbers and underscores, and start with a letter ' +
226
303
  'or underscore, so they remain valid identifiers in generated artifacts.');
227
304
  }
228
- if (typeof config.source !== 'string' || config.source.trim().length === 0) {
229
- fail(name, 'a non-empty source table is required.');
305
+ if (isDatasetSqlSource(config.source)) {
306
+ const source = resolveDatasetSqlSource(name, config.source);
307
+ if (config.rowResolution !== undefined || config.final) {
308
+ fail(name, 'rowResolution and final apply to a table, not a SQL source. Write FROM <table> FINAL ' +
309
+ '(and any deletion filter) inside the SQL instead.');
310
+ }
311
+ validateSqlSourceReferences(name, config, source.alias, source.columns);
230
312
  }
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.');
313
+ else {
314
+ if (typeof config.source !== 'string' || config.source.trim().length === 0) {
315
+ fail(name, 'a non-empty source table is required.');
316
+ }
317
+ // `database.table` is the deepest qualification ClickHouse addresses.
318
+ if (!isSafeQualifiedName(config.source, 2)) {
319
+ fail(name, `source "${config.source}" is not a safe table identifier. Expected "table" or ` +
320
+ '"database.table", each segment containing only letters, numbers and underscores.');
321
+ }
235
322
  }
236
323
  if (config.final !== undefined && typeof config.final !== 'boolean') {
237
324
  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"}