@rocicorp/zero 1.12.0-canary.4 → 1.12.0-canary.6
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/replicache/src/btree/node.js +1 -1
- package/out/replicache/src/deleted-clients.d.ts.map +1 -1
- package/out/replicache/src/deleted-clients.js +2 -1
- package/out/replicache/src/deleted-clients.js.map +1 -1
- package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
- package/out/replicache/src/kv/sqlite-store.js +7 -3
- package/out/replicache/src/kv/sqlite-store.js.map +1 -1
- package/out/replicache/src/replicache-impl.d.ts.map +1 -1
- package/out/replicache/src/replicache-impl.js +17 -14
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/z2s/src/compiler.js +3 -3
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +22 -23
- 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/config/zero-config.js +2 -2
- package/out/zero-cache/src/config/zero-config.js.map +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.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +33 -10
- package/out/zero-cache/src/server/change-streamer.js.map +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/change-source.d.ts +7 -0
- package/out/zero-cache/src/services/change-source/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts +25 -0
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.js.map +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.d.ts +8 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js +35 -18
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +12 -0
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +66 -9
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/fork-request.d.ts +57 -0
- package/out/zero-cache/src/services/change-source/pg/fork-request.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-source/pg/fork-request.js +54 -0
- package/out/zero-cache/src/services/change-source/pg/fork-request.js.map +1 -0
- 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/replication-slots.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +6 -0
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/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-source/protocol/current/downstream.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts +3 -0
- package/out/zero-cache/src/services/change-source/protocol/current/status.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/status.js +2 -1
- package/out/zero-cache/src/services/change-source/protocol/current/status.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts +1 -3
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +6 -6
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +41 -2
- package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js +55 -20
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +9 -0
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +27 -8
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +1 -12
- package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/litestream-sync-requester.d.ts +29 -2
- package/out/zero-cache/src/services/change-streamer/litestream-sync-requester.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/litestream-sync-requester.js +80 -11
- package/out/zero-cache/src/services/change-streamer/litestream-sync-requester.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.d.ts +2 -2
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/litestream3-prometheus-poller.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts +2 -2
- package/out/zero-cache/src/services/change-streamer/replica-poller.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-poller.js +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-poller.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/server-start-metrics.d.ts +33 -0
- package/out/zero-cache/src/services/change-streamer/server-start-metrics.d.ts.map +1 -0
- package/out/zero-cache/src/services/change-streamer/server-start-metrics.js +42 -0
- package/out/zero-cache/src/services/change-streamer/server-start-metrics.js.map +1 -0
- 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/change-streamer/subscriber.d.ts +17 -6
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.js +5 -4
- package/out/zero-cache/src/services/change-streamer/subscriber.js.map +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/zero-protocol/src/ast.d.ts.map +1 -1
- package/out/zero-protocol/src/ast.js +2 -1
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +27 -27
- 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 +22 -23
- 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":"ast.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAChD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAY,KAAK,GAAG,EAAC,MAAM,WAAW,CAAC;AAE9C,eAAO,MAAM,WAAW,WAAW,CAAC;AAEpC,eAAO,MAAM,cAAc,gBAAa,CAAC;AACzC,eAAO,MAAM,aAAa,eAAW,CAAC;AACtC,eAAO,MAAM,YAAY,eAAmB,CAAC;AAM7C,eAAO,MAAM,cAAc,wDAAyC,CAAC;AACrE,MAAM,MAAM,MAAM,GAAG,aAAa,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEvD,eAAO,MAAM,eAAe,8EAK3B,CAAC;AAEF,eAAO,MAAM,iBAAiB,sCAA4C,CAAC;AAE3E,eAAO,MAAM,cAAc,iCAAuC,CAAC;AAEnE,eAAO,MAAM,aAAa,qDAKzB,CAAC;AAEF,eAAO,MAAM,WAAW,yBAAiC,CAAC;AAE1D,eAAO,MAAM,oBAAoB,oKAKhC,CAAC;AAiBF;;;;;;;;;;;;;;;;GAgBG;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,SAAS,GAAG,SAAS,CAiD7D;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,iBAKlD;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,UAAU,aAMnB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { assert } from "../../shared/src/asserts.js";
|
|
2
2
|
import { literalUnion, readonly, readonlyArray, readonlyObject, strict, valita_exports } from "../../shared/src/valita.js";
|
|
3
3
|
import { getOrInsertComputed } from "../../shared/src/map.js";
|
|
4
|
+
import { toSorted } from "../../shared/src/iterables.js";
|
|
4
5
|
import { isPlainObject } from "../../shared/src/deep-merge.js";
|
|
5
6
|
import { must } from "../../shared/src/must.js";
|
|
6
7
|
import { rowSchema } from "./data.js";
|
|
@@ -290,7 +291,7 @@ function insertRelated(related, subquery) {
|
|
|
290
291
|
}
|
|
291
292
|
var normalizedConditions = /* @__PURE__ */ new WeakSet();
|
|
292
293
|
function normalizeRelated(related) {
|
|
293
|
-
for (let i = 1; i < related.length; i++) if (cmpRelated(related[i - 1], related[i]) > 0) return
|
|
294
|
+
for (let i = 1; i < related.length; i++) if (cmpRelated(related[i - 1], related[i]) > 0) return toSorted(related, cmpRelated);
|
|
294
295
|
return related;
|
|
295
296
|
}
|
|
296
297
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast.js","names":["v","v.readonly","v.literalUnion","v.readonlyArray","v.readonlyObject","v.strict"],"sources":["../../../../zero-protocol/src/ast.ts"],"sourcesContent":["/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {isPlainObject} from '../../shared/src/deep-merge.ts';\nimport {getOrInsertComputed} from '../../shared/src/map.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\nexport const planIdSymbol = Symbol('planId');\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.literalUnion('asc', 'desc')]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client' | 'test';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.literalUnion('=', '!=', 'IS', 'IS NOT');\n\nexport const orderOpsSchema = v.literalUnion('<', '>', '<=', '>=');\n\nexport const likeOpsSchema = v.literalUnion(\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n);\n\nexport const inOpsSchema = v.literalUnion('IN', 'NOT IN');\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.literalUnion('authData', 'preMutationRow'),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.literalUnion('EXISTS', 'NOT EXISTS');\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n flip: v.boolean().optional(),\n scalar: v.boolean().optional(),\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(\n Array.isArray(field) && field.length >= 1,\n 'Expected non-empty array for compound key',\n );\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n // oxlint-disable-next-line e18e/prefer-spread-syntax\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\n/**\n * The maximum nesting depth of an AST sent by a client, counting and/or\n * conditions, correlated subqueries and related subqueries. Parsing and the\n * AST visitors in zero-cache are recursive, so a single deeply nested AST can\n * otherwise overflow the stack or burn seconds of CPU. Realistic queries,\n * permission rules included, are less than 10 levels deep.\n */\nexport const MAX_AST_DEPTH = 50;\n\n/**\n * Returns whether the unparsed `ast` is nested deeper than `maxDepth`.\n */\nexport function exceedsASTDepth(\n ast: unknown,\n maxDepth = MAX_AST_DEPTH,\n): boolean {\n return astExceedsDepth(ast, 0, maxDepth);\n}\n\n// Every step down increases the depth, except the one from an AST into its\n// where clause, so the recursion stops within 2 * maxDepth steps and cannot\n// overflow the stack.\nfunction astExceedsDepth(\n ast: unknown,\n depth: number,\n maxDepth: number,\n): boolean {\n if (depth > maxDepth) {\n return true;\n }\n if (!isPlainObject(ast)) {\n return false;\n }\n const {where, related} = ast;\n return (\n conditionExceedsDepth(where, depth, maxDepth) ||\n (Array.isArray(related) &&\n related.some(\n r =>\n isPlainObject(r) && astExceedsDepth(r.subquery, depth + 1, maxDepth),\n ))\n );\n}\n\nfunction conditionExceedsDepth(\n cond: unknown,\n depth: number,\n maxDepth: number,\n): boolean {\n if (depth > maxDepth) {\n return true;\n }\n if (!isPlainObject(cond)) {\n return false;\n }\n const {conditions, related} = cond;\n return (\n (Array.isArray(conditions) &&\n conditions.some(c => conditionExceedsDepth(c, depth + 1, maxDepth))) ||\n (isPlainObject(related) &&\n astExceedsDepth(related.subquery, depth + 1, maxDepth))\n );\n}\n\n/**\n * {@link astSchema} for ASTs sent by clients, which rejects ASTs nested deeper\n * than {@link MAX_AST_DEPTH} before parsing them. ASTs the server stored itself\n * (e.g. in the CVR) are parsed with {@link astSchema} so that ones stored\n * before the limit existed can still be read.\n */\nexport const depthBoundedAstSchema: v.Type<AST> = Object.assign(\n v\n .unknown()\n .chain((value, options) =>\n exceedsASTDepth(value)\n ? v.err(`AST exceeds the maximum depth of ${MAX_AST_DEPTH}`)\n : astSchema.try(value, options),\n ),\n // A transform serializes as just its name. Show astSchema too, so a change\n // to it still changes the hash in protocol-version.test.ts.\n {depthBounded: astSchema},\n);\n\n/**\n * {@link depthBoundedAstSchema} parsed strictly even inside a lenient parse. A\n * server that ignored an AST field it doesn't know would run a different query.\n */\nexport const strictASTSchema: v.Type<AST> = v.strict(depthBoundedAstSchema);\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n flip?: boolean | undefined;\n scalar?: boolean | undefined;\n [planIdSymbol]?: number | undefined;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: ast.where\n ? transformWhere(ast.where, ast.table, transform)\n : undefined,\n related: ast.related?.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: where.conditions.map(c => transformWhere(c, table, transform)),\n };\n}\n\ndeclare const normalizedTag: unique symbol;\n\n/**\n * An {@link AST} in its normalized form: `related` is sorted, `where` is\n * flattened and sorted, and every field is present, in a fixed order. Two ASTs\n * that describe the same query have the same JSON encoding, and thus the same\n * hash, once normalized.\n *\n * The tag only exists in the type, so the only way to get one is from\n * {@link normalizeAST}, {@link normalizedAST} or {@link tableAST}. Spreading\n * one keeps the tag, which is what lets a query builder derive a normalized\n * AST from another one by replacing a field it knows to be safe.\n */\nexport type NormalizedAST = Required<AST> & {readonly [normalizedTag]: true};\n\nfunction asNormalized(ast: Required<AST>): NormalizedAST {\n return ast as NormalizedAST;\n}\n\nconst normalizeCache = new WeakMap<AST, NormalizedAST>();\n\nexport function normalizeAST(ast: AST): NormalizedAST {\n return getOrInsertComputed(normalizeCache, ast, normalizeASTUncached);\n}\n\nfunction normalizeASTUncached(ast: AST): NormalizedAST {\n // normalizedAST() normalizes a single level, so normalize the subqueries\n // first.\n const {where, related} = ast;\n return normalizedAST({\n ...ast,\n where: where && normalizeSubqueries(where),\n related: related?.map(r =>\n normalizedRelated({...r, subquery: normalizeAST(r.subquery)}),\n ),\n });\n}\n\n/**\n * Normalizes the ASTs of the correlated subqueries of `cond`. The condition\n * itself is normalized by {@link normalizeCondition}.\n */\nfunction normalizeSubqueries(cond: Condition): Condition {\n switch (cond.type) {\n case 'simple':\n return cond;\n case 'correlatedSubquery':\n return {\n ...cond,\n related: {\n ...cond.related,\n subquery: normalizeAST(cond.related.subquery),\n },\n };\n default:\n return {\n type: cond.type,\n conditions: cond.conditions.map(normalizeSubqueries),\n };\n }\n}\n\n/**\n * Normalizes a single level of an AST, assuming that the ASTs of its\n * subqueries (i.e. those in `related` and in correlated subquery conditions)\n * are already normalized and that the `related` entries have the shape that\n * {@link normalizedRelated} gives them.\n *\n * This lets a query builder keep its AST normalized as it builds it up\n * instead of normalizing the whole tree afterwards. A builder that knows\n * which of the rules a step can break at all is better off applying just\n * those (see {@link tableAST}, {@link insertRelated} and\n * {@link normalizeCondition}).\n */\nexport function normalizedAST(ast: AST): NormalizedAST {\n const {schema, table, alias, where, related, start, limit, orderBy} = ast;\n // Every field is written, in the same order, so that all normalized ASTs\n // have the same shape (one hidden class) and the same JSON encoding (and\n // thus the same hash) no matter how they were put together. The fields that\n // are undefined are dropped by JSON.stringify() anyway.\n return asNormalized({\n schema,\n table,\n alias,\n where: where === undefined ? undefined : normalizeCondition(where),\n related: related === undefined ? undefined : normalizeRelated(related),\n start,\n limit,\n orderBy,\n });\n}\n\n/**\n * The normalized AST that selects a whole table. Spreading it (or any other\n * normalized AST) and replacing a field keeps the field order, since a\n * normalized AST has every field.\n */\nexport function tableAST(\n table: string,\n alias?: string | undefined,\n): NormalizedAST {\n return asNormalized({\n schema: undefined,\n table,\n alias,\n where: undefined,\n related: undefined,\n start: undefined,\n limit: undefined,\n orderBy: undefined,\n });\n}\n\n/**\n * Adds `subquery` to the `related` of a normalized AST, at the position that\n * keeps it sorted.\n */\nexport function insertRelated(\n related: readonly CorrelatedSubquery[] | undefined,\n subquery: CorrelatedSubquery,\n): readonly CorrelatedSubquery[] {\n const normalized = normalizedRelated(subquery);\n if (related === undefined) {\n return [normalized];\n }\n // Sorting is stable, so an entry goes after the ones it compares equal to.\n let i = related.length;\n while (i > 0 && cmpRelated(related[i - 1], normalized) > 0) {\n i--;\n }\n return related.toSpliced(i, 0, normalized);\n}\n\n// Conjunctions and disjunctions that are known to be normalized. The query\n// builder rebuilds its AST for every step, so this keeps the conditions that\n// did not change from being normalized over and over again.\nconst normalizedConditions = new WeakSet<Condition>();\n\nfunction normalizeRelated(\n related: readonly CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n for (let i = 1; i < related.length; i++) {\n if (cmpRelated(related[i - 1], related[i]) > 0) {\n return related.toSorted(cmpRelated);\n }\n }\n return related;\n}\n\n/**\n * Gives a correlated subquery the shape that a normalized AST has: every\n * field, in a fixed order (see {@link normalizedAST}). Its `subquery` must\n * already be normalized.\n */\nexport function normalizedRelated(\n related: CorrelatedSubquery,\n): Required<CorrelatedSubquery> {\n const {correlation, hidden, subquery, system} = related;\n return {\n correlation: {\n parentField: correlation.parentField,\n childField: correlation.childField,\n },\n hidden,\n subquery,\n system,\n };\n}\n\nfunction normalizeValuePosition<T extends ValuePosition>(v: T): T {\n switch (v.type) {\n case 'literal':\n return {type: 'literal', value: v.value} as T;\n case 'column':\n return {type: 'column', name: v.name} as T;\n default:\n return {type: 'static', anchor: v.anchor, field: v.field} as T;\n }\n}\n\n/**\n * Normalizes a condition, assuming that the ASTs of any correlated subqueries\n * it contains are already normalized.\n *\n * Like {@link normalizedAST}, this rebuilds every node with its fields in a\n * fixed order, so that structurally equal conditions have the same JSON\n * encoding (and thus the same hash) no matter how they were put together.\n * That includes a round trip through Postgres, whose jsonb type reorders\n * object keys: without the rebuild, every query record reloaded from the CVR\n * re-hashed to a different transformationHash than was stored, making it look\n * changed and re-execute on every view-syncer restart.\n */\nexport function normalizeCondition(cond: Condition): Condition {\n if (normalizedConditions.has(cond)) {\n return cond;\n }\n if (cond.type === 'simple') {\n const normalized: Condition = {\n type: 'simple',\n op: cond.op,\n left: normalizeValuePosition(cond.left),\n right: normalizeValuePosition(cond.right),\n };\n normalizedConditions.add(normalized);\n return normalized;\n }\n if (cond.type === 'correlatedSubquery') {\n const normalized: Condition = {\n type: 'correlatedSubquery',\n related: normalizedRelated(cond.related),\n op: cond.op,\n flip: cond.flip,\n scalar: cond.scalar,\n };\n normalizedConditions.add(normalized);\n return normalized;\n }\n\n // Flatten the conditions of nested conjunctions of the same type and sort\n // them. The nested conditions are normalized (and thus flattened and sorted)\n // first.\n const conditions: Condition[] = [];\n for (const c of cond.conditions) {\n const n = normalizeCondition(c);\n if (n.type === cond.type) {\n conditions.push(...n.conditions);\n } else {\n conditions.push(n);\n }\n }\n\n // A singleton conjunction is the same as the condition itself. Empty\n // conjunctions, on the other hand, are meaningful: an empty 'and' is always\n // true and an empty 'or' is always false.\n if (conditions.length === 1) {\n return conditions[0];\n }\n conditions.sort(cmpCondition);\n const normalized: Condition = {type: cond.type, conditions};\n normalizedConditions.add(normalized);\n return normalized;\n}\n\n/**\n * Maps the table and column names of `ast`. The result is not a\n * {@link NormalizedAST} even if `ast` was normalized: the names it sorts by\n * are the ones that changed.\n */\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n });\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return (\n cmpRelated(a.related, b.related) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n cmpOptionalBool(a.flip, b.flip) ||\n cmpOptionalBool(a.scalar, b.scalar)\n );\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal', 'Expected literal type for comparison');\n return cmpLiteralValue(a.value, b.value);\n case 'column':\n assert(b.type === 'column', 'Expected column type for comparison');\n return compareUTF8(a.name, b.name);\n case 'static':\n assert(b.type === 'static', 'Expected static type for comparison');\n // A field is a string or a path of strings, which cmpLiteralValue()\n // tells apart.\n return (\n compareUTF8(a.anchor, b.anchor) || cmpLiteralValue(a.field, b.field)\n );\n }\n}\n\n// null < boolean < number < string < array. Ordering values of different\n// types by their string form would make distinct values compare equal (['a',\n// 'b'] and 'a,b', or 1 and '1'), which would leave their order up to the\n// order they were written in, and with it the hash of the query.\nconst LITERAL_VALUE_TYPES = ['object', 'boolean', 'number', 'string'];\n\nfunction literalValueType(value: LiteralValue): number {\n return Array.isArray(value)\n ? LITERAL_VALUE_TYPES.length\n : LITERAL_VALUE_TYPES.indexOf(typeof value);\n}\n\nfunction cmpLiteralValue(a: LiteralValue, b: LiteralValue): number {\n const type = literalValueType(a) - literalValueType(b);\n if (type !== 0) {\n return type;\n }\n\n if (Array.isArray(a)) {\n assert(Array.isArray(b), 'Expected array for comparison');\n for (let i = 0; i < a.length && i < b.length; i++) {\n const val = cmpLiteralValue(a[i], b[i]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.length - b.length;\n }\n\n switch (typeof a) {\n case 'string':\n assert(typeof b === 'string', 'Expected string for comparison');\n return compareUTF8(a, b);\n case 'number':\n assert(typeof b === 'number', 'Expected number for comparison');\n return a < b ? -1 : a > b ? 1 : 0;\n case 'boolean':\n assert(typeof b === 'boolean', 'Expected boolean for comparison');\n return Number(a) - Number(b);\n default:\n return 0; // null\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n\nfunction cmpOptionalBool(\n a: boolean | undefined,\n b: boolean | undefined,\n): number {\n // undefined < false < true\n const toNum = (v: boolean | undefined) => (v === undefined ? 0 : v ? 2 : 1);\n return toNum(a) - toNum(b);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,IAAa,cAAc;AAE3B,IAAa,iBAAiBA,eAAE,OAAO;AACvC,IAAa,gBAAgB,OAAO;AACpC,IAAa,eAAe,OAAO,QAAQ;AAE3C,IAAM,wBAAwBC,SAC5BD,eAAE,MAAM,CAAC,gBAAgBE,aAAe,OAAO,MAAM,CAAC,CAAC,CACzD;AAEA,IAAa,iBAAiBC,cAAgB,qBAAqB;AAGpCH,eAAE,MAC/BA,eAAE,OAAO,GACTA,eAAE,OAAO,GACTA,eAAE,QAAQ,GACVA,eAAE,KAAK,CACT;AAEA,IAAa,oBAAoBE,aAAe,KAAK,MAAM,MAAM,QAAQ;AAEzE,IAAa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,IAAI,IAAI,GAAG,IAAI,EAAE,UAAU,IAAI,EAAE,QAAQ,KAAK;GACjD,MAAM,MAAM,gBAAgB,EAAE,IAAI,EAAE,EAAE;GACtC,IAAI,QAAQ,GACV,OAAO;EAEX;EAEA,OAAO,EAAE,SAAS,EAAE;CACtB;CAEA,QAAQ,OAAO,GAAf;EACE,KAAK;GACH,OAAO,OAAO,MAAM,UAAU,gCAAgC;GAC9D,OAAO,YAAY,GAAG,CAAC;EACzB,KAAK;GACH,OAAO,OAAO,MAAM,UAAU,gCAAgC;GAC9D,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;EAClC,KAAK;GACH,OAAO,OAAO,MAAM,WAAW,iCAAiC;GAChE,OAAO,OAAO,CAAC,IAAI,OAAO,CAAC;EAC7B,SACE,OAAO;CACX;AACF;AAEA,SAAS,WAAW,GAAuB,GAA+B;CACxE,OAAO,YAAY,KAAK,EAAE,SAAS,KAAK,GAAG,KAAK,EAAE,SAAS,KAAK,CAAC;AACnE;AAEA,SAAS,qBAAqB,GAAkB,GAA0B;CACxE,IAAI,MAAM,QAAQ,MAAM,MACtB,OAAO,YAAY,GAAG,CAAC;CAEzB,IAAI,MAAM,MACR,OAAO;CAET,IAAI,MAAM,MACR,OAAO;CAET,OAAO;AACT;AAEA,SAAS,gBACP,GACA,GACQ;CAER,MAAM,SAAS,MAA4B,MAAM,KAAA,IAAY,IAAI,IAAI,IAAI;CACzE,OAAO,MAAM,CAAC,IAAI,MAAM,CAAC;AAC3B"}
|
|
1
|
+
{"version":3,"file":"ast.js","names":["v","v.readonly","v.literalUnion","v.readonlyArray","v.readonlyObject","v.strict"],"sources":["../../../../zero-protocol/src/ast.ts"],"sourcesContent":["/**\n * Wire-format representation of the zql AST interface.\n *\n * `v.Type<...>` types are explicitly declared to facilitate Typescript verification\n * that the schemas satisfy the zql type definitions. (Incidentally, explicit types\n * are also required for recursive schema definitions.)\n */\n\nimport {compareUTF8} from 'compare-utf8';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {isPlainObject} from '../../shared/src/deep-merge.ts';\nimport {toSorted} from '../../shared/src/iterables.ts';\nimport {getOrInsertComputed} from '../../shared/src/map.ts';\nimport {must} from '../../shared/src/must.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport type {NameMapper} from '../../zero-types/src/name-mapper.ts';\nimport {rowSchema, type Row} from './data.ts';\n\nexport const SUBQ_PREFIX = 'zsubq_';\n\nexport const selectorSchema = v.string();\nexport const toStaticParam = Symbol();\nexport const planIdSymbol = Symbol('planId');\n\nconst orderingElementSchema = v.readonly(\n v.tuple([selectorSchema, v.literalUnion('asc', 'desc')]),\n);\n\nexport const orderingSchema = v.readonlyArray(orderingElementSchema);\nexport type System = 'permissions' | 'client' | 'test';\n\nexport const primitiveSchema = v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n);\n\nexport const equalityOpsSchema = v.literalUnion('=', '!=', 'IS', 'IS NOT');\n\nexport const orderOpsSchema = v.literalUnion('<', '>', '<=', '>=');\n\nexport const likeOpsSchema = v.literalUnion(\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n);\n\nexport const inOpsSchema = v.literalUnion('IN', 'NOT IN');\n\nexport const simpleOperatorSchema = v.union(\n equalityOpsSchema,\n orderOpsSchema,\n likeOpsSchema,\n inOpsSchema,\n);\n\nconst literalReferenceSchema: v.Type<LiteralReference> = v.readonlyObject({\n type: v.literal('literal'),\n value: v.union(\n v.string(),\n v.number(),\n v.boolean(),\n v.null(),\n v.readonlyArray(v.union(v.string(), v.number(), v.boolean())),\n ),\n});\nconst columnReferenceSchema: v.Type<ColumnReference> = v.readonlyObject({\n type: v.literal('column'),\n name: v.string(),\n});\n\n/**\n * A parameter is a value that is not known at the time the query is written\n * and is resolved at runtime.\n *\n * Static parameters refer to something provided by the caller.\n * Static parameters are injected when the query pipeline is built from the AST\n * and do not change for the life of that pipeline.\n *\n * An example static parameter is the current authentication data.\n * When a user is authenticated, queries on the server have access\n * to the user's authentication data in order to evaluate authorization rules.\n * Authentication data doesn't change over the life of a query as a change\n * in auth data would represent a log-in / log-out of the user.\n *\n * AncestorParameters refer to rows encountered while running the query.\n * They are used by subqueries to refer to rows emitted by parent queries.\n */\nconst parameterReferenceSchema = v.readonlyObject({\n type: v.literal('static'),\n // The \"namespace\" of the injected parameter.\n // Write authorization will send the value of a row\n // prior to the mutation being run (preMutationRow).\n // Read and write authorization will both send the\n // current authentication data (authData).\n anchor: v.literalUnion('authData', 'preMutationRow'),\n field: v.union(v.string(), v.array(v.string())),\n});\n\nconst conditionValueSchema = v.union(\n literalReferenceSchema,\n columnReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v.readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n});\n\ntype ConditionValue = v.Infer<typeof conditionValueSchema>;\n\nexport const correlatedSubqueryConditionOperatorSchema: v.Type<CorrelatedSubqueryConditionOperator> =\n v.literalUnion('EXISTS', 'NOT EXISTS');\n\nexport const correlatedSubqueryConditionSchema: v.Type<CorrelatedSubqueryCondition> =\n v.readonlyObject({\n type: v.literal('correlatedSubquery'),\n related: v.lazy(() => correlatedSubquerySchema),\n op: correlatedSubqueryConditionOperatorSchema,\n flip: v.boolean().optional(),\n scalar: v.boolean().optional(),\n });\n\nexport const conditionSchema: v.Type<Condition> = v.union(\n simpleConditionSchema,\n v.lazy(() => conjunctionSchema),\n v.lazy(() => disjunctionSchema),\n correlatedSubqueryConditionSchema,\n);\n\nconst conjunctionSchema: v.Type<Conjunction> = v.readonlyObject({\n type: v.literal('and'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nconst disjunctionSchema: v.Type<Disjunction> = v.readonlyObject({\n type: v.literal('or'),\n conditions: v.readonlyArray(conditionSchema),\n});\n\nexport type CompoundKey = readonly [string, ...string[]];\n\nfunction mustCompoundKey(field: readonly string[]): CompoundKey {\n assert(\n Array.isArray(field) && field.length >= 1,\n 'Expected non-empty array for compound key',\n );\n return field as unknown as CompoundKey;\n}\n\nexport const compoundKeySchema: v.Type<CompoundKey> = v.readonly(\n // oxlint-disable-next-line e18e/prefer-spread-syntax\n v.tuple([v.string()]).concat(v.array(v.string())),\n);\n\nconst correlationSchema = v.readonlyObject({\n parentField: compoundKeySchema,\n childField: compoundKeySchema,\n});\n\n// Split out so that its inferred type can be checked against\n// Omit<CorrelatedSubquery, 'correlation'> in ast-type-test.ts.\n// The mutually-recursive reference of the 'other' field to astSchema\n// is the only thing added in v.lazy. The v.lazy is necessary due to the\n// mutually-recursive types, but v.lazy prevents inference of the resulting\n// type.\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n});\n\nexport const correlatedSubquerySchema: v.Type<CorrelatedSubquery> =\n correlatedSubquerySchemaOmitSubquery.extend({\n subquery: v.lazy(() => astSchema),\n });\n\nexport const astSchema: v.Type<AST> = v.readonlyObject({\n schema: v.string().optional(),\n table: v.string(),\n alias: v.string().optional(),\n where: conditionSchema.optional(),\n related: v.readonlyArray(correlatedSubquerySchema).optional(),\n limit: v.number().optional(),\n orderBy: orderingSchema.optional(),\n start: v\n .object({\n row: rowSchema,\n exclusive: v.boolean(),\n })\n .optional(),\n});\n\n/**\n * The maximum nesting depth of an AST sent by a client, counting and/or\n * conditions, correlated subqueries and related subqueries. Parsing and the\n * AST visitors in zero-cache are recursive, so a single deeply nested AST can\n * otherwise overflow the stack or burn seconds of CPU. Realistic queries,\n * permission rules included, are less than 10 levels deep.\n */\nexport const MAX_AST_DEPTH = 50;\n\n/**\n * Returns whether the unparsed `ast` is nested deeper than `maxDepth`.\n */\nexport function exceedsASTDepth(\n ast: unknown,\n maxDepth = MAX_AST_DEPTH,\n): boolean {\n return astExceedsDepth(ast, 0, maxDepth);\n}\n\n// Every step down increases the depth, except the one from an AST into its\n// where clause, so the recursion stops within 2 * maxDepth steps and cannot\n// overflow the stack.\nfunction astExceedsDepth(\n ast: unknown,\n depth: number,\n maxDepth: number,\n): boolean {\n if (depth > maxDepth) {\n return true;\n }\n if (!isPlainObject(ast)) {\n return false;\n }\n const {where, related} = ast;\n return (\n conditionExceedsDepth(where, depth, maxDepth) ||\n (Array.isArray(related) &&\n related.some(\n r =>\n isPlainObject(r) && astExceedsDepth(r.subquery, depth + 1, maxDepth),\n ))\n );\n}\n\nfunction conditionExceedsDepth(\n cond: unknown,\n depth: number,\n maxDepth: number,\n): boolean {\n if (depth > maxDepth) {\n return true;\n }\n if (!isPlainObject(cond)) {\n return false;\n }\n const {conditions, related} = cond;\n return (\n (Array.isArray(conditions) &&\n conditions.some(c => conditionExceedsDepth(c, depth + 1, maxDepth))) ||\n (isPlainObject(related) &&\n astExceedsDepth(related.subquery, depth + 1, maxDepth))\n );\n}\n\n/**\n * {@link astSchema} for ASTs sent by clients, which rejects ASTs nested deeper\n * than {@link MAX_AST_DEPTH} before parsing them. ASTs the server stored itself\n * (e.g. in the CVR) are parsed with {@link astSchema} so that ones stored\n * before the limit existed can still be read.\n */\nexport const depthBoundedAstSchema: v.Type<AST> = Object.assign(\n v\n .unknown()\n .chain((value, options) =>\n exceedsASTDepth(value)\n ? v.err(`AST exceeds the maximum depth of ${MAX_AST_DEPTH}`)\n : astSchema.try(value, options),\n ),\n // A transform serializes as just its name. Show astSchema too, so a change\n // to it still changes the hash in protocol-version.test.ts.\n {depthBounded: astSchema},\n);\n\n/**\n * {@link depthBoundedAstSchema} parsed strictly even inside a lenient parse. A\n * server that ignored an AST field it doesn't know would run a different query.\n */\nexport const strictASTSchema: v.Type<AST> = v.strict(depthBoundedAstSchema);\n\nexport type Bound = {\n row: Row;\n exclusive: boolean;\n};\n\n/**\n * As in SQL you can have multiple orderings. We don't currently\n * support ordering on anything other than the root query.\n */\nexport type OrderPart = readonly [field: string, direction: 'asc' | 'desc'];\nexport type Ordering = readonly OrderPart[];\n\nexport type SimpleOperator = EqualityOps | OrderOps | LikeOps | InOps;\nexport type EqualityOps = '=' | '!=' | 'IS' | 'IS NOT';\nexport type OrderOps = '<' | '>' | '<=' | '>=';\nexport type LikeOps = 'LIKE' | 'NOT LIKE' | 'ILIKE' | 'NOT ILIKE';\nexport type InOps = 'IN' | 'NOT IN';\n\nexport type AST = {\n readonly schema?: string | undefined;\n readonly table: string;\n\n // A query would be aliased if the AST is a subquery.\n // e.g., when two subqueries select from the same table\n // they need an alias to differentiate them.\n // `SELECT\n // [SELECT * FROM issue WHERE issue.id = outer.parentId] AS parent\n // [SELECT * FROM issue WHERE issue.parentId = outer.id] AS children\n // FROM issue as outer`\n readonly alias?: string | undefined;\n\n // `select` is missing given we return all columns for now.\n\n // The PipelineBuilder will pick what to use to correlate\n // a subquery with a parent query. It can choose something from the\n // where conditions or choose the _first_ `related` entry.\n // Choosing the first `related` entry is almost always the best choice if\n // one exists.\n readonly where?: Condition | undefined;\n\n readonly related?: readonly CorrelatedSubquery[] | undefined;\n readonly start?: Bound | undefined;\n readonly limit?: number | undefined;\n readonly orderBy?: Ordering | undefined;\n};\n\nexport type Correlation = {\n readonly parentField: CompoundKey;\n readonly childField: CompoundKey;\n};\n\nexport type CorrelatedSubquery = {\n /**\n * Only equality correlation are supported for now.\n * E.g., direct foreign key relationships.\n */\n readonly correlation: Correlation;\n readonly subquery: AST;\n readonly system?: System | undefined;\n // If a hop in the subquery chain should be hidden from the output view.\n // A common example is junction edges. The query API provides the illusion\n // that they don't exist: `issue.related('labels')` instead of `issue.related('issue_labels').related('labels')`.\n // To maintain this illusion, the junction edge should be hidden.\n // When `hidden` is set to true, this hop will not be included in the output view\n // but its children will be.\n readonly hidden?: boolean | undefined;\n};\n\nexport type ValuePosition = LiteralReference | Parameter | ColumnReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * Not a path yet as we're currently not allowing\n * comparisons across tables. This will need to\n * be a path through the tree in the near future.\n */\n readonly name: string;\n};\n\nexport type LiteralReference = {\n readonly type: 'literal';\n readonly value: LiteralValue;\n};\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | ReadonlyArray<string | number | boolean>;\n\n/**\n * Starting only with SimpleCondition for now.\n * ivm1 supports Conjunctions and Disjunctions.\n * We'll support them in the future.\n */\nexport type Condition =\n | SimpleCondition\n | Conjunction\n | Disjunction\n | CorrelatedSubqueryCondition;\n\nexport type SimpleCondition = {\n readonly type: 'simple';\n readonly op: SimpleOperator;\n readonly left: ValuePosition;\n\n /**\n * `null` is absent since we do not have an `IS` or `IS NOT`\n * operator defined and `null != null` in SQL.\n */\n readonly right: Exclude<ValuePosition, ColumnReference>;\n};\n\nexport type Conjunction = {\n type: 'and';\n conditions: readonly Condition[];\n};\n\nexport type Disjunction = {\n type: 'or';\n conditions: readonly Condition[];\n};\n\nexport type CorrelatedSubqueryCondition = {\n type: 'correlatedSubquery';\n related: CorrelatedSubquery;\n op: CorrelatedSubqueryConditionOperator;\n flip?: boolean | undefined;\n scalar?: boolean | undefined;\n [planIdSymbol]?: number | undefined;\n};\n\nexport type CorrelatedSubqueryConditionOperator = 'EXISTS' | 'NOT EXISTS';\n\ninterface ASTTransform {\n tableName(orig: string): string;\n columnName(origTable: string, origColumn: string): string;\n}\n\nfunction transformAST(ast: AST, transform: ASTTransform): Required<AST> {\n // Name mapping functions (e.g. to server names)\n const {tableName, columnName} = transform;\n const colName = (c: string) => columnName(ast.table, c);\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n const transformed = {\n schema: ast.schema,\n table: tableName(ast.table),\n alias: ast.alias,\n where: ast.where\n ? transformWhere(ast.where, ast.table, transform)\n : undefined,\n related: ast.related?.map(\n r =>\n ({\n correlation: {\n parentField: key(ast.table, r.correlation.parentField),\n childField: key(r.subquery.table, r.correlation.childField),\n },\n hidden: r.hidden,\n subquery: transformAST(r.subquery, transform),\n system: r.system,\n }) satisfies Required<CorrelatedSubquery>,\n ),\n start: ast.start\n ? {\n ...ast.start,\n row: Object.fromEntries(\n Object.entries(ast.start.row).map(([col, val]) => [\n colName(col),\n val,\n ]),\n ),\n }\n : undefined,\n limit: ast.limit,\n orderBy: ast.orderBy?.map(([col, dir]) => [colName(col), dir] as const),\n };\n\n return transformed;\n}\n\nfunction transformWhere(\n where: Condition,\n table: string,\n transform: ASTTransform,\n): Condition {\n // Name mapping functions (e.g. to server names)\n const {columnName} = transform;\n const condValue = (c: ConditionValue) =>\n c.type !== 'column' ? c : {...c, name: columnName(table, c.name)};\n const key = (table: string, k: CompoundKey) => {\n const serverKey = k.map(col => columnName(table, col));\n return mustCompoundKey(serverKey);\n };\n\n if (where.type === 'simple') {\n return {...where, left: condValue(where.left)};\n } else if (where.type === 'correlatedSubquery') {\n const {correlation, subquery} = where.related;\n return {\n ...where,\n related: {\n ...where.related,\n correlation: {\n parentField: key(table, correlation.parentField),\n childField: key(subquery.table, correlation.childField),\n },\n subquery: transformAST(subquery, transform),\n },\n };\n }\n\n return {\n type: where.type,\n conditions: where.conditions.map(c => transformWhere(c, table, transform)),\n };\n}\n\ndeclare const normalizedTag: unique symbol;\n\n/**\n * An {@link AST} in its normalized form: `related` is sorted, `where` is\n * flattened and sorted, and every field is present, in a fixed order. Two ASTs\n * that describe the same query have the same JSON encoding, and thus the same\n * hash, once normalized.\n *\n * The tag only exists in the type, so the only way to get one is from\n * {@link normalizeAST}, {@link normalizedAST} or {@link tableAST}. Spreading\n * one keeps the tag, which is what lets a query builder derive a normalized\n * AST from another one by replacing a field it knows to be safe.\n */\nexport type NormalizedAST = Required<AST> & {readonly [normalizedTag]: true};\n\nfunction asNormalized(ast: Required<AST>): NormalizedAST {\n return ast as NormalizedAST;\n}\n\nconst normalizeCache = new WeakMap<AST, NormalizedAST>();\n\nexport function normalizeAST(ast: AST): NormalizedAST {\n return getOrInsertComputed(normalizeCache, ast, normalizeASTUncached);\n}\n\nfunction normalizeASTUncached(ast: AST): NormalizedAST {\n // normalizedAST() normalizes a single level, so normalize the subqueries\n // first.\n const {where, related} = ast;\n return normalizedAST({\n ...ast,\n where: where && normalizeSubqueries(where),\n related: related?.map(r =>\n normalizedRelated({...r, subquery: normalizeAST(r.subquery)}),\n ),\n });\n}\n\n/**\n * Normalizes the ASTs of the correlated subqueries of `cond`. The condition\n * itself is normalized by {@link normalizeCondition}.\n */\nfunction normalizeSubqueries(cond: Condition): Condition {\n switch (cond.type) {\n case 'simple':\n return cond;\n case 'correlatedSubquery':\n return {\n ...cond,\n related: {\n ...cond.related,\n subquery: normalizeAST(cond.related.subquery),\n },\n };\n default:\n return {\n type: cond.type,\n conditions: cond.conditions.map(normalizeSubqueries),\n };\n }\n}\n\n/**\n * Normalizes a single level of an AST, assuming that the ASTs of its\n * subqueries (i.e. those in `related` and in correlated subquery conditions)\n * are already normalized and that the `related` entries have the shape that\n * {@link normalizedRelated} gives them.\n *\n * This lets a query builder keep its AST normalized as it builds it up\n * instead of normalizing the whole tree afterwards. A builder that knows\n * which of the rules a step can break at all is better off applying just\n * those (see {@link tableAST}, {@link insertRelated} and\n * {@link normalizeCondition}).\n */\nexport function normalizedAST(ast: AST): NormalizedAST {\n const {schema, table, alias, where, related, start, limit, orderBy} = ast;\n // Every field is written, in the same order, so that all normalized ASTs\n // have the same shape (one hidden class) and the same JSON encoding (and\n // thus the same hash) no matter how they were put together. The fields that\n // are undefined are dropped by JSON.stringify() anyway.\n return asNormalized({\n schema,\n table,\n alias,\n where: where === undefined ? undefined : normalizeCondition(where),\n related: related === undefined ? undefined : normalizeRelated(related),\n start,\n limit,\n orderBy,\n });\n}\n\n/**\n * The normalized AST that selects a whole table. Spreading it (or any other\n * normalized AST) and replacing a field keeps the field order, since a\n * normalized AST has every field.\n */\nexport function tableAST(\n table: string,\n alias?: string | undefined,\n): NormalizedAST {\n return asNormalized({\n schema: undefined,\n table,\n alias,\n where: undefined,\n related: undefined,\n start: undefined,\n limit: undefined,\n orderBy: undefined,\n });\n}\n\n/**\n * Adds `subquery` to the `related` of a normalized AST, at the position that\n * keeps it sorted.\n */\nexport function insertRelated(\n related: readonly CorrelatedSubquery[] | undefined,\n subquery: CorrelatedSubquery,\n): readonly CorrelatedSubquery[] {\n const normalized = normalizedRelated(subquery);\n if (related === undefined) {\n return [normalized];\n }\n // Sorting is stable, so an entry goes after the ones it compares equal to.\n let i = related.length;\n while (i > 0 && cmpRelated(related[i - 1], normalized) > 0) {\n i--;\n }\n return related.toSpliced(i, 0, normalized);\n}\n\n// Conjunctions and disjunctions that are known to be normalized. The query\n// builder rebuilds its AST for every step, so this keeps the conditions that\n// did not change from being normalized over and over again.\nconst normalizedConditions = new WeakSet<Condition>();\n\nfunction normalizeRelated(\n related: readonly CorrelatedSubquery[],\n): readonly CorrelatedSubquery[] {\n for (let i = 1; i < related.length; i++) {\n if (cmpRelated(related[i - 1], related[i]) > 0) {\n // Not Array.prototype.toSorted: Hermes (React Native) does not\n // implement it.\n return toSorted(related, cmpRelated);\n }\n }\n return related;\n}\n\n/**\n * Gives a correlated subquery the shape that a normalized AST has: every\n * field, in a fixed order (see {@link normalizedAST}). Its `subquery` must\n * already be normalized.\n */\nexport function normalizedRelated(\n related: CorrelatedSubquery,\n): Required<CorrelatedSubquery> {\n const {correlation, hidden, subquery, system} = related;\n return {\n correlation: {\n parentField: correlation.parentField,\n childField: correlation.childField,\n },\n hidden,\n subquery,\n system,\n };\n}\n\nfunction normalizeValuePosition<T extends ValuePosition>(v: T): T {\n switch (v.type) {\n case 'literal':\n return {type: 'literal', value: v.value} as T;\n case 'column':\n return {type: 'column', name: v.name} as T;\n default:\n return {type: 'static', anchor: v.anchor, field: v.field} as T;\n }\n}\n\n/**\n * Normalizes a condition, assuming that the ASTs of any correlated subqueries\n * it contains are already normalized.\n *\n * Like {@link normalizedAST}, this rebuilds every node with its fields in a\n * fixed order, so that structurally equal conditions have the same JSON\n * encoding (and thus the same hash) no matter how they were put together.\n * That includes a round trip through Postgres, whose jsonb type reorders\n * object keys: without the rebuild, every query record reloaded from the CVR\n * re-hashed to a different transformationHash than was stored, making it look\n * changed and re-execute on every view-syncer restart.\n */\nexport function normalizeCondition(cond: Condition): Condition {\n if (normalizedConditions.has(cond)) {\n return cond;\n }\n if (cond.type === 'simple') {\n const normalized: Condition = {\n type: 'simple',\n op: cond.op,\n left: normalizeValuePosition(cond.left),\n right: normalizeValuePosition(cond.right),\n };\n normalizedConditions.add(normalized);\n return normalized;\n }\n if (cond.type === 'correlatedSubquery') {\n const normalized: Condition = {\n type: 'correlatedSubquery',\n related: normalizedRelated(cond.related),\n op: cond.op,\n flip: cond.flip,\n scalar: cond.scalar,\n };\n normalizedConditions.add(normalized);\n return normalized;\n }\n\n // Flatten the conditions of nested conjunctions of the same type and sort\n // them. The nested conditions are normalized (and thus flattened and sorted)\n // first.\n const conditions: Condition[] = [];\n for (const c of cond.conditions) {\n const n = normalizeCondition(c);\n if (n.type === cond.type) {\n conditions.push(...n.conditions);\n } else {\n conditions.push(n);\n }\n }\n\n // A singleton conjunction is the same as the condition itself. Empty\n // conjunctions, on the other hand, are meaningful: an empty 'and' is always\n // true and an empty 'or' is always false.\n if (conditions.length === 1) {\n return conditions[0];\n }\n conditions.sort(cmpCondition);\n const normalized: Condition = {type: cond.type, conditions};\n normalizedConditions.add(normalized);\n return normalized;\n}\n\n/**\n * Maps the table and column names of `ast`. The result is not a\n * {@link NormalizedAST} even if `ast` was normalized: the names it sorts by\n * are the ones that changed.\n */\nexport function mapAST(ast: AST, mapper: NameMapper) {\n return transformAST(ast, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n });\n}\n\nexport function mapCondition(\n cond: Condition,\n table: string,\n mapper: NameMapper,\n) {\n return transformWhere(cond, table, {\n tableName: table => mapper.tableName(table),\n columnName: (table, col) => mapper.columnName(table, col),\n });\n}\n\nfunction cmpCondition(a: Condition, b: Condition): number {\n if (a.type === 'simple') {\n if (b.type !== 'simple') {\n return -1; // Order SimpleConditions first\n }\n\n return (\n compareValuePosition(a.left, b.left) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n compareValuePosition(a.right, b.right)\n );\n }\n\n if (b.type === 'simple') {\n return 1; // Order SimpleConditions first\n }\n\n if (a.type === 'correlatedSubquery') {\n if (b.type !== 'correlatedSubquery') {\n return -1; // Order subquery before conjuctions/disjuctions\n }\n return (\n cmpRelated(a.related, b.related) ||\n compareUTF8MaybeNull(a.op, b.op) ||\n cmpOptionalBool(a.flip, b.flip) ||\n cmpOptionalBool(a.scalar, b.scalar)\n );\n }\n if (b.type === 'correlatedSubquery') {\n return -1; // Order correlatedSubquery before conjuctions/disjuctions\n }\n\n const val = compareUTF8MaybeNull(a.type, b.type);\n if (val !== 0) {\n return val;\n }\n for (\n let l = 0, r = 0;\n l < a.conditions.length && r < b.conditions.length;\n l++, r++\n ) {\n const val = cmpCondition(a.conditions[l], b.conditions[r]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.conditions.length - b.conditions.length;\n}\n\nfunction compareValuePosition(a: ValuePosition, b: ValuePosition): number {\n if (a.type !== b.type) {\n return compareUTF8(a.type, b.type);\n }\n switch (a.type) {\n case 'literal':\n assert(b.type === 'literal', 'Expected literal type for comparison');\n return cmpLiteralValue(a.value, b.value);\n case 'column':\n assert(b.type === 'column', 'Expected column type for comparison');\n return compareUTF8(a.name, b.name);\n case 'static':\n assert(b.type === 'static', 'Expected static type for comparison');\n // A field is a string or a path of strings, which cmpLiteralValue()\n // tells apart.\n return (\n compareUTF8(a.anchor, b.anchor) || cmpLiteralValue(a.field, b.field)\n );\n }\n}\n\n// null < boolean < number < string < array. Ordering values of different\n// types by their string form would make distinct values compare equal (['a',\n// 'b'] and 'a,b', or 1 and '1'), which would leave their order up to the\n// order they were written in, and with it the hash of the query.\nconst LITERAL_VALUE_TYPES = ['object', 'boolean', 'number', 'string'];\n\nfunction literalValueType(value: LiteralValue): number {\n return Array.isArray(value)\n ? LITERAL_VALUE_TYPES.length\n : LITERAL_VALUE_TYPES.indexOf(typeof value);\n}\n\nfunction cmpLiteralValue(a: LiteralValue, b: LiteralValue): number {\n const type = literalValueType(a) - literalValueType(b);\n if (type !== 0) {\n return type;\n }\n\n if (Array.isArray(a)) {\n assert(Array.isArray(b), 'Expected array for comparison');\n for (let i = 0; i < a.length && i < b.length; i++) {\n const val = cmpLiteralValue(a[i], b[i]);\n if (val !== 0) {\n return val;\n }\n }\n // prefixes first\n return a.length - b.length;\n }\n\n switch (typeof a) {\n case 'string':\n assert(typeof b === 'string', 'Expected string for comparison');\n return compareUTF8(a, b);\n case 'number':\n assert(typeof b === 'number', 'Expected number for comparison');\n return a < b ? -1 : a > b ? 1 : 0;\n case 'boolean':\n assert(typeof b === 'boolean', 'Expected boolean for comparison');\n return Number(a) - Number(b);\n default:\n return 0; // null\n }\n}\n\nfunction cmpRelated(a: CorrelatedSubquery, b: CorrelatedSubquery): number {\n return compareUTF8(must(a.subquery.alias), must(b.subquery.alias));\n}\n\nfunction compareUTF8MaybeNull(a: string | null, b: string | null): number {\n if (a !== null && b !== null) {\n return compareUTF8(a, b);\n }\n if (b !== null) {\n return -1;\n }\n if (a !== null) {\n return 1;\n }\n return 0;\n}\n\nfunction cmpOptionalBool(\n a: boolean | undefined,\n b: boolean | undefined,\n): number {\n // undefined < false < true\n const toNum = (v: boolean | undefined) => (v === undefined ? 0 : v ? 2 : 1);\n return toNum(a) - toNum(b);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,cAAc;AAE3B,IAAa,iBAAiBA,eAAE,OAAO;AACvC,IAAa,gBAAgB,OAAO;AACpC,IAAa,eAAe,OAAO,QAAQ;AAE3C,IAAM,wBAAwBC,SAC5BD,eAAE,MAAM,CAAC,gBAAgBE,aAAe,OAAO,MAAM,CAAC,CAAC,CACzD;AAEA,IAAa,iBAAiBC,cAAgB,qBAAqB;AAGpCH,eAAE,MAC/BA,eAAE,OAAO,GACTA,eAA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AI,SAAS,GACX,OAAO;CAGT,IAAI,MAAM,QAAQ,CAAC,GAAG;EACpB,OAAO,MAAM,QAAQ,CAAC,GAAG,+BAA+B;EACxD,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,UAAU,IAAI,EAAE,QAAQ,KAAK;GACjD,MAAM,MAAM,gBAAgB,EAAE,IAAI,EAAE,EAAE;GACtC,IAAI,QAAQ,GACV,OAAO;EAEX;EAEA,OAAO,EAAE,SAAS,EAAE;CACtB;CAEA,QAAQ,OAAO,GAAf;EACE,KAAK;GACH,OAAO,OAAO,MAAM,UAAU,gCAAgC;GAC9D,OAAO,YAAY,GAAG,CAAC;EACzB,KAAK;GACH,OAAO,OAAO,MAAM,UAAU,gCAAgC;GAC9D,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;EAClC,KAAK;GACH,OAAO,OAAO,MAAM,WAAW,iCAAiC;GAChE,OAAO,OAAO,CAAC,IAAI,OAAO,CAAC;EAC7B,SACE,OAAO;CACX;AACF;AAEA,SAAS,WAAW,GAAuB,GAA+B;CACxE,OAAO,YAAY,KAAK,EAAE,SAAS,KAAK,GAAG,KAAK,EAAE,SAAS,KAAK,CAAC;AACnE;AAEA,SAAS,qBAAqB,GAAkB,GAA0B;CACxE,IAAI,MAAM,QAAQ,MAAM,MACtB,OAAO,YAAY,GAAG,CAAC;CAEzB,IAAI,MAAM,MACR,OAAO;CAET,IAAI,MAAM,MACR,OAAO;CAET,OAAO;AACT;AAEA,SAAS,gBACP,GACA,GACQ;CAER,MAAM,SAAS,MAA4B,MAAM,KAAA,IAAY,IAAI,IAAI,IAAI;CACzE,OAAO,MAAM,CAAC,IAAI,MAAM,CAAC;AAC3B"}
|
|
@@ -191,6 +191,33 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
191
191
|
type: "attempt-start";
|
|
192
192
|
attemptNumber: number;
|
|
193
193
|
totalAttempts: number;
|
|
194
|
+
} | {
|
|
195
|
+
type: "connection-selected";
|
|
196
|
+
attemptNumber: number;
|
|
197
|
+
connection: string;
|
|
198
|
+
cost: number;
|
|
199
|
+
isRoot: boolean;
|
|
200
|
+
} | {
|
|
201
|
+
type: "plan-failed";
|
|
202
|
+
attemptNumber: number;
|
|
203
|
+
reason: string;
|
|
204
|
+
} | {
|
|
205
|
+
type: "best-plan-selected";
|
|
206
|
+
bestAttemptNumber: number;
|
|
207
|
+
totalCost: number;
|
|
208
|
+
flipPattern: number;
|
|
209
|
+
joinStates: {
|
|
210
|
+
join: string;
|
|
211
|
+
type: "flipped" | "semi" | "unflippable" | v.Unrecognized<string>;
|
|
212
|
+
}[];
|
|
213
|
+
} | {
|
|
214
|
+
type: "node-constraint";
|
|
215
|
+
attemptNumber?: number | undefined;
|
|
216
|
+
nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus" | v.Unrecognized<string>;
|
|
217
|
+
node: string;
|
|
218
|
+
branchPattern: number[];
|
|
219
|
+
constraint?: Record<string, unknown> | null | undefined;
|
|
220
|
+
from: string;
|
|
194
221
|
} | {
|
|
195
222
|
type: "connection-costs";
|
|
196
223
|
attemptNumber: number;
|
|
@@ -216,12 +243,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
216
243
|
limit?: number | undefined;
|
|
217
244
|
}>;
|
|
218
245
|
}[];
|
|
219
|
-
} | {
|
|
220
|
-
type: "connection-selected";
|
|
221
|
-
attemptNumber: number;
|
|
222
|
-
connection: string;
|
|
223
|
-
cost: number;
|
|
224
|
-
isRoot: boolean;
|
|
225
246
|
} | {
|
|
226
247
|
type: "constraints-propagated";
|
|
227
248
|
attemptNumber: number;
|
|
@@ -246,19 +267,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
246
267
|
join: string;
|
|
247
268
|
type: "flipped" | "semi" | "unflippable" | v.Unrecognized<string>;
|
|
248
269
|
}[];
|
|
249
|
-
} | {
|
|
250
|
-
type: "plan-failed";
|
|
251
|
-
attemptNumber: number;
|
|
252
|
-
reason: string;
|
|
253
|
-
} | {
|
|
254
|
-
type: "best-plan-selected";
|
|
255
|
-
bestAttemptNumber: number;
|
|
256
|
-
totalCost: number;
|
|
257
|
-
flipPattern: number;
|
|
258
|
-
joinStates: {
|
|
259
|
-
join: string;
|
|
260
|
-
type: "flipped" | "semi" | "unflippable" | v.Unrecognized<string>;
|
|
261
|
-
}[];
|
|
262
270
|
} | {
|
|
263
271
|
type: "node-cost";
|
|
264
272
|
attemptNumber?: number | undefined;
|
|
@@ -277,14 +285,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
277
285
|
filters?: import("./ast.ts").Condition | undefined;
|
|
278
286
|
ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
|
|
279
287
|
joinType?: "flipped" | "semi" | "unflippable" | v.Unrecognized<string> | undefined;
|
|
280
|
-
} | {
|
|
281
|
-
type: "node-constraint";
|
|
282
|
-
attemptNumber?: number | undefined;
|
|
283
|
-
nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus" | v.Unrecognized<string>;
|
|
284
|
-
node: string;
|
|
285
|
-
branchPattern: number[];
|
|
286
|
-
constraint?: Record<string, unknown> | null | undefined;
|
|
287
|
-
from: string;
|
|
288
288
|
})[]>;
|
|
289
289
|
}, undefined>;
|
|
290
290
|
}, undefined>, v.ObjectType<Omit<{
|
package/out/zql/src/ivm/cap.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Change } from './change.ts';
|
|
2
|
-
import type
|
|
2
|
+
import { type Node } from './data.ts';
|
|
3
3
|
import { type FetchRequest, type Input, type InputBase, type Operator, type Output, type Storage } from './operator.ts';
|
|
4
4
|
import type { SourceSchema } from './schema.ts';
|
|
5
5
|
import { type Stream } from './stream.ts';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cap.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/cap.ts"],"names":[],"mappings":"AAMA,OAAO,EAAgB,KAAK,MAAM,EAAkB,MAAM,aAAa,CAAC;AAExE,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"cap.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/cap.ts"],"names":[],"mappings":"AAMA,OAAO,EAAgB,KAAK,MAAM,EAAkB,MAAM,aAAa,CAAC;AAExE,OAAO,EAA8B,KAAK,IAAI,EAAC,MAAM,WAAW,CAAC;AACjE,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,KAAK,EACV,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,OAAO,EACb,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAGL,KAAK,YAAY,EAClB,MAAM,WAAW,CAAC;AAcnB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,GAAI,YAAW,QAAQ;;IAUlC,YACE,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,MAAM,EACb,YAAY,CAAC,EAAE,YAAY,EAW5B;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,CA+ChD;IAsDA,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAiFrC;IAsCD,OAAO,IAAI,IAAI,CAGd;IAEA,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAI9C;CACF"}
|
package/out/zql/src/ivm/cap.js
CHANGED
|
@@ -2,6 +2,7 @@ import { assert } from "../../../shared/src/asserts.js";
|
|
|
2
2
|
import { emptyArray } from "../../../shared/src/sentinels.js";
|
|
3
3
|
import { throwOutput } from "./operator.js";
|
|
4
4
|
import { makeAddChange } from "./change.js";
|
|
5
|
+
import { valueToKey } from "./data.js";
|
|
5
6
|
import { constraintMatchesPartitionKey, makePartitionKeyComparator } from "./take.js";
|
|
6
7
|
//#region ../zql/src/ivm/cap.ts
|
|
7
8
|
/**
|
|
@@ -55,6 +56,10 @@ var Cap = class {
|
|
|
55
56
|
return;
|
|
56
57
|
}
|
|
57
58
|
if (capState.size === 0) return;
|
|
59
|
+
if (req.countOnly) {
|
|
60
|
+
for (let i = 0; i < capState.size; i++) yield placeholderNode;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
58
63
|
for (const pk of capState.pks) {
|
|
59
64
|
const pkConstraint = deserializePKToConstraint(pk, this.#primaryKey);
|
|
60
65
|
const constraint = req.constraint ? {
|
|
@@ -193,7 +198,12 @@ var Cap = class {
|
|
|
193
198
|
if (this.#output.reconcile) yield* this.#output.reconcile(this);
|
|
194
199
|
}
|
|
195
200
|
};
|
|
201
|
+
var placeholderNode = Object.freeze({
|
|
202
|
+
row: Object.freeze({}),
|
|
203
|
+
relationships: Object.freeze({})
|
|
204
|
+
});
|
|
196
205
|
function getCapStateKey(partitionKey, rowOrConstraint) {
|
|
206
|
+
if (partitionKey?.length === 1 && rowOrConstraint) return "cap:" + valueToKey(rowOrConstraint[partitionKey[0]]);
|
|
197
207
|
const partitionValues = [];
|
|
198
208
|
if (partitionKey && rowOrConstraint) for (const key of partitionKey) partitionValues.push(rowOrConstraint[key]);
|
|
199
209
|
return JSON.stringify(["cap", ...partitionValues]);
|
|
@@ -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,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,IAAI,WAAW;EAC9C,IAAI,CAAC,UAAU;GACb,OAAO,KAAK,cAAc,KAAK,WAAW;GAC1C;EACF;EACA,IAAI,SAAS,SAAS,GACpB;EAIF,KAAK,MAAM,MAAM,SAAS,KAAK;GAC7B,MAAM,eAAe,0BAA0B,IAAI,KAAK,WAAW;GAGnE,MAAM,aAAa,IAAI,aACnB;IAAC,GAAG,IAAI;IAAY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;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;C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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;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,EAA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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,KAAK;CACT,IAAI,KAAK;CAET,IAAI,MAAM,GACR,OAAO;CAGT,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UASxC,OAAO,YAAY,GAAG,CAAC;CAGzB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO,IAAI;CAGb,IAAI,OAAO,MAAM,aAAa,OAAO,MAAM,WACzC,OAAO,IAAI,IAAI;CAKjB,IAAI,MAAM,MACR,OAAO;CAET,IAAI,MAAM,MACR,OAAO;CAGT,IAAI,OAAO,MAAM,OAAO,GACtB,MAAM,IAAI,MACR,6CAA6C,OAAO,EAAE,OAAO,OAAO,GACtE;CAGF,MAAM,IAAI,MAAM,qBAAqB,OAAO,GAAG;AACjD;;;;;;AASA,SAAgB,mBAAmB,GAA2B;CAC5D,OAAO,KAAK;AACd;;;;;;;;;;;AAYA,SAAgB,WAAW,GAAkB;CAC3C,OAAO,OAAO,MAAM,YAAY,CAAC,YAAY,KAAK,CAAC,IAC/C,MAAM,IACN,KAAK,UAAU,KAAK,IAAI;AAC9B;AAEA,IAAM,cAAc;AAIpB,SAAgB,eAAe,OAAiB,SAA+B;CAK7E,IAAI,MAAM,WAAW,KAAK,MAAM,EAAE,CAAC,OAAO,SAAS,CAAC,SAAS;EAC3D,MAAM,QAAQ,MAAM,EAAE,CAAC;EACvB,QAAQ,GAAG,MAAM,cAAc,EAAE,QAAQ,EAAE,MAAM;CACnD;CAEA,MAAM,SAAS,MAAM;CACrB,QAAQ,GAAG,MAAM;EAKf,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;GAC/B,MAAM,MAAM,MAAM;GAClB,MAAM,OAAO,cAAc,EAAE,IAAI,KAAK,EAAE,IAAI,GAAG;GAC/C,IAAI,SAAS,GAAG;IACd,MAAM,SAAS,IAAI,OAAO,QAAQ,OAAO,CAAC;IAC1C,OAAO,UAAU,CAAC,SAAS;GAC7B;EACF;EACA,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,YAAY,GAAU,GAAmB;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
|