@hypequery/datasets 0.31.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-catalog.d.ts +3 -3
- package/dist/agent-catalog.d.ts.map +1 -1
- package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
- package/dist/cache/protocol-cache-keys.js +25 -1
- package/dist/cache/query-signature.d.ts.map +1 -1
- package/dist/cache/query-signature.js +16 -5
- package/dist/catalog.d.ts +5 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +9 -0
- package/dist/client-contract/build-from-deployment.d.ts +2 -2
- package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
- package/dist/client-contract/build-from-deployment.js +7 -0
- package/dist/cloud-publication.d.ts +37 -0
- package/dist/cloud-publication.d.ts.map +1 -0
- package/dist/cloud-publication.js +46 -0
- package/dist/cloud-publishing.d.ts +2 -2
- package/dist/cloud-publishing.d.ts.map +1 -1
- package/dist/codegen/dataset-source.d.ts.map +1 -1
- package/dist/codegen/dataset-source.js +4 -1
- package/dist/contract-3-authoring.fixture.d.ts +103 -0
- package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
- package/dist/contract-3-authoring.fixture.js +40 -0
- package/dist/contract.d.ts +5 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +9 -0
- package/dist/dataset-compilation.d.ts +3 -0
- package/dist/dataset-compilation.d.ts.map +1 -1
- package/dist/dataset-query.d.ts +5 -0
- package/dist/dataset-query.d.ts.map +1 -1
- package/dist/dataset.d.ts.map +1 -1
- package/dist/dataset.js +12 -2
- package/dist/event-operations.d.ts +43 -0
- package/dist/event-operations.d.ts.map +1 -0
- package/dist/event-operations.js +137 -0
- package/dist/execution-capabilities.d.ts +2 -1
- package/dist/execution-capabilities.d.ts.map +1 -1
- package/dist/execution-capabilities.js +1 -1
- package/dist/execution-capabilities.json +6 -6
- package/dist/executor.d.ts +13 -0
- package/dist/executor.d.ts.map +1 -1
- package/dist/executor.js +42 -8
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/portable-execution-errors.d.ts +11 -0
- package/dist/portable-execution-errors.d.ts.map +1 -1
- package/dist/portable-execution-errors.js +14 -0
- package/dist/portable-executor.d.ts +22 -5
- package/dist/portable-executor.d.ts.map +1 -1
- package/dist/portable-executor.js +64 -5
- package/dist/protocol-adapter.d.ts +12 -0
- package/dist/protocol-adapter.d.ts.map +1 -1
- package/dist/protocol-adapter.js +30 -8
- package/dist/protocol-deployment-adapter.d.ts +10 -3
- package/dist/protocol-deployment-adapter.d.ts.map +1 -1
- package/dist/protocol-deployment-adapter.js +60 -26
- package/dist/protocol-rehydrate.d.ts +3 -16
- package/dist/protocol-rehydrate.d.ts.map +1 -1
- package/dist/protocol-rehydrate.js +71 -11
- package/dist/query-builder-protocol.d.ts +10 -0
- package/dist/query-builder-protocol.d.ts.map +1 -1
- package/dist/query-planner.d.ts.map +1 -1
- package/dist/query-planner.js +3 -1
- package/dist/relationship-check.d.ts.map +1 -1
- package/dist/relationship-check.js +2 -0
- package/dist/semantic-planner.d.ts.map +1 -1
- package/dist/semantic-planner.js +16 -3
- package/dist/types.d.ts +109 -7
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/agent-catalog-projection.d.ts +11 -2
- package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
- package/dist/utils/agent-catalog-projection.js +49 -5
- package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
- package/dist/utils/build-dataset-query-builder.js +4 -8
- package/dist/utils/calculation-stage-sql.d.ts +31 -0
- package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
- package/dist/utils/calculation-stage-sql.js +98 -0
- package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
- package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
- package/dist/utils/compile-calculated-dataset-query.js +133 -0
- package/dist/utils/compile-dataset-query.d.ts.map +1 -1
- package/dist/utils/compile-dataset-query.js +11 -3
- package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
- package/dist/utils/dataset-definition-validation.js +90 -6
- package/dist/utils/dataset-events.d.ts +19 -0
- package/dist/utils/dataset-events.d.ts.map +1 -0
- package/dist/utils/dataset-events.js +46 -0
- package/dist/utils/dataset-having.d.ts.map +1 -1
- package/dist/utils/dataset-having.js +6 -1
- package/dist/utils/dataset-query-result.d.ts.map +1 -1
- package/dist/utils/dataset-query-result.js +7 -1
- package/dist/utils/dataset-query-validation.d.ts +1 -1
- package/dist/utils/dataset-query-validation.d.ts.map +1 -1
- package/dist/utils/dataset-query-validation.js +25 -47
- package/dist/utils/dataset-source.d.ts +2 -2
- package/dist/utils/dataset-source.d.ts.map +1 -1
- package/dist/utils/dataset-source.js +8 -1
- package/dist/utils/dimension-selection-overrides.d.ts +19 -0
- package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
- package/dist/utils/dimension-selection-overrides.js +22 -0
- package/dist/utils/event-breakdown-sql.d.ts +15 -0
- package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
- package/dist/utils/event-breakdown-sql.js +17 -0
- package/dist/utils/event-condition-sql.d.ts +18 -0
- package/dist/utils/event-condition-sql.d.ts.map +1 -0
- package/dist/utils/event-condition-sql.js +63 -0
- package/dist/utils/event-operation-shape.d.ts +8 -0
- package/dist/utils/event-operation-shape.d.ts.map +1 -0
- package/dist/utils/event-operation-shape.js +66 -0
- package/dist/utils/event-operation-spec.d.ts +43 -0
- package/dist/utils/event-operation-spec.d.ts.map +1 -0
- package/dist/utils/event-operation-spec.js +68 -0
- package/dist/utils/event-range-span.d.ts +4 -0
- package/dist/utils/event-range-span.d.ts.map +1 -0
- package/dist/utils/event-range-span.js +22 -0
- package/dist/utils/event-result-values.d.ts +8 -0
- package/dist/utils/event-result-values.d.ts.map +1 -0
- package/dist/utils/event-result-values.js +21 -0
- package/dist/utils/event-source-sql.d.ts +38 -0
- package/dist/utils/event-source-sql.d.ts.map +1 -0
- package/dist/utils/event-source-sql.js +71 -0
- package/dist/utils/filter-predicate-tree.d.ts +28 -0
- package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
- package/dist/utils/filter-predicate-tree.js +80 -0
- package/dist/utils/filter-tree.d.ts +42 -0
- package/dist/utils/filter-tree.d.ts.map +1 -0
- package/dist/utils/filter-tree.js +164 -0
- package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
- package/dist/utils/filtered-aggregation-sql.js +3 -0
- package/dist/utils/funnel-rows.d.ts +10 -0
- package/dist/utils/funnel-rows.d.ts.map +1 -0
- package/dist/utils/funnel-rows.js +30 -0
- package/dist/utils/funnel-sql.d.ts +18 -0
- package/dist/utils/funnel-sql.d.ts.map +1 -0
- package/dist/utils/funnel-sql.js +104 -0
- package/dist/utils/metric-derived-query.d.ts.map +1 -1
- package/dist/utils/metric-derived-query.js +4 -5
- package/dist/utils/metric-query-builder.d.ts.map +1 -1
- package/dist/utils/metric-query-builder.js +4 -5
- package/dist/utils/metric-query-validation.d.ts.map +1 -1
- package/dist/utils/metric-query-validation.js +18 -7
- package/dist/utils/other-bucket-sql.d.ts +23 -0
- package/dist/utils/other-bucket-sql.d.ts.map +1 -0
- package/dist/utils/other-bucket-sql.js +51 -0
- package/dist/utils/portable-aggregations.d.ts +10 -6
- package/dist/utils/portable-aggregations.d.ts.map +1 -1
- package/dist/utils/portable-aggregations.js +13 -8
- package/dist/utils/portable-grains.d.ts +17 -8
- package/dist/utils/portable-grains.d.ts.map +1 -1
- package/dist/utils/portable-grains.js +26 -11
- package/dist/utils/portable-query-calculations.d.ts +14 -0
- package/dist/utils/portable-query-calculations.d.ts.map +1 -0
- package/dist/utils/portable-query-calculations.js +31 -0
- package/dist/utils/portable-semantic-query.d.ts.map +1 -1
- package/dist/utils/portable-semantic-query.js +27 -1
- package/dist/utils/protocol-contract-3.d.ts +30 -0
- package/dist/utils/protocol-contract-3.d.ts.map +1 -0
- package/dist/utils/protocol-contract-3.js +93 -0
- package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
- package/dist/utils/protocol-metric-capabilities.js +2 -1
- package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
- package/dist/utils/protocol-metric-expressions.js +6 -1
- package/dist/utils/protocol-rehydrate-filters.js +2 -1
- package/dist/utils/protocol-rehydrate-time-keys.d.ts +5 -0
- package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
- package/dist/utils/protocol-rehydrate-time-keys.js +5 -0
- package/dist/utils/query-calculation-errors.d.ts +6 -0
- package/dist/utils/query-calculation-errors.d.ts.map +1 -0
- package/dist/utils/query-calculation-errors.js +9 -0
- package/dist/utils/query-calculation-formula.d.ts +19 -0
- package/dist/utils/query-calculation-formula.d.ts.map +1 -0
- package/dist/utils/query-calculation-formula.js +77 -0
- package/dist/utils/query-calculation-outputs.d.ts +24 -0
- package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
- package/dist/utils/query-calculation-outputs.js +72 -0
- package/dist/utils/query-calculation-plan.d.ts +67 -0
- package/dist/utils/query-calculation-plan.d.ts.map +1 -0
- package/dist/utils/query-calculation-plan.js +416 -0
- package/dist/utils/query-calculation-types.d.ts +97 -0
- package/dist/utils/query-calculation-types.d.ts.map +1 -0
- package/dist/utils/query-calculation-types.js +8 -0
- package/dist/utils/query-field-references.d.ts.map +1 -1
- package/dist/utils/query-field-references.js +2 -1
- package/dist/utils/query-filter-errors.d.ts +11 -0
- package/dist/utils/query-filter-errors.d.ts.map +1 -0
- package/dist/utils/query-filter-errors.js +65 -0
- package/dist/utils/query-timezone.d.ts +6 -3
- package/dist/utils/query-timezone.d.ts.map +1 -1
- package/dist/utils/query-timezone.js +5 -1
- package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
- package/dist/utils/relationship-builder-plan.js +2 -1
- package/dist/utils/relationship-fields.d.ts.map +1 -1
- package/dist/utils/relationship-fields.js +5 -0
- package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
- package/dist/utils/relationship-measure-sql.js +2 -0
- package/dist/utils/relationship-validation.d.ts +3 -1
- package/dist/utils/relationship-validation.d.ts.map +1 -1
- package/dist/utils/relationship-validation.js +8 -4
- package/dist/utils/relative-date-filters.d.ts +21 -0
- package/dist/utils/relative-date-filters.d.ts.map +1 -0
- package/dist/utils/relative-date-filters.js +86 -0
- package/dist/utils/relative-date-range.d.ts +20 -0
- package/dist/utils/relative-date-range.d.ts.map +1 -0
- package/dist/utils/relative-date-range.js +75 -0
- package/dist/utils/retention-rows.d.ts +9 -0
- package/dist/utils/retention-rows.d.ts.map +1 -0
- package/dist/utils/retention-rows.js +30 -0
- package/dist/utils/retention-sql.d.ts +16 -0
- package/dist/utils/retention-sql.d.ts.map +1 -0
- package/dist/utils/retention-sql.js +68 -0
- package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
- package/dist/utils/scoped-dataset-source.js +4 -0
- package/dist/utils/segments.d.ts +3 -2
- package/dist/utils/segments.d.ts.map +1 -1
- package/dist/utils/segments.js +5 -4
- package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
- package/dist/utils/semantic-query-syntax.js +8 -2
- package/dist/utils/sql-dataset-source.d.ts +36 -0
- package/dist/utils/sql-dataset-source.d.ts.map +1 -0
- package/dist/utils/sql-dataset-source.js +126 -0
- package/dist/utils/time-axis-bounds.d.ts +11 -4
- package/dist/utils/time-axis-bounds.d.ts.map +1 -1
- package/dist/utils/time-axis-bounds.js +14 -6
- package/dist/utils/time-measure-axis.d.ts +2 -2
- package/dist/utils/time-measure-axis.d.ts.map +1 -1
- package/dist/utils/time-measure-axis.js +13 -3
- package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
- package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
- package/dist/utils/time-measure-dataset-sql.js +15 -5
- package/dist/utils/time-measure-source-sql.d.ts +2 -2
- package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
- package/dist/utils/time-measure-source-sql.js +7 -8
- package/dist/utils/time-query-measures.d.ts +5 -0
- package/dist/utils/time-query-measures.d.ts.map +1 -1
- package/dist/utils/time-query-measures.js +7 -0
- package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
- package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
- package/dist/utils/unsupported-contract-reasons.js +5 -1
- package/package.json +3 -3
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { isFilterGroup } from './filter-tree.js';
|
|
2
|
+
/**
|
|
3
|
+
* One RFC 0027 condition as a SQL boolean over an already-projected column.
|
|
4
|
+
* Every caller value is bound as a parameter, never inlined.
|
|
5
|
+
*/
|
|
6
|
+
export function eventConditionSql(column, filter, statement) {
|
|
7
|
+
const bind = (value) => statement.bind(value);
|
|
8
|
+
switch (filter.operator) {
|
|
9
|
+
case 'eq': return `${column} = ${bind(filter.value)}`;
|
|
10
|
+
case 'neq': return `${column} != ${bind(filter.value)}`;
|
|
11
|
+
case 'gt': return `${column} > ${bind(filter.value)}`;
|
|
12
|
+
case 'gte': return `${column} >= ${bind(filter.value)}`;
|
|
13
|
+
case 'lt': return `${column} < ${bind(filter.value)}`;
|
|
14
|
+
case 'lte': return `${column} <= ${bind(filter.value)}`;
|
|
15
|
+
case 'like': return `${column} LIKE ${bind(filter.value)}`;
|
|
16
|
+
case 'isNull': return `${column} IS NULL`;
|
|
17
|
+
case 'isNotNull': return `${column} IS NOT NULL`;
|
|
18
|
+
case 'in':
|
|
19
|
+
case 'notIn': {
|
|
20
|
+
if (!Array.isArray(filter.value) || filter.value.length === 0) {
|
|
21
|
+
throw new Error(`"${filter.operator}" conditions require a non-empty array.`);
|
|
22
|
+
}
|
|
23
|
+
const values = filter.value.map(bind).join(', ');
|
|
24
|
+
return `${column} ${filter.operator === 'in' ? 'IN' : 'NOT IN'} (${values})`;
|
|
25
|
+
}
|
|
26
|
+
case 'between': {
|
|
27
|
+
if (!Array.isArray(filter.value) || filter.value.length !== 2) {
|
|
28
|
+
throw new Error('"between" conditions require a two-item array.');
|
|
29
|
+
}
|
|
30
|
+
return `${column} BETWEEN ${bind(filter.value[0])} AND ${bind(filter.value[1])}`;
|
|
31
|
+
}
|
|
32
|
+
default:
|
|
33
|
+
// `inDateRange` applies only to the time axis, which conditions can't use.
|
|
34
|
+
throw new Error(`Operator "${filter.operator}" can't be used in an event condition.`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* AND-combined conditions as a non-null 0/1 flag: a NULL comparison is a
|
|
39
|
+
* non-match, so array and aggregate functions never see a Nullable flag.
|
|
40
|
+
*
|
|
41
|
+
* `predicatesFor` turns one condition into the predicates that test it, the
|
|
42
|
+
* way a caller filter on the same field is applied: a timestamp instant is
|
|
43
|
+
* compared in UTC, and a mixed range splits into one predicate per kind.
|
|
44
|
+
*/
|
|
45
|
+
export function eventConditionFlagSql(conditions, predicatesFor, statement) {
|
|
46
|
+
const leaf = (condition) => predicatesFor(condition).map(predicate => {
|
|
47
|
+
const filter = { field: condition.field, operator: predicate.operator, value: predicate.value };
|
|
48
|
+
return `(${eventConditionSql(predicate.expression, filter, statement)})`;
|
|
49
|
+
}).join(' AND ');
|
|
50
|
+
// RFC 0029 groups render as written. SQL three-valued logic makes a NULL
|
|
51
|
+
// field fail a comparison and its negation alike, and the outer ifNull
|
|
52
|
+
// reads what is left NULL as "no match".
|
|
53
|
+
const node = (item) => {
|
|
54
|
+
if (!isFilterGroup(item))
|
|
55
|
+
return `(${leaf(item)})`;
|
|
56
|
+
const group = item;
|
|
57
|
+
if (group.not !== undefined)
|
|
58
|
+
return `(NOT ${node(group.not)})`;
|
|
59
|
+
const items = (group.and ?? group.or ?? []).map(node);
|
|
60
|
+
return `(${items.join(group.and ? ' AND ' : ' OR ')})`;
|
|
61
|
+
};
|
|
62
|
+
return `toUInt8(ifNull(${conditions.map(node).join(' AND ')}, 0))`;
|
|
63
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { EventOperationSpec } from './event-operation-spec.js';
|
|
2
|
+
/**
|
|
3
|
+
* The RFC 0027 shape rules the protocol validator applies, for specs built
|
|
4
|
+
* directly in code: bounds, unique names, and breakdown names that can't
|
|
5
|
+
* collide with an output column (which would overwrite the breakdown value).
|
|
6
|
+
*/
|
|
7
|
+
export declare function eventOperationShapeErrors(spec: EventOperationSpec): string[];
|
|
8
|
+
//# sourceMappingURL=event-operation-shape.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-operation-shape.d.ts","sourceRoot":"","sources":["../../src/utils/event-operation-shape.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,kBAAkB,EAA6B,MAAM,2BAA2B,CAAC;AAI/F;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,EAAE,CAuB5E"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { PROTOCOL_EVENT_OPERATION_LIMITS as LIMITS, PROTOCOL_FUNNEL_COLUMNS, PROTOCOL_RETENTION_COLUMNS, } from '@hypequery/protocol';
|
|
2
|
+
const COHORT_GRAINS = new Set(['day', 'week', 'month']);
|
|
3
|
+
/**
|
|
4
|
+
* The RFC 0027 shape rules the protocol validator applies, for specs built
|
|
5
|
+
* directly in code: bounds, unique names, and breakdown names that can't
|
|
6
|
+
* collide with an output column (which would overwrite the breakdown value).
|
|
7
|
+
*/
|
|
8
|
+
export function eventOperationShapeErrors(spec) {
|
|
9
|
+
const errors = [];
|
|
10
|
+
const reserved = spec.kind === 'retention' ? PROTOCOL_RETENTION_COLUMNS : PROTOCOL_FUNNEL_COLUMNS;
|
|
11
|
+
if (spec.breakdown.length > LIMITS.maxBreakdown) {
|
|
12
|
+
errors.push(`At most ${LIMITS.maxBreakdown} breakdown dimensions may be used.`);
|
|
13
|
+
}
|
|
14
|
+
if (new Set(spec.breakdown).size !== spec.breakdown.length)
|
|
15
|
+
errors.push('Breakdown dimensions must be unique.');
|
|
16
|
+
for (const name of spec.breakdown) {
|
|
17
|
+
if (reserved.has(name))
|
|
18
|
+
errors.push(`Breakdown dimension "${name}" collides with the "${name}" output column.`);
|
|
19
|
+
}
|
|
20
|
+
if (!Number.isSafeInteger(spec.breakdownLimit) || spec.breakdownLimit < 1 || spec.breakdownLimit > LIMITS.maxBreakdownLimit) {
|
|
21
|
+
errors.push(`breakdownLimit must be an integer from 1 to ${LIMITS.maxBreakdownLimit}.`);
|
|
22
|
+
}
|
|
23
|
+
// Each kind checks only its own fields, so a new kind can't read another's.
|
|
24
|
+
switch (spec.kind) {
|
|
25
|
+
case 'funnel':
|
|
26
|
+
errors.push(...funnelShapeErrors(spec));
|
|
27
|
+
break;
|
|
28
|
+
case 'retention':
|
|
29
|
+
errors.push(...retentionShapeErrors(spec));
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
return errors;
|
|
33
|
+
}
|
|
34
|
+
function conditionErrors(name, where) {
|
|
35
|
+
return where.length < 1 || where.length > LIMITS.maxConditions
|
|
36
|
+
? [`${name} needs 1 to ${LIMITS.maxConditions} conditions.`]
|
|
37
|
+
: [];
|
|
38
|
+
}
|
|
39
|
+
function funnelShapeErrors(spec) {
|
|
40
|
+
const errors = [];
|
|
41
|
+
if (spec.steps.length < LIMITS.minSteps || spec.steps.length > LIMITS.maxSteps) {
|
|
42
|
+
errors.push(`A funnel has ${LIMITS.minSteps} to ${LIMITS.maxSteps} steps.`);
|
|
43
|
+
}
|
|
44
|
+
if (new Set(spec.steps.map(step => step.name)).size !== spec.steps.length)
|
|
45
|
+
errors.push('Step names must be unique.');
|
|
46
|
+
for (const step of spec.steps)
|
|
47
|
+
errors.push(...conditionErrors(`Step "${step.name}"`, step.where));
|
|
48
|
+
if (!Number.isSafeInteger(spec.windowMs) || spec.windowMs < 1 || spec.windowMs > LIMITS.maxWindowMilliseconds) {
|
|
49
|
+
errors.push('The funnel window must be a whole number of milliseconds, at most 365 days.');
|
|
50
|
+
}
|
|
51
|
+
if (spec.by !== undefined && !COHORT_GRAINS.has(spec.by))
|
|
52
|
+
errors.push(`Cohort grain "${spec.by}" is not day, week or month.`);
|
|
53
|
+
return errors;
|
|
54
|
+
}
|
|
55
|
+
function retentionShapeErrors(spec) {
|
|
56
|
+
const errors = [
|
|
57
|
+
...conditionErrors('The start condition', spec.start),
|
|
58
|
+
...conditionErrors('The return condition', spec.return),
|
|
59
|
+
];
|
|
60
|
+
if (!Number.isSafeInteger(spec.periods) || spec.periods < 1 || spec.periods > LIMITS.maxPeriods) {
|
|
61
|
+
errors.push(`periods must be an integer from 1 to ${LIMITS.maxPeriods}.`);
|
|
62
|
+
}
|
|
63
|
+
if (!COHORT_GRAINS.has(spec.grain))
|
|
64
|
+
errors.push(`Cohort grain "${spec.grain}" is not day, week or month.`);
|
|
65
|
+
return errors;
|
|
66
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ProtocolEventOperation, ProtocolExpression } from '@hypequery/protocol';
|
|
2
|
+
import type { AnyDatasetInstance, DatasetFilterNode, MetricFilter } from '../types.js';
|
|
3
|
+
export type EventCohortGrain = 'day' | 'week' | 'month';
|
|
4
|
+
/** An RFC 0027 funnel in the dataset layer's vocabulary. */
|
|
5
|
+
export interface FunnelSpec {
|
|
6
|
+
readonly kind: 'funnel';
|
|
7
|
+
readonly entity: string;
|
|
8
|
+
/** Each step's conditions: comparisons or and/or/not groups (RFC 0029), ANDed. */
|
|
9
|
+
readonly steps: readonly {
|
|
10
|
+
readonly name: string;
|
|
11
|
+
readonly where: readonly DatasetFilterNode[];
|
|
12
|
+
}[];
|
|
13
|
+
readonly windowMs: number;
|
|
14
|
+
readonly order: 'strict' | 'any';
|
|
15
|
+
/** Caller filters, ANDed; groups and `inDateRange` as a dataset query takes them. */
|
|
16
|
+
readonly filters: readonly DatasetFilterNode[];
|
|
17
|
+
readonly breakdown: readonly string[];
|
|
18
|
+
readonly breakdownLimit: number;
|
|
19
|
+
readonly by?: EventCohortGrain;
|
|
20
|
+
readonly timezone?: string;
|
|
21
|
+
}
|
|
22
|
+
/** An RFC 0027 retention operation in the dataset layer's vocabulary. */
|
|
23
|
+
export interface RetentionSpec {
|
|
24
|
+
readonly kind: 'retention';
|
|
25
|
+
readonly entity: string;
|
|
26
|
+
/** What starts a cohort and what counts as a return: comparisons or groups (RFC 0029), ANDed. */
|
|
27
|
+
readonly start: readonly DatasetFilterNode[];
|
|
28
|
+
readonly return: readonly DatasetFilterNode[];
|
|
29
|
+
readonly grain: EventCohortGrain;
|
|
30
|
+
readonly periods: number;
|
|
31
|
+
readonly filters: readonly DatasetFilterNode[];
|
|
32
|
+
readonly breakdown: readonly string[];
|
|
33
|
+
readonly breakdownLimit: number;
|
|
34
|
+
readonly timezone?: string;
|
|
35
|
+
}
|
|
36
|
+
export type EventOperationSpec = FunnelSpec | RetentionSpec;
|
|
37
|
+
/** Every condition list the operation tests events against. */
|
|
38
|
+
export declare function eventOperationConditions(spec: EventOperationSpec): readonly DatasetFilterNode[];
|
|
39
|
+
/** Enforced constraints (RFC 0019) as the dataset layer's trusted filters: comparisons only. */
|
|
40
|
+
export declare function eventConstraintFilters(expressions: readonly ProtocolExpression[]): MetricFilter[];
|
|
41
|
+
/** Resolve a validated protocol operation against the dataset that serves it. */
|
|
42
|
+
export declare function eventOperationSpec(operation: ProtocolEventOperation, dataset: AnyDatasetInstance): EventOperationSpec;
|
|
43
|
+
//# sourceMappingURL=event-operation-spec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-operation-spec.d.ts","sourceRoot":"","sources":["../../src/utils/event-operation-spec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEtF,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKvF,MAAM,MAAM,gBAAgB,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAExD,4DAA4D;AAC5D,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,kFAAkF;IAClF,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAA;KAAE,EAAE,CAAC;IACnG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,KAAK,CAAC;IACjC,qFAAqF;IACrF,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC;IAC/B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,yEAAyE;AACzE,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iGAAiG;IACjG,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC9C,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,aAAa,CAAC;AAE5D,+DAA+D;AAC/D,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,kBAAkB,GAAG,SAAS,iBAAiB,EAAE,CAE/F;AAwBD,gGAAgG;AAChG,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,SAAS,kBAAkB,EAAE,GAAG,YAAY,EAAE,CAEjG;AAED,iFAAiF;AACjF,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,sBAAsB,EAAE,OAAO,EAAE,kBAAkB,GAAG,kBAAkB,CAsCrH"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { PROTOCOL_EVENT_OPERATION_LIMITS, parseProtocolEventWindow } from '@hypequery/protocol';
|
|
2
|
+
import { PortableExecutionUnsupportedError } from '../portable-execution-errors.js';
|
|
3
|
+
import { rehydrateMeasureFilter } from './protocol-rehydrate-filters.js';
|
|
4
|
+
import { UNSUPPORTED_CONTRACT_REASONS } from './unsupported-contract-reasons.js';
|
|
5
|
+
/** Every condition list the operation tests events against. */
|
|
6
|
+
export function eventOperationConditions(spec) {
|
|
7
|
+
return spec.kind === 'retention' ? [...spec.start, ...spec.return] : spec.steps.flatMap(step => step.where);
|
|
8
|
+
}
|
|
9
|
+
function comparison(expression, path) {
|
|
10
|
+
return rehydrateMeasureFilter(expression, () => new PortableExecutionUnsupportedError(`${path} is not a field/operator/value comparison, so it cannot be planned.`, { reason: UNSUPPORTED_CONTRACT_REASONS.queryFilterNotComparison }));
|
|
11
|
+
}
|
|
12
|
+
/** A predicate as a filter node: `logical` becomes an and/or/not group (RFC 0029). */
|
|
13
|
+
function filterNode(expression, path) {
|
|
14
|
+
if (expression.kind !== 'logical')
|
|
15
|
+
return comparison(expression, path);
|
|
16
|
+
if (expression.operator === 'not')
|
|
17
|
+
return { not: filterNode(expression.operand, `${path}.operand`) };
|
|
18
|
+
const items = expression.operands.map((operand, index) => filterNode(operand, `${path}.operands[${index}]`));
|
|
19
|
+
return expression.operator === 'and' ? { and: items } : { or: items };
|
|
20
|
+
}
|
|
21
|
+
function filters(expressions, path) {
|
|
22
|
+
return expressions.map((expression, index) => filterNode(expression, `${path}[${index}]`));
|
|
23
|
+
}
|
|
24
|
+
/** Enforced constraints (RFC 0019) as the dataset layer's trusted filters: comparisons only. */
|
|
25
|
+
export function eventConstraintFilters(expressions) {
|
|
26
|
+
return expressions.map((expression, index) => comparison(expression, `constraints[${index}]`));
|
|
27
|
+
}
|
|
28
|
+
/** Resolve a validated protocol operation against the dataset that serves it. */
|
|
29
|
+
export function eventOperationSpec(operation, dataset) {
|
|
30
|
+
if (!dataset.events) {
|
|
31
|
+
throw new Error(`Dataset "${dataset.name}" does not declare events, so it has no ${operation.kind}.`);
|
|
32
|
+
}
|
|
33
|
+
const common = {
|
|
34
|
+
entity: String(operation.entity ?? dataset.events.entity),
|
|
35
|
+
filters: filters(operation.filters, 'filters'),
|
|
36
|
+
breakdown: (operation.breakdown ?? []).map(String),
|
|
37
|
+
breakdownLimit: operation.breakdownLimit ?? PROTOCOL_EVENT_OPERATION_LIMITS.defaultBreakdownLimit,
|
|
38
|
+
...(operation.timezone === undefined ? {} : { timezone: operation.timezone }),
|
|
39
|
+
};
|
|
40
|
+
if (operation.kind === 'retention') {
|
|
41
|
+
return {
|
|
42
|
+
kind: 'retention',
|
|
43
|
+
...common,
|
|
44
|
+
start: filters(operation.start.where, 'start.where'),
|
|
45
|
+
return: filters(operation.return.where, 'return.where'),
|
|
46
|
+
grain: operation.grain,
|
|
47
|
+
periods: operation.periods,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const window = parseProtocolEventWindow(operation.window);
|
|
51
|
+
if (!window)
|
|
52
|
+
throw new Error(`Invalid funnel window "${operation.window}".`);
|
|
53
|
+
return {
|
|
54
|
+
kind: 'funnel',
|
|
55
|
+
entity: String(operation.entity ?? dataset.events.entity),
|
|
56
|
+
steps: operation.steps.map((step, index) => ({
|
|
57
|
+
name: String(step.name),
|
|
58
|
+
where: filters(step.where, `steps[${index}].where`),
|
|
59
|
+
})),
|
|
60
|
+
windowMs: window.milliseconds,
|
|
61
|
+
order: operation.order ?? 'strict',
|
|
62
|
+
filters: filters(operation.filters, 'filters'),
|
|
63
|
+
breakdown: (operation.breakdown ?? []).map(String),
|
|
64
|
+
breakdownLimit: operation.breakdownLimit ?? PROTOCOL_EVENT_OPERATION_LIMITS.defaultBreakdownLimit,
|
|
65
|
+
...(operation.by === undefined ? {} : { by: operation.by }),
|
|
66
|
+
...(operation.timezone === undefined ? {} : { timezone: operation.timezone }),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { TimeAxisRange } from './time-axis-bounds.js';
|
|
2
|
+
/** The range's span in days, with both bounds read in the operation's zone (RFC 0025). */
|
|
3
|
+
export declare function eventRangeSpanDays(range: TimeAxisRange, timezone: string | undefined): number;
|
|
4
|
+
//# sourceMappingURL=event-range-span.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-range-span.d.ts","sourceRoot":"","sources":["../../src/utils/event-range-span.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAqB3D,0FAA0F;AAC1F,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAG7F"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const DAY_MS = 86_400_000;
|
|
2
|
+
/** How far `timezone`'s wall clock is ahead of UTC at instant `at`. */
|
|
3
|
+
function zoneOffset(at, timezone) {
|
|
4
|
+
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', {
|
|
5
|
+
timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
|
|
6
|
+
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
7
|
+
}).formatToParts(new Date(at)).filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));
|
|
8
|
+
const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
9
|
+
return wall - Math.floor(at / 1000) * 1000;
|
|
10
|
+
}
|
|
11
|
+
/** A bound as an instant: an offset-free bound is a wall clock in the query zone, as the scan reads it. */
|
|
12
|
+
function boundInstant(bound, timezone) {
|
|
13
|
+
if (bound.hasOffset || timezone === 'UTC')
|
|
14
|
+
return bound.milliseconds;
|
|
15
|
+
// Two passes settle a wall clock next to a DST change.
|
|
16
|
+
return bound.milliseconds - zoneOffset(bound.milliseconds - zoneOffset(bound.milliseconds, timezone), timezone);
|
|
17
|
+
}
|
|
18
|
+
/** The range's span in days, with both bounds read in the operation's zone (RFC 0025). */
|
|
19
|
+
export function eventRangeSpanDays(range, timezone) {
|
|
20
|
+
const zone = timezone ?? 'UTC';
|
|
21
|
+
return (boundInstant(range.end, zone) - boundInstant(range.start, zone)) / DAY_MS;
|
|
22
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type EventResultValue = string | number | boolean | null;
|
|
2
|
+
export type EventResultRow = Readonly<Record<string, EventResultValue>>;
|
|
3
|
+
/** A ClickHouse count arrives as a number or, for 64-bit types, a quoted string. */
|
|
4
|
+
export declare function countValue(value: unknown): number;
|
|
5
|
+
export declare function ratio(numerator: number, denominator: number): number | null;
|
|
6
|
+
/** A result cell: scalars pass through; anything else becomes its string form. */
|
|
7
|
+
export declare function scalar(value: unknown): EventResultValue;
|
|
8
|
+
//# sourceMappingURL=event-result-values.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-result-values.d.ts","sourceRoot":"","sources":["../../src/utils/event-result-values.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAExE,oFAAoF;AACpF,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAMjD;AAED,wBAAgB,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3E;AAED,kFAAkF;AAClF,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAKvD"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** A ClickHouse count arrives as a number or, for 64-bit types, a quoted string. */
|
|
2
|
+
export function countValue(value) {
|
|
3
|
+
const count = typeof value === 'string' ? Number(value) : value;
|
|
4
|
+
if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0) {
|
|
5
|
+
throw new Error('The executor returned a count that is not a non-negative integer.');
|
|
6
|
+
}
|
|
7
|
+
return count;
|
|
8
|
+
}
|
|
9
|
+
export function ratio(numerator, denominator) {
|
|
10
|
+
return denominator === 0 ? null : numerator / denominator;
|
|
11
|
+
}
|
|
12
|
+
/** A result cell: scalars pass through; anything else becomes its string form. */
|
|
13
|
+
export function scalar(value) {
|
|
14
|
+
if (value === null || value === undefined)
|
|
15
|
+
return null;
|
|
16
|
+
if (typeof value === 'string' || typeof value === 'boolean')
|
|
17
|
+
return value;
|
|
18
|
+
if (typeof value === 'number')
|
|
19
|
+
return Number.isFinite(value) ? value : null;
|
|
20
|
+
return String(value);
|
|
21
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { AnyDatasetInstance, DatasetFilterNode, MetricFilter } from '../types.js';
|
|
2
|
+
import type { QueryTimePredicate } from './query-timezone.js';
|
|
3
|
+
import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
|
|
4
|
+
import { type RelationshipBuilderContext } from './relationship-builder-plan.js';
|
|
5
|
+
import type { StatementParameters } from './statement-parameters.js';
|
|
6
|
+
/** What an event scan projects, and the aliases later stages read. */
|
|
7
|
+
export interface EventSourceRequest {
|
|
8
|
+
readonly entity: string;
|
|
9
|
+
readonly breakdown: readonly string[];
|
|
10
|
+
/** Filter names that step, start or return conditions test. */
|
|
11
|
+
readonly conditionFields: readonly string[];
|
|
12
|
+
/** Every caller filter, including the time range; groups allowed (RFC 0029). */
|
|
13
|
+
readonly filters: readonly DatasetFilterNode[];
|
|
14
|
+
readonly timezone?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface EventSourceSql {
|
|
17
|
+
/** `_hq_raw` and `_hq_events`. */
|
|
18
|
+
readonly ctes: readonly string[];
|
|
19
|
+
/** `_hq_b0`, `_hq_b1`, … in breakdown order. */
|
|
20
|
+
readonly breakdown: readonly string[];
|
|
21
|
+
/** Condition field name -> its projected alias. */
|
|
22
|
+
readonly conditionColumn: (field: string) => string;
|
|
23
|
+
/** One condition as predicates over its projected alias, as a caller filter on that field. */
|
|
24
|
+
readonly conditionPredicates: (condition: MetricFilter) => readonly QueryTimePredicate[];
|
|
25
|
+
readonly joinCtx: RelationshipBuilderContext | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The event rows an RFC 0027 operation reads: the dataset's source with every
|
|
29
|
+
* trusted restriction applied (tenancy, row policies, enforced constraints,
|
|
30
|
+
* `FINAL`), the caller's filters, and only the columns the operation needs.
|
|
31
|
+
*
|
|
32
|
+
* Authored expressions stay inside their own SELECT and come out as one
|
|
33
|
+
* positional tuple, so internal aliases can't capture a source column name.
|
|
34
|
+
* `_hq_events` has `_hq_time` (in the query zone), `_hq_entity`, the
|
|
35
|
+
* breakdown aliases and the condition aliases.
|
|
36
|
+
*/
|
|
37
|
+
export declare function buildEventSourceSql(ds: AnyDatasetInstance, request: EventSourceRequest, options: DatasetQueryExecutionOptions, statement: StatementParameters): EventSourceSql;
|
|
38
|
+
//# sourceMappingURL=event-source-sql.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-source-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-source-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,EAAmC,KAAK,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAGlH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAErE,sEAAsE;AACtE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,+DAA+D;IAC/D,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,gFAAgF;IAChF,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,cAAc;IAC7B,kCAAkC;IAClC,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,mDAAmD;IACnD,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;IACpD,8FAA8F;IAC9F,QAAQ,CAAC,mBAAmB,EAAE,CAAC,SAAS,EAAE,YAAY,KAAK,SAAS,kBAAkB,EAAE,CAAC;IACzF,QAAQ,CAAC,OAAO,EAAE,0BAA0B,GAAG,SAAS,CAAC;CAC1D;AAED;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,kBAAkB,EACtB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,4BAA4B,EACrC,SAAS,EAAE,mBAAmB,GAC7B,cAAc,CA2DhB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { applyFilterTree } from './filter-predicate-tree.js';
|
|
2
|
+
import { resolveDimensionExpression, resolveFilterField } from '../query-planner.js';
|
|
3
|
+
import { buildRelationshipBuilderContext } from './relationship-builder-plan.js';
|
|
4
|
+
import { queryTimeFilter, queryTimeSql } from './query-timezone.js';
|
|
5
|
+
import { scopedDatasetSource } from './scoped-dataset-source.js';
|
|
6
|
+
/**
|
|
7
|
+
* The event rows an RFC 0027 operation reads: the dataset's source with every
|
|
8
|
+
* trusted restriction applied (tenancy, row policies, enforced constraints,
|
|
9
|
+
* `FINAL`), the caller's filters, and only the columns the operation needs.
|
|
10
|
+
*
|
|
11
|
+
* Authored expressions stay inside their own SELECT and come out as one
|
|
12
|
+
* positional tuple, so internal aliases can't capture a source column name.
|
|
13
|
+
* `_hq_events` has `_hq_time` (in the query zone), `_hq_entity`, the
|
|
14
|
+
* breakdown aliases and the condition aliases.
|
|
15
|
+
*/
|
|
16
|
+
export function buildEventSourceSql(ds, request, options, statement) {
|
|
17
|
+
const { dialect } = statement;
|
|
18
|
+
if (!ds.timeKey)
|
|
19
|
+
throw new Error(`Dataset "${ds.name}" has no time key for events.`);
|
|
20
|
+
const joinCtx = buildRelationshipBuilderContext(ds, {
|
|
21
|
+
dimensions: [request.entity, ...request.breakdown],
|
|
22
|
+
filters: [...request.filters],
|
|
23
|
+
}, options.context, dialect);
|
|
24
|
+
let raw = scopedDatasetSource({
|
|
25
|
+
builderFactory: options.builderFactory, ds, context: options.context, joinCtx, dialect, timezone: request.timezone,
|
|
26
|
+
});
|
|
27
|
+
const parts = [
|
|
28
|
+
resolveDimensionExpression(ds, ds.timeKey, joinCtx),
|
|
29
|
+
resolveDimensionExpression(ds, request.entity, joinCtx),
|
|
30
|
+
...request.breakdown.map(name => resolveDimensionExpression(ds, name, joinCtx)),
|
|
31
|
+
...request.conditionFields.map(name => resolveFilterField(ds, name, joinCtx)),
|
|
32
|
+
];
|
|
33
|
+
const identifiers = [
|
|
34
|
+
...parts,
|
|
35
|
+
...Object.keys(ds.dimensions),
|
|
36
|
+
...Object.values(ds.dimensions).map(dimension => dimension.sql ?? dimension.column ?? ''),
|
|
37
|
+
...Object.values(ds.filters).map(filter => filter.field ?? ''),
|
|
38
|
+
ds.tenantKey ?? '',
|
|
39
|
+
];
|
|
40
|
+
let rowAlias = '_hq_row';
|
|
41
|
+
while (identifiers.some(text => text.includes(rowAlias)))
|
|
42
|
+
rowAlias += '_';
|
|
43
|
+
raw = raw.select([`${dialect.packRow(parts)} AS ${rowAlias}`]);
|
|
44
|
+
raw = applyFilterTree(raw, request.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), request.timezone)));
|
|
45
|
+
const breakdown = request.breakdown.map((_, index) => `_hq_b${index}`);
|
|
46
|
+
const conditionAliases = new Map(request.conditionFields.map((name, index) => [name, `_hq_f${index}`]));
|
|
47
|
+
const element = (position) => dialect.rowElement(rowAlias, position);
|
|
48
|
+
const columns = [
|
|
49
|
+
`${queryTimeSql(dialect, dialect.assumeNotNull(element(1)), request.timezone)} AS _hq_time`,
|
|
50
|
+
`${element(2)} AS _hq_entity`,
|
|
51
|
+
...breakdown.map((alias, index) => `${element(3 + index)} AS ${alias}`),
|
|
52
|
+
...request.conditionFields.map((name, index) => (`${element(3 + breakdown.length + index)} AS ${conditionAliases.get(name)}`)),
|
|
53
|
+
];
|
|
54
|
+
const conditionColumn = (field) => {
|
|
55
|
+
const alias = conditionAliases.get(field);
|
|
56
|
+
if (!alias)
|
|
57
|
+
throw new Error(`Condition field "${field}" was not projected.`);
|
|
58
|
+
return alias;
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
ctes: [
|
|
62
|
+
`_hq_raw AS (${statement.embedBuilder(raw)})`,
|
|
63
|
+
// An event with no time or no entity can't be placed in a sequence.
|
|
64
|
+
`_hq_events AS (SELECT ${columns.join(', ')} FROM _hq_raw WHERE ${dialect.isNotNull(element(1))} AND ${dialect.isNotNull(element(2))})`,
|
|
65
|
+
],
|
|
66
|
+
breakdown,
|
|
67
|
+
conditionColumn,
|
|
68
|
+
conditionPredicates: condition => queryTimeFilter(dialect, ds, condition, conditionColumn(condition.field), request.timezone),
|
|
69
|
+
joinCtx,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { DatasetFilterNode, MetricFilterOperator } from '../types.js';
|
|
2
|
+
import type { QueryBuilderLike } from '../query-builder-protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* Operators a planned comparison may carry. `notLike` exists only here: it is
|
|
5
|
+
* how a negated `like` renders, never something a caller writes (RFC 0029).
|
|
6
|
+
*/
|
|
7
|
+
export type PlannedFilterOperator = MetricFilterOperator | 'notLike';
|
|
8
|
+
/** A comparison after `not` has been pushed down to it. */
|
|
9
|
+
export interface PlannedFilter {
|
|
10
|
+
readonly field: string;
|
|
11
|
+
readonly operator: PlannedFilterOperator;
|
|
12
|
+
readonly value?: unknown;
|
|
13
|
+
}
|
|
14
|
+
/** One `where` call: the column side, its operator, and the value to bind. */
|
|
15
|
+
export interface PlannedWherePredicate {
|
|
16
|
+
readonly expression: string;
|
|
17
|
+
readonly operator: PlannedFilterOperator;
|
|
18
|
+
readonly value: unknown;
|
|
19
|
+
}
|
|
20
|
+
type Predicates = (filter: PlannedFilter) => readonly PlannedWherePredicate[];
|
|
21
|
+
/**
|
|
22
|
+
* Apply caller filters to `builder`. A flat list makes exactly the `where`
|
|
23
|
+
* calls it always has, so its SQL is unchanged; groups use the builder's
|
|
24
|
+
* group methods and fail loudly on a builder without them.
|
|
25
|
+
*/
|
|
26
|
+
export declare function applyFilterTree(builder: QueryBuilderLike, nodes: readonly DatasetFilterNode[] | undefined, predicates: Predicates): QueryBuilderLike;
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=filter-predicate-tree.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filter-predicate-tree.d.ts","sourceRoot":"","sources":["../../src/utils/filter-predicate-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAgB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAGrE;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG,oBAAoB,GAAG,SAAS,CAAC;AAErE,2DAA2D;AAC3D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;IACzC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,8EAA8E;AAC9E,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AA2CD,KAAK,UAAU,GAAG,CAAC,MAAM,EAAE,aAAa,KAAK,SAAS,qBAAqB,EAAE,CAAC;AAyC9E;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,EAC/C,UAAU,EAAE,UAAU,GACrB,gBAAgB,CAKlB"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { isFilterGroup } from './filter-tree.js';
|
|
2
|
+
const NEGATED = {
|
|
3
|
+
eq: 'neq', neq: 'eq', gt: 'lte', gte: 'lt', lt: 'gte', lte: 'gt',
|
|
4
|
+
in: 'notIn', notIn: 'in', isNull: 'isNotNull', isNotNull: 'isNull', like: 'notLike',
|
|
5
|
+
};
|
|
6
|
+
function negateLeaf(filter) {
|
|
7
|
+
if (filter.operator === 'between') {
|
|
8
|
+
const [low, high] = filter.value;
|
|
9
|
+
return {
|
|
10
|
+
kind: 'or',
|
|
11
|
+
items: [
|
|
12
|
+
{ kind: 'leaf', filter: { field: filter.field, operator: 'lt', value: low } },
|
|
13
|
+
{ kind: 'leaf', filter: { field: filter.field, operator: 'gt', value: high } },
|
|
14
|
+
],
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const operator = NEGATED[filter.operator];
|
|
18
|
+
if (!operator)
|
|
19
|
+
throw new Error(`Filter operator "${filter.operator}" cannot be negated.`);
|
|
20
|
+
return { kind: 'leaf', filter: { ...filter, operator } };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Negation normal form: `not` pushed to the leaves by De Morgan. Each rewrite
|
|
24
|
+
* is exact under SQL three-valued logic, so the rows are those of the
|
|
25
|
+
* authored tree.
|
|
26
|
+
*/
|
|
27
|
+
function normalize(node, negated) {
|
|
28
|
+
if (!isFilterGroup(node))
|
|
29
|
+
return negated ? negateLeaf(node) : { kind: 'leaf', filter: node };
|
|
30
|
+
if ('not' in node && node.not !== undefined)
|
|
31
|
+
return normalize(node.not, !negated);
|
|
32
|
+
const isAnd = 'and' in node && node.and !== undefined;
|
|
33
|
+
const items = (isAnd ? node.and : node.or)
|
|
34
|
+
.map(item => normalize(item, negated));
|
|
35
|
+
if (items.length === 1)
|
|
36
|
+
return items[0];
|
|
37
|
+
// De Morgan: a negated AND is an OR of the negated items, and vice versa.
|
|
38
|
+
return { kind: isAnd !== negated ? 'and' : 'or', items };
|
|
39
|
+
}
|
|
40
|
+
function requireGroups(builder) {
|
|
41
|
+
if (!builder.whereGroup || !builder.orWhere || !builder.orWhereGroup) {
|
|
42
|
+
throw new Error('Filter groups with "or" or "not" need a query builder with whereGroup, orWhere and orWhereGroup.');
|
|
43
|
+
}
|
|
44
|
+
return builder;
|
|
45
|
+
}
|
|
46
|
+
/** AND the node's predicates onto `builder`. */
|
|
47
|
+
function applyAnd(builder, node, predicates) {
|
|
48
|
+
if (node.kind === 'leaf') {
|
|
49
|
+
return predicates(node.filter).reduce((current, predicate) => current.where(predicate.expression, predicate.operator, predicate.value), builder);
|
|
50
|
+
}
|
|
51
|
+
if (node.kind === 'and')
|
|
52
|
+
return node.items.reduce((current, item) => applyAnd(current, item, predicates), builder);
|
|
53
|
+
return requireGroups(builder).whereGroup(group => applyOr(group, node.items, predicates));
|
|
54
|
+
}
|
|
55
|
+
/** OR the items together inside an open group. */
|
|
56
|
+
function applyOr(builder, items, predicates) {
|
|
57
|
+
return items.reduce((current, item, index) => {
|
|
58
|
+
const groups = requireGroups(current);
|
|
59
|
+
const leafPredicates = item.kind === 'leaf' ? predicates(item.filter) : undefined;
|
|
60
|
+
if (leafPredicates?.length === 1) {
|
|
61
|
+
const [predicate] = leafPredicates;
|
|
62
|
+
return index === 0
|
|
63
|
+
? groups.where(predicate.expression, predicate.operator, predicate.value)
|
|
64
|
+
: groups.orWhere(predicate.expression, predicate.operator, predicate.value);
|
|
65
|
+
}
|
|
66
|
+
// A multi-predicate leaf, or a nested AND/OR, is one parenthesized alternative.
|
|
67
|
+
const nested = (inner) => (item.kind === 'or'
|
|
68
|
+
? applyOr(inner, item.items, predicates)
|
|
69
|
+
: applyAnd(inner, item, predicates));
|
|
70
|
+
return index === 0 ? groups.whereGroup(nested) : groups.orWhereGroup(nested);
|
|
71
|
+
}, builder);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Apply caller filters to `builder`. A flat list makes exactly the `where`
|
|
75
|
+
* calls it always has, so its SQL is unchanged; groups use the builder's
|
|
76
|
+
* group methods and fail loudly on a builder without them.
|
|
77
|
+
*/
|
|
78
|
+
export function applyFilterTree(builder, nodes, predicates) {
|
|
79
|
+
return (nodes ?? []).reduce((current, node) => applyAnd(current, normalize(node, false), predicates), builder);
|
|
80
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { DatasetFilterGroup, DatasetFilterNode, MetricFilter, MetricFilterOperator } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Nested caller filters (RFC 0029): a query's `filters` list is an implicit
|
|
4
|
+
* AND of comparisons and `{ and }` / `{ or }` / `{ not }` groups.
|
|
5
|
+
*/
|
|
6
|
+
/** Deepest group nesting a query may use, so a hostile tree cannot exhaust the stack. */
|
|
7
|
+
export declare const MAX_FILTER_GROUP_DEPTH = 32;
|
|
8
|
+
/** True for a `{ and }`, `{ or }` or `{ not }` node, as opposed to a comparison. */
|
|
9
|
+
export declare function isFilterGroup(node: unknown): node is DatasetFilterGroup;
|
|
10
|
+
/** True when `nodes` holds any group, so the flat, builder-free paths cannot run it. */
|
|
11
|
+
export declare function hasFilterGroups(nodes: readonly DatasetFilterNode[] | undefined): boolean;
|
|
12
|
+
/** Every comparison in the tree, depth first, as authored. */
|
|
13
|
+
export declare function filterLeaves(nodes: readonly DatasetFilterNode[] | undefined): MetricFilter[];
|
|
14
|
+
/** Number of comparisons the query applies: what `maxFilters` bounds. */
|
|
15
|
+
export declare function filterLeafCount(nodes: readonly DatasetFilterNode[] | undefined): number;
|
|
16
|
+
/**
|
|
17
|
+
* The operator a comparison has once `not` is pushed down to it, as the
|
|
18
|
+
* operator allowlist sees it. `between` negates to a pair; `like` has no
|
|
19
|
+
* portable negation and is checked as itself.
|
|
20
|
+
*/
|
|
21
|
+
export declare function negatedFilterOperators(operator: MetricFilterOperator): readonly MetricFilterOperator[];
|
|
22
|
+
export interface EffectiveFilterLeaf {
|
|
23
|
+
/** The comparison as authored. */
|
|
24
|
+
readonly filter: MetricFilter;
|
|
25
|
+
/** True under an odd number of `not`s. */
|
|
26
|
+
readonly negated: boolean;
|
|
27
|
+
/** Operators the allowlist must permit for this comparison (RFC 0029). */
|
|
28
|
+
readonly operators: readonly MetricFilterOperator[];
|
|
29
|
+
}
|
|
30
|
+
/** Every comparison with the operators it effectively applies. */
|
|
31
|
+
export declare function effectiveFilterLeaves(nodes: readonly DatasetFilterNode[] | undefined): EffectiveFilterLeaf[];
|
|
32
|
+
/** Structural problems with the groups themselves; leaves are validated separately. */
|
|
33
|
+
export declare function filterTreeErrors(nodes: unknown): string[];
|
|
34
|
+
/**
|
|
35
|
+
* The top-level conjuncts: top-level `and` groups and one-item `or` groups
|
|
36
|
+
* are spliced in, so `[{ and: [a, b] }, c]` reads as `[a, b, c]`. Only these
|
|
37
|
+
* can bound a time axis.
|
|
38
|
+
*/
|
|
39
|
+
export declare function topLevelFilterNodes(nodes: readonly DatasetFilterNode[] | undefined): DatasetFilterNode[];
|
|
40
|
+
/** Comparisons nested under an `or` or `not`, which filter rows but bound nothing. */
|
|
41
|
+
export declare function nestedFilterLeaves(nodes: readonly DatasetFilterNode[] | undefined): MetricFilter[];
|
|
42
|
+
//# sourceMappingURL=filter-tree.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filter-tree.d.ts","sourceRoot":"","sources":["../../src/utils/filter-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,YAAY,EACZ,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAErB;;;GAGG;AAEH,yFAAyF;AACzF,eAAO,MAAM,sBAAsB,KAAK,CAAC;AAIzC,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,kBAAkB,CAIvE;AAED,wFAAwF;AACxF,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,OAAO,CAExF;AAOD,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,YAAY,EAAE,CAc5F;AAED,yEAAyE;AACzE,wBAAgB,eAAe,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,MAAM,CAEvF;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,oBAAoB,GAAG,SAAS,oBAAoB,EAAE,CAiBtG;AAED,MAAM,WAAW,mBAAmB;IAClC,kCAAkC;IAClC,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,0CAA0C;IAC1C,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,0EAA0E;IAC1E,QAAQ,CAAC,SAAS,EAAE,SAAS,oBAAoB,EAAE,CAAC;CACrD;AAED,kEAAkE;AAClE,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,mBAAmB,EAAE,CAoB5G;AAMD,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,CAqCzD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,iBAAiB,EAAE,CAcxG;AAED,sFAAsF;AACtF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,GAAG,SAAS,GAAG,YAAY,EAAE,CAElG"}
|