@rocicorp/zero 1.12.0-canary.4 → 1.12.0-canary.5
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/analyze-cli.d.ts.map +1 -1
- package/out/analyze-query/src/analyze-cli.js +2 -1
- package/out/analyze-query/src/analyze-cli.js.map +1 -1
- package/out/analyze-query/src/bin-transform.js +1 -1
- package/out/analyze-query/src/zql-chain.d.ts +23 -0
- package/out/analyze-query/src/zql-chain.d.ts.map +1 -0
- package/out/analyze-query/src/zql-chain.js +162 -0
- package/out/analyze-query/src/zql-chain.js.map +1 -0
- package/out/ast-to-zql/src/bin.js +1 -1
- package/out/zero/package.js +21 -22
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/load-permissions.js +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +1 -1
- package/out/zero-cache/src/scripts/decommission.js +1 -1
- package/out/zero-cache/src/scripts/deploy-permissions.js +1 -1
- package/out/zero-cache/src/server/change-streamer.js +1 -1
- package/out/zero-cache/src/server/replicator.js +1 -1
- package/out/zero-cache/src/server/syncer.js +3 -3
- package/out/zero-cache/src/services/analyze.js +2 -2
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-schema.js +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js +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/change-source-init.js +2 -2
- package/out/zero-cache/src/services/change-source/pg/change-source.js +2 -2
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +4 -4
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +2 -2
- 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/published.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-poller.js +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +2 -2
- package/out/zero-cache/src/services/change-streamer/storer.js +1 -1
- package/out/zero-cache/src/services/life-cycle.js +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +2 -2
- package/out/zero-cache/src/services/plannerz.js +2 -2
- package/out/zero-cache/src/services/replicator/change-log-db.js +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +3 -3
- package/out/zero-cache/src/services/replicator/schema/backfilling.js +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js +3 -3
- package/out/zero-cache/src/services/run-ast.js +1 -1
- package/out/zero-cache/src/services/statz.js +2 -2
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +5 -5
- package/out/zero-cache/src/services/view-syncer/row-record-cache.js +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 +6 -6
- package/out/zero-cache/src/types/profiler.js +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zql/src/ivm/cap.d.ts +1 -1
- package/out/zql/src/ivm/cap.d.ts.map +1 -1
- package/out/zql/src/ivm/cap.js +10 -0
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/data.d.ts +15 -1
- package/out/zql/src/ivm/data.d.ts.map +1 -1
- package/out/zql/src/ivm/data.js +15 -1
- package/out/zql/src/ivm/data.js.map +1 -1
- package/out/zql/src/ivm/exists.d.ts.map +1 -1
- package/out/zql/src/ivm/exists.js +12 -4
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts +5 -0
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/join.d.ts.map +1 -1
- package/out/zql/src/ivm/join.js +6 -3
- package/out/zql/src/ivm/join.js.map +1 -1
- package/out/zql/src/ivm/memory-source.js +1 -1
- package/out/zql/src/ivm/operator.d.ts +6 -0
- package/out/zql/src/ivm/operator.d.ts.map +1 -1
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/ivm/take.d.ts.map +1 -1
- package/out/zql/src/ivm/take.js +4 -3
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zqlite/src/table-source.js +1 -1
- package/package.json +21 -22
- package/out/analyze-query/src/bin-analyze.d.ts +0 -2
- package/out/analyze-query/src/bin-analyze.d.ts.map +0 -1
- package/out/analyze-query/src/bin-analyze.js +0 -285
- package/out/analyze-query/src/bin-analyze.js.map +0 -1
- package/out/zero/src/analyze-query.d.ts +0 -3
- package/out/zero/src/analyze-query.d.ts.map +0 -1
- package/out/zero/src/analyze-query.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cap.js","names":[],"sources":["../../../../../zql/src/ivm/cap.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, type Change, type EditChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport type {Comparator, Node} 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 Stream} from './stream.ts';\nimport {\n constraintMatchesPartitionKey,\n makePartitionKeyComparator,\n type PartitionKey,\n} from './take.ts';\n\ntype CapState = {\n size: number;\n pks: string[];\n};\n\ninterface CapStorage {\n get(key: string): CapState | undefined;\n set(key: string, value: CapState): void;\n del(key: string): void;\n destroy(): void;\n}\n\n/**\n * The Cap operator is a count-based limiter for EXISTS subqueries that\n * does not require ordering. Unlike Take, it tracks membership by primary\n * key set rather than by a sorted bound. This means:\n *\n * - No comparator needed (no ordering requirement)\n * - No `start` or `reverse` fetch support\n * - No `#rowHiddenFromFetch` complexity (we can defer when adding to the pk set)\n *\n * Cap is used in EXISTS child pipelines where only the count of matching\n * rows matters, not their order. This allows SQLite to skip ORDER BY\n * entirely, enabling much faster query plans.\n *\n * Cap can count rows globally or by unique value of some partition key\n * (same as Take).\n */\nexport class Cap implements Operator {\n readonly #input: Input;\n readonly #storage: CapStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n readonly #primaryKey: PrimaryKey;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as CapStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n this.#primaryKey = input.getSchema().primaryKey;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(!req.start, 'Cap does not support start');\n assert(!req.reverse, 'Cap does not support reverse');\n\n // Cap is only built for non-flipped EXISTS subqueries, whose only\n // downstream consumer is a Join that always fetches with a constraint\n // built from the correlation's childField — which is Cap's partition\n // key. So either partitionKey is undefined, or constraint matches.\n assert(\n !this.#partitionKey ||\n (req.constraint !== undefined &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey)),\n 'Cap fetch: constraint must match partition key when partitioned',\n );\n\n const capStateKey = getCapStateKey(this.#partitionKey, req.constraint);\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n yield* this.#initialFetch(req, capStateKey);\n return;\n }\n if (capState.size === 0) {\n return;\n }\n // PK-based point lookups: fetch each tracked row by its PK directly,\n // rather than scanning the partition and filtering.\n for (const pk of capState.pks) {\n const pkConstraint = deserializePKToConstraint(pk, this.#primaryKey);\n // Preserve req.constraint (the partition key) so upstream partitioned\n // operators (e.g. Take) retain their partition scope and do not throw.\n const constraint = req.constraint\n ? {...req.constraint, ...pkConstraint}\n : pkConstraint;\n for (const inputNode of this.#input.fetch({constraint})) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(\n req: FetchRequest,\n capStateKey: string,\n ): Stream<Node | 'yield'> {\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n // The caller (fetch) has already checked that there is no state for\n // capStateKey.\n\n let size = 0;\n const pks: string[] = [];\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n pks.push(serializePK(inputNode.row, this.#primaryKey));\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#storage.set(capStateKey, {size, pks});\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that capState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n yield* this.#pushEditChange(change);\n return;\n }\n\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return;\n }\n\n const pk = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (capState.size < this.#limit) {\n const pks = [...capState.pks, pk];\n this.#storage.set(capStateKey, {size: capState.size + 1, pks});\n yield* this.#output.push(change, this);\n return;\n }\n // Full — drop\n return;\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n const pkIndex = capState.pks.indexOf(pk);\n if (pkIndex === -1) {\n // Not in our set — drop\n return;\n }\n // Remove from set\n const pks = [...capState.pks];\n pks.splice(pkIndex, 1);\n const newSize = capState.size - 1;\n\n // Try to refill: fetch from input with partition constraint,\n // find first row NOT in PK set\n const pkSet = new Set(pks);\n const constraint = this.#partitionKey\n ? (Object.fromEntries(\n this.#partitionKey.map(\n key => [key, change[ChangeIndex.NODE].row[key]] as const,\n ),\n ) as Constraint)\n : undefined;\n\n let replacement: Node | undefined;\n for (const node of this.#input.fetch({constraint})) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const nodePK = serializePK(node.row, this.#primaryKey);\n if (!pkSet.has(nodePK)) {\n replacement = node;\n break;\n }\n }\n\n if (replacement) {\n // Store state WITHOUT replacement during remove forward,\n // matching Take's pattern of hiding in-flight changes from re-fetches.\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n // Now add replacement to set and forward the add.\n const replacementPK = serializePK(replacement.row, this.#primaryKey);\n pks.push(replacementPK);\n this.#storage.set(capStateKey, {size: newSize + 1, pks});\n yield* this.#output.push(makeAddChange(replacement), this);\n } else {\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n }\n } else if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n const pkSet = new Set(capState.pks);\n if (pkSet.has(pk)) {\n yield* this.#output.push(change, this);\n }\n }\n }\n\n #pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.OLD_NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return emptyArray;\n }\n\n const oldPK = serializePK(\n change[ChangeIndex.OLD_NODE].row,\n this.#primaryKey,\n );\n const pkSet = new Set(capState.pks);\n if (pkSet.has(oldPK)) {\n // Update the PK in our set if it changed\n const newPK = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n if (oldPK !== newPK) {\n const pks = capState.pks.map(p => (p === oldPK ? newPK : p));\n this.#storage.set(capStateKey, {size: capState.size, pks});\n }\n return this.#output.push(change, this);\n }\n // If not in our set, drop\n return emptyArray;\n }\n\n destroy(): void {\n this.#input.destroy();\n this.#storage.destroy();\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n}\n\nfunction getCapStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['cap', ...partitionValues]);\n}\n\nfunction serializePK(row: Row, primaryKey: PrimaryKey): string {\n return JSON.stringify(primaryKey.map(k => row[k]));\n}\n\nfunction deserializePKToConstraint(\n pk: string,\n primaryKey: PrimaryKey,\n): Constraint {\n const values = JSON.parse(pk) as Value[];\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < primaryKey.length; i++) {\n constraint[primaryKey[i]] = values[i];\n }\n return constraint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,MAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,UAAkB;CAElB,YACE,OACA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WACP;EAEA,IAAI,IADc,IAAI,SAAS,GAC3B,CAAA,CAAM,IAAI,KAAK,GAAG;GAEpB,MAAM,QAAQ,YAAY,OAAO,EAAiB,CAAC,KAAK,KAAK,WAAW;GACxE,IAAI,UAAU,OAAO;IACnB,MAAM,MAAM,SAAS,IAAI,KAAI,MAAM,MAAM,QAAQ,QAAQ,CAAE;IAC3D,KAAK,SAAS,IAAI,aAAa;KAAC,MAAM,SAAS;KAAM;IAAG,CAAC;GAC3D;GACA,OAAO,KAAK,QAAQ,KAAK,QAAQ,IAAI;EACvC;EAEA,OAAO;CACT;CAEA,UAAgB;EACd,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;CACxB;CAEA,CAAC,UAAU,SAAqC;EAC9C,IAAI,KAAK,QAAQ,WACf,OAAO,KAAK,QAAQ,UAAU,IAAI;CAEtC;AACF;AAEA,SAAS,eACP,cACA,iBACQ;CACR,MAAM,kBAA2B,CAAC;CAElC,IAAI,gBAAgB,iBAClB,KAAK,MAAM,OAAO,cAChB,gBAAgB,KAAK,gBAAgB,IAAI;CAI7C,OAAO,KAAK,UAAU,CAAC,OAAO,GAAG,eAAe,CAAC;AACnD;AAEA,SAAS,YAAY,KAAU,YAAgC;CAC7D,OAAO,KAAK,UAAU,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AACnD;AAEA,SAAS,0BACP,IACA,YACY;CACZ,MAAM,SAAS,KAAK,MAAM,EAAE;CAC5B,MAAM,aAAoC,CAAC;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,WAAW,WAAW,MAAM,OAAO;CAErC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"cap.js","names":[],"sources":["../../../../../zql/src/ivm/cap.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, type Change, type EditChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {valueToKey, type Comparator, type Node} 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 Stream} from './stream.ts';\nimport {\n constraintMatchesPartitionKey,\n makePartitionKeyComparator,\n type PartitionKey,\n} from './take.ts';\n\ntype CapState = {\n size: number;\n pks: string[];\n};\n\ninterface CapStorage {\n get(key: string): CapState | undefined;\n set(key: string, value: CapState): void;\n del(key: string): void;\n destroy(): void;\n}\n\n/**\n * The Cap operator is a count-based limiter for EXISTS subqueries that\n * does not require ordering. Unlike Take, it tracks membership by primary\n * key set rather than by a sorted bound. This means:\n *\n * - No comparator needed (no ordering requirement)\n * - No `start` or `reverse` fetch support\n * - No `#rowHiddenFromFetch` complexity (we can defer when adding to the pk set)\n *\n * Cap is used in EXISTS child pipelines where only the count of matching\n * rows matters, not their order. This allows SQLite to skip ORDER BY\n * entirely, enabling much faster query plans.\n *\n * Cap can count rows globally or by unique value of some partition key\n * (same as Take).\n */\nexport class Cap implements Operator {\n readonly #input: Input;\n readonly #storage: CapStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n readonly #primaryKey: PrimaryKey;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as CapStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n this.#primaryKey = input.getSchema().primaryKey;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(!req.start, 'Cap does not support start');\n assert(!req.reverse, 'Cap does not support reverse');\n\n // Cap is only built for non-flipped EXISTS subqueries, whose only\n // downstream consumer is a Join that always fetches with a constraint\n // built from the correlation's childField — which is Cap's partition\n // key. So either partitionKey is undefined, or constraint matches.\n assert(\n !this.#partitionKey ||\n (req.constraint !== undefined &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey)),\n 'Cap fetch: constraint must match partition key when partitioned',\n );\n\n const capStateKey = getCapStateKey(this.#partitionKey, req.constraint);\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n yield* this.#initialFetch(req, capStateKey);\n return;\n }\n if (capState.size === 0) {\n return;\n }\n if (req.countOnly) {\n for (let i = 0; i < capState.size; i++) {\n yield placeholderNode;\n }\n return;\n }\n // PK-based point lookups: fetch each tracked row by its PK directly,\n // rather than scanning the partition and filtering.\n for (const pk of capState.pks) {\n const pkConstraint = deserializePKToConstraint(pk, this.#primaryKey);\n // Preserve req.constraint (the partition key) so upstream partitioned\n // operators (e.g. Take) retain their partition scope and do not throw.\n const constraint = req.constraint\n ? {...req.constraint, ...pkConstraint}\n : pkConstraint;\n for (const inputNode of this.#input.fetch({constraint})) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(\n req: FetchRequest,\n capStateKey: string,\n ): Stream<Node | 'yield'> {\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n // The caller (fetch) has already checked that there is no state for\n // capStateKey.\n\n let size = 0;\n const pks: string[] = [];\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n pks.push(serializePK(inputNode.row, this.#primaryKey));\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#storage.set(capStateKey, {size, pks});\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that capState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n yield* this.#pushEditChange(change);\n return;\n }\n\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return;\n }\n\n const pk = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (capState.size < this.#limit) {\n const pks = [...capState.pks, pk];\n this.#storage.set(capStateKey, {size: capState.size + 1, pks});\n yield* this.#output.push(change, this);\n return;\n }\n // Full — drop\n return;\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n const pkIndex = capState.pks.indexOf(pk);\n if (pkIndex === -1) {\n // Not in our set — drop\n return;\n }\n // Remove from set\n const pks = [...capState.pks];\n pks.splice(pkIndex, 1);\n const newSize = capState.size - 1;\n\n // Try to refill: fetch from input with partition constraint,\n // find first row NOT in PK set\n const pkSet = new Set(pks);\n const constraint = this.#partitionKey\n ? (Object.fromEntries(\n this.#partitionKey.map(\n key => [key, change[ChangeIndex.NODE].row[key]] as const,\n ),\n ) as Constraint)\n : undefined;\n\n let replacement: Node | undefined;\n for (const node of this.#input.fetch({constraint})) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const nodePK = serializePK(node.row, this.#primaryKey);\n if (!pkSet.has(nodePK)) {\n replacement = node;\n break;\n }\n }\n\n if (replacement) {\n // Store state WITHOUT replacement during remove forward,\n // matching Take's pattern of hiding in-flight changes from re-fetches.\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n // Now add replacement to set and forward the add.\n const replacementPK = serializePK(replacement.row, this.#primaryKey);\n pks.push(replacementPK);\n this.#storage.set(capStateKey, {size: newSize + 1, pks});\n yield* this.#output.push(makeAddChange(replacement), this);\n } else {\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n }\n } else if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n const pkSet = new Set(capState.pks);\n if (pkSet.has(pk)) {\n yield* this.#output.push(change, this);\n }\n }\n }\n\n #pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.OLD_NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return emptyArray;\n }\n\n const oldPK = serializePK(\n change[ChangeIndex.OLD_NODE].row,\n this.#primaryKey,\n );\n const pkSet = new Set(capState.pks);\n if (pkSet.has(oldPK)) {\n // Update the PK in our set if it changed\n const newPK = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n if (oldPK !== newPK) {\n const pks = capState.pks.map(p => (p === oldPK ? newPK : p));\n this.#storage.set(capStateKey, {size: capState.size, pks});\n }\n return this.#output.push(change, this);\n }\n // If not in our set, drop\n return emptyArray;\n }\n\n destroy(): void {\n this.#input.destroy();\n this.#storage.destroy();\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n}\n\n// Yielded for each tracked row of a countOnly fetch.\nconst placeholderNode: Node = Object.freeze({\n row: Object.freeze({}),\n relationships: Object.freeze({}),\n});\n\nfunction getCapStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n if (partitionKey?.length === 1 && rowOrConstraint) {\n return 'cap:' + valueToKey(rowOrConstraint[partitionKey[0]]);\n }\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['cap', ...partitionValues]);\n}\n\nfunction serializePK(row: Row, primaryKey: PrimaryKey): string {\n return JSON.stringify(primaryKey.map(k => row[k]));\n}\n\nfunction deserializePKToConstraint(\n pk: string,\n primaryKey: PrimaryKey,\n): Constraint {\n const values = JSON.parse(pk) as Value[];\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < primaryKey.length; i++) {\n constraint[primaryKey[i]] = values[i];\n }\n return constraint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,MAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,UAAkB;CAElB,YACE,OACA,SACA,OACA,cACA;EACA,OAAO,SAAS,GAAG,4BAA4B;EAC/C,MAAM,UAAU,IAAI;EACpB,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,SAAS;EACd,KAAK,gBAAgB;EACrB,KAAK,0BACH,gBAAgB,2BAA2B,YAAY;EACzD,KAAK,cAAc,MAAM,UAAU,CAAC,CAAC;CACvC;CAEA,UAAU,QAAsB;EAC9B,KAAK,UAAU;CACjB;CAEA,YAA0B;EACxB,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,CAAC,MAAM,KAA2C;EAChD,OAAO,CAAC,IAAI,OAAO,4BAA4B;EAC/C,OAAO,CAAC,IAAI,SAAS,8BAA8B;EAMnD,OACE,CAAC,KAAK,iBACH,IAAI,eAAe,KAAA,KAClB,8BAA8B,IAAI,YAAY,KAAK,aAAa,GACpE,iEACF;EAEA,MAAM,cAAc,eAAe,KAAK,eAAe,IAAI,UAAU;EACrE,MAAM,WAAW,KAAK,SAAS,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AU,IAAI;CAEtC;AACF;AAGA,IAAM,kBAAwB,OAAO,OAAO;CAC1C,KAAK,OAAO,OAAO,CAAC,CAAC;CACrB,eAAe,OAAO,OAAO,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,eACP,cACA,iBACQ;CACR,IAAI,cAAc,WAAW,KAAK,iBAChC,OAAO,SAAS,WAAW,gBAAgB,aAAa,GAAG;CAE7D,MAAM,kBAA2B,CAAC;CAElC,IAAI,gBAAgB,iBAClB,KAAK,MAAM,OAAO,cAChB,gBAAgB,KAAK,gBAAgB,IAAI;CAI7C,OAAO,KAAK,UAAU,CAAC,OAAO,GAAG,eAAe,CAAC;AACnD;AAEA,SAAS,YAAY,KAAU,YAAgC;CAC7D,OAAO,KAAK,UAAU,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AACnD;AAEA,SAAS,0BACP,IACA,YACY;CACZ,MAAM,SAAS,KAAK,MAAM,EAAE;CAC5B,MAAM,aAAoC,CAAC;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,WAAW,WAAW,MAAM,OAAO;CAErC,OAAO;AACT"}
|
|
@@ -11,8 +11,11 @@ export type Node = {
|
|
|
11
11
|
* Relationships are generated lazily as read.
|
|
12
12
|
* The stream may contain 'yield' to indicate the operator has yielded control.
|
|
13
13
|
* See {@link Operator.fetch} for more details about yields.
|
|
14
|
+
*
|
|
15
|
+
* A caller that only counts the nodes can pass `countOnly`, see
|
|
16
|
+
* `FetchRequest.countOnly`.
|
|
14
17
|
*/
|
|
15
|
-
relationships: Record<string, () => Stream<Node | 'yield'>>;
|
|
18
|
+
relationships: Record<string, (countOnly?: boolean | undefined) => Stream<Node | 'yield'>>;
|
|
16
19
|
};
|
|
17
20
|
/**
|
|
18
21
|
* Compare two values. The values must be of the same type. This function
|
|
@@ -34,6 +37,17 @@ export type NormalizedValue = Exclude<Value, undefined>;
|
|
|
34
37
|
* of input values, so we just normalize at use when necessary.
|
|
35
38
|
*/
|
|
36
39
|
export declare function normalizeUndefined(v: Value): NormalizedValue;
|
|
40
|
+
/**
|
|
41
|
+
* Encodes a single value for use in a string key, more cheaply than
|
|
42
|
+
* `JSON.stringify` for strings. Distinct values get distinct keys because
|
|
43
|
+
* `JSON.stringify` of a value that is not a string never starts with `s`.
|
|
44
|
+
* `undefined` is encoded like `null`.
|
|
45
|
+
*
|
|
46
|
+
* Strings with surrogates also use `JSON.stringify`, which escapes lone
|
|
47
|
+
* surrogates. Encoded as UTF-8 (e.g. by SQLite), distinct lone surrogates
|
|
48
|
+
* would otherwise become the same key.
|
|
49
|
+
*/
|
|
50
|
+
export declare function valueToKey(v: Value): string;
|
|
37
51
|
export type Comparator = (r1: Row, r2: Row) => number;
|
|
38
52
|
export declare function makeComparator(order: Ordering, reverse?: boolean): Comparator;
|
|
39
53
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/data.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,mCAAmC,CAAC;AAChE,OAAO,KAAK,EAAC,GAAG,EAAE,KAAK,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,GAAG,CAAC;IACT
|
|
1
|
+
{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/data.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,mCAAmC,CAAC;AAChE,OAAO,KAAK,EAAC,GAAG,EAAE,KAAK,EAAC,MAAM,oCAAoC,CAAC;AACnE,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,GAAG,EAAE,GAAG,CAAC;IACT;;;;;;;OAOG;IACH,aAAa,EAAE,MAAM,CACnB,MAAM,EACN,CAAC,SAAS,CAAC,EAAE,OAAO,GAAG,SAAS,KAAK,MAAM,CAAC,IAAI,GAAG,OAAO,CAAC,CAC5D,CAAC;CACH,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CA4CxD;AAED,MAAM,MAAM,eAAe,GAAG,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAExD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,KAAK,GAAG,eAAe,CAE5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,GAAG,MAAM,CAI3C;AAID,MAAM,MAAM,UAAU,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,KAAK,MAAM,CAAC;AAEtD,wBAAgB,cAAc,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,UAAU,CA0B7E;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,GAAG,OAAO,CAMvD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,QAShD"}
|
package/out/zql/src/ivm/data.js
CHANGED
|
@@ -32,6 +32,20 @@ function compareValues(a, b) {
|
|
|
32
32
|
function normalizeUndefined(v) {
|
|
33
33
|
return v ?? null;
|
|
34
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* Encodes a single value for use in a string key, more cheaply than
|
|
37
|
+
* `JSON.stringify` for strings. Distinct values get distinct keys because
|
|
38
|
+
* `JSON.stringify` of a value that is not a string never starts with `s`.
|
|
39
|
+
* `undefined` is encoded like `null`.
|
|
40
|
+
*
|
|
41
|
+
* Strings with surrogates also use `JSON.stringify`, which escapes lone
|
|
42
|
+
* surrogates. Encoded as UTF-8 (e.g. by SQLite), distinct lone surrogates
|
|
43
|
+
* would otherwise become the same key.
|
|
44
|
+
*/
|
|
45
|
+
function valueToKey(v) {
|
|
46
|
+
return typeof v === "string" && !surrogateRe.test(v) ? "s" + v : JSON.stringify(v ?? null);
|
|
47
|
+
}
|
|
48
|
+
var surrogateRe = /[\ud800-\udfff]/;
|
|
35
49
|
function makeComparator(order, reverse) {
|
|
36
50
|
if (order.length === 1 && order[0][1] === "asc" && !reverse) {
|
|
37
51
|
const field = order[0][0];
|
|
@@ -61,6 +75,6 @@ function valuesEqual(a, b) {
|
|
|
61
75
|
return a === b;
|
|
62
76
|
}
|
|
63
77
|
//#endregion
|
|
64
|
-
export { compareValues, makeComparator, normalizeUndefined, valuesEqual };
|
|
78
|
+
export { compareValues, makeComparator, normalizeUndefined, valueToKey, valuesEqual };
|
|
65
79
|
|
|
66
80
|
//# sourceMappingURL=data.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data.js","names":[],"sources":["../../../../../zql/src/ivm/data.ts"],"sourcesContent":["import {compareUTF8} from 'compare-utf8';\nimport type {Ordering} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * A row flowing through the pipeline, plus its relationships.\n * Relationships are generated lazily as read.\n */\nexport type Node = {\n row: Row;\n /**\n * Relationships are generated lazily as read.\n * The stream may contain 'yield' to indicate the operator has yielded control.\n * See {@link Operator.fetch} for more details about yields.\n */\n relationships: Record
|
|
1
|
+
{"version":3,"file":"data.js","names":[],"sources":["../../../../../zql/src/ivm/data.ts"],"sourcesContent":["import {compareUTF8} from 'compare-utf8';\nimport type {Ordering} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {Stream} from './stream.ts';\n\n/**\n * A row flowing through the pipeline, plus its relationships.\n * Relationships are generated lazily as read.\n */\nexport type Node = {\n row: Row;\n /**\n * Relationships are generated lazily as read.\n * The stream may contain 'yield' to indicate the operator has yielded control.\n * See {@link Operator.fetch} for more details about yields.\n *\n * A caller that only counts the nodes can pass `countOnly`, see\n * `FetchRequest.countOnly`.\n */\n relationships: Record<\n string,\n (countOnly?: boolean | undefined) => Stream<Node | 'yield'>\n >;\n};\n\n/**\n * Compare two values. The values must be of the same type. This function\n * throws at runtime if the types differ.\n *\n * Note, this function considers `null === null` and\n * `undefined === undefined`. This is different than SQL. In join code,\n * null must be treated separately.\n *\n * See: https://github.com/rocicorp/mono/pull/2116/files#r1704811479\n *\n * @returns < 0 if a < b, 0 if a === b, > 0 if a > b\n */\nexport function compareValues(a: Value, b: Value): number {\n a = a ?? null;\n b = b ?? null;\n\n if (a === b) {\n return 0;\n }\n\n if (typeof a === 'string' && typeof b === 'string') {\n // We compare all strings in Zero as UTF-8. This is the default on SQLite\n // and we need to match it. See:\n // https://blog.replicache.dev/blog/replicache-11-adventures-in-text-encoding.\n //\n // TODO: We could change this since SQLite supports UTF-16. Microbenchmark\n // to see if there's a big win.\n //\n // https://www.sqlite.org/c3ref/create_collation.html\n return compareUTF8(a, b);\n }\n\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n\n if (typeof a === 'boolean' && typeof b === 'boolean') {\n return a ? 1 : -1;\n }\n\n // check with null after since it is less likely to be the common case and we\n // want to avoid the extra checks in that case\n if (a === null) {\n return -1;\n }\n if (b === null) {\n return 1;\n }\n\n if (typeof a !== typeof b) {\n throw new Error(\n `Cannot compare values of different types: ${typeof a} and ${typeof b}`,\n );\n }\n\n throw new Error(`Unsupported type: ${typeof a}`);\n}\n\nexport type NormalizedValue = Exclude<Value, undefined>;\n\n/**\n * We allow undefined to be passed for the convenience of developers, but we\n * treat it equivalently to null. It's better for perf to not create an copy\n * of input values, so we just normalize at use when necessary.\n */\nexport function normalizeUndefined(v: Value): NormalizedValue {\n return v ?? null;\n}\n\n/**\n * Encodes a single value for use in a string key, more cheaply than\n * `JSON.stringify` for strings. Distinct values get distinct keys because\n * `JSON.stringify` of a value that is not a string never starts with `s`.\n * `undefined` is encoded like `null`.\n *\n * Strings with surrogates also use `JSON.stringify`, which escapes lone\n * surrogates. Encoded as UTF-8 (e.g. by SQLite), distinct lone surrogates\n * would otherwise become the same key.\n */\nexport function valueToKey(v: Value): string {\n return typeof v === 'string' && !surrogateRe.test(v)\n ? 's' + v\n : JSON.stringify(v ?? null);\n}\n\nconst surrogateRe = /[\\ud800-\\udfff]/;\n\nexport type Comparator = (r1: Row, r2: Row) => number;\n\nexport function makeComparator(order: Ordering, reverse?: boolean): Comparator {\n // A single ascending field is the common shape -- it is what every source\n // ordered by a single-column primary key gets -- and specializing it drops\n // the loop, the direction test and the reverse test from the hottest\n // function in hydration.\n if (order.length === 1 && order[0][1] === 'asc' && !reverse) {\n const field = order[0][0];\n return (a, b) => compareValues(a[field], b[field]);\n }\n\n const length = order.length;\n return (a, b) => {\n // Skip destructuring here since it is hot code. An indexed loop rather\n // than `for...of` for the same reason: Hermes allocates an iterator and\n // calls `next()` per element, which costs more than the comparison for an\n // ordering this short.\n for (let i = 0; i < length; i++) {\n const ord = order[i];\n const comp = compareValues(a[ord[0]], b[ord[0]]);\n if (comp !== 0) {\n const result = ord[1] === 'asc' ? comp : -comp;\n return reverse ? -result : result;\n }\n }\n return 0;\n };\n}\n\n/**\n * Determine if two values are equal. Note that unlike compareValues() above,\n * this function treats `null` as unequal to itself (and same for `undefined`).\n * This is required to make joins work correctly, but may not be the right\n * semantic for your application.\n */\nexport function valuesEqual(a: Value, b: Value): boolean {\n // oxlint-disable-next-line eqeqeq\n if (a == null || b == null) {\n return false;\n }\n return a === b;\n}\n\nexport function drainStreams(node: Node | 'yield') {\n if (node === 'yield') {\n return;\n }\n for (const stream of Object.values(node.relationships)) {\n for (const node of stream()) {\n drainStreams(node);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqCA,SAAgB,cAAc,GAAU,GAAkB;CACxD,IAAI,KAA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mB;CAEvD,IAAI,KAAK,QAAQ,KAAK,MACpB,OAAO;CAET,OAAO,MAAM;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exists.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/exists.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,mCAAmC,CAAC;AAGnE,OAAO,EAAkC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AACzE,OAAO,
|
|
1
|
+
{"version":3,"file":"exists.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/exists.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,mCAAmC,CAAC;AAGnE,OAAO,EAAkC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AACzE,OAAO,EAGL,KAAK,IAAI,EAEV,MAAM,WAAW,CAAC;AACnB,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,qBAAa,MAAO,YAAW,cAAc;;IAoB3C,YACE,KAAK,EAAE,WAAW,EAClB,gBAAgB,EAAE,MAAM,EACxB,aAAa,EAAE,WAAW,EAC1B,IAAI,EAAE,QAAQ,GAAG,YAAY,EAC7B,wBAAwB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAoB/C;IAED,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAE1C;IAED,WAAW,SAEV;IAED,SAAS,SAGR;IAEA,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAmBtD;IAED,OAAO,IAAI,IAAI,CAEd;IAED,SAAS,IAAI,YAAY,CAExB;IAEA,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAI9C;IAEA,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAmGrC;CA6EF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
2
2
|
import { areEqual } from "../../../shared/src/arrays.js";
|
|
3
3
|
import { makeAddChange, makeRemoveChange } from "./change.js";
|
|
4
|
-
import { normalizeUndefined } from "./data.js";
|
|
4
|
+
import { normalizeUndefined, valueToKey } from "./data.js";
|
|
5
5
|
import { throwFilterOutput } from "./filter-operators.js";
|
|
6
6
|
//#region ../zql/src/ivm/exists.ts
|
|
7
7
|
/**
|
|
@@ -134,6 +134,7 @@ var Exists = class {
|
|
|
134
134
|
return this.#not ? !exists : exists;
|
|
135
135
|
}
|
|
136
136
|
#getCacheKey(node, def) {
|
|
137
|
+
if (def.length === 1) return valueToKey(node.row[def[0]]);
|
|
137
138
|
const values = [];
|
|
138
139
|
for (const key of def) values.push(normalizeUndefined(node.row[key]));
|
|
139
140
|
return JSON.stringify(values);
|
|
@@ -150,10 +151,17 @@ var Exists = class {
|
|
|
150
151
|
*#fetchSize(node) {
|
|
151
152
|
const relationship = node.relationships[this.#relationshipName];
|
|
152
153
|
assert(relationship, () => `Exists: relationship "${this.#relationshipName}" not found on node`);
|
|
153
|
-
|
|
154
|
+
if (this.#inPush) {
|
|
155
|
+
let size = 0;
|
|
156
|
+
for (const n of relationship(true)) if (n === "yield") yield "yield";
|
|
157
|
+
else size++;
|
|
158
|
+
return size;
|
|
159
|
+
}
|
|
160
|
+
const children = [];
|
|
154
161
|
for (const n of relationship()) if (n === "yield") yield "yield";
|
|
155
|
-
else
|
|
156
|
-
|
|
162
|
+
else children.push(n);
|
|
163
|
+
node.relationships[this.#relationshipName] = () => children;
|
|
164
|
+
return children.length;
|
|
157
165
|
}
|
|
158
166
|
};
|
|
159
167
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exists.js","names":[],"sources":["../../../../../zql/src/ivm/exists.ts"],"sourcesContent":["import {areEqual} from '../../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, makeRemoveChange, type Change} from './change.ts';\nimport {normalizeUndefined, type Node, type NormalizedValue} from './data.ts';\nimport {\n throwFilterOutput,\n type FilterInput,\n type FilterOperator,\n type FilterOutput,\n} from './filter-operators.ts';\nimport type {InputBase} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\n/**\n * The Exists operator filters data based on whether or not a relationship is\n * non-empty.\n */\nexport class Exists implements FilterOperator {\n readonly #input: FilterInput;\n readonly #relationshipName: string;\n readonly #not: boolean;\n readonly #parentJoinKey: CompoundKey;\n readonly #noSizeReuse: boolean;\n #cache: Map<string, boolean>;\n #cacheHitCountsForTesting: Map<string, number> | undefined;\n #output: FilterOutput = throwFilterOutput;\n\n /**\n * This instance variable is `true` when this operator is processing a `push`,\n * and is used to disable reuse of cached sizes across rows with the\n * same parent join key value.\n * This is necessary because during a push relationships can be inconsistent\n * due to push communicating changes (which may change multiple Nodes) one\n * Node at a time.\n */\n #inPush = false;\n\n constructor(\n input: FilterInput,\n relationshipName: string,\n parentJoinKey: CompoundKey,\n type: 'EXISTS' | 'NOT EXISTS',\n cacheHitCountsForTesting?: Map<string, number>,\n ) {\n this.#input = input;\n this.#relationshipName = relationshipName;\n this.#input.setFilterOutput(this);\n this.#cache = new Map();\n this.#cacheHitCountsForTesting = cacheHitCountsForTesting;\n assert(\n this.#input.getSchema().relationships[relationshipName],\n // log-leak-ignore -- relationship name is schema, allowed in errors\n `Input schema missing ${relationshipName}`,\n );\n this.#not = type === 'NOT EXISTS';\n this.#parentJoinKey = parentJoinKey;\n\n // If the parentJoinKey is the primary key, no sense in trying to reuse.\n this.#noSizeReuse = areEqual(\n parentJoinKey,\n this.#input.getSchema().primaryKey,\n );\n }\n\n setFilterOutput(output: FilterOutput): void {\n this.#output = output;\n }\n\n beginFilter() {\n this.#output.beginFilter();\n }\n\n endFilter() {\n this.#cache = new Map();\n this.#output.endFilter();\n }\n\n *filter(node: Node): IterableIterator<'yield', boolean> {\n let exists: boolean | undefined;\n if (!this.#noSizeReuse && !this.#inPush) {\n const key = this.#getCacheKey(node, this.#parentJoinKey);\n exists = this.#cache.get(key);\n if (exists === undefined) {\n exists = yield* this.#fetchExists(node);\n this.#cache.set(key, exists);\n } else if (this.#cacheHitCountsForTesting) {\n this.#cacheHitCountsForTesting.set(\n key,\n (this.#cacheHitCountsForTesting.get(key) ?? 0) + 1,\n );\n }\n }\n\n const result =\n (yield* this.#filter(node, exists)) && (yield* this.#output.filter(node));\n return result;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n assert(!this.#inPush, 'Unexpected re-entrancy');\n this.#inPush = true;\n try {\n switch (change[ChangeIndex.TYPE]) {\n // add, remove and edit cannot change the size of the\n // this.#relationshipName relationship, so simply #pushWithFilter\n case ChangeType.ADD:\n case ChangeType.EDIT:\n case ChangeType.REMOVE: {\n yield* this.#pushWithFilter(change);\n return;\n }\n case ChangeType.CHILD:\n // Only add and remove child changes for the\n // this.#relationshipName relationship, can change the size\n // of the this.#relationshipName relationship, for other\n // child changes simply #pushWithFilter\n if (\n change[ChangeIndex.CHILD_DATA].relationshipName !==\n this.#relationshipName ||\n change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE] ===\n ChangeType.EDIT ||\n change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE] ===\n ChangeType.CHILD\n ) {\n yield* this.#pushWithFilter(change);\n return;\n }\n switch (change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE]) {\n case ChangeType.ADD: {\n const size = yield* this.#fetchSize(change[ChangeIndex.NODE]);\n if (size === 1) {\n if (this.#not) {\n // Since the add child change currently being processed is not\n // pushed to output, the added child needs to be excluded from\n // the remove being pushed to output (since the child has\n // never been added to the output).\n yield* this.#output.push(\n makeRemoveChange({\n row: change[ChangeIndex.NODE].row,\n relationships: {\n ...change[ChangeIndex.NODE].relationships,\n [this.#relationshipName]: () => [],\n },\n }),\n this,\n );\n } else {\n yield* this.#output.push(\n makeAddChange(change[ChangeIndex.NODE]),\n this,\n );\n }\n } else {\n yield* this.#pushWithFilter(change, size > 0);\n }\n return;\n }\n case ChangeType.REMOVE: {\n const size = yield* this.#fetchSize(change[ChangeIndex.NODE]);\n if (size === 0) {\n if (this.#not) {\n yield* this.#output.push(\n makeAddChange(change[ChangeIndex.NODE]),\n this,\n );\n } else {\n // Since the remove child change currently being processed is\n // not pushed to output, the removed child needs to be added to\n // the remove being pushed to output.\n yield* this.#output.push(\n makeRemoveChange({\n row: change[ChangeIndex.NODE].row,\n relationships: {\n ...change[ChangeIndex.NODE].relationships,\n [this.#relationshipName]: () => [\n change[ChangeIndex.CHILD_DATA].change[\n ChangeIndex.NODE\n ],\n ],\n },\n }),\n this,\n );\n }\n } else {\n yield* this.#pushWithFilter(change, size > 0);\n }\n return;\n }\n }\n return;\n default:\n unreachable(change);\n }\n } finally {\n this.#inPush = false;\n }\n }\n\n /**\n * Returns whether or not the node's this.#relationshipName\n * relationship passes the exist/not exists filter condition.\n * If the optional `size` is passed it is used.\n * Otherwise, if there is a stored size for the row it is used.\n * Otherwise the size is computed by streaming the node's\n * relationship with this.#relationshipName (this computed size is also\n * stored).\n */\n *#filter(node: Node, exists?: boolean): IterableIterator<'yield', boolean> {\n exists = exists ?? (yield* this.#fetchExists(node));\n return this.#not ? !exists : exists;\n }\n\n #getCacheKey(node: Node, def: CompoundKey): string {\n const values: NormalizedValue[] = [];\n for (const key of def) {\n values.push(normalizeUndefined(node.row[key]));\n }\n return JSON.stringify(values);\n }\n\n /**\n * Pushes a change if this.#filter is true for its row.\n */\n *#pushWithFilter(change: Change, exists?: boolean): Stream<'yield'> {\n if (yield* this.#filter(change[ChangeIndex.NODE], exists)) {\n yield* this.#output.push(change, this);\n }\n }\n\n *#fetchExists(node: Node): IterableIterator<'yield', boolean> {\n // While it seems like this should be able to fetch just 1 node\n // to check for exists, we can't because Take does not support\n // early return during initial fetch.\n return (yield* this.#fetchSize(node)) > 0;\n }\n\n *#fetchSize(node: Node): IterableIterator<'yield', number> {\n const relationship = node.relationships[this.#relationshipName];\n assert(\n relationship,\n () =>\n `Exists: relationship \"${this.#relationshipName}\" not found on node`,\n );\n let size = 0;\n for (const n of relationship()) {\n if (n === 'yield') {\n yield 'yield';\n } else {\n size++;\n }\n }\n return size;\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,SAAb,MAA8C;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA,UAAwB;;;;;;;;;CAUxB,UAAU;CAEV,YACE,OACA,kBACA,eACA,MACA,0BACA;EACA,KAAK,SAAS;EACd,KAAK,oBAAoB;EACzB,KAAK,OAAO,gBAAgB,IAAI;EAChC,KAAK,yBAAS,IAAI,IAAI;EACtB,KAAK,4BAA4B;EACjC,OACE,KAAK,OAAO,UAAU,CAAC,CAAC,cAAc,mBAEtC,wBAAwB,kBAC1B;EACA,KAAK,OAAO,SAAS;EACrB,KAAK,iBAAiB;EAGtB,KAAK,eAAe,SAClB,eACA,KAAK,OAAO,UAAU,CAAC,CAAC,UAC1B;CACF;CAEA,gBAAgB,QAA4B;EAC1C,KAAK,UAAU;CACjB;CAEA,cAAc;EACZ,KAAK,QAAQ,YAAY;CAC3B;CAEA,YAAY;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IAAI;CAEzC;CAEA,CAAC,aAAa,MAAgD;EAI5D,QAAQ,OAAO,KAAK,WAAW,IAAI,KAAK;CAC1C;CAEA,CAAC,WAAW,MAA+C;EACzD,MAAM,eAAe,KAAK,cAAc,KAAK;EAC7C,OACE,oBAEE,yBAAyB,KAAK,kBAAkB,oBACpD;EACA,IAAI,OAAO;EACX,KAAK,MAAM,KAAK,aAAa,GAC3B,IAAI,MAAM,SACR,MAAM;OAEN;EAGJ,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"exists.js","names":[],"sources":["../../../../../zql/src/ivm/exists.ts"],"sourcesContent":["import {areEqual} from '../../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, makeRemoveChange, type Change} from './change.ts';\nimport {\n normalizeUndefined,\n valueToKey,\n type Node,\n type NormalizedValue,\n} from './data.ts';\nimport {\n throwFilterOutput,\n type FilterInput,\n type FilterOperator,\n type FilterOutput,\n} from './filter-operators.ts';\nimport type {InputBase} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\n/**\n * The Exists operator filters data based on whether or not a relationship is\n * non-empty.\n */\nexport class Exists implements FilterOperator {\n readonly #input: FilterInput;\n readonly #relationshipName: string;\n readonly #not: boolean;\n readonly #parentJoinKey: CompoundKey;\n readonly #noSizeReuse: boolean;\n #cache: Map<string, boolean>;\n #cacheHitCountsForTesting: Map<string, number> | undefined;\n #output: FilterOutput = throwFilterOutput;\n\n /**\n * This instance variable is `true` when this operator is processing a `push`,\n * and is used to disable reuse of cached sizes across rows with the\n * same parent join key value.\n * This is necessary because during a push relationships can be inconsistent\n * due to push communicating changes (which may change multiple Nodes) one\n * Node at a time.\n */\n #inPush = false;\n\n constructor(\n input: FilterInput,\n relationshipName: string,\n parentJoinKey: CompoundKey,\n type: 'EXISTS' | 'NOT EXISTS',\n cacheHitCountsForTesting?: Map<string, number>,\n ) {\n this.#input = input;\n this.#relationshipName = relationshipName;\n this.#input.setFilterOutput(this);\n this.#cache = new Map();\n this.#cacheHitCountsForTesting = cacheHitCountsForTesting;\n assert(\n this.#input.getSchema().relationships[relationshipName],\n // log-leak-ignore -- relationship name is schema, allowed in errors\n `Input schema missing ${relationshipName}`,\n );\n this.#not = type === 'NOT EXISTS';\n this.#parentJoinKey = parentJoinKey;\n\n // If the parentJoinKey is the primary key, no sense in trying to reuse.\n this.#noSizeReuse = areEqual(\n parentJoinKey,\n this.#input.getSchema().primaryKey,\n );\n }\n\n setFilterOutput(output: FilterOutput): void {\n this.#output = output;\n }\n\n beginFilter() {\n this.#output.beginFilter();\n }\n\n endFilter() {\n this.#cache = new Map();\n this.#output.endFilter();\n }\n\n *filter(node: Node): IterableIterator<'yield', boolean> {\n let exists: boolean | undefined;\n if (!this.#noSizeReuse && !this.#inPush) {\n const key = this.#getCacheKey(node, this.#parentJoinKey);\n exists = this.#cache.get(key);\n if (exists === undefined) {\n exists = yield* this.#fetchExists(node);\n this.#cache.set(key, exists);\n } else if (this.#cacheHitCountsForTesting) {\n this.#cacheHitCountsForTesting.set(\n key,\n (this.#cacheHitCountsForTesting.get(key) ?? 0) + 1,\n );\n }\n }\n\n const result =\n (yield* this.#filter(node, exists)) && (yield* this.#output.filter(node));\n return result;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n assert(!this.#inPush, 'Unexpected re-entrancy');\n this.#inPush = true;\n try {\n switch (change[ChangeIndex.TYPE]) {\n // add, remove and edit cannot change the size of the\n // this.#relationshipName relationship, so simply #pushWithFilter\n case ChangeType.ADD:\n case ChangeType.EDIT:\n case ChangeType.REMOVE: {\n yield* this.#pushWithFilter(change);\n return;\n }\n case ChangeType.CHILD:\n // Only add and remove child changes for the\n // this.#relationshipName relationship, can change the size\n // of the this.#relationshipName relationship, for other\n // child changes simply #pushWithFilter\n if (\n change[ChangeIndex.CHILD_DATA].relationshipName !==\n this.#relationshipName ||\n change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE] ===\n ChangeType.EDIT ||\n change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE] ===\n ChangeType.CHILD\n ) {\n yield* this.#pushWithFilter(change);\n return;\n }\n switch (change[ChangeIndex.CHILD_DATA].change[ChangeIndex.TYPE]) {\n case ChangeType.ADD: {\n const size = yield* this.#fetchSize(change[ChangeIndex.NODE]);\n if (size === 1) {\n if (this.#not) {\n // Since the add child change currently being processed is not\n // pushed to output, the added child needs to be excluded from\n // the remove being pushed to output (since the child has\n // never been added to the output).\n yield* this.#output.push(\n makeRemoveChange({\n row: change[ChangeIndex.NODE].row,\n relationships: {\n ...change[ChangeIndex.NODE].relationships,\n [this.#relationshipName]: () => [],\n },\n }),\n this,\n );\n } else {\n yield* this.#output.push(\n makeAddChange(change[ChangeIndex.NODE]),\n this,\n );\n }\n } else {\n yield* this.#pushWithFilter(change, size > 0);\n }\n return;\n }\n case ChangeType.REMOVE: {\n const size = yield* this.#fetchSize(change[ChangeIndex.NODE]);\n if (size === 0) {\n if (this.#not) {\n yield* this.#output.push(\n makeAddChange(change[ChangeIndex.NODE]),\n this,\n );\n } else {\n // Since the remove child change currently being processed is\n // not pushed to output, the removed child needs to be added to\n // the remove being pushed to output.\n yield* this.#output.push(\n makeRemoveChange({\n row: change[ChangeIndex.NODE].row,\n relationships: {\n ...change[ChangeIndex.NODE].relationships,\n [this.#relationshipName]: () => [\n change[ChangeIndex.CHILD_DATA].change[\n ChangeIndex.NODE\n ],\n ],\n },\n }),\n this,\n );\n }\n } else {\n yield* this.#pushWithFilter(change, size > 0);\n }\n return;\n }\n }\n return;\n default:\n unreachable(change);\n }\n } finally {\n this.#inPush = false;\n }\n }\n\n /**\n * Returns whether or not the node's this.#relationshipName\n * relationship passes the exist/not exists filter condition.\n * If the optional `size` is passed it is used.\n * Otherwise, if there is a stored size for the row it is used.\n * Otherwise the size is computed by streaming the node's\n * relationship with this.#relationshipName (this computed size is also\n * stored).\n */\n *#filter(node: Node, exists?: boolean): IterableIterator<'yield', boolean> {\n exists = exists ?? (yield* this.#fetchExists(node));\n return this.#not ? !exists : exists;\n }\n\n #getCacheKey(node: Node, def: CompoundKey): string {\n if (def.length === 1) {\n return valueToKey(node.row[def[0]]);\n }\n const values: NormalizedValue[] = [];\n for (const key of def) {\n values.push(normalizeUndefined(node.row[key]));\n }\n return JSON.stringify(values);\n }\n\n /**\n * Pushes a change if this.#filter is true for its row.\n */\n *#pushWithFilter(change: Change, exists?: boolean): Stream<'yield'> {\n if (yield* this.#filter(change[ChangeIndex.NODE], exists)) {\n yield* this.#output.push(change, this);\n }\n }\n\n *#fetchExists(node: Node): IterableIterator<'yield', boolean> {\n // While it seems like this should be able to fetch just 1 node\n // to check for exists, we can't because Take does not support\n // early return during initial fetch.\n return (yield* this.#fetchSize(node)) > 0;\n }\n\n *#fetchSize(node: Node): IterableIterator<'yield', number> {\n const relationship = node.relationships[this.#relationshipName];\n assert(\n relationship,\n () =>\n `Exists: relationship \"${this.#relationshipName}\" not found on node`,\n );\n if (this.#inPush) {\n // Only the size is needed, which Cap can answer from its state.\n let size = 0;\n for (const n of relationship(true)) {\n if (n === 'yield') {\n yield 'yield';\n } else {\n size++;\n }\n }\n return size;\n }\n // During a fetch, keep the children read to count them and make the\n // node's relationship return them, so that the consumer of the node does\n // not fetch them again. The exists subquery is limited, so this holds at\n // most a few nodes. `node.relationships` is created per node by the Join.\n const children: Node[] = [];\n for (const n of relationship()) {\n if (n === 'yield') {\n yield 'yield';\n } else {\n children.push(n);\n }\n }\n node.relationships[this.#relationshipName] = () => children;\n return children.length;\n }\n}\n"],"mappings":";;;;;;;;;;AA0BA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AAK,gBAAgB,QAAQ,OAAO,CAAC;OAE9C;MACF;KACF;KACA;IACF,SACE,YAAY,MAAM;GACtB;EACF,UAAU;GACR,KAAK,UAAU;EACjB;CACF;;;;;;;;;;CAWA,CAAC,QAAQ,MAAY,QAAsD;EACzE,SAAS,WAAW,OAAO,KAAK,aAAa,IAAI;EACjD,OAAO,KAAK,OAAO,CAAC,SAAS;CAC/B;CAEA,aAAa,MAAY,KAA0B;EACjD,IAAI,IAAI,WAAW,GACjB,OAAO,WAAW,KAAK,IAAI,IAAI,GAAG;EAEpC,MAAM,SAA4B,CAAC;EACnC,KAAK,MAAM,OAAO,KAChB,OAAO,KAAK,mBAAmB,KAAK,IAAI,IAAI,CAAC;EAE/C,OAAO,KAAK,UAAU,MAAM;CAC9B;;;;CAKA,CAAC,gBAAgB,QAAgB,QAAmC;EAClE,IAAI,OAAO,KAAK,QAAQ,OAAO,IAAmB,MAAM,GACtD,OAAO,KAAK,QAAQ,KAAK,QAAQ,IAAI;CAEzC;CAEA,CAAC,aAAa,MAAgD;EAI5D,QAAQ,OAAO,KAAK,WAAW,IAAI,KAAK;CAC1C;CAEA,CAAC,WAAW,MAA+C;EACzD,MAAM,eAAe,KAAK,cAAc,KAAK;EAC7C,OACE,oBAEE,yBAAyB,KAAK,kBAAkB,oBACpD;EACA,IAAI,KAAK,SAAS;GAEhB,IAAI,OAAO;GACX,KAAK,MAAM,KAAK,aAAa,IAAI,GAC/B,IAAI,MAAM,SACR,MAAM;QAEN;GAGJ,OAAO;EACT;EAKA,MAAM,WAAmB,CAAC;EAC1B,KAAK,MAAM,KAAK,aAAa,GAC3B,IAAI,MAAM,SACR,MAAM;OAEN,SAAS,KAAK,CAAC;EAGnB,KAAK,cAAc,KAAK,2BAA2B;EACnD,OAAO,SAAS;CAClB;AACF"}
|
|
@@ -18,6 +18,11 @@ import { type Stream } from './stream.ts';
|
|
|
18
18
|
* `Node` `row`s or `relationship`s, but they shouldn't, they should just
|
|
19
19
|
* filter.
|
|
20
20
|
*
|
|
21
|
+
* One exception: during a fetch, `Exists` replaces the relationship it read
|
|
22
|
+
* with a function returning the children it read, so that the consumer does
|
|
23
|
+
* not fetch them again. The relationship yields the same nodes, so other
|
|
24
|
+
* branches of a `FanOut`, which see the same node object, are not affected.
|
|
25
|
+
*
|
|
21
26
|
* This `FilterOperator` abstraction enables much more efficient processing of
|
|
22
27
|
* `fetch` for `where` clauses containing OR conditions.
|
|
23
28
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filter-operators.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/filter-operators.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,sBAAsB,CAAC;AAC9D,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAC,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAC,MAAM,eAAe,CAAC;AAC1E,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC
|
|
1
|
+
{"version":3,"file":"filter-operators.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/filter-operators.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,sBAAsB,CAAC;AAC9D,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAAC,KAAK,IAAI,EAAC,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAC,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAC,MAAM,eAAe,C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AAM,CAAC,KAAK,EAAE,IAAI,kCAEjB;IAED,SAAS,CAAC,MAAM,EAAE,MAAM,QAEvB;IAED,OAAO,IAAI,IAAI,CAEd;IAED,SAAS,IAAI,YAAY,CAExB;IAED,IAAI,CAAC,MAAM,EAAE,MAAM,mBAElB;IAEA,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAI9C;CACF;AAID,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,eAAe,EACzB,QAAQ,EAAE,CAAC,WAAW,EAAE,WAAW,KAAK,WAAW,EACnD,SAAS,CAAC,EAAE,mBAAmB,GAC9B,KAAK,CAQP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filter-operators.js","names":[],"sources":["../../../../../zql/src/ivm/filter-operators.ts"],"sourcesContent":["import {makeEmptyIteratorWithReturn} from '../../../shared/src/iterables.ts';\nimport type {BuilderDelegate} from '../builder/builder.ts';\nimport type {NoSubqueryCondition} from '../builder/filter.ts';\nimport type {Change} from './change.ts';\nimport {type Node} from './data.ts';\nimport type {FetchRequest, Input, InputBase, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\n/**\n * The `where` clause of a ZQL query is implemented using a sub-graph of\n * `FilterOperators`. This sub-graph starts with a `FilterStart` operator,\n * that adapts from the normal `Operator` `Output`, to the\n * `FilterOperator` `FilterInput`, and ends with a `FilterEnd` operator that\n * adapts from a `FilterOperator` `FilterOutput` to a normal `Operator` `Input`.\n * `FilterOperator`'s do not have `fetch` instead they have a\n * `filter(node: Node): boolean` method.\n * They also have `push` which is just like normal `Operator` push.\n * Not having a `fetch` means these `FilterOperator`'s cannot modify\n * `Node` `row`s or `relationship`s, but they shouldn't, they should just\n * filter.\n *\n * This `FilterOperator` abstraction enables much more efficient processing of\n * `fetch` for `where` clauses containing OR conditions.\n *\n * See https://github.com/rocicorp/mono/pull/4339\n */\n\nexport interface FilterInput extends InputBase {\n /** Tell the input where to send its output. */\n setFilterOutput(output: FilterOutput): void;\n}\n\nexport interface FilterOutput extends Output {\n // Lets the operator know that we're in a loop of filtering\n // nodes. E.g., so the operator can cache results for the\n // duration of the loop.\n beginFilter(): void;\n filter(node: Node): IterableIterator<'yield', boolean>;\n endFilter(): void;\n}\n\nexport interface FilterOperator extends FilterInput, FilterOutput {}\n\n/**\n * An implementation of FilterOutput that throws if push or filter is called.\n * It is used as the initial value for for an operator's output before it is\n * set.\n */\nexport const throwFilterOutput: FilterOutput = {\n // oxlint-disable-next-line require-yield\n *push(_change: Change): Stream<'yield'> {\n throw new Error('Output not set');\n },\n\n // oxlint-disable-next-line require-yield\n *filter(_node: Node): IterableIterator<'yield', boolean> {\n throw new Error('Output not set');\n },\n\n reconcile(): Stream<'yield'> {\n throw new Error('Output not set');\n },\n\n beginFilter() {},\n endFilter() {},\n};\n\nexport class FilterStart implements FilterInput, Output {\n readonly #input: Input;\n readonly #condition: NoSubqueryCondition | undefined;\n #output: FilterOutput = throwFilterOutput;\n\n constructor(input: Input, condition?: NoSubqueryCondition) {\n this.#input = input;\n this.#condition = condition;\n input.setOutput(this);\n }\n\n setFilterOutput(output: FilterOutput) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n push(change: Change) {\n return this.#output.push(change, this);\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n const mergedFilter = mergeFilters(req.filter, this.#condition);\n const childReq =\n mergedFilter === req.filter ? req : {...req, filter: mergedFilter};\n this.#output.beginFilter();\n try {\n for (const node of this.#input.fetch(childReq)) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n if (yield* this.#output.filter(node)) {\n yield node;\n }\n }\n } finally {\n // finally is important if an exception is thrown or\n // if the stream is not fully consumed.\n this.#output.endFilter();\n }\n }\n}\n\nfunction mergeFilters(\n reqFilter: NoSubqueryCondition | undefined,\n ownCondition: NoSubqueryCondition | undefined,\n): NoSubqueryCondition | undefined {\n if (!ownCondition) {\n return reqFilter;\n }\n if (!reqFilter) {\n return ownCondition;\n }\n return {type: 'and', conditions: [reqFilter, ownCondition]};\n}\n\nexport class FilterEnd implements Input, FilterOutput {\n readonly #start: FilterStart;\n readonly #input: FilterInput;\n\n #output: Output = throwFilterOutput;\n\n constructor(start: FilterStart, input: FilterInput) {\n this.#start = start;\n this.#input = input;\n input.setFilterOutput(this);\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n return this.#start.fetch(req);\n }\n\n beginFilter() {}\n endFilter() {}\n\n filter(_node: Node) {\n return returnTrueEmptyIterator;\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n push(change: Change) {\n return this.#output.push(change, this);\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n}\n\nconst returnTrueEmptyIterator = makeEmptyIteratorWithReturn(true);\n\nexport function buildFilterPipeline(\n input: Input,\n delegate: BuilderDelegate,\n pipeline: (filterInput: FilterInput) => FilterInput,\n condition?: NoSubqueryCondition,\n): Input {\n const filterStart = new FilterStart(input, condition);\n delegate.addEdge(input, filterStart);\n const middle = pipeline(filterStart);\n delegate.addEdge(filterStart, middle);\n const filterEnd = new FilterEnd(filterStart, middle);\n delegate.addEdge(middle, filterEnd);\n return filterEnd;\n}\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"filter-operators.js","names":[],"sources":["../../../../../zql/src/ivm/filter-operators.ts"],"sourcesContent":["import {makeEmptyIteratorWithReturn} from '../../../shared/src/iterables.ts';\nimport type {BuilderDelegate} from '../builder/builder.ts';\nimport type {NoSubqueryCondition} from '../builder/filter.ts';\nimport type {Change} from './change.ts';\nimport {type Node} from './data.ts';\nimport type {FetchRequest, Input, InputBase, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\n/**\n * The `where` clause of a ZQL query is implemented using a sub-graph of\n * `FilterOperators`. This sub-graph starts with a `FilterStart` operator,\n * that adapts from the normal `Operator` `Output`, to the\n * `FilterOperator` `FilterInput`, and ends with a `FilterEnd` operator that\n * adapts from a `FilterOperator` `FilterOutput` to a normal `Operator` `Input`.\n * `FilterOperator`'s do not have `fetch` instead they have a\n * `filter(node: Node): boolean` method.\n * They also have `push` which is just like normal `Operator` push.\n * Not having a `fetch` means these `FilterOperator`'s cannot modify\n * `Node` `row`s or `relationship`s, but they shouldn't, they should just\n * filter.\n *\n * One exception: during a fetch, `Exists` replaces the relationship it read\n * with a function returning the children it read, so that the consumer does\n * not fetch them again. The relationship yields the same nodes, so other\n * branches of a `FanOut`, which see the same node object, are not affected.\n *\n * This `FilterOperator` abstraction enables much more efficient processing of\n * `fetch` for `where` clauses containing OR conditions.\n *\n * See https://github.com/rocicorp/mono/pull/4339\n */\n\nexport interface FilterInput extends InputBase {\n /** Tell the input where to send its output. */\n setFilterOutput(output: FilterOutput): void;\n}\n\nexport interface FilterOutput extends Output {\n // Lets the operator know that we're in a loop of filtering\n // nodes. E.g., so the operator can cache results for the\n // duration of the loop.\n beginFilter(): void;\n filter(node: Node): IterableIterator<'yield', boolean>;\n endFilter(): void;\n}\n\nexport interface FilterOperator extends FilterInput, FilterOutput {}\n\n/**\n * An implementation of FilterOutput that throws if push or filter is called.\n * It is used as the initial value for for an operator's output before it is\n * set.\n */\nexport const throwFilterOutput: FilterOutput = {\n // oxlint-disable-next-line require-yield\n *push(_change: Change): Stream<'yield'> {\n throw new Error('Output not set');\n },\n\n // oxlint-disable-next-line require-yield\n *filter(_node: Node): IterableIterator<'yield', boolean> {\n throw new Error('Output not set');\n },\n\n reconcile(): Stream<'yield'> {\n throw new Error('Output not set');\n },\n\n beginFilter() {},\n endFilter() {},\n};\n\nexport class FilterStart implements FilterInput, Output {\n readonly #input: Input;\n readonly #condition: NoSubqueryCondition | undefined;\n #output: FilterOutput = throwFilterOutput;\n\n constructor(input: Input, condition?: NoSubqueryCondition) {\n this.#input = input;\n this.#condition = condition;\n input.setOutput(this);\n }\n\n setFilterOutput(output: FilterOutput) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n push(change: Change) {\n return this.#output.push(change, this);\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n const mergedFilter = mergeFilters(req.filter, this.#condition);\n const childReq =\n mergedFilter === req.filter ? req : {...req, filter: mergedFilter};\n this.#output.beginFilter();\n try {\n for (const node of this.#input.fetch(childReq)) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n if (yield* this.#output.filter(node)) {\n yield node;\n }\n }\n } finally {\n // finally is important if an exception is thrown or\n // if the stream is not fully consumed.\n this.#output.endFilter();\n }\n }\n}\n\nfunction mergeFilters(\n reqFilter: NoSubqueryCondition | undefined,\n ownCondition: NoSubqueryCondition | undefined,\n): NoSubqueryCondition | undefined {\n if (!ownCondition) {\n return reqFilter;\n }\n if (!reqFilter) {\n return ownCondition;\n }\n return {type: 'and', conditions: [reqFilter, ownCondition]};\n}\n\nexport class FilterEnd implements Input, FilterOutput {\n readonly #start: FilterStart;\n readonly #input: FilterInput;\n\n #output: Output = throwFilterOutput;\n\n constructor(start: FilterStart, input: FilterInput) {\n this.#start = start;\n this.#input = input;\n input.setFilterOutput(this);\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n return this.#start.fetch(req);\n }\n\n beginFilter() {}\n endFilter() {}\n\n filter(_node: Node) {\n return returnTrueEmptyIterator;\n }\n\n setOutput(output: Output) {\n this.#output = output;\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n push(change: Change) {\n return this.#output.push(change, this);\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n}\n\nconst returnTrueEmptyIterator = makeEmptyIteratorWithReturn(true);\n\nexport function buildFilterPipeline(\n input: Input,\n delegate: BuilderDelegate,\n pipeline: (filterInput: FilterInput) => FilterInput,\n condition?: NoSubqueryCondition,\n): Input {\n const filterStart = new FilterStart(input, condition);\n delegate.addEdge(input, filterStart);\n const middle = pipeline(filterStart);\n delegate.addEdge(filterStart, middle);\n const filterEnd = new FilterEnd(filterStart, middle);\n delegate.addEdge(middle, filterEnd);\n return filterEnd;\n}\n"],"mappings":";;;;;;;;AAsDA,IAAa,oBAAkC;CAE7C,CAAC,KAAK,SAAkC;EACtC,MAAM,IAAI,MAAM,gBAAgB;CAClC;CAGA,CAAC,OAAO,OAAiD;EACvD,MAAM,IAAI,MAAM,gBAAgB;CAClC;CAEA,YAA6B;EAC3B,MAAM,IAAI,MAAM,gBAAgB;CAClC;CAEA,cAAc,CAAC;CACf,YAAY,CAAC;AACf;AAEA,IAAa,cAAb,MAAwD;CACtD;CACA;CACA,UAAwB;CAExB,YAAY,OAAc,WAAiC;EACzD,KAAK,SAAS;EACd,KAAK,aAAa;EAClB,MAAM,UAAU,IAAI;CACtB;CAEA,gBAAgB,QAAsB;EACpC,KAAK,UAAU;CACjB;CAEA,UAAgB;EACd,KAAK,OAAO,QAAQ;CACtB;CAEA,YAA0B;EACxB,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,KAAK,QAAgB;EACnB,OAAO,KAAK,QAAQ,KAAK,QAAQ,IAAI;CACvC;CAEA,CAAC,UAAU,SAAqC;EAC9C,IAAI,KAAK,QAAQ,WACf,OAAO,KAAK,QAAQ,UAAU,IAAI;CAEtC;CAEA,CA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B,MAAM,EAAE,MAAM,CAAC;IACf,kBAAkB,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IAC7C,aAAa,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAC9C;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,CAAC,EAAE,EAAE,QAAQ,GAAG,YAAY,CAAC;IACrC,QAAQ,CAAC,WAAW,EAAE,SAAS,CAAC;CACjC,CAAC;AAEF;;;;;;;;;GASG;AACH,qBAAa,IAAK,YAAW,KAAK;;IAkChC,YAAY,EACV,MAAM,EACN,KAAK,EACL,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,MAAM,EACN,kBAAkB,EAClB,aAAa,EACb,MAAM,GACP,EAAE,IAAI,EAkDN;IAQD,OAAO,IAAI,IAAI,CAGd;IAED,IAAI,kBAAkB,IAAI,SAAS,CAElC;IAED,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAE9B;IAED,SAAS,IAAI,YAAY,CAExB;IAEA,KAAK,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAAC,IAAI,GAAG,OAAO,CAAC,CAShD;CA6QF"}
|
package/out/zql/src/ivm/join.js
CHANGED
|
@@ -216,16 +216,19 @@ var Join = class {
|
|
|
216
216
|
if (this.#indexesParents) this.#parentIndex.remove(row);
|
|
217
217
|
}
|
|
218
218
|
#processParentNode(parentNodeRow, parentNodeRelations) {
|
|
219
|
-
const childStream = () => {
|
|
219
|
+
const childStream = (countOnly) => {
|
|
220
220
|
const constraint = buildJoinConstraint(parentNodeRow, this.#parentKey, this.#childKey);
|
|
221
|
-
const stream = constraint ? this.#child.fetch({ constraint }) : [];
|
|
222
221
|
const inPushQueue = this.#isAfterInprogressPosition(parentNodeRow) && (this.#inprogressParentFetchBounds === void 0 || isInParentFetch(this.#inprogressParentFetchBounds, parentNodeRow, this.#schema.compareRows));
|
|
223
222
|
if (this.#inprogressChildChange && isJoinMatch(parentNodeRow, this.#parentKey, this.#inprogressChildChange[1].row, this.#childKey) && inPushQueue) {
|
|
223
|
+
const stream = constraint ? this.#child.fetch({ constraint }) : [];
|
|
224
224
|
const childSchema = this.#child.getSchema();
|
|
225
225
|
if (childSchema.sort === void 0) return generateWithOverlayUnordered(stream, this.#inprogressChildChange, childSchema);
|
|
226
226
|
return generateWithOverlay(stream, this.#inprogressChildChange, childSchema);
|
|
227
227
|
}
|
|
228
|
-
return
|
|
228
|
+
return constraint ? this.#child.fetch(countOnly ? {
|
|
229
|
+
constraint,
|
|
230
|
+
countOnly
|
|
231
|
+
} : { constraint }) : [];
|
|
229
232
|
};
|
|
230
233
|
return {
|
|
231
234
|
row: parentNodeRow,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join.js","names":[],"sources":["../../../../../zql/src/ivm/join.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {\n makeAddChange,\n makeChildChange,\n makeEditChange,\n makeRemoveChange,\n type Change,\n} from './change.ts';\nimport type {Node} from './data.ts';\nimport {JoinIndex} from './join-index.ts';\nimport {\n buildJoinConstraint,\n canonicalKey,\n generateWithOverlay,\n generateWithOverlayUnordered,\n isJoinMatch,\n rowEqualsForCompoundKey,\n} from './join-utils.ts';\nimport {mergeSortedStreams} from './memory-source.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\nimport {\n isInParentFetch,\n readParentFetchBounds,\n type ParentFetchBound,\n type TakeBoundProvider,\n} from './take-gate.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n relationshipName: string;\n hidden: boolean;\n system: System;\n parentPartitionKey?: CompoundKey | undefined;\n boundProvider?: TakeBoundProvider | undefined;\n /**\n * Set when this join feeds an EXISTS or NOT EXISTS condition. Its parent\n * index is then kept by a JoinIndexTap at the end of the pipeline, so it\n * only holds the parents the pipeline emits, not every parent this join\n * sees. A child change that misses the index is dropped unless it could\n * make a parent pass the condition: an add for EXISTS, a remove for NOT\n * EXISTS. Those still fetch the parents.\n */\n exists?: ExistsJoin | undefined;\n};\n\nexport type ExistsJoin = {\n readonly op: 'EXISTS' | 'NOT EXISTS';\n readonly parentIndex: JoinIndex;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n readonly #parentIndex: JoinIndex;\n /**\n * Whether this join adds and removes parents in #parentIndex itself. Not\n * so for EXISTS joins, see Args.exists.\n */\n readonly #indexesParents: boolean;\n /**\n * The child change type that is still pushed to the parents when no\n * indexed parent has its join key. See Args.exists.\n */\n readonly #qualifyingChildChange: ChangeType | undefined;\n readonly #boundProvider: TakeBoundProvider | undefined;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: Change | undefined;\n #inprogressChildChangePosition: Row | undefined;\n /**\n * Primary keys of the parents #inprogressChildChange has reached so far,\n * kept only when the parent input is unordered. An unordered stream is not\n * in `compareRows` order (SQLite returns it in whatever order its plan\n * visits, e.g. rowid order), so whether a parent is still in the push queue\n * cannot be decided by comparing it to #inprogressChildChangePosition.\n */\n #inprogressReachedParents: Set<string> | undefined;\n #inprogressParentFetchBounds: ParentFetchBound[] | undefined;\n\n constructor({\n parent,\n child,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n parentPartitionKey,\n boundProvider,\n exists,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n assert(!exists || !parentPartitionKey, 'EXISTS joins are not partitioned');\n this.#parent = parent;\n this.#child = child;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n if (exists) {\n this.#parentIndex = exists.parentIndex;\n this.#indexesParents = false;\n this.#qualifyingChildChange =\n exists.op === 'EXISTS' ? ChangeType.ADD : ChangeType.REMOVE;\n } else {\n this.#parentIndex = new JoinIndex(\n parentKey,\n parent.getSchema().primaryKey,\n parentPartitionKey,\n );\n this.#indexesParents = true;\n this.#qualifyingChildChange = undefined;\n }\n this.#boundProvider = boundProvider;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n reconcile: () => this.#reconcile(),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n reconcile: () => this.#reconcile(),\n });\n }\n\n *#reconcile(): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n get parentIndexForTest(): JoinIndex {\n return this.#parentIndex;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n for (const parentNode of this.#parent.fetch(req)) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#indexParentRow(parentNode.row);\n yield this.#processParentNode(parentNode.row, parentNode.relationships);\n }\n }\n\n *#pushParent(change: Change): Stream<'yield'> {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n this.#indexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeAddChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n ),\n this,\n );\n break;\n case ChangeType.REMOVE:\n this.#unindexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeRemoveChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n ),\n this,\n );\n break;\n case ChangeType.CHILD:\n yield* this.#output.push(\n makeChildChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n change[ChangeIndex.CHILD_DATA],\n ),\n this,\n );\n break;\n case ChangeType.EDIT: {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n this.#unindexParentRow(change[ChangeIndex.OLD_NODE].row);\n this.#indexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeEditChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n this.#processParentNode(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.OLD_NODE].relationships,\n ),\n ),\n this,\n );\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n *#pushChild(change: Change): Stream<'yield'> {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n case ChangeType.REMOVE:\n yield* this.#pushChildChange(change[ChangeIndex.NODE].row, change);\n break;\n case ChangeType.CHILD:\n yield* this.#pushChildChange(change[ChangeIndex.NODE].row, change);\n break;\n case ChangeType.EDIT: {\n const childRow = change[ChangeIndex.NODE].row;\n const oldChildRow = change[ChangeIndex.OLD_NODE].row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n yield* this.#pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#pushChildChange(childRow: Row, change: Change): Stream<'yield'> {\n this.#inprogressChildChange = change;\n this.#inprogressChildChangePosition = undefined;\n this.#inprogressReachedParents =\n this.#parent.getSchema().sort === undefined ? new Set() : undefined;\n try {\n const constraint = buildJoinConstraint(\n childRow,\n this.#childKey,\n this.#parentKey,\n );\n if (constraint) {\n const partitions = this.#parentIndex.lookup(childRow, this.#childKey);\n let fetchConstraints: Record<string, Value>[];\n if (partitions) {\n fetchConstraints = partitions.map(partitionConstraint =>\n partitionConstraint\n ? {...constraint, ...partitionConstraint}\n : constraint,\n );\n } else if (change[ChangeIndex.TYPE] === this.#qualifyingChildChange) {\n fetchConstraints = [constraint];\n } else {\n return;\n }\n\n if (this.#boundProvider) {\n this.#inprogressParentFetchBounds = readParentFetchBounds(\n this.#boundProvider,\n fetchConstraints,\n );\n }\n\n let parentNodeStream: Stream<Node | 'yield'>;\n if (fetchConstraints.length === 1) {\n parentNodeStream = this.#parent.fetch({\n constraint: fetchConstraints[0],\n });\n } else {\n const streams = fetchConstraints.map(c =>\n this.#parent.fetch({constraint: c}),\n );\n const compare = (a: Node, b: Node) =>\n this.#schema.compareRows(a.row, b.row);\n parentNodeStream = mergeSortedStreams(streams, compare);\n }\n\n for (const parentNode of parentNodeStream) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#inprogressChildChangePosition = parentNode.row;\n this.#inprogressReachedParents?.add(\n canonicalKey(parentNode.row, this.#schema.primaryKey),\n );\n const childChange = makeChildChange(\n this.#processParentNode(parentNode.row, parentNode.relationships),\n {\n relationshipName: this.#relationshipName,\n change,\n },\n );\n yield* this.#output.push(childChange, this);\n }\n }\n } finally {\n this.#inprogressChildChange = undefined;\n this.#inprogressChildChangePosition = undefined;\n this.#inprogressReachedParents = undefined;\n this.#inprogressParentFetchBounds = undefined;\n }\n }\n\n /**\n * Whether the in-progress child change has yet to reach `parentNodeRow`,\n * i.e. the row comes after #inprogressChildChangePosition in the parent\n * stream.\n */\n #isAfterInprogressPosition(parentNodeRow: Row): boolean {\n if (this.#inprogressChildChangePosition === undefined) {\n return false;\n }\n if (this.#inprogressReachedParents) {\n return !this.#inprogressReachedParents.has(\n canonicalKey(parentNodeRow, this.#schema.primaryKey),\n );\n }\n return (\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChangePosition,\n ) > 0\n );\n }\n\n #indexParentRow(row: Row): void {\n if (this.#indexesParents) {\n this.#parentIndex.add(row);\n }\n }\n\n #unindexParentRow(row: Row): void {\n if (this.#indexesParents) {\n this.#parentIndex.remove(row);\n }\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node | 'yield'>>,\n ): Node {\n const childStream = () => {\n const constraint = buildJoinConstraint(\n parentNodeRow,\n this.#parentKey,\n this.#childKey,\n );\n const stream = constraint ? this.#child.fetch({constraint}) : [];\n\n // The parent has yet to get the in-progress child change if it comes\n // after the current position and a parent fetch of the push yields it.\n // With a TakeGate the fetches are capped at the bounds read when they\n // started.\n const inPushQueue =\n this.#isAfterInprogressPosition(parentNodeRow) &&\n (this.#inprogressParentFetchBounds === undefined ||\n isInParentFetch(\n this.#inprogressParentFetchBounds,\n parentNodeRow,\n this.#schema.compareRows,\n ));\n\n if (\n this.#inprogressChildChange &&\n isJoinMatch(\n parentNodeRow,\n this.#parentKey,\n this.#inprogressChildChange[ChangeIndex.NODE].row,\n this.#childKey,\n ) &&\n inPushQueue\n ) {\n const childSchema = this.#child.getSchema();\n if (childSchema.sort === undefined) {\n return generateWithOverlayUnordered(\n stream,\n this.#inprogressChildChange,\n childSchema,\n );\n }\n return generateWithOverlay(\n stream,\n this.#inprogressChildChange,\n childSchema,\n );\n }\n return stream;\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2EA,IAAa,OAAb,MAAmC;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;;;;;CAKA;;;;;CAKA;CACA;CAEA,UAAkB;CAElB;CACA;;;;;;;;CAQA;CACA;CAEA,YAAY,EACV,QACA,OACA,WACA,UACA,kBACA,QACA,QACA,oBACA,eACA,UACO;EACP,OAAO,WAAW,OAAO,8CAA8C;EACvE,OACE,UAAU,WAAW,SAAS,QAC9B,uDACF;EACA,OAAO,CAAC,UAAU,CAAC,oBAAoB,kCAAkC;EACzE,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,aAAa;EAClB,KAAK,YAAY;EACjB,KAAK,oBAAoB;EACzB,IAAI,QAAQ;GACV,KAAK,eAAe,OAAO;GAC3B,KAAK,kBAAkB;GACvB,KAAK,yBACH,OAAO,OAAO,WAAW,IAAiB;EAC9C,OAAO;GACL,KAAK,eAAe,IAAI,UACtB,WACA,OAAO,UAAU,CAAC,CAAC,YACnB,kBACF;GACA,KAAK,kBAAkB;GACvB,KAAK,yBAAyB,KAAA;EAChC;EACA,KAAK,iBAAiB;EAEtB,MAAM,eAAe,OAAO,UAAU;EACtC,MAAM,cAAc,MAAM,UAAU;EACpC,KAAK,UAAU;GACb,GAAG;GACH,eAAe;IACb,GAAG,aAAa;KACf,mBAAmB;KAClB,GAAG;KACH,UAAU;KACV;IACF;GACF;EACF;EAEA,OAAO,UAAU;GACf,OAAO,WAAmB,KAAK,YAAY,MAAM;GACjD,iBAAiB,KAAK,WAAW;EACnC,CAAC;EACD,MAAM,UAAU;GACd,OAAO,WAAmB,KAAK,WAAW,MAAM;GAChD,iBAAiB,KAAK,WAAW;EACnC,CAAC;CACH;CAEA,CAAC,aAA8B;EAC7B,IAAI,KAAK,QAAQ,WACf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AC,IAAI,CAAC;GAM/D,MAAM,cACJ,KAAK,2BAA2B,aAAa,MAC5C,KAAK,iCAAiC,KAAA,KACrC,gBACE,KAAK,8BACL,eACA,KAAK,QAAQ,WACf;GAEJ,IACE,KAAK,0BACL,YACE,eACA,KAAK,YACL,KAAK,uBAAuB,EAAiB,CAAC,KAC9C,KAAK,SACP,KACA,aACA;IACA,MAAM,cAAc,KAAK,OAAO,UAAU;IAC1C,IAAI,YAAY,SAAS,KAAA,GACvB,OAAO,6BACL,QACA,KAAK,wBACL,WACF;IAEF,OAAO,oBACL,QACA,KAAK,wBACL,WACF;GACF;GACA,OAAO;EACT;EAEA,OAAO;GACL,KAAK;GACL,eAAe;IACb,GAAG;KACF,KAAK,oBAAoB;GAC5B;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"join.js","names":[],"sources":["../../../../../zql/src/ivm/join.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {\n makeAddChange,\n makeChildChange,\n makeEditChange,\n makeRemoveChange,\n type Change,\n} from './change.ts';\nimport type {Node} from './data.ts';\nimport {JoinIndex} from './join-index.ts';\nimport {\n buildJoinConstraint,\n canonicalKey,\n generateWithOverlay,\n generateWithOverlayUnordered,\n isJoinMatch,\n rowEqualsForCompoundKey,\n} from './join-utils.ts';\nimport {mergeSortedStreams} from './memory-source.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\nimport {\n isInParentFetch,\n readParentFetchBounds,\n type ParentFetchBound,\n type TakeBoundProvider,\n} from './take-gate.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n relationshipName: string;\n hidden: boolean;\n system: System;\n parentPartitionKey?: CompoundKey | undefined;\n boundProvider?: TakeBoundProvider | undefined;\n /**\n * Set when this join feeds an EXISTS or NOT EXISTS condition. Its parent\n * index is then kept by a JoinIndexTap at the end of the pipeline, so it\n * only holds the parents the pipeline emits, not every parent this join\n * sees. A child change that misses the index is dropped unless it could\n * make a parent pass the condition: an add for EXISTS, a remove for NOT\n * EXISTS. Those still fetch the parents.\n */\n exists?: ExistsJoin | undefined;\n};\n\nexport type ExistsJoin = {\n readonly op: 'EXISTS' | 'NOT EXISTS';\n readonly parentIndex: JoinIndex;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n readonly #parentIndex: JoinIndex;\n /**\n * Whether this join adds and removes parents in #parentIndex itself. Not\n * so for EXISTS joins, see Args.exists.\n */\n readonly #indexesParents: boolean;\n /**\n * The child change type that is still pushed to the parents when no\n * indexed parent has its join key. See Args.exists.\n */\n readonly #qualifyingChildChange: ChangeType | undefined;\n readonly #boundProvider: TakeBoundProvider | undefined;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: Change | undefined;\n #inprogressChildChangePosition: Row | undefined;\n /**\n * Primary keys of the parents #inprogressChildChange has reached so far,\n * kept only when the parent input is unordered. An unordered stream is not\n * in `compareRows` order (SQLite returns it in whatever order its plan\n * visits, e.g. rowid order), so whether a parent is still in the push queue\n * cannot be decided by comparing it to #inprogressChildChangePosition.\n */\n #inprogressReachedParents: Set<string> | undefined;\n #inprogressParentFetchBounds: ParentFetchBound[] | undefined;\n\n constructor({\n parent,\n child,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n parentPartitionKey,\n boundProvider,\n exists,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n assert(!exists || !parentPartitionKey, 'EXISTS joins are not partitioned');\n this.#parent = parent;\n this.#child = child;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n if (exists) {\n this.#parentIndex = exists.parentIndex;\n this.#indexesParents = false;\n this.#qualifyingChildChange =\n exists.op === 'EXISTS' ? ChangeType.ADD : ChangeType.REMOVE;\n } else {\n this.#parentIndex = new JoinIndex(\n parentKey,\n parent.getSchema().primaryKey,\n parentPartitionKey,\n );\n this.#indexesParents = true;\n this.#qualifyingChildChange = undefined;\n }\n this.#boundProvider = boundProvider;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n reconcile: () => this.#reconcile(),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n reconcile: () => this.#reconcile(),\n });\n }\n\n *#reconcile(): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n get parentIndexForTest(): JoinIndex {\n return this.#parentIndex;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n for (const parentNode of this.#parent.fetch(req)) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#indexParentRow(parentNode.row);\n yield this.#processParentNode(parentNode.row, parentNode.relationships);\n }\n }\n\n *#pushParent(change: Change): Stream<'yield'> {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n this.#indexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeAddChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n ),\n this,\n );\n break;\n case ChangeType.REMOVE:\n this.#unindexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeRemoveChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n ),\n this,\n );\n break;\n case ChangeType.CHILD:\n yield* this.#output.push(\n makeChildChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n change[ChangeIndex.CHILD_DATA],\n ),\n this,\n );\n break;\n case ChangeType.EDIT: {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n this.#unindexParentRow(change[ChangeIndex.OLD_NODE].row);\n this.#indexParentRow(change[ChangeIndex.NODE].row);\n yield* this.#output.push(\n makeEditChange(\n this.#processParentNode(\n change[ChangeIndex.NODE].row,\n change[ChangeIndex.NODE].relationships,\n ),\n this.#processParentNode(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.OLD_NODE].relationships,\n ),\n ),\n this,\n );\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n *#pushChild(change: Change): Stream<'yield'> {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n case ChangeType.REMOVE:\n yield* this.#pushChildChange(change[ChangeIndex.NODE].row, change);\n break;\n case ChangeType.CHILD:\n yield* this.#pushChildChange(change[ChangeIndex.NODE].row, change);\n break;\n case ChangeType.EDIT: {\n const childRow = change[ChangeIndex.NODE].row;\n const oldChildRow = change[ChangeIndex.OLD_NODE].row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n yield* this.#pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#pushChildChange(childRow: Row, change: Change): Stream<'yield'> {\n this.#inprogressChildChange = change;\n this.#inprogressChildChangePosition = undefined;\n this.#inprogressReachedParents =\n this.#parent.getSchema().sort === undefined ? new Set() : undefined;\n try {\n const constraint = buildJoinConstraint(\n childRow,\n this.#childKey,\n this.#parentKey,\n );\n if (constraint) {\n const partitions = this.#parentIndex.lookup(childRow, this.#childKey);\n let fetchConstraints: Record<string, Value>[];\n if (partitions) {\n fetchConstraints = partitions.map(partitionConstraint =>\n partitionConstraint\n ? {...constraint, ...partitionConstraint}\n : constraint,\n );\n } else if (change[ChangeIndex.TYPE] === this.#qualifyingChildChange) {\n fetchConstraints = [constraint];\n } else {\n return;\n }\n\n if (this.#boundProvider) {\n this.#inprogressParentFetchBounds = readParentFetchBounds(\n this.#boundProvider,\n fetchConstraints,\n );\n }\n\n let parentNodeStream: Stream<Node | 'yield'>;\n if (fetchConstraints.length === 1) {\n parentNodeStream = this.#parent.fetch({\n constraint: fetchConstraints[0],\n });\n } else {\n const streams = fetchConstraints.map(c =>\n this.#parent.fetch({constraint: c}),\n );\n const compare = (a: Node, b: Node) =>\n this.#schema.compareRows(a.row, b.row);\n parentNodeStream = mergeSortedStreams(streams, compare);\n }\n\n for (const parentNode of parentNodeStream) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#inprogressChildChangePosition = parentNode.row;\n this.#inprogressReachedParents?.add(\n canonicalKey(parentNode.row, this.#schema.primaryKey),\n );\n const childChange = makeChildChange(\n this.#processParentNode(parentNode.row, parentNode.relationships),\n {\n relationshipName: this.#relationshipName,\n change,\n },\n );\n yield* this.#output.push(childChange, this);\n }\n }\n } finally {\n this.#inprogressChildChange = undefined;\n this.#inprogressChildChangePosition = undefined;\n this.#inprogressReachedParents = undefined;\n this.#inprogressParentFetchBounds = undefined;\n }\n }\n\n /**\n * Whether the in-progress child change has yet to reach `parentNodeRow`,\n * i.e. the row comes after #inprogressChildChangePosition in the parent\n * stream.\n */\n #isAfterInprogressPosition(parentNodeRow: Row): boolean {\n if (this.#inprogressChildChangePosition === undefined) {\n return false;\n }\n if (this.#inprogressReachedParents) {\n return !this.#inprogressReachedParents.has(\n canonicalKey(parentNodeRow, this.#schema.primaryKey),\n );\n }\n return (\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChangePosition,\n ) > 0\n );\n }\n\n #indexParentRow(row: Row): void {\n if (this.#indexesParents) {\n this.#parentIndex.add(row);\n }\n }\n\n #unindexParentRow(row: Row): void {\n if (this.#indexesParents) {\n this.#parentIndex.remove(row);\n }\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node | 'yield'>>,\n ): Node {\n const childStream = (countOnly?: boolean | undefined) => {\n const constraint = buildJoinConstraint(\n parentNodeRow,\n this.#parentKey,\n this.#childKey,\n );\n\n // The parent has yet to get the in-progress child change if it comes\n // after the current position and a parent fetch of the push yields it.\n // With a TakeGate the fetches are capped at the bounds read when they\n // started.\n const inPushQueue =\n this.#isAfterInprogressPosition(parentNodeRow) &&\n (this.#inprogressParentFetchBounds === undefined ||\n isInParentFetch(\n this.#inprogressParentFetchBounds,\n parentNodeRow,\n this.#schema.compareRows,\n ));\n\n if (\n this.#inprogressChildChange &&\n isJoinMatch(\n parentNodeRow,\n this.#parentKey,\n this.#inprogressChildChange[ChangeIndex.NODE].row,\n this.#childKey,\n ) &&\n inPushQueue\n ) {\n // The overlay needs the child rows, so countOnly is not forwarded.\n const stream = constraint ? this.#child.fetch({constraint}) : [];\n const childSchema = this.#child.getSchema();\n if (childSchema.sort === undefined) {\n return generateWithOverlayUnordered(\n stream,\n this.#inprogressChildChange,\n childSchema,\n );\n }\n return generateWithOverlay(\n stream,\n this.#inprogressChildChange,\n childSchema,\n );\n }\n return constraint\n ? this.#child.fetch(countOnly ? {constraint, countOnly} : {constraint})\n : [];\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2EA,IAAa,OAAb,MAAmC;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;;;;;CAKA;;;;;CAKA;CACA;CAEA,UAAkB;CAElB;CACA;;;;;;;;CAQA;CACA;CAEA,YAAY,EACV,QACA,OACA,WACA,UACA,kBACA,QACA,QACA,oBACA,eACA,UACO;EACP,OAAO,WAAW,OAAO,8CAA8C;EACvE,OACE,UAAU,WAAW,SAAS,QAC9B,uDACF;EACA,OAAO,CAAC,UAAU,CAAC,oBAAoB,kCAAkC;EACzE,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,aAAa;EAClB,KAAK,YAAY;EACjB,KAAK,oBAAoB;EACzB,IAAI,QAAQ;GACV,KAAK,eAAe,OAAO;GAC3B,KAAK,kBAAkB;GACvB,KAAK,yBACH,OAAO,OAAO,WAAW,IAAiB;EAC9C,OAAO;GACL,KAAK,eAAe,IAAI,UACtB,WACA,OAAO,UAAU,CAAC,CAAC,YACnB,kBACF;GACA,KAAK,kBAAkB;GACvB,KAAK,yBAAyB,KAAA;EAChC;EACA,KAAK,iBAAiB;EAEtB,MAAM,eAAe,OAAO,UAAU;EACtC,MAAM,cAAc,MAAM,UAAU;EACpC,KAAK,UAAU;GACb,GAAG;GACH,eAAe;IACb,GAAG,aAAa;KACf,mBAAmB;KAClB,GAAG;KACH,UAAU;KACV;IACF;GACF;EACF;EAEA,OAAO,UAAU;GACf,OAAO,WAAmB,KAAK,YAAY,MAAM;GACjD,iBAAiB,KAAK,WAAW;EACnC,CAAC;EACD,MAAM,UAAU;GACd,OAAO,WAAmB,KAAK,WAAW,MAAM;GAChD,iBAAiB,KAAK,WAAW;EACnC,C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AK,SACP;GAMA,MAAM,cACJ,KAAK,2BAA2B,aAAa,MAC5C,KAAK,iCAAiC,KAAA,KACrC,gBACE,KAAK,8BACL,eACA,KAAK,QAAQ,WACf;GAEJ,IACE,KAAK,0BACL,YACE,eACA,KAAK,YACL,KAAK,uBAAuB,EAAiB,CAAC,KAC9C,KAAK,SACP,KACA,aACA;IAEA,MAAM,SAAS,aAAa,KAAK,OAAO,MAAM,EAAC,WAAU,CAAC,IAAI,CAAC;IAC/D,MAAM,cAAc,KAAK,OAAO,UAAU;IAC1C,IAAI,YAAY,SAAS,KAAA,GACvB,OAAO,6BACL,QACA,KAAK,wBACL,WACF;IAEF,OAAO,oBACL,QACA,KAAK,wBACL,WACF;GACF;GACA,OAAO,aACH,KAAK,OAAO,MAAM,YAAY;IAAC;IAAY;GAAS,IAAI,EAAC,WAAU,CAAC,IACpE,CAAC;EACP;EAEA,OAAO;GACL,KAAK;GACL,eAAe;IACb,GAAG;KACF,KAAK,oBAAoB;GAC5B;EACF;CACF;AACF"}
|
|
@@ -4,9 +4,9 @@ import { once, toSorted } from "../../../shared/src/iterables.js";
|
|
|
4
4
|
import { must } from "../../../shared/src/must.js";
|
|
5
5
|
import { skipYields } from "./skip-yields.js";
|
|
6
6
|
import { makeAddChange, makeEditChange, makeRemoveChange } from "./change.js";
|
|
7
|
+
import { compareValues, makeComparator, valuesEqual } from "./data.js";
|
|
7
8
|
import { consume } from "./stream.js";
|
|
8
9
|
import { assertOrderingIncludesPK } from "../query/complete-ordering.js";
|
|
9
|
-
import { compareValues, makeComparator, valuesEqual } from "./data.js";
|
|
10
10
|
import { filterPush } from "./filter-push.js";
|
|
11
11
|
import { constraintMatchesPrimaryKey, constraintMatchesRow, primaryKeyConstraintFromFilters } from "./constraint.js";
|
|
12
12
|
import { BTreeSet } from "../../../shared/src/btree-set.js";
|
|
@@ -72,6 +72,12 @@ export type FetchRequest = {
|
|
|
72
72
|
readonly start?: Start | undefined;
|
|
73
73
|
/** Whether to fetch in reverse order of the SourceSchema's sort. */
|
|
74
74
|
readonly reverse?: boolean | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* The caller only counts the nodes. An operator that knows the count may
|
|
77
|
+
* then yield that many placeholder nodes instead of fetching the rows.
|
|
78
|
+
* `Cap` does this from its state.
|
|
79
|
+
*/
|
|
80
|
+
readonly countOnly?: boolean | undefined;
|
|
75
81
|
/**
|
|
76
82
|
* Additional predicate the consumer wants the source/intermediate operators
|
|
77
83
|
* to apply to the fetched rows. The receiver must AND this with whatever
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operator.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/operator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,6BAA6B,CAAC;AAC3D,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,oCAAoC,CAAC;AAC5D,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,sBAAsB,CAAC;AAC9D,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAE5C;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,iDAAiD;IACjD,SAAS,IAAI,YAAY,CAAC;IAE1B;;;;OAIG;IACH,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,KAAM,SAAQ,SAAS;IACtC,+CAA+C;IAC/C,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEhC;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,GAAG,EAAE,YAAY,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ChD;AAED;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE,MAOzB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,WAAW,QAAS,SAAQ,KAAK,EAAE,MAAM;IAC7C;;;;OAIG;IACH,SAAS,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;CAC/C;AAED;;;GAGG;AACH,MAAM,WAAW,OAAO;IACtB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IACzC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC;IACzD;;OAEG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE;QAAC,MAAM,EAAE,MAAM,CAAA;KAAC,GAAG,MAAM,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB;;;;OAIG;IACH,OAAO,IAAI,IAAI,CAAC;CACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operator.js","names":[],"sources":["../../../../../zql/src/ivm/operator.ts"],"sourcesContent":["import type {JSONValue} from '../../../shared/src/json.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {NoSubqueryCondition} from '../builder/filter.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport type {Node} from './data.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\nexport {skipYields} from './skip-yields.ts';\n\n/**\n * Input to an operator.\n */\nexport interface InputBase {\n /** The schema of the data this input returns. */\n getSchema(): SourceSchema;\n\n /**\n * Completely destroy the input. Destroying an input\n * causes it to call destroy on its upstreams, fully\n * cleaning up a pipeline.\n */\n destroy(): void;\n}\n\nexport interface Input extends InputBase {\n /** Tell the input where to send its output. */\n setOutput(output: Output): void;\n\n /**\n * Fetch data. May modify the data in place.\n * Returns nodes sorted in order of `SourceSchema.compareRows`.\n *\n * The stream may contain 'yield' to yield control to the caller for purposes\n * of responsiveness.\n *\n * Contract:\n * - During fetch: If an input yields 'yield', 'yield' must be yielded to the\n * caller of fetch immediately.\n * - During push: If a fetch to an input consumed by the push logic yields\n * 'yield', it must be yielded to the caller of push immediately.\n * - During reconcile: If a fetch to an input consumed by reconcile logic\n * yields 'yield', it must be yielded to the caller of reconcile immediately.\n */\n fetch(req: FetchRequest): Stream<Node | 'yield'>;\n}\n\n/**\n * A single multi-row IN clause: a non-empty list of Constraints all\n * sharing the same column shape. Sources treat it as\n * `(col_a, col_b, …) IN VALUES (…)`.\n *\n * Caller invariants (sources rely on these — they are not re-checked):\n * - **Unique entries.** TableSource gets set semantics for free from SQL\n * `IN`; MemorySource fans sub-fetches out per entry, so duplicates\n * would yield the same row N times. FlippedJoin groups by canonical\n * parent-key (`flipped-join.ts:#fetchBatched`) before emitting.\n * - **Key-compatible with `req.constraint`.** Entries that contradict\n * `constraint` should be dropped upstream. FlippedJoin filters\n * incompatible children via `constraintsAreCompatible` before adding\n * them to a batch.\n */\nexport type MultiConstraint = readonly Constraint[];\n\nexport type FetchRequest = {\n readonly constraint?: Constraint | undefined;\n\n /**\n * List of multi-row IN clauses, all ANDed together (and ANDed with\n * `constraint` if both are provided). Each entry is a `MultiConstraint`\n * over its own set of columns.\n *\n * Used by FlippedJoin to push child→parent fetches into a single\n * batched statement, and to AND together constraints contributed by\n * chained FlippedJoins (e.g. `assigneeID IN (…) AND creatorID IN (…)`).\n */\n readonly multiConstraints?: readonly MultiConstraint[] | undefined;\n\n /** If supplied, `start.row` must have previously been output by fetch or push. */\n readonly start?: Start | undefined;\n\n /** Whether to fetch in reverse order of the SourceSchema's sort. */\n readonly reverse?: boolean | undefined;\n\n /**\n * Additional predicate the consumer wants the source/intermediate operators\n * to apply to the fetched rows. The receiver must AND this with whatever\n * filtering it already applies. Sources may use this to drive index\n * selection (e.g. PK lookup) the same way they use the connection-time\n * filter.\n *\n * Always a `NoSubqueryCondition` — anything passed via `req.filter` must\n * already have had correlated subqueries stripped (see `transformFilters`).\n *\n * Contract:\n * - The only operator that *introduces* `req.filter` is `FilterStart`. It\n * AND-merges its static condition with whatever `req.filter` it receives\n * and forwards the merged value upstream. No other operator should\n * construct a `req.filter`.\n * - \"Pass-through\" fetch operators (`Skip`, `Take`, `Join`, `FlippedJoin`,\n * `UnionFanIn`, `UnionFanOut`) MUST preserve `req.filter` when forwarding\n * to their input — typically via `{...req, ...overrides}` spread. Dropping\n * it silently regresses predicate pushdown for queries below the\n * forwarding operator.\n * - Operators that *initiate* internal fetches (e.g., `Join.#pushChildChange`,\n * `FlippedJoin.#pushChildChange`, `UnionFanIn.#pushInternalChange`,\n * `Take`'s push-time bound recomputation) construct fresh\n * `FetchRequest`s without `req.filter`, and that is correct: there is no\n * inbound consumer-side filter at those call sites. Any `FilterStart`\n * that sits between such an internal fetch and the source will still\n * apply its own condition on the way through, so the source still gets\n * the right WHERE.\n * - `Cap` is *not* a pass-through: it intentionally builds fresh\n * `{constraint}` requests when replaying tracked PKs and drops any\n * incoming `req.filter`. This is sound only because `Cap`'s sole\n * consumer in production is a `Join`'s child fetch (see\n * `Join.#processParentNode` in `join.ts`), which itself never carries\n * `req.filter` — Join's child fetches are constructed with just\n * `{constraint}` derived from join keys. If `Cap` is ever wired below\n * something that does push a `req.filter`, this carve-out becomes a\n * correctness bug.\n */\n readonly filter?: NoSubqueryCondition | undefined;\n};\n\nexport type Start = {\n readonly row: Row;\n readonly basis: 'at' | 'after';\n};\n\n/**\n * An output for an operator. Typically another Operator in an IVM pipeline,\n * but can also be a terminal sink (such as a View or test consumer).\n */\nexport interface Output {\n /**\n * Phase 1 of two-phase push: pushes incremental changes to data previously\n * received with fetch(). Consumers must apply all pushed changes or the\n * incremental result will be incorrect.\n *\n * Callers must maintain some invariants for correct operation:\n * - Only add rows which do not already exist (by deep equality).\n * - Only remove rows which do exist (by deep equality).\n *\n * Implementations can yield 'yield' to yield control to the caller for\n * purposes of responsiveness.\n *\n * Yield contract:\n * - During a push: If a push call to an output yields 'yield', it must be\n * yielded to the caller of push immediately.\n */\n push(change: Change, pusher: InputBase): Stream<'yield'>;\n\n /**\n * Phase 2 of two-phase push: invoked after Phase 1 changes have propagated.\n * Bounded operators (such as Take or Cap) use this signal to refill deficits,\n * emit refilled rows downstream via push(), and update their bounds.\n *\n * Implementations can yield 'yield' to yield control to the caller for\n * purposes of responsiveness.\n *\n * Yield contract:\n * - During reconcile: If an internal fetch, push, or downstream reconcile call\n * yields 'yield', it must be yielded to the caller of reconcile immediately.\n *\n * This method is optional on Output to allow terminal sinks (such as UI views\n * or custom third-party sinks) that only consume changes to omit it without\n * breaking compatibility. Intermediate operators must check\n * `if (this.#output.reconcile)` before forwarding.\n */\n reconcile?(pusher: InputBase): Stream<'yield'>;\n}\n\n/**\n * An implementation of Output that throws if pushed to. It is used as the\n * initial value for an operator's output before it is set.\n */\nexport const throwOutput: Output = {\n push(_change: Change): Stream<'yield'> {\n throw new Error('Output not set');\n },\n reconcile(): Stream<'yield'> {\n throw new Error('Output not set');\n },\n};\n\n/**\n * Operators are arranged into IVM pipelines.\n * They are stateful.\n * Each operator is an input to the next operator in the chain and an output\n * to the previous.\n */\nexport interface Operator extends Input, Output {\n /**\n * Intermediate pipeline operators MUST implement reconcile so that Phase 2\n * reconciliation reaches all bounded operators in the pipeline and is never\n * accidentally swallowed.\n */\n reconcile(pusher: InputBase): Stream<'yield'>;\n}\n\n/**\n * Operators get access to storage that they can store their internal\n * state in.\n */\nexport interface Storage {\n set(key: string, value: JSONValue): void;\n get(key: string, def?: JSONValue): JSONValue | undefined;\n /**\n * If options is not specified, defaults to scanning all entries.\n */\n scan(options?: {prefix: string}): Stream<[string, JSONValue]>;\n del(key: string): void;\n /**\n * Called by the operator that owns the storage when the operator is\n * destroyed. Releases anything the storage holds outside of the operator\n * (e.g. rows in a shared database). The storage is not used afterwards.\n */\n destroy(): void;\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"operator.js","names":[],"sources":["../../../../../zql/src/ivm/operator.ts"],"sourcesContent":["import type {JSONValue} from '../../../shared/src/json.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {NoSubqueryCondition} from '../builder/filter.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport type {Node} from './data.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\n\nexport {skipYields} from './skip-yields.ts';\n\n/**\n * Input to an operator.\n */\nexport interface InputBase {\n /** The schema of the data this input returns. */\n getSchema(): SourceSchema;\n\n /**\n * Completely destroy the input. Destroying an input\n * causes it to call destroy on its upstreams, fully\n * cleaning up a pipeline.\n */\n destroy(): void;\n}\n\nexport interface Input extends InputBase {\n /** Tell the input where to send its output. */\n setOutput(output: Output): void;\n\n /**\n * Fetch data. May modify the data in place.\n * Returns nodes sorted in order of `SourceSchema.compareRows`.\n *\n * The stream may contain 'yield' to yield control to the caller for purposes\n * of responsiveness.\n *\n * Contract:\n * - During fetch: If an input yields 'yield', 'yield' must be yielded to the\n * caller of fetch immediately.\n * - During push: If a fetch to an input consumed by the push logic yields\n * 'yield', it must be yielded to the caller of push immediately.\n * - During reconcile: If a fetch to an input consumed by reconcile logic\n * yields 'yield', it must be yielded to the caller of reconcile immediately.\n */\n fetch(req: FetchRequest): Stream<Node | 'yield'>;\n}\n\n/**\n * A single multi-row IN clause: a non-empty list of Constraints all\n * sharing the same column shape. Sources treat it as\n * `(col_a, col_b, …) IN VALUES (…)`.\n *\n * Caller invariants (sources rely on these — they are not re-checked):\n * - **Unique entries.** TableSource gets set semantics for free from SQL\n * `IN`; MemorySource fans sub-fetches out per entry, so duplicates\n * would yield the same row N times. FlippedJoin groups by canonical\n * parent-key (`flipped-join.ts:#fetchBatched`) before emitting.\n * - **Key-compatible with `req.constraint`.** Entries that contradict\n * `constraint` should be dropped upstream. FlippedJoin filters\n * incompatible children via `constraintsAreCompatible` before adding\n * them to a batch.\n */\nexport type MultiConstraint = readonly Constraint[];\n\nexport type FetchRequest = {\n readonly constraint?: Constraint | undefined;\n\n /**\n * List of multi-row IN clauses, all ANDed together (and ANDed with\n * `constraint` if both are provided). Each entry is a `MultiConstraint`\n * over its own set of columns.\n *\n * Used by FlippedJoin to push child→parent fetches into a single\n * batched statement, and to AND together constraints contributed by\n * chained FlippedJoins (e.g. `assigneeID IN (…) AND creatorID IN (…)`).\n */\n readonly multiConstraints?: readonly MultiConstraint[] | undefined;\n\n /** If supplied, `start.row` must have previously been output by fetch or push. */\n readonly start?: Start | undefined;\n\n /** Whether to fetch in reverse order of the SourceSchema's sort. */\n readonly reverse?: boolean | undefined;\n\n /**\n * The caller only counts the nodes. An operator that knows the count may\n * then yield that many placeholder nodes instead of fetching the rows.\n * `Cap` does this from its state.\n */\n readonly countOnly?: boolean | undefined;\n\n /**\n * Additional predicate the consumer wants the source/intermediate operators\n * to apply to the fetched rows. The receiver must AND this with whatever\n * filtering it already applies. Sources may use this to drive index\n * selection (e.g. PK lookup) the same way they use the connection-time\n * filter.\n *\n * Always a `NoSubqueryCondition` — anything passed via `req.filter` must\n * already have had correlated subqueries stripped (see `transformFilters`).\n *\n * Contract:\n * - The only operator that *introduces* `req.filter` is `FilterStart`. It\n * AND-merges its static condition with whatever `req.filter` it receives\n * and forwards the merged value upstream. No other operator should\n * construct a `req.filter`.\n * - \"Pass-through\" fetch operators (`Skip`, `Take`, `Join`, `FlippedJoin`,\n * `UnionFanIn`, `UnionFanOut`) MUST preserve `req.filter` when forwarding\n * to their input — typically via `{...req, ...overrides}` spread. Dropping\n * it silently regresses predicate pushdown for queries below the\n * forwarding operator.\n * - Operators that *initiate* internal fetches (e.g., `Join.#pushChildChange`,\n * `FlippedJoin.#pushChildChange`, `UnionFanIn.#pushInternalChange`,\n * `Take`'s push-time bound recomputation) construct fresh\n * `FetchRequest`s without `req.filter`, and that is correct: there is no\n * inbound consumer-side filter at those call sites. Any `FilterStart`\n * that sits between such an internal fetch and the source will still\n * apply its own condition on the way through, so the source still gets\n * the right WHERE.\n * - `Cap` is *not* a pass-through: it intentionally builds fresh\n * `{constraint}` requests when replaying tracked PKs and drops any\n * incoming `req.filter`. This is sound only because `Cap`'s sole\n * consumer in production is a `Join`'s child fetch (see\n * `Join.#processParentNode` in `join.ts`), which itself never carries\n * `req.filter` — Join's child fetches are constructed with just\n * `{constraint}` derived from join keys. If `Cap` is ever wired below\n * something that does push a `req.filter`, this carve-out becomes a\n * correctness bug.\n */\n readonly filter?: NoSubqueryCondition | undefined;\n};\n\nexport type Start = {\n readonly row: Row;\n readonly basis: 'at' | 'after';\n};\n\n/**\n * An output for an operator. Typically another Operator in an IVM pipeline,\n * but can also be a terminal sink (such as a View or test consumer).\n */\nexport interface Output {\n /**\n * Phase 1 of two-phase push: pushes incremental changes to data previously\n * received with fetch(). Consumers must apply all pushed changes or the\n * incremental result will be incorrect.\n *\n * Callers must maintain some invariants for correct operation:\n * - Only add rows which do not already exist (by deep equality).\n * - Only remove rows which do exist (by deep equality).\n *\n * Implementations can yield 'yield' to yield control to the caller for\n * purposes of responsiveness.\n *\n * Yield contract:\n * - During a push: If a push call to an output yields 'yield', it must be\n * yielded to the caller of push immediately.\n */\n push(change: Change, pusher: InputBase): Stream<'yield'>;\n\n /**\n * Phase 2 of two-phase push: invoked after Phase 1 changes have propagated.\n * Bounded operators (such as Take or Cap) use this signal to refill deficits,\n * emit refilled rows downstream via push(), and update their bounds.\n *\n * Implementations can yield 'yield' to yield control to the caller for\n * purposes of responsiveness.\n *\n * Yield contract:\n * - During reconcile: If an internal fetch, push, or downstream reconcile call\n * yields 'yield', it must be yielded to the caller of reconcile immediately.\n *\n * This method is optional on Output to allow terminal sinks (such as UI views\n * or custom third-party sinks) that only consume changes to omit it without\n * breaking compatibility. Intermediate operators must check\n * `if (this.#output.reconcile)` before forwarding.\n */\n reconcile?(pusher: InputBase): Stream<'yield'>;\n}\n\n/**\n * An implementation of Output that throws if pushed to. It is used as the\n * initial value for an operator's output before it is set.\n */\nexport const throwOutput: Output = {\n push(_change: Change): Stream<'yield'> {\n throw new Error('Output not set');\n },\n reconcile(): Stream<'yield'> {\n throw new Error('Output not set');\n },\n};\n\n/**\n * Operators are arranged into IVM pipelines.\n * They are stateful.\n * Each operator is an input to the next operator in the chain and an output\n * to the previous.\n */\nexport interface Operator extends Input, Output {\n /**\n * Intermediate pipeline operators MUST implement reconcile so that Phase 2\n * reconciliation reaches all bounded operators in the pipeline and is never\n * accidentally swallowed.\n */\n reconcile(pusher: InputBase): Stream<'yield'>;\n}\n\n/**\n * Operators get access to storage that they can store their internal\n * state in.\n */\nexport interface Storage {\n set(key: string, value: JSONValue): void;\n get(key: string, def?: JSONValue): JSONValue | undefined;\n /**\n * If options is not specified, defaults to scanning all entries.\n */\n scan(options?: {prefix: string}): Stream<[string, JSONValue]>;\n del(key: string): void;\n /**\n * Called by the operator that owns the storage when the operator is\n * destroyed. Releases anything the storage holds outside of the operator\n * (e.g. rows in a shared database). The storage is not used afterwards.\n */\n destroy(): void;\n}\n"],"mappings":";;;;;;AAyLA,IAAa,cAAsB;CACjC,KAAK,SAAkC;EACrC,MAAM,IAAI,MAAM,gBAAgB;CAClC;CACA,YAA6B;EAC3B,MAAM,IAAI,MAAM,gBAAgB;CAClC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"take.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/take.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,GAAG,EAAQ,MAAM,oCAAoC,CAAC;AACnE,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,2CAA2C,CAAC;AAI1E,OAAO,EAGL,KAAK,MAAM,EAEZ,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAChD,OAAO,
|
|
1
|
+
{"version":3,"file":"take.d.ts","sourceRoot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