@rocicorp/zero 1.13.0-canary.3 → 1.13.0-canary.4
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/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +6 -6
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/server/replicator.js +3 -3
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.js +17 -3
- package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js +11 -2
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +13 -15
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-client/src/client/custom.js +1 -1
- package/out/zero-client/src/client/mutation-tracker.js +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.js +1 -1
- package/out/zero-protocol/src/ast.d.ts +2 -2
- package/out/zero-protocol/src/ast.js +2 -2
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +27 -27
- package/out/zero-protocol/src/inspect-down.d.ts +81 -81
- package/out/zql/src/ivm/aggregate.js +5 -4
- package/out/zql/src/ivm/aggregate.js.map +1 -1
- package/out/zql/src/ivm/cap.d.ts.map +1 -1
- package/out/zql/src/ivm/cap.js +116 -63
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/deferred-input.js +1 -1
- package/out/zql/src/ivm/exists.d.ts.map +1 -1
- package/out/zql/src/ivm/exists.js +136 -73
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-in.js +3 -3
- package/out/zql/src/ivm/fan-in.js.map +1 -1
- package/out/zql/src/ivm/fan-out.d.ts +2 -2
- package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
- package/out/zql/src/ivm/fan-out.js +47 -12
- package/out/zql/src/ivm/fan-out.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js +98 -13
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/filter-push.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-push.js +5 -13
- package/out/zql/src/ivm/filter-push.js.map +1 -1
- package/out/zql/src/ivm/filter.d.ts.map +1 -1
- package/out/zql/src/ivm/filter.js +3 -2
- package/out/zql/src/ivm/filter.js.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +1 -0
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/group-by.js +1 -1
- package/out/zql/src/ivm/join-index-tap.d.ts +1 -1
- package/out/zql/src/ivm/join-index-tap.d.ts.map +1 -1
- package/out/zql/src/ivm/join-index-tap.js +9 -7
- package/out/zql/src/ivm/join-index-tap.js.map +1 -1
- package/out/zql/src/ivm/join.d.ts.map +1 -1
- package/out/zql/src/ivm/join.js +72 -67
- package/out/zql/src/ivm/join.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +163 -57
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/push-accumulated.d.ts +1 -1
- package/out/zql/src/ivm/push-accumulated.d.ts.map +1 -1
- package/out/zql/src/ivm/push-accumulated.js +23 -28
- package/out/zql/src/ivm/push-accumulated.js.map +1 -1
- package/out/zql/src/ivm/skip.d.ts.map +1 -1
- package/out/zql/src/ivm/skip.js +6 -9
- package/out/zql/src/ivm/skip.js.map +1 -1
- package/out/zql/src/ivm/stream.d.ts +58 -0
- package/out/zql/src/ivm/stream.d.ts.map +1 -1
- package/out/zql/src/ivm/stream.js +256 -1
- package/out/zql/src/ivm/stream.js.map +1 -1
- package/out/zql/src/ivm/take-gate.d.ts +1 -1
- package/out/zql/src/ivm/take-gate.d.ts.map +1 -1
- package/out/zql/src/ivm/take-gate.js +11 -21
- package/out/zql/src/ivm/take-gate.js.map +1 -1
- package/out/zql/src/ivm/take.d.ts.map +1 -1
- package/out/zql/src/ivm/take.js +243 -217
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zql/src/query/query.d.ts +4 -4
- package/package.json +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { assert } from "../../../shared/src/asserts.js";
|
|
2
2
|
import { must } from "../../../shared/src/must.js";
|
|
3
|
+
import { emptyFunction } from "../../../shared/src/sentinels.js";
|
|
3
4
|
import { asQueryInternals } from "../../../zql/src/query/query-internals.js";
|
|
4
5
|
import { createRunnableBuilder } from "../../../zql/src/query/create-builder.js";
|
|
5
6
|
import "../../../zql/src/query/query.js";
|
|
6
7
|
import { zeroData } from "../../../replicache/src/transactions.js";
|
|
7
|
-
import { emptyFunction } from "../../../shared/src/sentinels.js";
|
|
8
8
|
import { queryIDOf } from "../../../zql/src/query/query-delegate-base.js";
|
|
9
9
|
import { toGotQueriesKey } from "./keys.js";
|
|
10
10
|
import { ZeroContext } from "./context.js";
|
|
@@ -2,13 +2,13 @@ import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
|
2
2
|
import { resolver } from "../../../shared/src/resolver.js";
|
|
3
3
|
import { parse } from "../../../shared/src/valita.js";
|
|
4
4
|
import { must } from "../../../shared/src/must.js";
|
|
5
|
+
import { emptyObject } from "../../../shared/src/sentinels.js";
|
|
5
6
|
import { getErrorDetails } from "../../../shared/src/error.js";
|
|
6
7
|
import { ApplicationError, isApplicationError, wrapWithApplicationError } from "../../../zero-protocol/src/application-error.js";
|
|
7
8
|
import { InvalidPush, PushFailed } from "../../../zero-protocol/src/error-kind-enum.js";
|
|
8
9
|
import { Server, ZeroCache } from "../../../zero-protocol/src/error-origin-enum.js";
|
|
9
10
|
import { HTTP, Internal } from "../../../zero-protocol/src/error-reason-enum.js";
|
|
10
11
|
import { ProtocolError } from "../../../zero-protocol/src/error.js";
|
|
11
|
-
import { emptyObject } from "../../../shared/src/sentinels.js";
|
|
12
12
|
import { mutationResultSchema } from "../../../zero-protocol/src/mutation.js";
|
|
13
13
|
import { isZeroError } from "./error.js";
|
|
14
14
|
import "./keys.js";
|
|
@@ -9,6 +9,7 @@ import { dropDatabase, dropMatchingDatabases } from "../../../replicache/src/per
|
|
|
9
9
|
import { must } from "../../../shared/src/must.js";
|
|
10
10
|
import { clientToServer } from "../../../zero-schema/src/name-mapper.js";
|
|
11
11
|
import { h64 } from "../../../shared/src/hash.js";
|
|
12
|
+
import { emptyFunction } from "../../../shared/src/sentinels.js";
|
|
12
13
|
import { getErrorCauses, getErrorMessage } from "../../../shared/src/error.js";
|
|
13
14
|
import { ClientNotFound, InvalidMessage } from "../../../zero-protocol/src/error-kind-enum.js";
|
|
14
15
|
import { ProtocolError } from "../../../zero-protocol/src/error.js";
|
|
@@ -24,7 +25,6 @@ import { ReplicacheImpl } from "../../../replicache/src/replicache-impl.js";
|
|
|
24
25
|
import "../../../replicache/src/impl.js";
|
|
25
26
|
import { navigator as localNavigator } from "../../../shared/src/navigator.js";
|
|
26
27
|
import { promiseRace } from "../../../shared/src/promise-race.js";
|
|
27
|
-
import { emptyFunction } from "../../../shared/src/sentinels.js";
|
|
28
28
|
import { Subscribable } from "../../../shared/src/subscribable.js";
|
|
29
29
|
import { encodeSecProtocols } from "../../../zero-protocol/src/connect.js";
|
|
30
30
|
import { CRUD, Custom } from "../../../zero-protocol/src/mutation-type-enum.js";
|
|
@@ -206,8 +206,8 @@ export type Aggregate = {
|
|
|
206
206
|
/**
|
|
207
207
|
* The value an aggregate reduces for `row`: the `field` column itself, or, with
|
|
208
208
|
* a `path`, the JSON leaf at that path when it is one the aggregate takes: a
|
|
209
|
-
* number for `sum`/`avg`, a number or a string for `min`/`max` (
|
|
210
|
-
* before
|
|
209
|
+
* number for `sum`/`avg`, a number or a string for `min`/`max` (strings order
|
|
210
|
+
* before numbers, see `compareAggregateValues`). Any other leaf, or a missing
|
|
211
211
|
* one, is `null`, which aggregates skip. Shared by the IVM operator, the
|
|
212
212
|
* junction lift and the client's optimistic delta so the rule cannot drift.
|
|
213
213
|
*/
|
|
@@ -265,8 +265,8 @@ var strictASTSchema = strict(depthBoundedAstSchema);
|
|
|
265
265
|
/**
|
|
266
266
|
* The value an aggregate reduces for `row`: the `field` column itself, or, with
|
|
267
267
|
* a `path`, the JSON leaf at that path when it is one the aggregate takes: a
|
|
268
|
-
* number for `sum`/`avg`, a number or a string for `min`/`max` (
|
|
269
|
-
* before
|
|
268
|
+
* number for `sum`/`avg`, a number or a string for `min`/`max` (strings order
|
|
269
|
+
* before numbers, see `compareAggregateValues`). Any other leaf, or a missing
|
|
270
270
|
* one, is `null`, which aggregates skip. Shared by the IVM operator, the
|
|
271
271
|
* junction lift and the client's optimistic delta so the rule cannot drift.
|
|
272
272
|
*/
|
|
@@ -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 {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\nconst 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 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\nconst 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 * Upper bound for an array-index segment. SQLite parses a `$[i]` index as an\n * unsigned 32-bit integer (larger values silently wrap), and the Postgres `->`\n * operator takes an `int4`, so anything above this is not a usable index on\n * every engine.\n */\nexport const MAX_JSON_PATH_INDEX = 2 ** 31 - 1;\n\n/**\n * A numeric JSON path segment is an array index and must be an integer in\n * `[0, MAX_JSON_PATH_INDEX]`. Negative indices are rejected because the engines\n * disagree on them (Postgres counts from the end, while JavaScript and SQLite\n * yield null); larger values are rejected because SQLite wraps them modulo\n * 2^32 (silently addressing another element) and Postgres cannot take them as\n * an `int4` operand.\n */\nexport function isValidJsonPathIndex(index: number): boolean {\n return Number.isInteger(index) && index >= 0 && index <= MAX_JSON_PATH_INDEX;\n}\n\n/**\n * The JS type a JSON leaf must have to be compared against `literal`\n * (`'string' | 'number' | 'boolean'`), or `undefined` for `null` and for an\n * empty list. For an `IN`/`NOT IN` list, the type of its first element (lists\n * are homogeneous: enforced by the builder's types, by `cmp()` and at the\n * wire). Shared by the in-memory predicate, the SQLite pushdown and the\n * Postgres compiler so the type-strict rule cannot drift between engines.\n */\nexport function jsonLiteralType(\n literal: LiteralValue,\n): 'string' | 'number' | 'boolean' | undefined {\n const v = Array.isArray(literal) ? literal[0] : literal;\n switch (typeof v) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n default:\n return undefined;\n }\n}\n\nconst negatedOperators: ReadonlySet<SimpleOperator> = new Set([\n '!=',\n 'NOT LIKE',\n 'NOT ILIKE',\n 'NOT IN',\n]);\n\n/**\n * The operators under which a JSON leaf of a *different* type than the literal\n * is a match (it is \"not equal\"); under every other operator a mismatch is a\n * non-match. `IS NOT` is not listed: `IS`/`IS NOT` are null-safe equality and\n * already yield the strict answer.\n */\nexport function isNegatedOperator(op: SimpleOperator): boolean {\n return negatedOperators.has(op);\n}\n\nconst likeOperators: ReadonlySet<SimpleOperator> = new Set([\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n]);\n\n/**\n * The pattern-matching operators, which compare text and therefore require a\n * string leaf whatever the literal's type.\n */\nexport function isLikeOperator(op: SimpleOperator): boolean {\n return likeOperators.has(op);\n}\n\n/**\n * Formats a JSON path reference for debug/display output, e.g.\n * `metadata.tags[0]`. Shared by the builder's filter names, the planner debug\n * output and test stringifiers so they cannot drift.\n */\nexport function formatJsonPathReference(ref: JsonPathReference): string {\n return `${ref.value.name}${ref.path\n .map(s => (typeof s === 'number' ? `[${s}]` : `.${s}`))\n .join('')}`;\n}\n\n/**\n * A JSON path (object keys and array indices) into a `json()` column, shared by\n * {@link JsonPathReference} and {@link Aggregate}.\n */\nconst jsonPathSchema = v\n .readonlyArray(\n v.union(\n v.string(),\n v\n .number()\n .assert(\n isValidJsonPathIndex,\n 'expected a non-negative integer array index',\n ),\n ),\n )\n // `json(col, ...path)` types the path as non-empty; reject an empty one at\n // the wire too, since the compilers address the last segment and a bare\n // column is not a JSON leaf.\n .assert(path => path.length > 0, 'expected a non-empty JSON path');\n\nconst jsonPathReferenceSchema: v.Type<JsonPathReference> = v.readonlyObject({\n type: v.literal('json'),\n value: columnReferenceSchema,\n path: jsonPathSchema,\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 jsonPathReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\n/**\n * The literal compared against a JSON path leaf has the shape its operator\n * needs: `IN`/`NOT IN` take a list (or `null`, the explicitly supported\n * constant-false case) and every other operator a scalar. The builder's types\n * guarantee this for a literal, but a parameter is bound to whatever the\n * anchor holds; without this check a scalar bound to `IN` trips the in-memory\n * predicate's array assertion and a list bound to `=` the Postgres compiler's\n * plural assertion. A plain column's literal is not checked here (its shape\n * was never validated at the wire, and changing that is out of scope).\n */\nfunction hasJsonLeafLiteralShape(c: SimpleCondition): boolean {\n if (c.left.type !== 'json' || c.right.type !== 'literal') {\n return true;\n }\n const isList = Array.isArray(c.right.value);\n return c.op === 'IN' || c.op === 'NOT IN'\n ? isList || c.right.value === null\n : !isList;\n}\n\n/**\n * An `IN`/`NOT IN` list against a JSON path leaf is homogeneous: the engines\n * compare the leaf against the type of the list's first element (see\n * `jsonLiteralType`), and a mixed list would cast-fail on Postgres while\n * silently dropping elements elsewhere. `cmp()` rejects one for a `json()`\n * reference; this rejects it at the wire so a hand-built AST cannot bypass\n * that. A plain column's list is not restricted (its type is the column's).\n */\nfunction hasHomogeneousJsonInList(c: SimpleCondition): boolean {\n if (\n c.left.type !== 'json' ||\n (c.op !== 'IN' && c.op !== 'NOT IN') ||\n c.right.type !== 'literal'\n ) {\n return true;\n }\n const {value} = c.right;\n if (!Array.isArray(value)) {\n return true;\n }\n return isHomogeneousList(value);\n}\n\n/**\n * Whether every element of `list` has the JS type of its first element (an\n * empty list is homogeneous). Shared by the wire check above and `cmp()`.\n */\nexport function isHomogeneousList(list: readonly unknown[]): boolean {\n return list.every(e => typeof e === typeof list[0]);\n}\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v\n .readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n })\n .assert(\n hasJsonLeafLiteralShape,\n 'expected a list for IN/NOT IN against a JSON path and a scalar for other operators',\n )\n .assert(\n hasHomogeneousJsonInList,\n 'expected a list of values of one type for IN/NOT IN against a JSON path',\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.\nconst aggregateSchema = v\n .readonlyObject({\n fn: v.literalUnion('count', 'sum', 'avg', 'min', 'max'),\n field: v.string().optional(),\n path: jsonPathSchema.optional(),\n distinct: v.readonlyArray(v.string()).optional(),\n })\n .assert(\n a => a.path === undefined || (a.field !== undefined && a.fn !== 'count'),\n 'expected an aggregate JSON path to have a field and not be a count',\n )\n .assert(\n a =>\n a.distinct === undefined ||\n (a.fn === 'count' && a.field === undefined && a.distinct.length > 0),\n 'expected an aggregate over distinct columns to be a count of at least one',\n );\n\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n aggregate: aggregateSchema.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 aggregate: aggregateSchema.optional(),\n groupBy: v\n .readonlyArray(v.string())\n .assert(cols => cols.length > 0, 'expected groupBy to name a column')\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 /**\n * Reduces the query to a single aggregate over its rows: the result is that\n * scalar rather than a list of rows. As in SQL, it reduces the rows left\n * after `where`, `start` and `limit`, so `orderBy` matters only when a bound\n * is present; `related` does not apply. See zql's `ivm/aggregate.ts`.\n */\n readonly aggregate?: Aggregate | undefined;\n\n /**\n * Groups the rows that pass `where` by these columns: one row per\n * combination of their values, as in `GROUP BY`. Without an `aggregate` it\n * is a `SELECT DISTINCT` of the columns; with one, that aggregate per group,\n * other than a count of distinct values. `NULL` is a value like\n * any other. `orderBy` orders the groups and may only name these columns;\n * `start`, `limit` and `related` do not apply. See zql's `ivm/group-by.ts`.\n */\n readonly groupBy?: readonly string[] | 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 /**\n * Reduces the subquery to one aggregate per parent row: the relationship\n * is that scalar rather than the child rows. The aggregate is on this entry,\n * not on `subquery`, whose own `aggregate` stays unset. See zql's\n * `ivm/aggregate.ts`.\n */\n readonly aggregate?: Aggregate | undefined;\n};\n\nexport type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max';\n\nexport type Aggregate = {\n readonly fn: AggregateFunction;\n // The column to aggregate. Required for `sum`/`avg`/`min`/`max`; absent for\n // `count` (which is `count(*)`). Subject to client→server name mapping. For a\n // junction relationship it names a column of the destination table.\n readonly field?: string | undefined;\n // Navigates into `field`, which is then a `json()` column, to a scalar leaf.\n // Data, not a schema name: name mapping leaves it alone. Not for `count`.\n readonly path?: readonly (string | number)[] | undefined;\n // For `count`: counts the distinct combinations of these columns among the\n // rows, the rows a `groupBy` of them would give, rather than the rows. A\n // `NULL` is a value like any other, unlike in SQL's `COUNT(DISTINCT x)`.\n // Subject to name mapping.\n readonly distinct?: readonly string[] | undefined;\n};\n\n/**\n * The value an aggregate reduces for `row`: the `field` column itself, or, with\n * a `path`, the JSON leaf at that path when it is one the aggregate takes: a\n * number for `sum`/`avg`, a number or a string for `min`/`max` (numbers order\n * before strings, see `compareAggregateValues`). Any other leaf, or a missing\n * one, is `null`, which aggregates skip. Shared by the IVM operator, the\n * junction lift and the client's optimistic delta so the rule cannot drift.\n */\nexport function aggregateValue(\n agg: Aggregate,\n row: Readonly<Record<string, unknown>>,\n): unknown {\n const v = row[must(agg.field)];\n if (agg.path === undefined) {\n return v;\n }\n const leaf = jsonValueAtPath(v, agg.path);\n switch (typeof leaf) {\n case 'number':\n return leaf;\n case 'string':\n return agg.fn === 'min' || agg.fn === 'max' ? leaf : null;\n default:\n return null;\n }\n}\n\n/**\n * Navigates into a JSON value following `path`, strictly: a `number` segment\n * indexes an array and a `string` segment reads an own property of a plain\n * object. Any other step (a null/undefined or scalar intermediate, a segment of\n * the wrong kind, a missing key) yields `null`. See `zql/src/builder/filter.ts`\n * for why this is the rule.\n */\nexport function jsonValueAtPath(\n value: unknown,\n path: readonly (string | number)[],\n): unknown {\n let v: unknown = value;\n for (const seg of path) {\n if (v === null || typeof v !== 'object') {\n return null;\n }\n if (Array.isArray(v)) {\n if (typeof seg !== 'number') {\n return null;\n }\n v = v[seg];\n } else if (typeof seg === 'string' && Object.hasOwn(v, seg)) {\n v = (v as Record<string, unknown>)[seg];\n } else {\n return null;\n }\n }\n return v ?? null;\n}\n\nexport type ValuePosition =\n | LiteralReference\n | Parameter\n | ColumnReference\n | JsonPathReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * The name of the column on the current table.\n *\n * Note: this is *not* a path through the relationship tree. Cross-table\n * comparisons are not yet supported and would be modeled separately.\n */\n readonly name: string;\n};\n\n/**\n * A reference to a value *inside* a `json()` column, produced by `eb.json()`.\n *\n * Wraps a {@link ColumnReference} and navigates into its JSON value via `path`:\n * segments are applied left-to-right as object keys (string) and array indices\n * (number). A `JsonPathReference` is allowed wherever a {@link ColumnReference} is\n * (currently only the left operand of a filter predicate).\n *\n * Evaluation semantics, implemented identically by the in-memory predicate\n * (`zql/src/builder/filter.ts`), the SQLite pushdown (`zqlite/src/query-builder.ts`)\n * and the Postgres compiler (`z2s/src/compiler.ts`); the engine comments refer\n * here rather than restating the rules:\n *\n * - **Segments are strict.** A number segment indexes an array and a string\n * segment reads an own key of an object. Any other step (a segment of the\n * wrong kind, a missing key, a scalar or null intermediate) yields null.\n * - **Missing and JSON null collapse to null:** a non-match for every value\n * operator, a match for `IS NULL`.\n * - **Comparison is type-strict.** A leaf whose JSON type differs from the\n * literal's is never equal: a non-match for a positive operator, a match for a\n * negated one (`!=`, `NOT IN`, `NOT LIKE`, `NOT ILIKE`), and never an error.\n * Only scalar leaves are comparable.\n *\n * A path references a value inside a single column; it never crosses tables.\n * Because a path-extracted value is not a stored/indexed column, it can never\n * be a primary-key or join constraint key (see {@link extractColumn}, which\n * excludes it from constraint/PK lookups).\n */\nexport type JsonPathReference = {\n readonly type: 'json';\n readonly value: ColumnReference;\n readonly path: readonly (string | number)[];\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 | JsonPathReference>;\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 // The column wrapped by a JSON path reference. A mapper that knows column\n // types rejects a column that is not a json column here.\n jsonColumnName(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 aggregate: r.aggregate\n ? transformAggregate(r.aggregate, aggregateFieldTable(r), transform)\n : undefined,\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 aggregate: ast.aggregate\n ? transformAggregate(ast.aggregate, ast.table, transform)\n : undefined,\n groupBy: ast.groupBy?.map(colName),\n };\n\n return transformed;\n}\n\n/**\n * Maps an aggregate's `field` (validated to be a json column when the\n * aggregate has a JSON path); the path is data and passes through.\n */\nfunction transformAggregate(\n agg: Aggregate,\n table: string,\n {columnName, jsonColumnName}: ASTTransform,\n): Aggregate {\n const {fn, field, path, distinct} = agg;\n if (distinct !== undefined) {\n return {fn, distinct: distinct.map(col => columnName(table, col))};\n }\n if (field === undefined) {\n return {fn, field: undefined};\n }\n return path === undefined\n ? {fn, field: columnName(table, field)}\n : {fn, field: jsonColumnName(table, field), path};\n}\n\n/**\n * The table an aggregate relationship's `field` belongs to. For a junction\n * (many-to-many) aggregate the subquery is the junction table and its single\n * `related` entry is the destination the field lives on. The query builder\n * rejects any other `related` under an aggregate, so one being present means\n * a junction.\n */\nfunction aggregateFieldTable(r: CorrelatedSubquery): string {\n const dest = r.subquery.related?.[0];\n return dest ? dest.subquery.table : r.subquery.table;\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, jsonColumnName} = transform;\n const condValue = (c: ConditionValue): ConditionValue => {\n switch (c.type) {\n case 'column':\n return {...c, name: columnName(table, c.name)};\n case 'json':\n // The column name maps client->server (and is validated to be a json\n // column); the path is data and is preserved as-is.\n return {\n ...c,\n value: {...c.value, name: jsonColumnName(table, c.value.name)},\n };\n default:\n return c;\n }\n };\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 {\n schema,\n table,\n alias,\n where,\n related,\n start,\n limit,\n orderBy,\n aggregate,\n groupBy,\n } = 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 aggregate,\n groupBy,\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 aggregate: undefined,\n groupBy: 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, aggregate} = related;\n return {\n correlation: {\n parentField: correlation.parentField,\n childField: correlation.childField,\n },\n hidden,\n subquery,\n system,\n aggregate,\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 case 'json':\n return {\n type: 'json',\n value: normalizeValuePosition(v.value),\n path: v.path,\n } 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 jsonColumnName: (table, col) => mapper.jsonColumnName(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 jsonColumnName: (table, col) => mapper.jsonColumnName(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 'json':\n assert(b.type === 'json', 'Expected json type for comparison');\n return (\n compareValuePosition(a.value, b.value) ||\n // A path is strings and numbers, which cmpLiteralValue() orders by\n // type, so `['0']` (an object key) and `[0]` (an array index) differ.\n cmpLiteralValue(a.path, b.path)\n );\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,IAAM,iBAAiBA,eAAE,OAAO;AAChC,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;AAGnE,IAAa,oBAAoBD,aAAe,KAAK,MAAM,MAAM,QAAQ;AAEzE,IAAa,iBAAiBA,aAAe,KAAK,KAAK,MAAM,IAAI;AAEjE,IAAa,gBAAgBA,aAC3B,QACA,YACA,SACA,W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ACQ;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\nconst 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 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\nconst 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 * Upper bound for an array-index segment. SQLite parses a `$[i]` index as an\n * unsigned 32-bit integer (larger values silently wrap), and the Postgres `->`\n * operator takes an `int4`, so anything above this is not a usable index on\n * every engine.\n */\nexport const MAX_JSON_PATH_INDEX = 2 ** 31 - 1;\n\n/**\n * A numeric JSON path segment is an array index and must be an integer in\n * `[0, MAX_JSON_PATH_INDEX]`. Negative indices are rejected because the engines\n * disagree on them (Postgres counts from the end, while JavaScript and SQLite\n * yield null); larger values are rejected because SQLite wraps them modulo\n * 2^32 (silently addressing another element) and Postgres cannot take them as\n * an `int4` operand.\n */\nexport function isValidJsonPathIndex(index: number): boolean {\n return Number.isInteger(index) && index >= 0 && index <= MAX_JSON_PATH_INDEX;\n}\n\n/**\n * The JS type a JSON leaf must have to be compared against `literal`\n * (`'string' | 'number' | 'boolean'`), or `undefined` for `null` and for an\n * empty list. For an `IN`/`NOT IN` list, the type of its first element (lists\n * are homogeneous: enforced by the builder's types, by `cmp()` and at the\n * wire). Shared by the in-memory predicate, the SQLite pushdown and the\n * Postgres compiler so the type-strict rule cannot drift between engines.\n */\nexport function jsonLiteralType(\n literal: LiteralValue,\n): 'string' | 'number' | 'boolean' | undefined {\n const v = Array.isArray(literal) ? literal[0] : literal;\n switch (typeof v) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n default:\n return undefined;\n }\n}\n\nconst negatedOperators: ReadonlySet<SimpleOperator> = new Set([\n '!=',\n 'NOT LIKE',\n 'NOT ILIKE',\n 'NOT IN',\n]);\n\n/**\n * The operators under which a JSON leaf of a *different* type than the literal\n * is a match (it is \"not equal\"); under every other operator a mismatch is a\n * non-match. `IS NOT` is not listed: `IS`/`IS NOT` are null-safe equality and\n * already yield the strict answer.\n */\nexport function isNegatedOperator(op: SimpleOperator): boolean {\n return negatedOperators.has(op);\n}\n\nconst likeOperators: ReadonlySet<SimpleOperator> = new Set([\n 'LIKE',\n 'NOT LIKE',\n 'ILIKE',\n 'NOT ILIKE',\n]);\n\n/**\n * The pattern-matching operators, which compare text and therefore require a\n * string leaf whatever the literal's type.\n */\nexport function isLikeOperator(op: SimpleOperator): boolean {\n return likeOperators.has(op);\n}\n\n/**\n * Formats a JSON path reference for debug/display output, e.g.\n * `metadata.tags[0]`. Shared by the builder's filter names, the planner debug\n * output and test stringifiers so they cannot drift.\n */\nexport function formatJsonPathReference(ref: JsonPathReference): string {\n return `${ref.value.name}${ref.path\n .map(s => (typeof s === 'number' ? `[${s}]` : `.${s}`))\n .join('')}`;\n}\n\n/**\n * A JSON path (object keys and array indices) into a `json()` column, shared by\n * {@link JsonPathReference} and {@link Aggregate}.\n */\nconst jsonPathSchema = v\n .readonlyArray(\n v.union(\n v.string(),\n v\n .number()\n .assert(\n isValidJsonPathIndex,\n 'expected a non-negative integer array index',\n ),\n ),\n )\n // `json(col, ...path)` types the path as non-empty; reject an empty one at\n // the wire too, since the compilers address the last segment and a bare\n // column is not a JSON leaf.\n .assert(path => path.length > 0, 'expected a non-empty JSON path');\n\nconst jsonPathReferenceSchema: v.Type<JsonPathReference> = v.readonlyObject({\n type: v.literal('json'),\n value: columnReferenceSchema,\n path: jsonPathSchema,\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 jsonPathReferenceSchema,\n parameterReferenceSchema,\n);\n\nexport type Parameter = v.Infer<typeof parameterReferenceSchema>;\n\n/**\n * The literal compared against a JSON path leaf has the shape its operator\n * needs: `IN`/`NOT IN` take a list (or `null`, the explicitly supported\n * constant-false case) and every other operator a scalar. The builder's types\n * guarantee this for a literal, but a parameter is bound to whatever the\n * anchor holds; without this check a scalar bound to `IN` trips the in-memory\n * predicate's array assertion and a list bound to `=` the Postgres compiler's\n * plural assertion. A plain column's literal is not checked here (its shape\n * was never validated at the wire, and changing that is out of scope).\n */\nfunction hasJsonLeafLiteralShape(c: SimpleCondition): boolean {\n if (c.left.type !== 'json' || c.right.type !== 'literal') {\n return true;\n }\n const isList = Array.isArray(c.right.value);\n return c.op === 'IN' || c.op === 'NOT IN'\n ? isList || c.right.value === null\n : !isList;\n}\n\n/**\n * An `IN`/`NOT IN` list against a JSON path leaf is homogeneous: the engines\n * compare the leaf against the type of the list's first element (see\n * `jsonLiteralType`), and a mixed list would cast-fail on Postgres while\n * silently dropping elements elsewhere. `cmp()` rejects one for a `json()`\n * reference; this rejects it at the wire so a hand-built AST cannot bypass\n * that. A plain column's list is not restricted (its type is the column's).\n */\nfunction hasHomogeneousJsonInList(c: SimpleCondition): boolean {\n if (\n c.left.type !== 'json' ||\n (c.op !== 'IN' && c.op !== 'NOT IN') ||\n c.right.type !== 'literal'\n ) {\n return true;\n }\n const {value} = c.right;\n if (!Array.isArray(value)) {\n return true;\n }\n return isHomogeneousList(value);\n}\n\n/**\n * Whether every element of `list` has the JS type of its first element (an\n * empty list is homogeneous). Shared by the wire check above and `cmp()`.\n */\nexport function isHomogeneousList(list: readonly unknown[]): boolean {\n return list.every(e => typeof e === typeof list[0]);\n}\n\nexport const simpleConditionSchema: v.Type<SimpleCondition> = v\n .readonlyObject({\n type: v.literal('simple'),\n op: simpleOperatorSchema,\n left: conditionValueSchema,\n right: v.union(parameterReferenceSchema, literalReferenceSchema),\n })\n .assert(\n hasJsonLeafLiteralShape,\n 'expected a list for IN/NOT IN against a JSON path and a scalar for other operators',\n )\n .assert(\n hasHomogeneousJsonInList,\n 'expected a list of values of one type for IN/NOT IN against a JSON path',\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.\nconst aggregateSchema = v\n .readonlyObject({\n fn: v.literalUnion('count', 'sum', 'avg', 'min', 'max'),\n field: v.string().optional(),\n path: jsonPathSchema.optional(),\n distinct: v.readonlyArray(v.string()).optional(),\n })\n .assert(\n a => a.path === undefined || (a.field !== undefined && a.fn !== 'count'),\n 'expected an aggregate JSON path to have a field and not be a count',\n )\n .assert(\n a =>\n a.distinct === undefined ||\n (a.fn === 'count' && a.field === undefined && a.distinct.length > 0),\n 'expected an aggregate over distinct columns to be a count of at least one',\n );\n\nexport const correlatedSubquerySchemaOmitSubquery = v.readonlyObject({\n correlation: correlationSchema,\n hidden: v.boolean().optional(),\n system: v.literalUnion('permissions', 'client', 'test').optional(),\n aggregate: aggregateSchema.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 aggregate: aggregateSchema.optional(),\n groupBy: v\n .readonlyArray(v.string())\n .assert(cols => cols.length > 0, 'expected groupBy to name a column')\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 /**\n * Reduces the query to a single aggregate over its rows: the result is that\n * scalar rather than a list of rows. As in SQL, it reduces the rows left\n * after `where`, `start` and `limit`, so `orderBy` matters only when a bound\n * is present; `related` does not apply. See zql's `ivm/aggregate.ts`.\n */\n readonly aggregate?: Aggregate | undefined;\n\n /**\n * Groups the rows that pass `where` by these columns: one row per\n * combination of their values, as in `GROUP BY`. Without an `aggregate` it\n * is a `SELECT DISTINCT` of the columns; with one, that aggregate per group,\n * other than a count of distinct values. `NULL` is a value like\n * any other. `orderBy` orders the groups and may only name these columns;\n * `start`, `limit` and `related` do not apply. See zql's `ivm/group-by.ts`.\n */\n readonly groupBy?: readonly string[] | 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 /**\n * Reduces the subquery to one aggregate per parent row: the relationship\n * is that scalar rather than the child rows. The aggregate is on this entry,\n * not on `subquery`, whose own `aggregate` stays unset. See zql's\n * `ivm/aggregate.ts`.\n */\n readonly aggregate?: Aggregate | undefined;\n};\n\nexport type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max';\n\nexport type Aggregate = {\n readonly fn: AggregateFunction;\n // The column to aggregate. Required for `sum`/`avg`/`min`/`max`; absent for\n // `count` (which is `count(*)`). Subject to client→server name mapping. For a\n // junction relationship it names a column of the destination table.\n readonly field?: string | undefined;\n // Navigates into `field`, which is then a `json()` column, to a scalar leaf.\n // Data, not a schema name: name mapping leaves it alone. Not for `count`.\n readonly path?: readonly (string | number)[] | undefined;\n // For `count`: counts the distinct combinations of these columns among the\n // rows, the rows a `groupBy` of them would give, rather than the rows. A\n // `NULL` is a value like any other, unlike in SQL's `COUNT(DISTINCT x)`.\n // Subject to name mapping.\n readonly distinct?: readonly string[] | undefined;\n};\n\n/**\n * The value an aggregate reduces for `row`: the `field` column itself, or, with\n * a `path`, the JSON leaf at that path when it is one the aggregate takes: a\n * number for `sum`/`avg`, a number or a string for `min`/`max` (strings order\n * before numbers, see `compareAggregateValues`). Any other leaf, or a missing\n * one, is `null`, which aggregates skip. Shared by the IVM operator, the\n * junction lift and the client's optimistic delta so the rule cannot drift.\n */\nexport function aggregateValue(\n agg: Aggregate,\n row: Readonly<Record<string, unknown>>,\n): unknown {\n const v = row[must(agg.field)];\n if (agg.path === undefined) {\n return v;\n }\n const leaf = jsonValueAtPath(v, agg.path);\n switch (typeof leaf) {\n case 'number':\n return leaf;\n case 'string':\n return agg.fn === 'min' || agg.fn === 'max' ? leaf : null;\n default:\n return null;\n }\n}\n\n/**\n * Navigates into a JSON value following `path`, strictly: a `number` segment\n * indexes an array and a `string` segment reads an own property of a plain\n * object. Any other step (a null/undefined or scalar intermediate, a segment of\n * the wrong kind, a missing key) yields `null`. See `zql/src/builder/filter.ts`\n * for why this is the rule.\n */\nexport function jsonValueAtPath(\n value: unknown,\n path: readonly (string | number)[],\n): unknown {\n let v: unknown = value;\n for (const seg of path) {\n if (v === null || typeof v !== 'object') {\n return null;\n }\n if (Array.isArray(v)) {\n if (typeof seg !== 'number') {\n return null;\n }\n v = v[seg];\n } else if (typeof seg === 'string' && Object.hasOwn(v, seg)) {\n v = (v as Record<string, unknown>)[seg];\n } else {\n return null;\n }\n }\n return v ?? null;\n}\n\nexport type ValuePosition =\n | LiteralReference\n | Parameter\n | ColumnReference\n | JsonPathReference;\n\nexport type ColumnReference = {\n readonly type: 'column';\n /**\n * The name of the column on the current table.\n *\n * Note: this is *not* a path through the relationship tree. Cross-table\n * comparisons are not yet supported and would be modeled separately.\n */\n readonly name: string;\n};\n\n/**\n * A reference to a value *inside* a `json()` column, produced by `eb.json()`.\n *\n * Wraps a {@link ColumnReference} and navigates into its JSON value via `path`:\n * segments are applied left-to-right as object keys (string) and array indices\n * (number). A `JsonPathReference` is allowed wherever a {@link ColumnReference} is\n * (currently only the left operand of a filter predicate).\n *\n * Evaluation semantics, implemented identically by the in-memory predicate\n * (`zql/src/builder/filter.ts`), the SQLite pushdown (`zqlite/src/query-builder.ts`)\n * and the Postgres compiler (`z2s/src/compiler.ts`); the engine comments refer\n * here rather than restating the rules:\n *\n * - **Segments are strict.** A number segment indexes an array and a string\n * segment reads an own key of an object. Any other step (a segment of the\n * wrong kind, a missing key, a scalar or null intermediate) yields null.\n * - **Missing and JSON null collapse to null:** a non-match for every value\n * operator, a match for `IS NULL`.\n * - **Comparison is type-strict.** A leaf whose JSON type differs from the\n * literal's is never equal: a non-match for a positive operator, a match for a\n * negated one (`!=`, `NOT IN`, `NOT LIKE`, `NOT ILIKE`), and never an error.\n * Only scalar leaves are comparable.\n *\n * A path references a value inside a single column; it never crosses tables.\n * Because a path-extracted value is not a stored/indexed column, it can never\n * be a primary-key or join constraint key (see {@link extractColumn}, which\n * excludes it from constraint/PK lookups).\n */\nexport type JsonPathReference = {\n readonly type: 'json';\n readonly value: ColumnReference;\n readonly path: readonly (string | number)[];\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 | JsonPathReference>;\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 // The column wrapped by a JSON path reference. A mapper that knows column\n // types rejects a column that is not a json column here.\n jsonColumnName(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 aggregate: r.aggregate\n ? transformAggregate(r.aggregate, aggregateFieldTable(r), transform)\n : undefined,\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 aggregate: ast.aggregate\n ? transformAggregate(ast.aggregate, ast.table, transform)\n : undefined,\n groupBy: ast.groupBy?.map(colName),\n };\n\n return transformed;\n}\n\n/**\n * Maps an aggregate's `field` (validated to be a json column when the\n * aggregate has a JSON path); the path is data and passes through.\n */\nfunction transformAggregate(\n agg: Aggregate,\n table: string,\n {columnName, jsonColumnName}: ASTTransform,\n): Aggregate {\n const {fn, field, path, distinct} = agg;\n if (distinct !== undefined) {\n return {fn, distinct: distinct.map(col => columnName(table, col))};\n }\n if (field === undefined) {\n return {fn, field: undefined};\n }\n return path === undefined\n ? {fn, field: columnName(table, field)}\n : {fn, field: jsonColumnName(table, field), path};\n}\n\n/**\n * The table an aggregate relationship's `field` belongs to. For a junction\n * (many-to-many) aggregate the subquery is the junction table and its single\n * `related` entry is the destination the field lives on. The query builder\n * rejects any other `related` under an aggregate, so one being present means\n * a junction.\n */\nfunction aggregateFieldTable(r: CorrelatedSubquery): string {\n const dest = r.subquery.related?.[0];\n return dest ? dest.subquery.table : r.subquery.table;\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, jsonColumnName} = transform;\n const condValue = (c: ConditionValue): ConditionValue => {\n switch (c.type) {\n case 'column':\n return {...c, name: columnName(table, c.name)};\n case 'json':\n // The column name maps client->server (and is validated to be a json\n // column); the path is data and is preserved as-is.\n return {\n ...c,\n value: {...c.value, name: jsonColumnName(table, c.value.name)},\n };\n default:\n return c;\n }\n };\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 {\n schema,\n table,\n alias,\n where,\n related,\n start,\n limit,\n orderBy,\n aggregate,\n groupBy,\n } = 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 aggregate,\n groupBy,\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 aggregate: undefined,\n groupBy: 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, aggregate} = related;\n return {\n correlation: {\n parentField: correlation.parentField,\n childField: correlation.childField,\n },\n hidden,\n subquery,\n system,\n aggregate,\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 case 'json':\n return {\n type: 'json',\n value: normalizeValuePosition(v.value),\n path: v.path,\n } 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 jsonColumnName: (table, col) => mapper.jsonColumnName(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 jsonColumnName: (table, col) => mapper.jsonColumnName(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 'json':\n assert(b.type === 'json', 'Expected json type for comparison');\n return (\n compareValuePosition(a.value, b.value) ||\n // A path is strings and numbers, which cmpLiteralValue() orders by\n // type, so `['0']` (an object key) and `[0]` (an array index) differ.\n cmpLiteralValue(a.path, b.path)\n );\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,IAAM,iBAAiBA,eAAE,OAAO;AAChC,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;AAGnE,IAAa,oBAAoBD,aAAe,KAAK,MAAM,MAAM,QAAQ;AAEzE,IAAa,iBAAiBA,aAAe,KAAK,KAAK,MAAM,IAAI;AAEjE,IAAa,gBAAgBA,aAC3B,QACA,YACA,SACA,WACF;AAEA,IAAM,cAAcA,aAAe,MAAM,QAAQ;AAEjD,IAAa,uBAAuBF,eAAE,MACpC,mBACA,gBACA,eACA,WACF;AAEA,IAAM,yBAAmDI,eAAiB;CACxE,MAAMJ,eAAE,QAAQ,SAAS;CACzB,OAAOA,eAAE,MACPA,eAAE,OAAO,GACTA,eAAE,OAAO,GACTA,eAAE,QAAQ,GACVA,eAAE,KAAK,GACPG,cAAgBH,eAAE,MAAMA,eAAE,OAAO,GAAGA,eAAE,OAAO,GAAGA,eAAE,QAAQ,CAAC,CAAC,CAC9D;AACF,CAAC;AACD,IAAM,wBAAiDI,eAAiB;CACtE,MAAMJ,eAAE,QAAQ,QAAQ;CACxB,MAAMA,eAAE,OAAO;AACjB,CAAC;;;;;;;AAQD,IAAa,sBAAsB,KAAK,KAAK;;;;;;;;;AAU7C,SA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AAE;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<{
|