@rocicorp/zero 1.12.0-canary.10 → 1.12.0-canary.12
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/out/analyze-query/src/zql-chain.js +9 -1
- package/out/analyze-query/src/zql-chain.js.map +1 -1
- package/out/ast-to-zql/src/ast-to-zql.d.ts.map +1 -1
- package/out/ast-to-zql/src/ast-to-zql.js +61 -20
- package/out/ast-to-zql/src/ast-to-zql.js.map +1 -1
- package/out/z2s/src/compiler.d.ts +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +339 -2
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/z2s/src/sql.d.ts +8 -0
- package/out/z2s/src/sql.d.ts.map +1 -1
- package/out/z2s/src/sql.js +58 -11
- package/out/z2s/src/sql.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero/src/bindings.js +4 -4
- package/out/zero-cache/src/auth/write-authorizer.js +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +4 -0
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +13 -0
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/db/create.js +1 -1
- package/out/zero-cache/src/scripts/decommission.js +1 -1
- package/out/zero-cache/src/server/replicator.js +4 -2
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/run-worker.d.ts.map +1 -1
- package/out/zero-cache/src/server/runner/run-worker.js +8 -5
- package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
- package/out/zero-cache/src/server/serving-checkpointer.js +41 -0
- package/out/zero-cache/src/server/serving-checkpointer.js.map +1 -0
- package/out/zero-cache/src/server/worker-urls.d.ts +1 -0
- package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
- package/out/zero-cache/src/server/worker-urls.js +2 -1
- package/out/zero-cache/src/server/worker-urls.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +1 -1
- package/out/zero-cache/src/services/http-service.d.ts +6 -0
- package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/http-service.js +13 -1
- package/out/zero-cache/src/services/http-service.js.map +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts +19 -0
- package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js +53 -1
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +1 -1
- package/out/zero-cache/src/services/replicator/serving-checkpointer.js +85 -0
- package/out/zero-cache/src/services/replicator/serving-checkpointer.js.map +1 -0
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +101 -13
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.js +2 -2
- package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +1 -1
- package/out/zero-cache/src/types/processes.js +4 -4
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/row-key.js +8 -1
- package/out/zero-cache/src/types/row-key.js.map +1 -1
- package/out/zero-cache/src/workers/connection.js +2 -2
- package/out/zero-cache/src/workers/replicator.js +9 -4
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-client/src/client/bindings.d.ts +1 -1
- package/out/zero-client/src/client/bindings.d.ts.map +1 -1
- package/out/zero-client/src/client/bindings.js +4 -4
- package/out/zero-client/src/client/context.d.ts +7 -1
- package/out/zero-client/src/client/context.d.ts.map +1 -1
- package/out/zero-client/src/client/context.js +7 -0
- package/out/zero-client/src/client/context.js.map +1 -1
- package/out/zero-client/src/client/crud-impl.d.ts.map +1 -1
- package/out/zero-client/src/client/crud-impl.js +171 -2
- package/out/zero-client/src/client/crud-impl.js.map +1 -1
- package/out/zero-client/src/client/custom.d.ts.map +1 -1
- package/out/zero-client/src/client/custom.js +42 -3
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/ivm-branch.d.ts +62 -2
- package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
- package/out/zero-client/src/client/ivm-branch.js +152 -31
- package/out/zero-client/src/client/ivm-branch.js.map +1 -1
- package/out/zero-client/src/client/keys.d.ts +33 -0
- package/out/zero-client/src/client/keys.d.ts.map +1 -1
- package/out/zero-client/src/client/keys.js +43 -4
- package/out/zero-client/src/client/keys.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
- package/out/zero-client/src/client/zero-poke-handler.js +29 -1
- package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
- package/out/zero-client/src/client/zero-rep.d.ts +1 -1
- package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
- package/out/zero-client/src/client/zero-rep.js +2 -15
- package/out/zero-client/src/client/zero-rep.js.map +1 -1
- package/out/zero-client/src/client/zero.js +1 -1
- package/out/zero-client/src/mod.d.ts +3 -3
- package/out/zero-client/src/mod.d.ts.map +1 -1
- package/out/zero-protocol/src/aggregate-table.d.ts +15 -0
- package/out/zero-protocol/src/aggregate-table.d.ts.map +1 -0
- package/out/zero-protocol/src/aggregate-table.js +5 -0
- package/out/zero-protocol/src/aggregate-table.js.map +1 -0
- package/out/zero-protocol/src/ast.d.ts +141 -5
- package/out/zero-protocol/src/ast.d.ts.map +1 -1
- package/out/zero-protocol/src/ast.js +244 -18
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +29 -29
- package/out/zero-protocol/src/inspect-down.d.ts +81 -81
- package/out/zero-protocol/src/protocol-version.d.ts +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/query-hash-visitor.d.ts.map +1 -1
- package/out/zero-protocol/src/query-hash-visitor.js +38 -0
- package/out/zero-protocol/src/query-hash-visitor.js.map +1 -1
- package/out/zero-react/src/bindings.js +4 -4
- package/out/zero-react/src/use-query.d.ts +3 -1
- package/out/zero-react/src/use-query.d.ts.map +1 -1
- package/out/zero-react/src/use-query.js +4 -2
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-schema/src/builder/schema-builder.d.ts.map +1 -1
- package/out/zero-schema/src/builder/schema-builder.js +2 -0
- package/out/zero-schema/src/builder/schema-builder.js.map +1 -1
- package/out/zero-schema/src/name-mapper.d.ts.map +1 -1
- package/out/zero-schema/src/name-mapper.js +7 -4
- package/out/zero-schema/src/name-mapper.js.map +1 -1
- package/out/zero-server/src/custom.js +1 -1
- package/out/zero-server/src/schema.d.ts.map +1 -1
- package/out/zero-server/src/schema.js +13 -2
- package/out/zero-server/src/schema.js.map +1 -1
- package/out/zero-solid/src/bindings.js +4 -4
- package/out/zero-solid/src/solid-view.d.ts.map +1 -1
- package/out/zero-solid/src/solid-view.js +3 -3
- package/out/zero-solid/src/solid-view.js.map +1 -1
- package/out/zero-types/src/format.d.ts +13 -0
- package/out/zero-types/src/format.d.ts.map +1 -1
- package/out/zero-types/src/format.js.map +1 -1
- package/out/zero-types/src/name-mapper.d.ts +14 -0
- package/out/zero-types/src/name-mapper.d.ts.map +1 -1
- package/out/zero-types/src/name-mapper.js +12 -0
- package/out/zero-types/src/name-mapper.js.map +1 -1
- package/out/zero-types/src/schema-value.d.ts +2 -0
- package/out/zero-types/src/schema-value.d.ts.map +1 -1
- package/out/zero-types/src/schema-value.js +15 -0
- package/out/zero-types/src/schema-value.js.map +1 -0
- package/out/zero-types/src/server-schema.d.ts +18 -0
- package/out/zero-types/src/server-schema.d.ts.map +1 -1
- package/out/zql/src/builder/builder.d.ts +126 -1
- package/out/zql/src/builder/builder.d.ts.map +1 -1
- package/out/zql/src/builder/builder.js +281 -11
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/builder/filter.d.ts +1 -1
- package/out/zql/src/builder/filter.d.ts.map +1 -1
- package/out/zql/src/builder/filter.js +41 -3
- package/out/zql/src/builder/filter.js.map +1 -1
- package/out/zql/src/ivm/aggregate.d.ts +188 -0
- package/out/zql/src/ivm/aggregate.d.ts.map +1 -0
- package/out/zql/src/ivm/aggregate.js +470 -0
- package/out/zql/src/ivm/aggregate.js.map +1 -0
- package/out/zql/src/ivm/array-view.d.ts +1 -1
- package/out/zql/src/ivm/array-view.d.ts.map +1 -1
- package/out/zql/src/ivm/array-view.js +3 -3
- package/out/zql/src/ivm/array-view.js.map +1 -1
- package/out/zql/src/ivm/cap.js +2 -2
- package/out/zql/src/ivm/constraint.d.ts.map +1 -1
- package/out/zql/src/ivm/constraint.js +2 -1
- package/out/zql/src/ivm/constraint.js.map +1 -1
- package/out/zql/src/ivm/deferred-input.js +1 -1
- package/out/zql/src/ivm/fan-in.js +1 -1
- package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +3 -2
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/group-by.d.ts +98 -0
- package/out/zql/src/ivm/group-by.d.ts.map +1 -0
- package/out/zql/src/ivm/group-by.js +384 -0
- package/out/zql/src/ivm/group-by.js.map +1 -0
- package/out/zql/src/ivm/join-index.d.ts.map +1 -1
- package/out/zql/src/ivm/join-index.js +2 -1
- package/out/zql/src/ivm/join-index.js.map +1 -1
- package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
- package/out/zql/src/ivm/join-utils.js +2 -1
- package/out/zql/src/ivm/join-utils.js.map +1 -1
- package/out/zql/src/ivm/join.js +1 -1
- package/out/zql/src/ivm/lift-field.d.ts +54 -0
- package/out/zql/src/ivm/lift-field.d.ts.map +1 -0
- package/out/zql/src/ivm/lift-field.js +168 -0
- package/out/zql/src/ivm/lift-field.js.map +1 -0
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +1 -1
- package/out/zql/src/ivm/memory-source.d.ts +2 -0
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +9 -4
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/push-accumulated.js +1 -1
- package/out/zql/src/ivm/schema.d.ts +1 -0
- package/out/zql/src/ivm/schema.d.ts.map +1 -1
- package/out/zql/src/ivm/source.d.ts +21 -0
- package/out/zql/src/ivm/source.d.ts.map +1 -1
- package/out/zql/src/ivm/source.js.map +1 -1
- package/out/zql/src/ivm/take.js +1 -1
- package/out/zql/src/ivm/union-fan-in.js +1 -1
- package/out/zql/src/ivm/view-apply-change.d.ts +5 -0
- package/out/zql/src/ivm/view-apply-change.d.ts.map +1 -1
- package/out/zql/src/ivm/view-apply-change.js +23 -3
- package/out/zql/src/ivm/view-apply-change.js.map +1 -1
- package/out/zql/src/planner/planner-debug.d.ts +1 -1
- package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
- package/out/zql/src/planner/planner-debug.js +4 -0
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/query/expression.d.ts +50 -3
- package/out/zql/src/query/expression.d.ts.map +1 -1
- package/out/zql/src/query/expression.js +62 -6
- package/out/zql/src/query/expression.js.map +1 -1
- package/out/zql/src/query/measure-push-operator.js +1 -1
- package/out/zql/src/query/query-delegate-base.d.ts +8 -0
- package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
- package/out/zql/src/query/query-delegate-base.js +13 -5
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +17 -3
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js +239 -7
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query.d.ts +319 -7
- package/out/zql/src/query/query.d.ts.map +1 -1
- package/out/zqlite/src/pending-delta.d.ts.map +1 -1
- package/out/zqlite/src/pending-delta.js +4 -3
- package/out/zqlite/src/pending-delta.js.map +1 -1
- package/out/zqlite/src/query-builder.d.ts +12 -1
- package/out/zqlite/src/query-builder.d.ts.map +1 -1
- package/out/zqlite/src/query-builder.js +114 -13
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +37 -3
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
2
|
+
import { must } from "../../../shared/src/must.js";
|
|
3
|
+
import { aggregateValue } from "../../../zero-protocol/src/ast.js";
|
|
4
|
+
import { assignProperty } from "../../../shared/src/objects.js";
|
|
5
|
+
import { makeEditChange } from "./change.js";
|
|
6
|
+
import { compareValues, makeComparator, normalizeUndefined, valueToKey } from "./data.js";
|
|
7
|
+
import { throwOutput } from "./operator.js";
|
|
8
|
+
//#region ../zql/src/ivm/aggregate.ts
|
|
9
|
+
/**
|
|
10
|
+
* The name of the synthetic column that holds the aggregate result in the rows
|
|
11
|
+
* this operator emits. The value is projected to a bare scalar in the view, so
|
|
12
|
+
* this name is internal.
|
|
13
|
+
*
|
|
14
|
+
* The synthetic columns share the emitted row with the group key, whose names
|
|
15
|
+
* come from the user's schema, so they use the reserved `_0_` prefix (as
|
|
16
|
+
* `_0_version` does) rather than plain words a schema could also use.
|
|
17
|
+
*/
|
|
18
|
+
var AGGREGATE_VALUE_COLUMN = "_0_value";
|
|
19
|
+
/**
|
|
20
|
+
* A top-level (ungrouped) aggregate has no group key, but the synced path keys
|
|
21
|
+
* every row in the CVR and forbids empty row keys (see zero-cache
|
|
22
|
+
* `types/row-key.ts`). Since there is no group key, the single global row is
|
|
23
|
+
* given one synthetic, constant-valued key column so it still has a (non-empty)
|
|
24
|
+
* primary key. The materialized-view path ignores it (it projects only
|
|
25
|
+
* `AGGREGATE_VALUE_COLUMN`), so this name is internal.
|
|
26
|
+
*
|
|
27
|
+
* The row holds nothing but this column and the payload columns, so any name
|
|
28
|
+
* other than theirs (and `_0_version`) is collision-free. It must not be empty:
|
|
29
|
+
* a SQLite-backed source cannot declare a zero-length column name.
|
|
30
|
+
*/
|
|
31
|
+
var AGGREGATE_KEY_COLUMN = "_0_key";
|
|
32
|
+
/** The constant value of {@link AGGREGATE_KEY_COLUMN} (one global row). */
|
|
33
|
+
var AGGREGATE_KEY_VALUE = 0;
|
|
34
|
+
/**
|
|
35
|
+
* `sum` and `avg` additionally carry their running components so the synced
|
|
36
|
+
* client can adjust them optimistically: you can't move an average from the
|
|
37
|
+
* final value alone, and a sum's value alone can't tell an empty group (`null`)
|
|
38
|
+
* from one summing to 0. The value column stays the result (for display); these are the
|
|
39
|
+
* sum of non-null field values and the count of non-null contributors.
|
|
40
|
+
*/
|
|
41
|
+
var AGGREGATE_SUM_COLUMN = "_0_sum";
|
|
42
|
+
var AGGREGATE_COUNT_COLUMN = "_0_count";
|
|
43
|
+
/**
|
|
44
|
+
* A grouped `sum`/`avg` row also carries its group's number of rows, nulls
|
|
45
|
+
* included, which neither component gives: the synced client adds a group with
|
|
46
|
+
* its first row and removes it with its last, as it does a count's.
|
|
47
|
+
*/
|
|
48
|
+
var AGGREGATE_ROWS_COLUMN = "_0_rows";
|
|
49
|
+
/**
|
|
50
|
+
* Whether `col` is the name of a synthetic column of an aggregate or grouped
|
|
51
|
+
* row: `_0_key` or a payload column.
|
|
52
|
+
*/
|
|
53
|
+
function isSyntheticColumn(col) {
|
|
54
|
+
return col === "_0_key" || AGGREGATE_PAYLOAD_COLUMNS.has(col);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Asserts that the group key column `col` of an aggregate, or a column of a
|
|
58
|
+
* grouped query, is not a synthetic column. The synthetic columns are written over
|
|
59
|
+
* the group's columns in the emitted row, the payload is stripped from it by
|
|
60
|
+
* the client's row key and `_0_key` alone keys a row that has it, so a
|
|
61
|
+
* collision would silently merge or corrupt the groups. Their reserved `_0_`
|
|
62
|
+
* prefix keeps real schemas clear of this; the check guards the invariant.
|
|
63
|
+
*/
|
|
64
|
+
function assertNotSyntheticColumn(col) {
|
|
65
|
+
assert(!isSyntheticColumn(col), () => `Aggregate: group key column "${col}" collides with the synthetic aggregate column of the same name`);
|
|
66
|
+
}
|
|
67
|
+
/** Whether `fn`'s rows carry the sum and count components. */
|
|
68
|
+
function carriesComponents(fn) {
|
|
69
|
+
return fn === "sum" || fn === "avg";
|
|
70
|
+
}
|
|
71
|
+
/** The synthetic payload columns (not part of an aggregate row's key). */
|
|
72
|
+
var AGGREGATE_PAYLOAD_COLUMNS = /* @__PURE__ */ new Set([
|
|
73
|
+
AGGREGATE_VALUE_COLUMN,
|
|
74
|
+
AGGREGATE_SUM_COLUMN,
|
|
75
|
+
AGGREGATE_COUNT_COLUMN,
|
|
76
|
+
AGGREGATE_ROWS_COLUMN
|
|
77
|
+
]);
|
|
78
|
+
/**
|
|
79
|
+
* The type of the synthetic value column for an aggregate result: `count` is a
|
|
80
|
+
* non-null number; `sum`/`avg` are nullable numbers; `min`/`max` take the
|
|
81
|
+
* field's own type (`json` for a JSON path, whose leaf can be a number or a
|
|
82
|
+
* string) and are nullable (empty group).
|
|
83
|
+
*/
|
|
84
|
+
function aggregateValueColumn(fn, field, inputColumns, path) {
|
|
85
|
+
switch (fn) {
|
|
86
|
+
case "count": return { type: "number" };
|
|
87
|
+
case "sum":
|
|
88
|
+
case "avg": return {
|
|
89
|
+
type: "number",
|
|
90
|
+
optional: true
|
|
91
|
+
};
|
|
92
|
+
case "min":
|
|
93
|
+
case "max": {
|
|
94
|
+
if (path !== void 0) return {
|
|
95
|
+
type: "json",
|
|
96
|
+
optional: true
|
|
97
|
+
};
|
|
98
|
+
const fieldSchema = inputColumns[must(field)];
|
|
99
|
+
assert(fieldSchema, () => `Aggregate: ${fn} field "${field}" missing`);
|
|
100
|
+
return {
|
|
101
|
+
...fieldSchema,
|
|
102
|
+
optional: true
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
default: unreachable(fn);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The synthetic schema (columns + primary key) an aggregate produces, derived
|
|
110
|
+
* from the *input* columns (the rows being aggregated), the group key, and the
|
|
111
|
+
* fn/field. Shared by the {@link Aggregate} operator (compute mode) and the
|
|
112
|
+
* client query builder (`aggregatesFromSource` mode) so both agree on the
|
|
113
|
+
* synthetic source's shape. For a top-level (empty group key) aggregate the
|
|
114
|
+
* single synthetic key column is added; otherwise the group key is the key.
|
|
115
|
+
*/
|
|
116
|
+
function aggregateSourceSchema(inputColumns, groupKey, fn, field, path) {
|
|
117
|
+
const columns = {};
|
|
118
|
+
for (const col of groupKey) {
|
|
119
|
+
assertNotSyntheticColumn(col);
|
|
120
|
+
const colSchema = inputColumns[col];
|
|
121
|
+
assert(colSchema, () => `Aggregate: group key column "${col}" missing`);
|
|
122
|
+
assignProperty(columns, col, colSchema);
|
|
123
|
+
}
|
|
124
|
+
const keyColumns = groupKey.length > 0 ? groupKey : [AGGREGATE_KEY_COLUMN];
|
|
125
|
+
if (groupKey.length === 0) columns[AGGREGATE_KEY_COLUMN] = { type: "number" };
|
|
126
|
+
columns[AGGREGATE_VALUE_COLUMN] = aggregateValueColumn(fn, field, inputColumns, path);
|
|
127
|
+
if (carriesComponents(fn)) {
|
|
128
|
+
columns[AGGREGATE_SUM_COLUMN] = { type: "number" };
|
|
129
|
+
columns[AGGREGATE_COUNT_COLUMN] = { type: "number" };
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
columns,
|
|
133
|
+
primaryKey: keyColumns
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Whether a change to one input row maps to a fixed delta of the aggregate
|
|
138
|
+
* (`count`/`sum`/`avg`). Shared with the synced client, which only applies
|
|
139
|
+
* optimistic deltas to these functions.
|
|
140
|
+
*/
|
|
141
|
+
var isInvertible = (fn) => fn === "count" || fn === "sum" || fn === "avg";
|
|
142
|
+
/**
|
|
143
|
+
* How an aggregate function reduces a group's rows into an {@link AggState},
|
|
144
|
+
* and reads its result back. Shared by {@link Aggregate}, which keeps a state
|
|
145
|
+
* per parent of a relationship, and `GroupBy`, which keeps one per group.
|
|
146
|
+
*/
|
|
147
|
+
var Reducer = class {
|
|
148
|
+
fn;
|
|
149
|
+
field;
|
|
150
|
+
/** A JSON path into `field` (see `Aggregate.path`). */
|
|
151
|
+
path;
|
|
152
|
+
constructor(fn, field, path) {
|
|
153
|
+
assert(fn === "count" ? field === void 0 : field !== void 0, () => `Aggregate: ${fn} ${fn === "count" ? "takes no" : "requires a"} field`);
|
|
154
|
+
assert(path === void 0 || field !== void 0, "Aggregate: a JSON path requires a field");
|
|
155
|
+
this.fn = fn;
|
|
156
|
+
this.field = field;
|
|
157
|
+
this.path = path;
|
|
158
|
+
}
|
|
159
|
+
/** The state of a group with no rows. */
|
|
160
|
+
empty() {
|
|
161
|
+
return {
|
|
162
|
+
count: 0,
|
|
163
|
+
sum: 0,
|
|
164
|
+
nonNull: 0,
|
|
165
|
+
extreme: null
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** The scalar result for a state, per the aggregate function. */
|
|
169
|
+
value(s) {
|
|
170
|
+
switch (this.fn) {
|
|
171
|
+
case "count": return s.count;
|
|
172
|
+
case "sum": return s.nonNull === 0 ? null : s.sum;
|
|
173
|
+
case "avg": return s.nonNull === 0 ? null : s.sum / s.nonNull;
|
|
174
|
+
case "min":
|
|
175
|
+
case "max": return s.extreme;
|
|
176
|
+
default: unreachable(this.fn);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** Whether `v` should replace the current extreme for a min/max. */
|
|
180
|
+
#beats(v, current) {
|
|
181
|
+
const c = compareAggregateValues(v, current);
|
|
182
|
+
return this.fn === "max" ? c > 0 : c < 0;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The value `row` contributes: its field, or the JSON leaf at the path (see
|
|
186
|
+
* `aggregateValue`), `null` when it contributes nothing.
|
|
187
|
+
*/
|
|
188
|
+
#read(row) {
|
|
189
|
+
const field = must(this.field);
|
|
190
|
+
return normalizeUndefined(this.path === void 0 ? row[field] : aggregateValue({
|
|
191
|
+
fn: this.fn,
|
|
192
|
+
field,
|
|
193
|
+
path: this.path
|
|
194
|
+
}, row));
|
|
195
|
+
}
|
|
196
|
+
/** Whether an edit from `oldRow` to `newRow` leaves the value it reduces. */
|
|
197
|
+
sameValue(oldRow, newRow) {
|
|
198
|
+
return this.field === void 0 || compareAggregateValues(this.#read(oldRow), this.#read(newRow)) === 0;
|
|
199
|
+
}
|
|
200
|
+
/** Add one row's contribution to a (freshly accumulating) state. */
|
|
201
|
+
contribute(s, row) {
|
|
202
|
+
s.count++;
|
|
203
|
+
if (this.field === void 0) return;
|
|
204
|
+
const v = this.#read(row);
|
|
205
|
+
if (v === null) return;
|
|
206
|
+
s.nonNull++;
|
|
207
|
+
switch (this.fn) {
|
|
208
|
+
case "sum":
|
|
209
|
+
case "avg":
|
|
210
|
+
assert(typeof v === "number", () => `Aggregate: ${this.fn} needs a number`);
|
|
211
|
+
s.sum += v;
|
|
212
|
+
break;
|
|
213
|
+
case "min":
|
|
214
|
+
case "max": if (s.extreme === null || this.#beats(v, s.extreme)) s.extreme = v;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** Invertible delta for count/sum/avg. */
|
|
218
|
+
applyInvertible(state, row, sign, fieldOnly = false) {
|
|
219
|
+
if (!fieldOnly) state.count += sign;
|
|
220
|
+
if (this.field !== void 0) {
|
|
221
|
+
const v = this.#read(row);
|
|
222
|
+
if (v !== null) {
|
|
223
|
+
assert(typeof v === "number", () => `Aggregate: ${this.fn}(${this.field}) requires a number`);
|
|
224
|
+
state.sum += sign * v;
|
|
225
|
+
state.nonNull += sign;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* min/max maintenance, applied to `state` in place. Cheap for adds and for
|
|
231
|
+
* removing a non-extreme value. Returns false when the current extreme is
|
|
232
|
+
* removed or edited away: the new extreme is not recoverable from running
|
|
233
|
+
* state, so the group has to be re-fetched.
|
|
234
|
+
*/
|
|
235
|
+
pushExtreme(state, change) {
|
|
236
|
+
switch (change[0]) {
|
|
237
|
+
case 0:
|
|
238
|
+
this.contribute(state, change[1].row);
|
|
239
|
+
return true;
|
|
240
|
+
case 1: {
|
|
241
|
+
const v = this.#read(change[1].row);
|
|
242
|
+
state.count--;
|
|
243
|
+
if (v === null) return true;
|
|
244
|
+
if (state.extreme !== null && compareAggregateValues(v, state.extreme) === 0) return false;
|
|
245
|
+
state.nonNull--;
|
|
246
|
+
return true;
|
|
247
|
+
}
|
|
248
|
+
case 2: return this.sameValue(change[2].row, change[1].row);
|
|
249
|
+
case 3: return true;
|
|
250
|
+
default: unreachable(change);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Whether a group's row changes from `stored` to `state`: its value, or, for
|
|
255
|
+
* sum/avg, the components even when the value doesn't (e.g. adding a 0 to a
|
|
256
|
+
* sum, or a row equal to the average), so the synced client's
|
|
257
|
+
* optimistic-delta base stays in sync.
|
|
258
|
+
*/
|
|
259
|
+
changed(stored, state) {
|
|
260
|
+
return this.value(stored) !== this.value(state) || carriesComponents(this.fn) && (stored.sum !== state.sum || stored.nonNull !== state.nonNull);
|
|
261
|
+
}
|
|
262
|
+
/** Writes the result, and for sum/avg its components, into `row`. */
|
|
263
|
+
writePayload(row, state) {
|
|
264
|
+
row[AGGREGATE_VALUE_COLUMN] = this.value(state);
|
|
265
|
+
if (carriesComponents(this.fn)) {
|
|
266
|
+
row[AGGREGATE_SUM_COLUMN] = state.sum;
|
|
267
|
+
row[AGGREGATE_COUNT_COLUMN] = state.nonNull;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Aggregate is a reducing operator for `count(*)` / `sum` / `avg` / `min` /
|
|
273
|
+
* `max` over a correlated relationship.
|
|
274
|
+
*
|
|
275
|
+
* It sits at the end of a related-subquery pipeline (where a normal `related`
|
|
276
|
+
* would emit child rows) and collapses the child rows for each parent into a
|
|
277
|
+
* *single* synthetic row `{ ...groupKey, value }`. Carrying the group key keeps
|
|
278
|
+
* the {@link Join} unchanged — it routes child changes by childField.
|
|
279
|
+
*
|
|
280
|
+
* Two maintenance strategies share the same fetch/emit machinery:
|
|
281
|
+
*
|
|
282
|
+
* - **Invertible** (count/sum/avg): add/remove/edit adjust running numbers in
|
|
283
|
+
* O(1); no re-fetch.
|
|
284
|
+
* - **Non-invertible** (min/max): add and removing a non-extreme value are
|
|
285
|
+
* O(1), but removing (or editing away) the current extreme is not
|
|
286
|
+
* invertible — the new extreme is unknown. In that case the group is marked
|
|
287
|
+
* dirty and re-fetched from the source in {@link reconcile}, as {@link Take}
|
|
288
|
+
* refills a partition. Re-fetching during the push itself could read
|
|
289
|
+
* operators upstream (e.g. an `EXISTS` under an `OR`) before they have
|
|
290
|
+
* settled the rest of the change.
|
|
291
|
+
*
|
|
292
|
+
* Null/empty semantics match SQL: every function except `count(*)` ignores null
|
|
293
|
+
* field values and is NULL for an empty (or all-null) group; `count(*)` counts
|
|
294
|
+
* all rows (0 when empty). An EDIT is emitted only when the derived value
|
|
295
|
+
* actually changes.
|
|
296
|
+
*/
|
|
297
|
+
var Aggregate = class {
|
|
298
|
+
#input;
|
|
299
|
+
#storage;
|
|
300
|
+
#groupKey;
|
|
301
|
+
#reducer;
|
|
302
|
+
#schema;
|
|
303
|
+
#countSource;
|
|
304
|
+
#output = throwOutput;
|
|
305
|
+
/**
|
|
306
|
+
* min/max groups whose extreme a push removed, by storage key, to recompute
|
|
307
|
+
* in {@link reconcile}. Until then their storage keeps the state last sent
|
|
308
|
+
* downstream, which a fetch keeps returning.
|
|
309
|
+
*/
|
|
310
|
+
#dirtyGroups = /* @__PURE__ */ new Map();
|
|
311
|
+
constructor(input, storage, groupKey, fn, field, tableName, countSource, path) {
|
|
312
|
+
this.#reducer = new Reducer(fn, field, path);
|
|
313
|
+
this.#input = input;
|
|
314
|
+
this.#storage = storage;
|
|
315
|
+
this.#groupKey = groupKey;
|
|
316
|
+
this.#countSource = fn === "count" ? countSource : void 0;
|
|
317
|
+
input.setOutput(this);
|
|
318
|
+
const inputSchema = input.getSchema();
|
|
319
|
+
const { columns, primaryKey: keyColumns } = aggregateSourceSchema(inputSchema.columns, groupKey, fn, field, path);
|
|
320
|
+
const sort = keyColumns.map((col) => [col, "asc"]);
|
|
321
|
+
this.#schema = {
|
|
322
|
+
tableName: tableName ?? inputSchema.tableName,
|
|
323
|
+
columns,
|
|
324
|
+
primaryKey: keyColumns,
|
|
325
|
+
relationships: {},
|
|
326
|
+
isHidden: false,
|
|
327
|
+
isAggregate: true,
|
|
328
|
+
system: inputSchema.system,
|
|
329
|
+
sort,
|
|
330
|
+
compareRows: makeComparator(sort)
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
setOutput(output) {
|
|
334
|
+
this.#output = output;
|
|
335
|
+
}
|
|
336
|
+
getSchema() {
|
|
337
|
+
return this.#schema;
|
|
338
|
+
}
|
|
339
|
+
destroy() {
|
|
340
|
+
this.#input.destroy();
|
|
341
|
+
this.#storage.destroy();
|
|
342
|
+
}
|
|
343
|
+
/** Recompute the whole group state from the source (already up to date). */
|
|
344
|
+
*#compute(constraint) {
|
|
345
|
+
const s = this.#reducer.empty();
|
|
346
|
+
const count = this.#countSource?.count?.(constraint);
|
|
347
|
+
if (count !== void 0) {
|
|
348
|
+
s.count = count;
|
|
349
|
+
return s;
|
|
350
|
+
}
|
|
351
|
+
for (const node of this.#input.fetch({ constraint })) {
|
|
352
|
+
if (node === "yield") {
|
|
353
|
+
yield node;
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
this.#reducer.contribute(s, node.row);
|
|
357
|
+
}
|
|
358
|
+
return s;
|
|
359
|
+
}
|
|
360
|
+
*fetch(req) {
|
|
361
|
+
const groupValues = this.#groupValuesFromConstraint(req.constraint);
|
|
362
|
+
const key = stateKey(groupValues);
|
|
363
|
+
let state = this.#storage.get(key);
|
|
364
|
+
if (state === void 0) {
|
|
365
|
+
state = yield* this.#compute(req.constraint);
|
|
366
|
+
this.#storage.set(key, state);
|
|
367
|
+
}
|
|
368
|
+
yield this.#makeNode(groupValues, state);
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Phase 2 of the two-phase push: recompute the min/max groups whose extreme
|
|
372
|
+
* Phase 1 removed, now that everything upstream has settled, then forward the
|
|
373
|
+
* signal for bounded operators downstream.
|
|
374
|
+
*/
|
|
375
|
+
*reconcile(_pusher) {
|
|
376
|
+
if (this.#dirtyGroups.size > 0) {
|
|
377
|
+
const dirty = [...this.#dirtyGroups];
|
|
378
|
+
this.#dirtyGroups.clear();
|
|
379
|
+
for (const [key, groupValues] of dirty) {
|
|
380
|
+
const stored = must(this.#storage.get(key));
|
|
381
|
+
const state = yield* this.#compute(this.#constraintFromGroup(groupValues));
|
|
382
|
+
this.#storage.set(key, state);
|
|
383
|
+
yield* this.#emitIfChanged(groupValues, stored, state);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
if (this.#output.reconcile) yield* this.#output.reconcile(this);
|
|
387
|
+
}
|
|
388
|
+
*push(change) {
|
|
389
|
+
const groupValues = this.#groupValuesFromRow(change[1].row);
|
|
390
|
+
const key = stateKey(groupValues);
|
|
391
|
+
const stored = this.#storage.get(key);
|
|
392
|
+
if (stored === void 0) return;
|
|
393
|
+
const state = { ...stored };
|
|
394
|
+
const reducer = this.#reducer;
|
|
395
|
+
if (isInvertible(reducer.fn)) switch (change[0]) {
|
|
396
|
+
case 0:
|
|
397
|
+
reducer.applyInvertible(state, change[1].row, 1);
|
|
398
|
+
break;
|
|
399
|
+
case 1:
|
|
400
|
+
reducer.applyInvertible(state, change[1].row, -1);
|
|
401
|
+
break;
|
|
402
|
+
case 2:
|
|
403
|
+
if (reducer.sameValue(change[2].row, change[1].row)) return;
|
|
404
|
+
reducer.applyInvertible(state, change[2].row, -1, true);
|
|
405
|
+
reducer.applyInvertible(state, change[1].row, 1, true);
|
|
406
|
+
break;
|
|
407
|
+
case 3: return;
|
|
408
|
+
default: unreachable(change);
|
|
409
|
+
}
|
|
410
|
+
else if (this.#dirtyGroups.has(key) || !reducer.pushExtreme(state, change)) {
|
|
411
|
+
this.#dirtyGroups.set(key, groupValues);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
assert(state.count >= 0, "Aggregate: removed a row from an empty group");
|
|
415
|
+
this.#storage.set(key, state);
|
|
416
|
+
yield* this.#emitIfChanged(groupValues, stored, state);
|
|
417
|
+
}
|
|
418
|
+
/** Sends downstream the move of a group from `stored` to `state`, if any. */
|
|
419
|
+
*#emitIfChanged(groupValues, stored, state) {
|
|
420
|
+
if (this.#reducer.changed(stored, state)) yield* this.#output.push(makeEditChange(this.#makeNode(groupValues, state), this.#makeNode(groupValues, stored)), this);
|
|
421
|
+
}
|
|
422
|
+
#makeNode(groupValues, state) {
|
|
423
|
+
const row = {};
|
|
424
|
+
for (let i = 0; i < this.#groupKey.length; i++) assignProperty(row, this.#groupKey[i], groupValues[i]);
|
|
425
|
+
if (this.#groupKey.length === 0) row[AGGREGATE_KEY_COLUMN] = AGGREGATE_KEY_VALUE;
|
|
426
|
+
this.#reducer.writePayload(row, state);
|
|
427
|
+
return {
|
|
428
|
+
row,
|
|
429
|
+
relationships: {}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
#constraintFromGroup(groupValues) {
|
|
433
|
+
const constraint = {};
|
|
434
|
+
for (let i = 0; i < this.#groupKey.length; i++) assignProperty(constraint, this.#groupKey[i], groupValues[i]);
|
|
435
|
+
return constraint;
|
|
436
|
+
}
|
|
437
|
+
#groupValuesFromConstraint(constraint) {
|
|
438
|
+
if (this.#groupKey.length === 0) return [];
|
|
439
|
+
assert(constraint, "Aggregate requires a constraint on the group key (relationship aggregate only)");
|
|
440
|
+
return this.#groupKey.map((col) => {
|
|
441
|
+
assert(Object.hasOwn(constraint, col), () => `Aggregate: constraint missing group key column "${col}"`);
|
|
442
|
+
return normalizeUndefined(constraint[col]);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
#groupValuesFromRow(row) {
|
|
446
|
+
return this.#groupKey.map((col) => normalizeUndefined(row[col]));
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
/**
|
|
450
|
+
* Orders the values a min/max reduces. A JSON path's leaves can be numbers or
|
|
451
|
+
* strings, decided per value; numbers order before strings, as in JS and
|
|
452
|
+
* SQLite (z2s compiles the same rule rather than Postgres's jsonb ordering,
|
|
453
|
+
* which puts strings first). Otherwise it is {@link compareValues}.
|
|
454
|
+
*/
|
|
455
|
+
function compareAggregateValues(a, b) {
|
|
456
|
+
if (a !== null && b !== null && typeof a !== typeof b && (typeof a === "number" || typeof a === "string") && (typeof b === "number" || typeof b === "string")) return typeof a === "number" ? -1 : 1;
|
|
457
|
+
return compareValues(a, b);
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* The storage key of a group's state. A relationship is usually correlated on
|
|
461
|
+
* one column, which gets the cheaper single-value encoding Take and Cap use;
|
|
462
|
+
* an operator's group key has a fixed length, so the two forms never meet.
|
|
463
|
+
*/
|
|
464
|
+
function stateKey(groupValues) {
|
|
465
|
+
return groupValues.length === 1 ? valueToKey(groupValues[0]) : JSON.stringify(groupValues);
|
|
466
|
+
}
|
|
467
|
+
//#endregion
|
|
468
|
+
export { AGGREGATE_COUNT_COLUMN, AGGREGATE_KEY_COLUMN, AGGREGATE_PAYLOAD_COLUMNS, AGGREGATE_ROWS_COLUMN, AGGREGATE_SUM_COLUMN, AGGREGATE_VALUE_COLUMN, Aggregate, Reducer, aggregateSourceSchema, assertNotSyntheticColumn, carriesComponents, isInvertible, isSyntheticColumn };
|
|
469
|
+
|
|
470
|
+
//# sourceMappingURL=aggregate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aggregate.js","names":[],"sources":["../../../../../zql/src/ivm/aggregate.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport {\n aggregateValue,\n type AggregateFunction,\n type Ordering,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue} from '../../../zero-types/src/schema-value.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeEditChange, type Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {\n compareValues,\n makeComparator,\n normalizeUndefined,\n valueToKey,\n type Node,\n type NormalizedValue,\n} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {SourceInput} from './source.ts';\nimport {type Stream} from './stream.ts';\n\n/**\n * The name of the synthetic column that holds the aggregate result in the rows\n * this operator emits. The value is projected to a bare scalar in the view, so\n * this name is internal.\n *\n * The synthetic columns share the emitted row with the group key, whose names\n * come from the user's schema, so they use the reserved `_0_` prefix (as\n * `_0_version` does) rather than plain words a schema could also use.\n */\nexport const AGGREGATE_VALUE_COLUMN = '_0_value';\n\n/**\n * A top-level (ungrouped) aggregate has no group key, but the synced path keys\n * every row in the CVR and forbids empty row keys (see zero-cache\n * `types/row-key.ts`). Since there is no group key, the single global row is\n * given one synthetic, constant-valued key column so it still has a (non-empty)\n * primary key. The materialized-view path ignores it (it projects only\n * `AGGREGATE_VALUE_COLUMN`), so this name is internal.\n *\n * The row holds nothing but this column and the payload columns, so any name\n * other than theirs (and `_0_version`) is collision-free. It must not be empty:\n * a SQLite-backed source cannot declare a zero-length column name.\n */\nexport const AGGREGATE_KEY_COLUMN = '_0_key';\n\n/** The constant value of {@link AGGREGATE_KEY_COLUMN} (one global row). */\nconst AGGREGATE_KEY_VALUE = 0;\n\n/**\n * `sum` and `avg` additionally carry their running components so the synced\n * client can adjust them optimistically: you can't move an average from the\n * final value alone, and a sum's value alone can't tell an empty group (`null`)\n * from one summing to 0. The value column stays the result (for display); these are the\n * sum of non-null field values and the count of non-null contributors.\n */\nexport const AGGREGATE_SUM_COLUMN = '_0_sum';\nexport const AGGREGATE_COUNT_COLUMN = '_0_count';\n\n/**\n * A grouped `sum`/`avg` row also carries its group's number of rows, nulls\n * included, which neither component gives: the synced client adds a group with\n * its first row and removes it with its last, as it does a count's.\n */\nexport const AGGREGATE_ROWS_COLUMN = '_0_rows';\n\n/**\n * Whether `col` is the name of a synthetic column of an aggregate or grouped\n * row: `_0_key` or a payload column.\n */\nexport function isSyntheticColumn(col: string): boolean {\n return col === AGGREGATE_KEY_COLUMN || AGGREGATE_PAYLOAD_COLUMNS.has(col);\n}\n\n/**\n * Asserts that the group key column `col` of an aggregate, or a column of a\n * grouped query, is not a synthetic column. The synthetic columns are written over\n * the group's columns in the emitted row, the payload is stripped from it by\n * the client's row key and `_0_key` alone keys a row that has it, so a\n * collision would silently merge or corrupt the groups. Their reserved `_0_`\n * prefix keeps real schemas clear of this; the check guards the invariant.\n */\nexport function assertNotSyntheticColumn(col: string): void {\n assert(\n !isSyntheticColumn(col),\n () =>\n `Aggregate: group key column \"${col}\" collides with the synthetic ` +\n `aggregate column of the same name`,\n );\n}\n\n/** Whether `fn`'s rows carry the sum and count components. */\nexport function carriesComponents(fn: AggregateFunction): boolean {\n return fn === 'sum' || fn === 'avg';\n}\n\n/** The synthetic payload columns (not part of an aggregate row's key). */\nexport const AGGREGATE_PAYLOAD_COLUMNS: ReadonlySet<string> = new Set([\n AGGREGATE_VALUE_COLUMN,\n AGGREGATE_SUM_COLUMN,\n AGGREGATE_COUNT_COLUMN,\n AGGREGATE_ROWS_COLUMN,\n]);\n\n/**\n * The type of the synthetic value column for an aggregate result: `count` is a\n * non-null number; `sum`/`avg` are nullable numbers; `min`/`max` take the\n * field's own type (`json` for a JSON path, whose leaf can be a number or a\n * string) and are nullable (empty group).\n */\nfunction aggregateValueColumn(\n fn: AggregateFunction,\n field: string | undefined,\n inputColumns: Record<string, SchemaValue>,\n path: readonly (string | number)[] | undefined,\n): SchemaValue {\n switch (fn) {\n case 'count':\n return {type: 'number'};\n case 'sum':\n case 'avg':\n return {type: 'number', optional: true};\n case 'min':\n case 'max': {\n if (path !== undefined) {\n // A JSON leaf: a number or a string, decided per value.\n return {type: 'json', optional: true};\n }\n const fieldSchema = inputColumns[must(field)];\n assert(fieldSchema, () => `Aggregate: ${fn} field \"${field}\" missing`);\n return {...fieldSchema, optional: true};\n }\n default:\n unreachable(fn);\n }\n}\n\n/**\n * The synthetic schema (columns + primary key) an aggregate produces, derived\n * from the *input* columns (the rows being aggregated), the group key, and the\n * fn/field. Shared by the {@link Aggregate} operator (compute mode) and the\n * client query builder (`aggregatesFromSource` mode) so both agree on the\n * synthetic source's shape. For a top-level (empty group key) aggregate the\n * single synthetic key column is added; otherwise the group key is the key.\n */\nexport function aggregateSourceSchema(\n inputColumns: Record<string, SchemaValue>,\n groupKey: readonly string[],\n fn: AggregateFunction,\n field: string | undefined,\n path?: readonly (string | number)[] | undefined,\n): {columns: Record<string, SchemaValue>; primaryKey: readonly string[]} {\n const columns: Record<string, SchemaValue> = {};\n for (const col of groupKey) {\n assertNotSyntheticColumn(col);\n const colSchema = inputColumns[col];\n assert(colSchema, () => `Aggregate: group key column \"${col}\" missing`);\n assignProperty(columns, col, colSchema);\n }\n const keyColumns = groupKey.length > 0 ? groupKey : [AGGREGATE_KEY_COLUMN];\n if (groupKey.length === 0) {\n columns[AGGREGATE_KEY_COLUMN] = {type: 'number'};\n }\n columns[AGGREGATE_VALUE_COLUMN] = aggregateValueColumn(\n fn,\n field,\n inputColumns,\n path,\n );\n if (carriesComponents(fn)) {\n // Components for optimistic adjustment on the synced client.\n columns[AGGREGATE_SUM_COLUMN] = {type: 'number'};\n columns[AGGREGATE_COUNT_COLUMN] = {type: 'number'};\n }\n return {columns, primaryKey: keyColumns};\n}\n\n/**\n * Per-group running state. We keep enough to derive any supported function:\n * - `count` → count(*) (all rows)\n * - `sum` → sum of non-null (NULL when nonNull === 0)\n * - `avg` → sum / nonNull (NULL when nonNull === 0)\n * - `min`/`max`→ extreme of non-null (NULL when nonNull === 0)\n */\nexport type AggState = {\n count: number;\n sum: number;\n nonNull: number;\n /** Current min/max of the non-null field values (null when nonNull === 0). */\n extreme: NormalizedValue;\n};\n\n/**\n * Typed view of the operator's {@link Storage} (mirrors Take): a group's state\n * by its key. Shared with `GroupBy`.\n */\nexport interface AggStorage {\n get(key: string): AggState | undefined;\n set(key: string, value: AggState): void;\n del(key: string): void;\n destroy(): void;\n}\n\n/**\n * Whether a change to one input row maps to a fixed delta of the aggregate\n * (`count`/`sum`/`avg`). Shared with the synced client, which only applies\n * optimistic deltas to these functions.\n */\nexport const isInvertible = (fn: AggregateFunction) =>\n fn === 'count' || fn === 'sum' || fn === 'avg';\n\n/**\n * How an aggregate function reduces a group's rows into an {@link AggState},\n * and reads its result back. Shared by {@link Aggregate}, which keeps a state\n * per parent of a relationship, and `GroupBy`, which keeps one per group.\n */\nexport class Reducer {\n readonly fn: AggregateFunction;\n readonly field: string | undefined;\n /** A JSON path into `field` (see `Aggregate.path`). */\n readonly path: readonly (string | number)[] | undefined;\n\n constructor(\n fn: AggregateFunction,\n field: string | undefined,\n path: readonly (string | number)[] | undefined,\n ) {\n assert(\n fn === 'count' ? field === undefined : field !== undefined,\n () =>\n `Aggregate: ${fn} ${fn === 'count' ? 'takes no' : 'requires a'} field`,\n );\n assert(\n path === undefined || field !== undefined,\n 'Aggregate: a JSON path requires a field',\n );\n this.fn = fn;\n this.field = field;\n this.path = path;\n }\n\n /** The state of a group with no rows. */\n empty(): AggState {\n return {count: 0, sum: 0, nonNull: 0, extreme: null};\n }\n\n /** The scalar result for a state, per the aggregate function. */\n value(s: AggState): Value {\n switch (this.fn) {\n case 'count':\n return s.count;\n case 'sum':\n return s.nonNull === 0 ? null : s.sum;\n case 'avg':\n return s.nonNull === 0 ? null : s.sum / s.nonNull;\n case 'min':\n case 'max':\n return s.extreme; // null when nonNull === 0\n default:\n unreachable(this.fn);\n }\n }\n\n /** Whether `v` should replace the current extreme for a min/max. */\n #beats(v: NormalizedValue, current: NormalizedValue): boolean {\n const c = compareAggregateValues(v, current);\n return this.fn === 'max' ? c > 0 : c < 0;\n }\n\n /**\n * The value `row` contributes: its field, or the JSON leaf at the path (see\n * `aggregateValue`), `null` when it contributes nothing.\n */\n #read(row: Row): NormalizedValue {\n const field = must(this.field);\n return normalizeUndefined(\n this.path === undefined\n ? row[field]\n : (aggregateValue({fn: this.fn, field, path: this.path}, row) as Value),\n );\n }\n\n /** Whether an edit from `oldRow` to `newRow` leaves the value it reduces. */\n sameValue(oldRow: Row, newRow: Row): boolean {\n return (\n this.field === undefined ||\n compareAggregateValues(this.#read(oldRow), this.#read(newRow)) === 0\n );\n }\n\n /** Add one row's contribution to a (freshly accumulating) state. */\n contribute(s: AggState, row: Row): void {\n s.count++;\n if (this.field === undefined) {\n return;\n }\n const v = this.#read(row);\n if (v === null) {\n return;\n }\n s.nonNull++;\n switch (this.fn) {\n case 'sum':\n case 'avg':\n assert(\n typeof v === 'number',\n () => `Aggregate: ${this.fn} needs a number`,\n );\n s.sum += v;\n break;\n case 'min':\n case 'max':\n if (s.extreme === null || this.#beats(v, s.extreme)) {\n s.extreme = v;\n }\n break;\n default:\n break;\n }\n }\n\n /** Invertible delta for count/sum/avg. */\n applyInvertible(\n state: AggState,\n row: Row,\n sign: 1 | -1,\n fieldOnly = false,\n ): void {\n if (!fieldOnly) {\n state.count += sign;\n }\n if (this.field !== undefined) {\n const v = this.#read(row);\n if (v !== null) {\n assert(\n typeof v === 'number',\n () => `Aggregate: ${this.fn}(${this.field}) requires a number`,\n );\n state.sum += sign * v;\n state.nonNull += sign;\n }\n }\n }\n\n /**\n * min/max maintenance, applied to `state` in place. Cheap for adds and for\n * removing a non-extreme value. Returns false when the current extreme is\n * removed or edited away: the new extreme is not recoverable from running\n * state, so the group has to be re-fetched.\n */\n pushExtreme(state: AggState, change: Change): boolean {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n // Adding can only extend the extreme outward — O(1).\n this.contribute(state, change[ChangeIndex.NODE].row);\n return true;\n case ChangeType.REMOVE: {\n const v = this.#read(change[ChangeIndex.NODE].row);\n state.count--;\n if (v === null) {\n return true; // null never contributed to the extreme\n }\n if (\n state.extreme !== null &&\n compareAggregateValues(v, state.extreme) === 0\n ) {\n return false; // removed (one of) the extreme\n }\n state.nonNull--; // a non-extreme value left; extreme unchanged\n return true;\n }\n case ChangeType.EDIT:\n // When the field moved, the extreme may have changed in either\n // direction.\n return this.sameValue(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n );\n case ChangeType.CHILD:\n return true;\n default:\n unreachable(change);\n }\n }\n\n /**\n * Whether a group's row changes from `stored` to `state`: its value, or, for\n * sum/avg, the components even when the value doesn't (e.g. adding a 0 to a\n * sum, or a row equal to the average), so the synced client's\n * optimistic-delta base stays in sync.\n */\n changed(stored: AggState, state: AggState): boolean {\n return (\n this.value(stored) !== this.value(state) ||\n (carriesComponents(this.fn) &&\n (stored.sum !== state.sum || stored.nonNull !== state.nonNull))\n );\n }\n\n /** Writes the result, and for sum/avg its components, into `row`. */\n writePayload(row: Record<string, Value>, state: AggState): void {\n row[AGGREGATE_VALUE_COLUMN] = this.value(state);\n if (carriesComponents(this.fn)) {\n // Carry the running components so the synced client can adjust them.\n row[AGGREGATE_SUM_COLUMN] = state.sum;\n row[AGGREGATE_COUNT_COLUMN] = state.nonNull;\n }\n }\n}\n\n/**\n * Aggregate is a reducing operator for `count(*)` / `sum` / `avg` / `min` /\n * `max` over a correlated relationship.\n *\n * It sits at the end of a related-subquery pipeline (where a normal `related`\n * would emit child rows) and collapses the child rows for each parent into a\n * *single* synthetic row `{ ...groupKey, value }`. Carrying the group key keeps\n * the {@link Join} unchanged — it routes child changes by childField.\n *\n * Two maintenance strategies share the same fetch/emit machinery:\n *\n * - **Invertible** (count/sum/avg): add/remove/edit adjust running numbers in\n * O(1); no re-fetch.\n * - **Non-invertible** (min/max): add and removing a non-extreme value are\n * O(1), but removing (or editing away) the current extreme is not\n * invertible — the new extreme is unknown. In that case the group is marked\n * dirty and re-fetched from the source in {@link reconcile}, as {@link Take}\n * refills a partition. Re-fetching during the push itself could read\n * operators upstream (e.g. an `EXISTS` under an `OR`) before they have\n * settled the rest of the change.\n *\n * Null/empty semantics match SQL: every function except `count(*)` ignores null\n * field values and is NULL for an empty (or all-null) group; `count(*)` counts\n * all rows (0 when empty). An EDIT is emitted only when the derived value\n * actually changes.\n */\nexport class Aggregate implements Operator {\n readonly #input: Input;\n readonly #storage: AggStorage;\n // Empty for a top-level (ungrouped) aggregate — a single global group.\n readonly #groupKey: readonly string[];\n readonly #reducer: Reducer;\n readonly #schema: SourceSchema;\n // The source connection `input` reads straight from, when nothing between\n // them drops rows. A `count` asks it for the number instead of reading every\n // row (see #compute).\n readonly #countSource: SourceInput | undefined;\n\n #output: Output = throwOutput;\n\n /**\n * min/max groups whose extreme a push removed, by storage key, to recompute\n * in {@link reconcile}. Until then their storage keeps the state last sent\n * downstream, which a fetch keeps returning.\n */\n readonly #dirtyGroups = new Map<string, readonly NormalizedValue[]>();\n\n constructor(\n input: Input,\n storage: Storage,\n groupKey: readonly string[],\n fn: AggregateFunction,\n field?: string,\n tableName?: string,\n countSource?: SourceInput,\n path?: readonly (string | number)[],\n ) {\n this.#reducer = new Reducer(fn, field, path);\n this.#input = input;\n this.#storage = storage as AggStorage;\n this.#groupKey = groupKey;\n this.#countSource = fn === 'count' ? countSource : undefined;\n input.setOutput(this);\n\n const inputSchema = input.getSchema();\n // Top-level (ungrouped) aggregate synthesizes a single constant-valued key\n // column (so the one global row has a non-empty primary key, required by the\n // synced/CVR path); grouped/relationship aggregates use the group key. The\n // same derivation runs on the client (aggregatesFromSource), so the two\n // sides agree on the synthetic source shape.\n const {columns, primaryKey: keyColumns} = aggregateSourceSchema(\n inputSchema.columns,\n groupKey,\n fn,\n field,\n path,\n );\n\n // Exactly one row per key, so the key is the primary key and a valid\n // (stable) sort.\n const sort: Ordering = keyColumns.map(col => [col, 'asc'] as const);\n this.#schema = {\n // The synthetic rows are routed (e.g. by the view-syncer streamer) to a\n // synthetic table, distinct from the child table, so they are never\n // confused with real child rows.\n tableName: tableName ?? inputSchema.tableName,\n columns,\n // The group key (relationship aggregate) or the synthetic singleton key\n // (top-level aggregate) — one row per key in either case.\n primaryKey: keyColumns as unknown as PrimaryKey,\n relationships: {},\n isHidden: false,\n isAggregate: true,\n system: inputSchema.system,\n sort,\n compareRows: makeComparator(sort),\n };\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n destroy(): void {\n this.#input.destroy();\n this.#storage.destroy();\n }\n\n /** Recompute the whole group state from the source (already up to date). */\n *#compute(constraint: Constraint | undefined): Generator<'yield', AggState> {\n const s = this.#reducer.empty();\n const count = this.#countSource?.count?.(constraint);\n if (count !== undefined) {\n s.count = count;\n return s;\n }\n for (const node of this.#input.fetch({constraint})) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n this.#reducer.contribute(s, node.row);\n }\n return s;\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n const groupValues = this.#groupValuesFromConstraint(req.constraint);\n const key = stateKey(groupValues);\n\n let state = this.#storage.get(key);\n if (state === undefined) {\n state = yield* this.#compute(req.constraint);\n this.#storage.set(key, state);\n }\n\n yield this.#makeNode(groupValues, state);\n }\n\n /**\n * Phase 2 of the two-phase push: recompute the min/max groups whose extreme\n * Phase 1 removed, now that everything upstream has settled, then forward the\n * signal for bounded operators downstream.\n */\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#dirtyGroups.size > 0) {\n const dirty = [...this.#dirtyGroups];\n this.#dirtyGroups.clear();\n for (const [key, groupValues] of dirty) {\n const stored = must(this.#storage.get(key));\n const state = yield* this.#compute(\n this.#constraintFromGroup(groupValues),\n );\n this.#storage.set(key, state);\n yield* this.#emitIfChanged(groupValues, stored, state);\n }\n }\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n const groupValues = this.#groupValuesFromRow(change[ChangeIndex.NODE].row);\n const key = stateKey(groupValues);\n const stored = this.#storage.get(key);\n\n // If we have no state for this group, nothing downstream has materialized\n // it, so there is nothing to update. When it is later fetched, fetch()\n // computes the true state from the source (which has already applied this\n // change). Mirrors Take's no-state no-op.\n if (stored === undefined) {\n return;\n }\n\n const state: AggState = {...stored};\n\n const reducer = this.#reducer;\n if (isInvertible(reducer.fn)) {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n reducer.applyInvertible(state, change[ChangeIndex.NODE].row, 1);\n break;\n case ChangeType.REMOVE:\n reducer.applyInvertible(state, change[ChangeIndex.NODE].row, -1);\n break;\n case ChangeType.EDIT: {\n // Group key unchanged (Join guarantees it); only the field moves the\n // value. count(*) is unaffected, and so is a sum/avg whose field kept\n // its value: subtracting and re-adding it would only add rounding\n // error.\n if (\n reducer.sameValue(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n )\n ) {\n return;\n }\n // Remove the old contribution, add the new.\n reducer.applyInvertible(\n state,\n change[ChangeIndex.OLD_NODE].row,\n -1,\n true,\n );\n reducer.applyInvertible(state, change[ChangeIndex.NODE].row, 1, true);\n break;\n }\n case ChangeType.CHILD:\n return;\n default:\n unreachable(change);\n }\n } else {\n // min/max — non-invertible. A dirty group is recomputed from the source\n // in reconcile, which covers this change too.\n if (this.#dirtyGroups.has(key) || !reducer.pushExtreme(state, change)) {\n this.#dirtyGroups.set(key, groupValues);\n return;\n }\n }\n\n assert(state.count >= 0, 'Aggregate: removed a row from an empty group');\n this.#storage.set(key, state);\n yield* this.#emitIfChanged(groupValues, stored, state);\n }\n\n /** Sends downstream the move of a group from `stored` to `state`, if any. */\n *#emitIfChanged(\n groupValues: readonly NormalizedValue[],\n stored: AggState,\n state: AggState,\n ): Stream<'yield'> {\n if (this.#reducer.changed(stored, state)) {\n yield* this.#output.push(\n makeEditChange(\n this.#makeNode(groupValues, state),\n this.#makeNode(groupValues, stored),\n ),\n this,\n );\n }\n }\n\n #makeNode(groupValues: readonly NormalizedValue[], state: AggState): Node {\n const row: Record<string, Value> = {};\n for (let i = 0; i < this.#groupKey.length; i++) {\n assignProperty(row, this.#groupKey[i], groupValues[i]);\n }\n if (this.#groupKey.length === 0) {\n // Top-level (ungrouped): the single row carries the synthetic key column.\n row[AGGREGATE_KEY_COLUMN] = AGGREGATE_KEY_VALUE;\n }\n this.#reducer.writePayload(row, state);\n return {row, relationships: {}};\n }\n\n #constraintFromGroup(groupValues: readonly NormalizedValue[]): Constraint {\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < this.#groupKey.length; i++) {\n assignProperty(constraint, this.#groupKey[i], groupValues[i]);\n }\n return constraint;\n }\n\n #groupValuesFromConstraint(\n constraint: Constraint | undefined,\n ): NormalizedValue[] {\n if (this.#groupKey.length === 0) {\n return []; // top-level (ungrouped) — one global group, no constraint\n }\n assert(\n constraint,\n 'Aggregate requires a constraint on the group key (relationship aggregate only)',\n );\n return this.#groupKey.map(col => {\n assert(\n Object.hasOwn(constraint, col),\n () => `Aggregate: constraint missing group key column \"${col}\"`,\n );\n return normalizeUndefined(constraint[col]);\n });\n }\n\n #groupValuesFromRow(row: Row): NormalizedValue[] {\n return this.#groupKey.map(col => normalizeUndefined(row[col]));\n }\n}\n\n/**\n * Orders the values a min/max reduces. A JSON path's leaves can be numbers or\n * strings, decided per value; numbers order before strings, as in JS and\n * SQLite (z2s compiles the same rule rather than Postgres's jsonb ordering,\n * which puts strings first). Otherwise it is {@link compareValues}.\n */\nfunction compareAggregateValues(\n a: NormalizedValue,\n b: NormalizedValue,\n): number {\n if (\n a !== null &&\n b !== null &&\n typeof a !== typeof b &&\n (typeof a === 'number' || typeof a === 'string') &&\n (typeof b === 'number' || typeof b === 'string')\n ) {\n return typeof a === 'number' ? -1 : 1;\n }\n return compareValues(a, b);\n}\n\n/**\n * The storage key of a group's state. A relationship is usually correlated on\n * one column, which gets the cheaper single-value encoding Take and Cap use;\n * an operator's group key has a fixed length, so the two forms never meet.\n */\nfunction stateKey(groupValues: readonly NormalizedValue[]): string {\n return groupValues.length === 1\n ? valueToKey(groupValues[0])\n : JSON.stringify(groupValues);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,IAAa,yBAAyB;;;;;;;;;;;;;AActC,IAAa,uBAAuB;;AAGpC,IAAM,sBAAsB;;;;;;;;AAS5B,IAAa,uBAAuB;AACpC,IAAa,yBAAyB;;;;;;AAOtC,IAAa,wBAAwB;;;;;AAMrC,SAAgB,kBAAkB,KAAsB;CACtD,OAAO,QAAA,YAAgC,0BAA0B,IAAI,GAAG;AAC1E;;;;;;;;;AAUA,SAAgB,yBAAyB,KAAmB;CAC1D,OACE,CAAC,kBAAkB,GAAG,SAEpB,gCAAgC,IAAI,gEAExC;AACF;;AAGA,SAAgB,kBAAkB,IAAgC;CAChE,OAAO,OAAO,SAAS,OAAO;AAChC;;AAGA,IAAa,4CAAiD,IAAI,IAAI;CACpE;CACA;CACA;CACA;AACF,CAAC;;;;;;;AAQD,SAAS,qBACP,IACA,OACA,cACA,MACa;CACb,QAAQ,IAAR;EACE,KA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EAC3C,CAAC;CACH;CAEA,oBAAoB,KAA6B;EAC/C,OAAO,KAAK,UAAU,KAAI,QAAO,mBAAmB,IAAI,IAAI,CAAC;CAC/D;AACF;;;;;;;AAQA,SAAS,uBACP,GACA,GACQ;CACR,IACE,MAAM,QACN,MAAM,QACN,OAAO,MAAM,OAAO,MACnB,OAAO,MAAM,YAAY,OAAO,MAAM,cACtC,OAAO,MAAM,YAAY,OAAO,MAAM,WAEvC,OAAO,OAAO,MAAM,WAAW,KAAK;CAEtC,OAAO,cAAc,GAAG,CAAC;AAC3B;;;;;;AAOA,SAAS,SAAS,aAAiD;CACjE,OAAO,YAAY,WAAW,IAC1B,WAAW,YAAY,EAAE,IACzB,KAAK,UAAU,WAAW;AAChC"}
|
|
@@ -15,7 +15,7 @@ import type { Format, View } from './view.ts';
|
|
|
15
15
|
* Also the plain array view is more convenient for consumers since you can dump
|
|
16
16
|
* it into console to see what it is, rather than having to iterate it.
|
|
17
17
|
*/
|
|
18
|
-
export declare class ArrayView<V
|
|
18
|
+
export declare class ArrayView<V = View> implements Output, TypedView<V> {
|
|
19
19
|
#private;
|
|
20
20
|
onDestroy: (() => void) | undefined;
|
|
21
21
|
constructor(input: Input, format: Format, queryComplete: true | ErroredQuery | Promise<true>, updateTTL: (ttl: TTL) => void);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-view.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/array-view.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8CAA8C,CAAC;AAC/E,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,iBAAiB,CAAC;AACzC,OAAO,KAAK,EAAC,QAAQ,EAAc,SAAS,EAAC,MAAM,wBAAwB,CAAC;AAG5E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAAa,KAAK,KAAK,EAAE,KAAK,MAAM,EAAC,MAAM,eAAe,CAAC;
|
|
1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I,CAInB;CAkBF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert } from "../../../shared/src/asserts.js";
|
|
2
|
-
import { emptyArray } from "../../../shared/src/sentinels.js";
|
|
3
2
|
import { skipYields } from "./skip-yields.js";
|
|
4
|
-
import {
|
|
3
|
+
import { emptyArray } from "../../../shared/src/sentinels.js";
|
|
4
|
+
import { applyChange, emptyViewValue } from "./view-apply-change.js";
|
|
5
5
|
//#region ../zql/src/ivm/array-view.ts
|
|
6
6
|
function changeToViewChange(change) {
|
|
7
7
|
switch (change[0]) {
|
|
@@ -59,7 +59,7 @@ var ArrayView = class {
|
|
|
59
59
|
this.#input = input;
|
|
60
60
|
this.#format = format;
|
|
61
61
|
this.#updateTTL = updateTTL;
|
|
62
|
-
this.#root = { "": format
|
|
62
|
+
this.#root = { "": emptyViewValue(format) };
|
|
63
63
|
input.setOutput(this);
|
|
64
64
|
if (queryComplete === true) this.#resultType = "complete";
|
|
65
65
|
else if ("error" in queryComplete) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-view.js","names":[],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange, type ViewChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\nfunction changeToViewChange(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {type: 'add', node: change[ChangeIndex.NODE]};\n case ChangeType.REMOVE:\n return {type: 'remove', node: change[ChangeIndex.NODE]};\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: change[ChangeIndex.NODE],\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: changeToViewChange(change[ChangeIndex.CHILD_DATA].change),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: change[ChangeIndex.NODE],\n oldNode: change[ChangeIndex.OLD_NODE],\n };\n }\n}\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n // Read lazily: a DeferredInput has no schema until its pipeline is attached,\n // and the schema is only needed once there is a change to apply.\n #schema: SourceSchema | undefined;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n //\n // applyChange is immutable: it returns a new root, preserving the references\n // of unchanged subtrees so consumers (React.memo / Solid) can skip them. We\n // therefore reassign #root on every change rather than mutating in place.\n #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n // Set by holdData(): the root that `data` and newly added listeners keep\n // seeing until releaseData() or the next flush, while pushes build up #root\n // behind it.\n #committedRoot: Entry | undefined;\n // From holdData() until the next flush. Outlasts #committedRoot, which\n // releaseData() drops first.\n #held = false;\n // The result type and error as of holdData(): what a listener added while\n // held is called with, so it never sees old rows paired with a new type.\n #heldResultType: ResultType = 'unknown';\n #heldError: ErroredQuery | undefined;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n // Objects/arrays created or cloned during the current (un-flushed)\n // transaction. applyChange may mutate these in place rather than copying\n // again, since they are not yet observed by any listener. Replaced at\n // flush(), after which the committed snapshot must be copied-on-write again.\n // A WeakSet (not a Set) so it never extends the lifetime of transient clones.\n #txnDirty: WeakSet<object> = new WeakSet();\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => this.#setResultType('complete'))\n .catch(e => this.#setResultType('error', e));\n }\n this.#hydrate();\n }\n\n get data() {\n return (this.#committedRoot ?? this.#root)[''] as V;\n }\n\n #getSchema(): SourceSchema {\n return (this.#schema ??= this.#input.getSchema());\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n listener(...this.#listenerArgs());\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n // Read the snapshot once: a listener may push() synchronously, and the\n // listeners after it must not be handed the root that push is building,\n // which the rest of the transaction would then mutate in place.\n const args = this.#listenerArgs();\n for (const listener of this.#listeners) {\n listener(...args);\n }\n }\n\n #listenerArgs(): Parameters<Listener<V>> {\n if (this.#committedRoot !== undefined) {\n // Held rows go with the held type; after releaseData() both are current.\n return [this.data as Immutable<V>, this.#heldResultType, this.#heldError];\n }\n return [this.data as Immutable<V>, this.#resultType, this.#error];\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n this.#root = applyChange(\n this.#root,\n {type: 'add', node},\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n true /* mutate: #root is freshly created and not yet observed by any\n consumer, so build it in place to avoid O(N^2) array copies.\n Every later push() is immutable, preserving reference\n stability for unchanged subtrees. */,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n const newRoot = applyChange(\n this.#root,\n changeToViewChange(change),\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n this.#txnDirty /* mutate: copy-on-write within this transaction */,\n );\n // applyChange returns the same root when the change did not affect the\n // view — e.g. a child change for a relationship that is not in the format,\n // such as a whereExists subquery (zsubq_*). Only mark dirty when the root\n // actually changed so flush() does not notify listeners with identical\n // data. Within a transaction the root keeps its reference across a *real*\n // change only if an earlier change in the same transaction already cloned\n // it (copy-on-write) — and that earlier change set #dirty, so an unchanged\n // reference here never hides a real change.\n if (newRoot !== this.#root) {\n this.#root = newRoot;\n this.#dirty = true;\n }\n return emptyArray;\n }\n\n /**\n * Keep exposing the current snapshot, whatever is pushed in the meantime,\n * until {@link releaseData} or the next {@link flush}. Result type\n * notifications are held back until that flush.\n *\n * A transaction is normally one synchronous task, so nobody can look at a\n * view between its pushes and its flush. Deferred pipelines are different:\n * they are hydrated over several tasks and flushed together (see\n * `QueryDelegate.onPipelinesReady`), and a view that already has its rows\n * must not show them early.\n */\n holdData(): void {\n this.#committedRoot = this.#root;\n this.#held = true;\n this.#heldResultType = this.#resultType;\n this.#heldError = this.#error;\n }\n\n /**\n * Make `data` current again without notifying anyone yet; listeners are\n * still only called by the next {@link flush}. Views released together get\n * this called on all of them before any is flushed, so a listener of one\n * that reads another sees its rows too.\n */\n releaseData(): void {\n this.#committedRoot = undefined;\n }\n\n flush() {\n this.#committedRoot = undefined;\n this.#held = false;\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n // The snapshot about to be handed to listeners becomes observed; the next\n // transaction must copy-on-write rather than mutate these objects. A fresh\n // WeakSet drops all \"owned\" marks (WeakSet has no clear()).\n //\n // Reset BEFORE notifying: a listener may throw (swallowed by\n // ZeroContext#endTransaction) or re-enter push(). If the committed root\n // kept its \"owned\" marks, a later transaction would mutate it in place and\n // return an identical reference — which push() would read as \"no change\",\n // permanently silencing the view.\n this.#txnDirty = new WeakSet();\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n\n /**\n * The store holds the server-confirmed complete result of this query from a\n * previous sync (the persisted got-queries key exists, pre-authoritative).\n * Never downgrades 'complete'/'error', and never resolves anything that\n * waits on 'complete' — freshness stays a promise only the connection can\n * keep.\n */\n markCached(): void {\n if (this.#resultType === 'unknown') {\n this.#setResultType('cached');\n }\n }\n\n /** The got key was deleted (eviction) while still pre-authoritative. */\n unmarkCached(): void {\n if (this.#resultType === 'cached') {\n this.#setResultType('unknown');\n }\n }\n\n #setResultType(resultType: ResultType, error?: ErroredQuery) {\n this.#resultType = resultType;\n this.#error = error;\n // A dirty view is mid-transaction: rows were pushed and not yet flushed,\n // and the objects in #txnDirty are still mutable. Firing now would hand\n // those to listeners and then fire again at flush() with the same data, so\n // let the pending flush deliver the new result type instead.\n // A held view is waiting to be exposed together with others at the next\n // flush; that goes for its result type as much as for its rows.\n if (this.#held) {\n // Dirty so that the flush notifies even when no rows were pushed.\n this.#dirty = true;\n } else if (!this.#dirty) {\n this.#fireListeners();\n }\n }\n}\n"],"mappings":";;;;;AAcA,SAAS,mBAAmB,QAA4B;CACtD,QAAQ,OAAO,IAAf;EACE,KAAK,GACH,OAAO;GAAC,MAAM;GAAO,MAAM,OAAO;EAAiB;EACrD,KAAK,GACH,OAAO;GAAC,MAAM;GAAU,MAAM,OAAO;EAAiB;EACxD,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,OAAO;IACL,kBAAkB,OAAO,EAAuB,CAAC;IACjD,QAAQ,mBAAmB,OAAO,EAAuB,CAAC,MAAM;GAClE;EACF;EACF,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,SAAS,OAAO;EAClB;CACJ;AACF;;;;;;;;;;;;AAaA,IAAa,YAAb,MAAuE;CACrE;CACA,6BAAsB,IAAI,IAAiB;CAG3C;CACA;CAQA;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,CAAC,CAAC,GACjD,KAAK,QAAQ,YACX,KAAK,OACL;GAAC,MAAM;GAAO;EAAI,GAClB,KAAK,WAAW,GAChB,IACA,KAAK,SACL,OACA,IAIF;EAEF,KAAK,MAAM;CACb;CAEA,KAAK,QAAgB;EACnB,MAAM,UAAU,YACd,KAAK,OACL,mBAAmB,MAAM,GACzB,KAAK,WAAW,GAChB,IACA,KAAK,SACL,OACA,KAAK,SACP;EASA,IAAI,YAAY,KAAK,OAAO;GAC1B,KAAK,QAAQ;GACb,KAAK,SAAS;EAChB;EACA,OAAO;CACT;;;;;;;;;;;;CAaA,WAAiB;EACf,KAAK,iBAAiB,KAAK;EAC3B,KAAK,QAAQ;EACb,KAAK,kBAAkB,KAAK;EAC5B,KAAK,aAAa,KAAK;CACzB;;;;;;;CAQA,cAAoB;EAClB,KAAK,iBAAiB,KAAA;CACxB;CAEA,QAAQ;EACN,KAAK,iBAAiB,KAAA;EACtB,KAAK,QAAQ;EACb,IAAI,CAAC,KAAK,QACR;EAEF,KAAK,SAAS;EAUd,KAAK,4BAAY,IAAI,QAAQ;EAC7B,KAAK,eAAe;CACtB;CAEA,UAAU,KAAU;EAClB,KAAK,WAAW,GAAG;CACrB;;;;;;;;CASA,aAAmB;EACjB,IAAI,KAAK,gBAAgB,WACvB,KAAK,eAAe,QAAQ;CAEhC;;CAGA,eAAqB;EACnB,IAAI,KAAK,gBAAgB,UACvB,KAAK,eAAe,SAAS;CAEjC;CAEA,eAAe,YAAwB,OAAsB;EAC3D,KAAK,cAAc;EACnB,KAAK,SAAS;EAOd,IAAI,KAAK,OAEP,KAAK,SAAS;OACT,IAAI,CAAC,KAAK,QACf,KAAK,eAAe;CAExB;AACF"}
|
|
1
|
+
{"version":3,"file":"array-view.js","names":[],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {\n applyChange,\n emptyViewValue,\n type ViewChange,\n} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\nfunction changeToViewChange(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {type: 'add', node: change[ChangeIndex.NODE]};\n case ChangeType.REMOVE:\n return {type: 'remove', node: change[ChangeIndex.NODE]};\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: change[ChangeIndex.NODE],\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: changeToViewChange(change[ChangeIndex.CHILD_DATA].change),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: change[ChangeIndex.NODE],\n oldNode: change[ChangeIndex.OLD_NODE],\n };\n }\n}\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\n// `V` is unconstrained: besides a `View` it may be a scalar `Value` for a\n// top-level aggregate query, whose materialized result is the bare value.\nexport class ArrayView<V = View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n // Read lazily: a DeferredInput has no schema until its pipeline is attached,\n // and the schema is only needed once there is a change to apply.\n #schema: SourceSchema | undefined;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n //\n // applyChange is immutable: it returns a new root, preserving the references\n // of unchanged subtrees so consumers (React.memo / Solid) can skip them. We\n // therefore reassign #root on every change rather than mutating in place.\n #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n // Set by holdData(): the root that `data` and newly added listeners keep\n // seeing until releaseData() or the next flush, while pushes build up #root\n // behind it.\n #committedRoot: Entry | undefined;\n // From holdData() until the next flush. Outlasts #committedRoot, which\n // releaseData() drops first.\n #held = false;\n // The result type and error as of holdData(): what a listener added while\n // held is called with, so it never sees old rows paired with a new type.\n #heldResultType: ResultType = 'unknown';\n #heldError: ErroredQuery | undefined;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n // Objects/arrays created or cloned during the current (un-flushed)\n // transaction. applyChange may mutate these in place rather than copying\n // again, since they are not yet observed by any listener. Replaced at\n // flush(), after which the committed snapshot must be copied-on-write again.\n // A WeakSet (not a Set) so it never extends the lifetime of transient clones.\n #txnDirty: WeakSet<object> = new WeakSet();\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': emptyViewValue(format)};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => this.#setResultType('complete'))\n .catch(e => this.#setResultType('error', e));\n }\n this.#hydrate();\n }\n\n get data() {\n return (this.#committedRoot ?? this.#root)[''] as V;\n }\n\n #getSchema(): SourceSchema {\n return (this.#schema ??= this.#input.getSchema());\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n listener(...this.#listenerArgs());\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n // Read the snapshot once: a listener may push() synchronously, and the\n // listeners after it must not be handed the root that push is building,\n // which the rest of the transaction would then mutate in place.\n const args = this.#listenerArgs();\n for (const listener of this.#listeners) {\n listener(...args);\n }\n }\n\n #listenerArgs(): Parameters<Listener<V>> {\n if (this.#committedRoot !== undefined) {\n // Held rows go with the held type; after releaseData() both are current.\n return [this.data as Immutable<V>, this.#heldResultType, this.#heldError];\n }\n return [this.data as Immutable<V>, this.#resultType, this.#error];\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n this.#root = applyChange(\n this.#root,\n {type: 'add', node},\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n true /* mutate: #root is freshly created and not yet observed by any\n consumer, so build it in place to avoid O(N^2) array copies.\n Every later push() is immutable, preserving reference\n stability for unchanged subtrees. */,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n const newRoot = applyChange(\n this.#root,\n changeToViewChange(change),\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n this.#txnDirty /* mutate: copy-on-write within this transaction */,\n );\n // applyChange returns the same root when the change did not affect the\n // view — e.g. a child change for a relationship that is not in the format,\n // such as a whereExists subquery (zsubq_*). Only mark dirty when the root\n // actually changed so flush() does not notify listeners with identical\n // data. Within a transaction the root keeps its reference across a *real*\n // change only if an earlier change in the same transaction already cloned\n // it (copy-on-write) — and that earlier change set #dirty, so an unchanged\n // reference here never hides a real change.\n if (newRoot !== this.#root) {\n this.#root = newRoot;\n this.#dirty = true;\n }\n return emptyArray;\n }\n\n /**\n * Keep exposing the current snapshot, whatever is pushed in the meantime,\n * until {@link releaseData} or the next {@link flush}. Result type\n * notifications are held back until that flush.\n *\n * A transaction is normally one synchronous task, so nobody can look at a\n * view between its pushes and its flush. Deferred pipelines are different:\n * they are hydrated over several tasks and flushed together (see\n * `QueryDelegate.onPipelinesReady`), and a view that already has its rows\n * must not show them early.\n */\n holdData(): void {\n this.#committedRoot = this.#root;\n this.#held = true;\n this.#heldResultType = this.#resultType;\n this.#heldError = this.#error;\n }\n\n /**\n * Make `data` current again without notifying anyone yet; listeners are\n * still only called by the next {@link flush}. Views released together get\n * this called on all of them before any is flushed, so a listener of one\n * that reads another sees its rows too.\n */\n releaseData(): void {\n this.#committedRoot = undefined;\n }\n\n flush() {\n this.#committedRoot = undefined;\n this.#held = false;\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n // The snapshot about to be handed to listeners becomes observed; the next\n // transaction must copy-on-write rather than mutate these objects. A fresh\n // WeakSet drops all \"owned\" marks (WeakSet has no clear()).\n //\n // Reset BEFORE notifying: a listener may throw (swallowed by\n // ZeroContext#endTransaction) or re-enter push(). If the committed root\n // kept its \"owned\" marks, a later transaction would mutate it in place and\n // return an identical reference — which push() would read as \"no change\",\n // permanently silencing the view.\n this.#txnDirty = new WeakSet();\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n\n /**\n * The store holds the server-confirmed complete result of this query from a\n * previous sync (the persisted got-queries key exists, pre-authoritative).\n * Never downgrades 'complete'/'error', and never resolves anything that\n * waits on 'complete' — freshness stays a promise only the connection can\n * keep.\n */\n markCached(): void {\n if (this.#resultType === 'unknown') {\n this.#setResultType('cached');\n }\n }\n\n /** The got key was deleted (eviction) while still pre-authoritative. */\n unmarkCached(): void {\n if (this.#resultType === 'cached') {\n this.#setResultType('unknown');\n }\n }\n\n #setResultType(resultType: ResultType, error?: ErroredQuery) {\n this.#resultType = resultType;\n this.#error = error;\n // A dirty view is mid-transaction: rows were pushed and not yet flushed,\n // and the objects in #txnDirty are still mutable. Firing now would hand\n // those to listeners and then fire again at flush() with the same data, so\n // let the pending flush deliver the new result type instead.\n // A held view is waiting to be exposed together with others at the next\n // flush; that goes for its result type as much as for its rows.\n if (this.#held) {\n // Dirty so that the flush notifies even when no rows were pushed.\n this.#dirty = true;\n } else if (!this.#dirty) {\n this.#fireListeners();\n }\n }\n}\n"],"mappings":";;;;;A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