@rocicorp/zero 1.13.0-canary.0 → 1.13.0-canary.2
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/shared/src/valita.d.ts.map +1 -1
- package/out/shared/src/valita.js +2 -1
- package/out/shared/src/valita.js.map +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +4 -2
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.js +2 -2
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +1 -1
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +0 -54
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +4 -4
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +12 -7
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +2 -2
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state.js +2 -2
- package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +2 -30
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js +1 -1
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
- package/out/zero-client/src/client/crud-impl.js +1 -1
- package/out/zero-client/src/client/ivm-branch.js +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-protocol/src/client-schema.js +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-schema/src/builder/schema-builder.js +1 -1
- package/out/zql/src/builder/builder.js +1 -1
- package/out/zql/src/ivm/aggregate.js +1 -1
- package/out/zql/src/ivm/flipped-join.js +1 -1
- package/out/zql/src/ivm/group-by.js +1 -1
- package/out/zql/src/ivm/join-index.js +1 -1
- package/out/zql/src/ivm/memory-source.js +1 -1
- package/out/zql/src/ivm/view-apply-change.js +1 -1
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +4 -2
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valita.d.ts","sourceRoot":"","sources":["../../../../shared/src/valita.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"valita.d.ts","sourceRoot":"","sources":["../../../../shared/src/valita.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,gBAAgB,CAAC;AAGpC,cAAc,gBAAgB,CAAC;AAwK/B;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,aAAa,GAAG,QAAQ,GAAG,OAAO,CAAC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CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,kBAAkB,CAAC,CAAC,CAAC,GAChD,KAAK,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;CAChC,CAgDA"}
|
package/out/shared/src/valita.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { __exportAll, __reExport } from "../../_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { getOwnProperty } from "./objects.js";
|
|
2
3
|
import * as v from "@badrap/valita";
|
|
3
4
|
export * from "@badrap/valita";
|
|
4
5
|
//#region ../shared/src/valita.ts
|
|
@@ -265,7 +266,7 @@ function taggedObjectUnion(key, objects, options) {
|
|
|
265
266
|
});
|
|
266
267
|
}
|
|
267
268
|
const expectedTag = `Expected ${displayList("or", [...tagTypes])}`;
|
|
268
|
-
const tagOf = (value) =>
|
|
269
|
+
const tagOf = (value) => getOwnProperty(value, key);
|
|
269
270
|
const type = v.unknown().chain((value, options) => {
|
|
270
271
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return v.err("Expected object");
|
|
271
272
|
const tag = tagOf(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valita.js","names":[],"sources":["../../../../shared/src/valita.ts"],"sourcesContent":["import * as v from '@badrap/valita';\n\nexport * from '@badrap/valita';\n\nfunction toDisplay(value: unknown): string {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return JSON.stringify(value);\n case 'undefined':\n return 'undefined';\n case 'bigint':\n return value.toString() + 'n';\n default:\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n }\n}\n\ntype Key = string | number;\n\nfunction toDisplayAtPath(v: unknown, path: Key[] | undefined): string {\n if (!path?.length) {\n return toDisplay(v);\n }\n\n let cur = v;\n for (const p of path) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n cur = (cur as any)[p];\n }\n return toDisplay(cur);\n}\n\nfunction displayList<T>(\n word: string,\n expected: T[],\n toDisplay: (x: T) => string | number = x => String(x),\n): string | number {\n if (expected.length === 1) {\n return toDisplay(expected[0]);\n }\n\n const suffix = `${toDisplay(\n expected[expected.length - 2],\n // oxlint-disable-next-line typescript/no-non-null-assertion\n )} ${word} ${toDisplay(expected.at(-1)!)}`;\n if (expected.length === 2) {\n return suffix;\n }\n return `${expected.slice(0, -2).map(toDisplay).join(', ')}, ${suffix}`;\n}\n\nfunction getMessage(\n err: v.Err,\n v: unknown,\n schema: v.Type | v.Optional,\n mode: ParseOptionsMode | undefined,\n): string {\n const firstIssue = err.issues[0];\n const {path} = firstIssue;\n const atPath = path?.length ? ` at ${path.join('.')}` : '';\n\n switch (firstIssue.code) {\n case 'invalid_type':\n return `Expected ${displayList(\n 'or',\n firstIssue.expected,\n )}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n case 'missing_value': {\n const atPath =\n path && path.length > 1 ? ` at ${path.slice(0, -1).join('.')}` : '';\n\n if (firstIssue.path?.length) {\n return `Missing property ${firstIssue.path.at(-1)}${atPath}`;\n }\n return `TODO Unknown missing property${atPath}`;\n }\n\n case 'invalid_literal':\n return `Expected literal value ${displayList(\n 'or',\n firstIssue.expected,\n toDisplay,\n )}${atPath} Got ${toDisplayAtPath(v, path)}`;\n\n case 'invalid_length': {\n return `Expected array with length ${\n firstIssue.minLength === firstIssue.maxLength\n ? firstIssue.minLength\n : `between ${firstIssue.minLength} and ${firstIssue.maxLength}`\n }${atPath}. Got array with length ${(v as {length: number}).length}`;\n }\n\n case 'unrecognized_keys':\n if (firstIssue.keys.length === 1) {\n return `Unexpected property ${firstIssue.keys[0]}${atPath}`;\n }\n return `Unexpected properties ${displayList(\n 'and',\n firstIssue.keys,\n )}${atPath}`;\n\n case 'invalid_union':\n return schema.name === 'union'\n ? getDeepestUnionParseError(v, schema as v.UnionType, mode ?? 'strict')\n : `Invalid union value${atPath}`;\n\n case 'custom_error':\n return `${firstIssue.message}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n }\n}\n\ntype FailedType = {type: v.Type; err: v.Err};\n\nfunction getDeepestUnionParseError(\n value: unknown,\n schema: v.UnionType,\n mode: ParseOptionsMode,\n): string {\n const failures: FailedType[] = [];\n for (const type of schema.options) {\n const r = type.try(value, {mode});\n if (!r.ok) {\n failures.push({type, err: r});\n }\n }\n if (failures.length) {\n // compare the first and second longest-path errors\n failures.sort(pathCmp);\n if (failures.length === 1 || pathCmp(failures[0], failures[1]) < 0) {\n return getMessage(failures[0].err, value, failures[0].type, mode);\n }\n }\n // paths are equivalent\n try {\n const str = JSON.stringify(value);\n return `Invalid union value: ${str}`;\n } catch {\n // fallback if the value could not be stringified\n return `Invalid union value`;\n }\n}\n\n// Descending-order comparison of Issue paths.\n// * [1, 'a'] sorts before [1]\n// * [1] sorts before [0] (i.e. errors later in the tuple sort before earlier errors)\nfunction pathCmp(a: FailedType, b: FailedType) {\n const aPath = a.err.issues[0].path;\n const bPath = b.err.issues[0].path;\n if (aPath.length !== bPath.length) {\n return bPath.length - aPath.length;\n }\n for (let i = 0; i < aPath.length; i++) {\n if (bPath[i] > aPath[i]) {\n return -1;\n }\n if (bPath[i] < aPath[i]) {\n return 1;\n }\n }\n return 0;\n}\n\n/**\n * 'strip' allows unknown properties and removes unknown properties.\n * 'strict' errors if there are unknown properties.\n * 'passthrough' allows unknown properties.\n */\nexport type ParseOptionsMode = 'passthrough' | 'strict' | 'strip';\n\nexport function parse<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): T {\n const res = test(value, schema, mode);\n if (!res.ok) {\n throw new TypeError(res.error);\n }\n return res.value;\n}\n\nexport function is<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): value is T {\n return test(value, schema, mode).ok;\n}\n\nexport function assert<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): asserts value is T {\n parse(value, schema, mode);\n}\n\ntype Result<T> = {ok: true; value: T} | {ok: false; error: string};\n\nexport function test<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): Result<T> {\n // A Type<T> only yields undefined if T includes it.\n return testOptional(value, schema, mode) as Result<T>;\n}\n\n/**\n * Similar to {@link test} but works for AbstractTypes such as Optional.\n * This is for advanced usage. Prefer {@link test} unless you really need\n * to operate directly on an Optional field.\n */\nexport function testOptional<T>(\n value: unknown,\n schema: v.Type<T> | v.Optional<T>,\n mode?: ParseOptionsMode,\n): Result<T | undefined> {\n const res = schema.try(value, mode ? {mode} : undefined);\n if (!res.ok) {\n return {ok: false, error: getMessage(res, value, schema, mode)};\n }\n return res;\n}\n\nconst STRICT = {mode: 'strict'} as const;\n\n/**\n * Parses `schema` in strict mode, whatever mode the enclosing parse uses. Use\n * it for the parts of a message that a reader must not silently ignore inside\n * a lenient parse.\n *\n * Wrap a field, not a union variant: a union sees the wrapped type as\n * `unknown`, so it can no longer pick the variant by its literal fields.\n */\nexport function strict<T>(schema: v.Type<T>): v.Type<T> {\n const type = v.unknown().chain(value => schema.try(value, STRICT));\n // A transform serializes as just its name. Show the wrapped schema too, so a\n // change to it still changes the hash in protocol-version.test.ts.\n return Object.assign(type, {strict: schema});\n}\n\n/**\n * Shallowly marks the schema as readonly.\n */\nexport function readonly<T extends v.Type>(t: T): v.Type<Readonly<v.Infer<T>>> {\n return t as v.Type<Readonly<v.Infer<T>>>;\n}\n\nexport function readonlyObject<T extends Record<string, v.Type | v.Optional>>(\n t: T,\n): v.ObjectType<Readonly<T>, undefined> {\n return v.object(t);\n}\n\nexport function readonlyArray<T extends v.Type>(\n t: T,\n): v.Type<readonly v.Infer<T>[]> {\n return v.array(t);\n}\n\nexport function readonlyRecord<T extends v.Type>(\n t: T,\n): v.Type<Readonly<Record<string, v.Infer<T>>>> {\n return v.record(t);\n}\n\nconst AbstractType = Object.getPrototypeOf(\n Object.getPrototypeOf(v.string().optional()),\n).constructor;\n\nexport function instanceOfAbstractType<T = unknown>(\n obj: unknown,\n): obj is v.Type<T> | v.Optional<T> {\n return obj instanceof AbstractType;\n}\n\n// valita does not export TerminalType.\nexport type TerminalType = Parameters<Parameters<v.Type['_toTerminals']>[0]>[0];\n\n/**\n * Calls `func` for each terminal type that `type` is composed of, looking\n * through unions, optionals and the transforms created by\n * `.optional(() => x)`, `.assert()`, `.map()` and `.chain()`.\n *\n * This is the only use of valita's internal `_toTerminals`. The public API\n * has no way to look inside a transform, so there is no alternative. The\n * `toTerminals` test in valita.test.ts pins the behavior options.ts depends\n * on, so a valita upgrade that changes it fails there instead of misparsing\n * flags.\n */\nexport function toTerminals(\n type: v.Type | v.Optional,\n func: (t: TerminalType) => void,\n): void {\n type._toTerminals(func);\n}\n\ntype ObjectShape = Record<string, typeof AbstractType>;\n\n/**\n * Similar to `ObjectType.partial()` except it recurses into nested objects.\n * Rest types are not supported.\n */\nexport function deepPartial<Shape extends ObjectShape>(\n s: v.ObjectType<Shape, undefined>,\n) {\n const shape = {} as Record<string, unknown>;\n for (const [key, type] of Object.entries(s.shape)) {\n if (type.name === 'object') {\n shape[key] = deepPartial(\n type as v.ObjectType<ObjectShape, undefined>,\n ).optional();\n } else {\n shape[key] = type.optional();\n }\n }\n return v.object(shape as {[K in keyof Shape]: v.Optional<v.Infer<Shape[K]>>});\n}\n\ntype Literal = string | number | bigint | boolean;\n\nexport function literalUnion<T extends [...Literal[]]>(\n ...literals: T\n): v.Type<T[number]> {\n return v.union(...literals.map(v.literal));\n}\n\ndeclare const unrecognized: unique symbol;\n\n/** A value of an open enum that this build doesn't know. Keeps the raw value. */\nexport type Unrecognized<T extends Literal = string> = T & {\n readonly [unrecognized]: true;\n};\n\n/**\n * Like {@link literalUnion}, but any string parses, so a reader accepts values\n * that a newer writer added. Unknown values keep their raw string and are typed\n * as {@link Unrecognized}.\n *\n * Use it only where a reader can ignore or display an unknown value. Never use\n * it for a value that changes what the reader computes, or for the\n * discriminator of a union.\n */\nexport function openLiteralUnion<T extends [string, ...string[]]>(\n ..._literals: T\n): v.Type<T[number] | Unrecognized> {\n return v.string() as v.Type<T[number] | Unrecognized>;\n}\n\n/**\n * Call in the `default` case of a `switch` over an open enum, so that a known\n * value without a `case` fails to compile.\n */\nexport function assertUnrecognized(_value: Unrecognized): void {}\n\n/** A tuple whose first element, its tag, is a literal. */\ntype TaggedTuple = v.TupleType<[v.Type<Literal>, ...v.Type[]]>;\n\n/** A tuple with a tag this build doesn't know, as {@link taggedTupleUnion} parses it. */\nexport type UnrecognizedTuple = [\n tag: Unrecognized<Literal>,\n ...rest: unknown[],\n];\n\n/**\n * A union of tuples tagged by a literal in their first element, such as\n * `['ping', {}]`. Unlike `union`, it picks the tuple by its tag instead of\n * trying each in turn.\n *\n * With `open`, a tuple whose tag it doesn't know, but of the same type as a\n * known tag, parses as is, typed as {@link UnrecognizedTuple}, so a reader can\n * skip kinds a newer writer added. Use `isKnown` to tell them apart:\n * TypeScript can't narrow the union by comparing the tag, because a tag\n * literal is comparable to `Unrecognized`. A closed union is not implemented\n * yet.\n */\nexport function taggedTupleUnion<T extends TaggedTuple[]>(\n tuples: T,\n options: {readonly open: boolean},\n): v.Type<v.Infer<T[number]> | UnrecognizedTuple> & {\n isKnown(\n value: v.Infer<T[number]> | UnrecognizedTuple,\n ): value is v.Infer<T[number]>;\n} {\n if (!options.open) {\n throw new Error('A closed taggedTupleUnion is not implemented');\n }\n type Known = v.Infer<T[number]>;\n const byTag = new Map<unknown, v.Type>();\n const tagTypes = new Set<string>();\n for (const tuple of tuples) {\n toTerminals(tuple.prefix[0], t => {\n if (t.name !== 'literal') {\n throw new Error('Expected every tag to be a literal');\n }\n if (byTag.has(t.value)) {\n throw new Error(`Duplicate tag ${toDisplay(t.value)}`);\n }\n byTag.set(t.value, tuple);\n tagTypes.add(typeof t.value);\n });\n }\n const expectedTag = `Expected ${displayList('or', [...tagTypes])}`;\n const type = v\n .unknown()\n .chain((value, options): v.ValitaResult<Known | UnrecognizedTuple> => {\n if (!Array.isArray(value)) {\n return v.err('Expected array');\n }\n const [tag] = value;\n const tuple = byTag.get(tag);\n if (tuple) {\n return tuple.try(value, options) as v.ValitaResult<Known>;\n }\n return tagTypes.has(typeof tag)\n ? v.ok(value as UnrecognizedTuple)\n : v.err({message: expectedTag, path: [0]});\n });\n return Object.assign(type, {\n // A transform serializes as just its name. Show the tuples too, so a\n // change to them still changes the hash in protocol-version.test.ts.\n taggedTupleUnion: tuples,\n isKnown: (value: Known | UnrecognizedTuple): value is Known =>\n byTag.has(value[0]),\n });\n}\n\n/** An object with a tag this build doesn't know, as {@link taggedObjectUnion} parses it. */\nexport type UnrecognizedObject<K extends string> = {\n readonly [P in K]: Unrecognized<Literal>;\n} & {readonly [key: string]: unknown};\n\n/**\n * A union of objects told apart by a literal in their `key` property, their\n * tag, such as `{op: 'queries', id: '1'}`. Unlike `union`, it picks the object\n * by its tag instead of trying each in turn, so a bad object of a known kind\n * fails with that kind's error.\n *\n * With `open`, an object whose tag it doesn't know, but of the same type as a\n * known tag, parses as is, typed as {@link UnrecognizedObject}, so a reader\n * can answer or skip kinds a newer writer added. Use `isKnown` to tell them\n * apart. A closed union is not implemented yet.\n */\nexport function taggedObjectUnion<K extends string, T extends v.ObjectType[]>(\n key: K,\n objects: T,\n options: {readonly open: boolean},\n): v.Type<v.Infer<T[number]> | UnrecognizedObject<K>> & {\n isKnown(\n value: v.Infer<T[number]> | UnrecognizedObject<K>,\n ): value is v.Infer<T[number]>;\n} {\n if (!options.open) {\n throw new Error('A closed taggedObjectUnion is not implemented');\n }\n type Known = v.Infer<T[number]>;\n const byTag = new Map<unknown, v.Type>();\n const tagTypes = new Set<string>();\n for (const object of objects) {\n const tag = object.shape[key] as v.Type | v.Optional | undefined;\n if (tag === undefined) {\n throw new Error(`Expected every object to have ${key}`);\n }\n toTerminals(tag, t => {\n if (t.name !== 'literal') {\n throw new Error('Expected every tag to be a literal');\n }\n if (byTag.has(t.value)) {\n throw new Error(`Duplicate tag ${toDisplay(t.value)}`);\n }\n byTag.set(t.value, object);\n tagTypes.add(typeof t.value);\n });\n }\n const expectedTag = `Expected ${displayList('or', [...tagTypes])}`;\n const tagOf = (value: object): unknown =>\n Object.hasOwn(value, key) ? (value as Record<K, unknown>)[key] : undefined;\n const type = v\n .unknown()\n .chain((value, options): v.ValitaResult<Known | UnrecognizedObject<K>> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return v.err('Expected object');\n }\n const tag = tagOf(value);\n const object = byTag.get(tag);\n if (object) {\n return object.try(value, options) as v.ValitaResult<Known>;\n }\n return tagTypes.has(typeof tag)\n ? v.ok(value as UnrecognizedObject<K>)\n : v.err({message: expectedTag, path: [key]});\n });\n return Object.assign(type, {\n // A transform serializes as just its name. Show the objects too, so a\n // change to them still changes the hash in protocol-version.test.ts.\n taggedObjectUnion: {key, objects},\n isKnown: (value: Known | UnrecognizedObject<K>): value is Known =>\n byTag.has(tagOf(value)),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,UAAU,OAAwB;CACzC,QAAQ,OAAO,OAAf;EACE,KAAK;EACL,KAAK;EACL,KAAK,WACH,OAAO,KAAK,UAAU,KAAK;EAC7B,KAAK,aACH,OAAO;EACT,KAAK,UACH,OAAO,MAAM,SAAS,IAAI;EAC5B;GACE,IAAI,UAAU,MACZ,OAAO;GAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO;GAET,OAAO,OAAO;CAClB;AACF;AAIA,SAAS,gBAAgB,GAAY,MAAiC;CACpE,IAAI,CAAC,MAAM,QACT,OAAO,UAAU,CAAC;CAGpB,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,MAEd,MAAO,IAAY;CAErB,OAAO,UAAU,GAAG;AACtB;AAEA,SAAS,YACP,MACA,UACA,aAAuC,MAAK,OAAO,CAAC,GACnC;CACjB,IAAI,SAAS,WAAW,GACtB,OAAO,UAAU,SAAS,EAAE;CAG9B,MAAM,SAAS,GAAG,UAChB,SAAS,SAAS,SAAS,EAE7B,EAAE,GA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cesContent":["import * as v from '@badrap/valita';\nimport {getOwnProperty} from './objects.ts';\n\nexport * from '@badrap/valita';\n\nfunction toDisplay(value: unknown): string {\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return JSON.stringify(value);\n case 'undefined':\n return 'undefined';\n case 'bigint':\n return value.toString() + 'n';\n default:\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n }\n}\n\ntype Key = string | number;\n\nfunction toDisplayAtPath(v: unknown, path: Key[] | undefined): string {\n if (!path?.length) {\n return toDisplay(v);\n }\n\n let cur = v;\n for (const p of path) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n cur = (cur as any)[p];\n }\n return toDisplay(cur);\n}\n\nfunction displayList<T>(\n word: string,\n expected: T[],\n toDisplay: (x: T) => string | number = x => String(x),\n): string | number {\n if (expected.length === 1) {\n return toDisplay(expected[0]);\n }\n\n const suffix = `${toDisplay(\n expected[expected.length - 2],\n // oxlint-disable-next-line typescript/no-non-null-assertion\n )} ${word} ${toDisplay(expected.at(-1)!)}`;\n if (expected.length === 2) {\n return suffix;\n }\n return `${expected.slice(0, -2).map(toDisplay).join(', ')}, ${suffix}`;\n}\n\nfunction getMessage(\n err: v.Err,\n v: unknown,\n schema: v.Type | v.Optional,\n mode: ParseOptionsMode | undefined,\n): string {\n const firstIssue = err.issues[0];\n const {path} = firstIssue;\n const atPath = path?.length ? ` at ${path.join('.')}` : '';\n\n switch (firstIssue.code) {\n case 'invalid_type':\n return `Expected ${displayList(\n 'or',\n firstIssue.expected,\n )}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n case 'missing_value': {\n const atPath =\n path && path.length > 1 ? ` at ${path.slice(0, -1).join('.')}` : '';\n\n if (firstIssue.path?.length) {\n return `Missing property ${firstIssue.path.at(-1)}${atPath}`;\n }\n return `TODO Unknown missing property${atPath}`;\n }\n\n case 'invalid_literal':\n return `Expected literal value ${displayList(\n 'or',\n firstIssue.expected,\n toDisplay,\n )}${atPath} Got ${toDisplayAtPath(v, path)}`;\n\n case 'invalid_length': {\n return `Expected array with length ${\n firstIssue.minLength === firstIssue.maxLength\n ? firstIssue.minLength\n : `between ${firstIssue.minLength} and ${firstIssue.maxLength}`\n }${atPath}. Got array with length ${(v as {length: number}).length}`;\n }\n\n case 'unrecognized_keys':\n if (firstIssue.keys.length === 1) {\n return `Unexpected property ${firstIssue.keys[0]}${atPath}`;\n }\n return `Unexpected properties ${displayList(\n 'and',\n firstIssue.keys,\n )}${atPath}`;\n\n case 'invalid_union':\n return schema.name === 'union'\n ? getDeepestUnionParseError(v, schema as v.UnionType, mode ?? 'strict')\n : `Invalid union value${atPath}`;\n\n case 'custom_error':\n return `${firstIssue.message}${atPath}. Got ${toDisplayAtPath(v, path)}`;\n }\n}\n\ntype FailedType = {type: v.Type; err: v.Err};\n\nfunction getDeepestUnionParseError(\n value: unknown,\n schema: v.UnionType,\n mode: ParseOptionsMode,\n): string {\n const failures: FailedType[] = [];\n for (const type of schema.options) {\n const r = type.try(value, {mode});\n if (!r.ok) {\n failures.push({type, err: r});\n }\n }\n if (failures.length) {\n // compare the first and second longest-path errors\n failures.sort(pathCmp);\n if (failures.length === 1 || pathCmp(failures[0], failures[1]) < 0) {\n return getMessage(failures[0].err, value, failures[0].type, mode);\n }\n }\n // paths are equivalent\n try {\n const str = JSON.stringify(value);\n return `Invalid union value: ${str}`;\n } catch {\n // fallback if the value could not be stringified\n return `Invalid union value`;\n }\n}\n\n// Descending-order comparison of Issue paths.\n// * [1, 'a'] sorts before [1]\n// * [1] sorts before [0] (i.e. errors later in the tuple sort before earlier errors)\nfunction pathCmp(a: FailedType, b: FailedType) {\n const aPath = a.err.issues[0].path;\n const bPath = b.err.issues[0].path;\n if (aPath.length !== bPath.length) {\n return bPath.length - aPath.length;\n }\n for (let i = 0; i < aPath.length; i++) {\n if (bPath[i] > aPath[i]) {\n return -1;\n }\n if (bPath[i] < aPath[i]) {\n return 1;\n }\n }\n return 0;\n}\n\n/**\n * 'strip' allows unknown properties and removes unknown properties.\n * 'strict' errors if there are unknown properties.\n * 'passthrough' allows unknown properties.\n */\nexport type ParseOptionsMode = 'passthrough' | 'strict' | 'strip';\n\nexport function parse<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): T {\n const res = test(value, schema, mode);\n if (!res.ok) {\n throw new TypeError(res.error);\n }\n return res.value;\n}\n\nexport function is<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): value is T {\n return test(value, schema, mode).ok;\n}\n\nexport function assert<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): asserts value is T {\n parse(value, schema, mode);\n}\n\ntype Result<T> = {ok: true; value: T} | {ok: false; error: string};\n\nexport function test<T>(\n value: unknown,\n schema: v.Type<T>,\n mode?: ParseOptionsMode,\n): Result<T> {\n // A Type<T> only yields undefined if T includes it.\n return testOptional(value, schema, mode) as Result<T>;\n}\n\n/**\n * Similar to {@link test} but works for AbstractTypes such as Optional.\n * This is for advanced usage. Prefer {@link test} unless you really need\n * to operate directly on an Optional field.\n */\nexport function testOptional<T>(\n value: unknown,\n schema: v.Type<T> | v.Optional<T>,\n mode?: ParseOptionsMode,\n): Result<T | undefined> {\n const res = schema.try(value, mode ? {mode} : undefined);\n if (!res.ok) {\n return {ok: false, error: getMessage(res, value, schema, mode)};\n }\n return res;\n}\n\nconst STRICT = {mode: 'strict'} as const;\n\n/**\n * Parses `schema` in strict mode, whatever mode the enclosing parse uses. Use\n * it for the parts of a message that a reader must not silently ignore inside\n * a lenient parse.\n *\n * Wrap a field, not a union variant: a union sees the wrapped type as\n * `unknown`, so it can no longer pick the variant by its literal fields.\n */\nexport function strict<T>(schema: v.Type<T>): v.Type<T> {\n const type = v.unknown().chain(value => schema.try(value, STRICT));\n // A transform serializes as just its name. Show the wrapped schema too, so a\n // change to it still changes the hash in protocol-version.test.ts.\n return Object.assign(type, {strict: schema});\n}\n\n/**\n * Shallowly marks the schema as readonly.\n */\nexport function readonly<T extends v.Type>(t: T): v.Type<Readonly<v.Infer<T>>> {\n return t as v.Type<Readonly<v.Infer<T>>>;\n}\n\nexport function readonlyObject<T extends Record<string, v.Type | v.Optional>>(\n t: T,\n): v.ObjectType<Readonly<T>, undefined> {\n return v.object(t);\n}\n\nexport function readonlyArray<T extends v.Type>(\n t: T,\n): v.Type<readonly v.Infer<T>[]> {\n return v.array(t);\n}\n\nexport function readonlyRecord<T extends v.Type>(\n t: T,\n): v.Type<Readonly<Record<string, v.Infer<T>>>> {\n return v.record(t);\n}\n\nconst AbstractType = Object.getPrototypeOf(\n Object.getPrototypeOf(v.string().optional()),\n).constructor;\n\nexport function instanceOfAbstractType<T = unknown>(\n obj: unknown,\n): obj is v.Type<T> | v.Optional<T> {\n return obj instanceof AbstractType;\n}\n\n// valita does not export TerminalType.\nexport type TerminalType = Parameters<Parameters<v.Type['_toTerminals']>[0]>[0];\n\n/**\n * Calls `func` for each terminal type that `type` is composed of, looking\n * through unions, optionals and the transforms created by\n * `.optional(() => x)`, `.assert()`, `.map()` and `.chain()`.\n *\n * This is the only use of valita's internal `_toTerminals`. The public API\n * has no way to look inside a transform, so there is no alternative. The\n * `toTerminals` test in valita.test.ts pins the behavior options.ts depends\n * on, so a valita upgrade that changes it fails there instead of misparsing\n * flags.\n */\nexport function toTerminals(\n type: v.Type | v.Optional,\n func: (t: TerminalType) => void,\n): void {\n type._toTerminals(func);\n}\n\ntype ObjectShape = Record<string, typeof AbstractType>;\n\n/**\n * Similar to `ObjectType.partial()` except it recurses into nested objects.\n * Rest types are not supported.\n */\nexport function deepPartial<Shape extends ObjectShape>(\n s: v.ObjectType<Shape, undefined>,\n) {\n const shape = {} as Record<string, unknown>;\n for (const [key, type] of Object.entries(s.shape)) {\n if (type.name === 'object') {\n shape[key] = deepPartial(\n type as v.ObjectType<ObjectShape, undefined>,\n ).optional();\n } else {\n shape[key] = type.optional();\n }\n }\n return v.object(shape as {[K in keyof Shape]: v.Optional<v.Infer<Shape[K]>>});\n}\n\ntype Literal = string | number | bigint | boolean;\n\nexport function literalUnion<T extends [...Literal[]]>(\n ...literals: T\n): v.Type<T[number]> {\n return v.union(...literals.map(v.literal));\n}\n\ndeclare const unrecognized: unique symbol;\n\n/** A value of an open enum that this build doesn't know. Keeps the raw value. */\nexport type Unrecognized<T extends Literal = string> = T & {\n readonly [unrecognized]: true;\n};\n\n/**\n * Like {@link literalUnion}, but any string parses, so a reader accepts values\n * that a newer writer added. Unknown values keep their raw string and are typed\n * as {@link Unrecognized}.\n *\n * Use it only where a reader can ignore or display an unknown value. Never use\n * it for a value that changes what the reader computes, or for the\n * discriminator of a union.\n */\nexport function openLiteralUnion<T extends [string, ...string[]]>(\n ..._literals: T\n): v.Type<T[number] | Unrecognized> {\n return v.string() as v.Type<T[number] | Unrecognized>;\n}\n\n/**\n * Call in the `default` case of a `switch` over an open enum, so that a known\n * value without a `case` fails to compile.\n */\nexport function assertUnrecognized(_value: Unrecognized): void {}\n\n/** A tuple whose first element, its tag, is a literal. */\ntype TaggedTuple = v.TupleType<[v.Type<Literal>, ...v.Type[]]>;\n\n/** A tuple with a tag this build doesn't know, as {@link taggedTupleUnion} parses it. */\nexport type UnrecognizedTuple = [\n tag: Unrecognized<Literal>,\n ...rest: unknown[],\n];\n\n/**\n * A union of tuples tagged by a literal in their first element, such as\n * `['ping', {}]`. Unlike `union`, it picks the tuple by its tag instead of\n * trying each in turn.\n *\n * With `open`, a tuple whose tag it doesn't know, but of the same type as a\n * known tag, parses as is, typed as {@link UnrecognizedTuple}, so a reader can\n * skip kinds a newer writer added. Use `isKnown` to tell them apart:\n * TypeScript can't narrow the union by comparing the tag, because a tag\n * literal is comparable to `Unrecognized`. A closed union is not implemented\n * yet.\n */\nexport function taggedTupleUnion<T extends TaggedTuple[]>(\n tuples: T,\n options: {readonly open: boolean},\n): v.Type<v.Infer<T[number]> | UnrecognizedTuple> & {\n isKnown(\n value: v.Infer<T[number]> | UnrecognizedTuple,\n ): value is v.Infer<T[number]>;\n} {\n if (!options.open) {\n throw new Error('A closed taggedTupleUnion is not implemented');\n }\n type Known = v.Infer<T[number]>;\n const byTag = new Map<unknown, v.Type>();\n const tagTypes = new Set<string>();\n for (const tuple of tuples) {\n toTerminals(tuple.prefix[0], t => {\n if (t.name !== 'literal') {\n throw new Error('Expected every tag to be a literal');\n }\n if (byTag.has(t.value)) {\n throw new Error(`Duplicate tag ${toDisplay(t.value)}`);\n }\n byTag.set(t.value, tuple);\n tagTypes.add(typeof t.value);\n });\n }\n const expectedTag = `Expected ${displayList('or', [...tagTypes])}`;\n const type = v\n .unknown()\n .chain((value, options): v.ValitaResult<Known | UnrecognizedTuple> => {\n if (!Array.isArray(value)) {\n return v.err('Expected array');\n }\n const [tag] = value;\n const tuple = byTag.get(tag);\n if (tuple) {\n return tuple.try(value, options) as v.ValitaResult<Known>;\n }\n return tagTypes.has(typeof tag)\n ? v.ok(value as UnrecognizedTuple)\n : v.err({message: expectedTag, path: [0]});\n });\n return Object.assign(type, {\n // A transform serializes as just its name. Show the tuples too, so a\n // change to them still changes the hash in protocol-version.test.ts.\n taggedTupleUnion: tuples,\n isKnown: (value: Known | UnrecognizedTuple): value is Known =>\n byTag.has(value[0]),\n });\n}\n\n/** An object with a tag this build doesn't know, as {@link taggedObjectUnion} parses it. */\nexport type UnrecognizedObject<K extends string> = {\n readonly [P in K]: Unrecognized<Literal>;\n} & {readonly [key: string]: unknown};\n\n/**\n * A union of objects told apart by a literal in their `key` property, their\n * tag, such as `{op: 'queries', id: '1'}`. Unlike `union`, it picks the object\n * by its tag instead of trying each in turn, so a bad object of a known kind\n * fails with that kind's error.\n *\n * With `open`, an object whose tag it doesn't know, but of the same type as a\n * known tag, parses as is, typed as {@link UnrecognizedObject}, so a reader\n * can answer or skip kinds a newer writer added. Use `isKnown` to tell them\n * apart. A closed union is not implemented yet.\n */\nexport function taggedObjectUnion<K extends string, T extends v.ObjectType[]>(\n key: K,\n objects: T,\n options: {readonly open: boolean},\n): v.Type<v.Infer<T[number]> | UnrecognizedObject<K>> & {\n isKnown(\n value: v.Infer<T[number]> | UnrecognizedObject<K>,\n ): value is v.Infer<T[number]>;\n} {\n if (!options.open) {\n throw new Error('A closed taggedObjectUnion is not implemented');\n }\n type Known = v.Infer<T[number]>;\n const byTag = new Map<unknown, v.Type>();\n const tagTypes = new Set<string>();\n for (const object of objects) {\n const tag = object.shape[key] as v.Type | v.Optional | undefined;\n if (tag === undefined) {\n throw new Error(`Expected every object to have ${key}`);\n }\n toTerminals(tag, t => {\n if (t.name !== 'literal') {\n throw new Error('Expected every tag to be a literal');\n }\n if (byTag.has(t.value)) {\n throw new Error(`Duplicate tag ${toDisplay(t.value)}`);\n }\n byTag.set(t.value, object);\n tagTypes.add(typeof t.value);\n });\n }\n const expectedTag = `Expected ${displayList('or', [...tagTypes])}`;\n const tagOf = (value: object): unknown =>\n getOwnProperty(value as Record<string, unknown>, key);\n const type = v\n .unknown()\n .chain((value, options): v.ValitaResult<Known | UnrecognizedObject<K>> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return v.err('Expected object');\n }\n const tag = tagOf(value);\n const object = byTag.get(tag);\n if (object) {\n return object.try(value, options) as v.ValitaResult<Known>;\n }\n return tagTypes.has(typeof tag)\n ? v.ok(value as UnrecognizedObject<K>)\n : v.err({message: expectedTag, path: [key]});\n });\n return Object.assign(type, {\n // A transform serializes as just its name. Show the objects too, so a\n // change to them still changes the hash in protocol-version.test.ts.\n taggedObjectUnion: {key, objects},\n isKnown: (value: Known | UnrecognizedObject<K>): value is Known =>\n byTag.has(tagOf(value)),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,UAAU,OAAwB;CACzC,QAAQ,OAAO,OAAf;EACE,KAAK;EACL,KAAK;EACL,KAAK,WACH,OAAO,KAAK,UAAU,KAAK;EAC7B,KAAK,aACH,OAAO;EACT,KAAK,UACH,OAAO,MAAM,SAAS,IAAI;EAC5B;GACE,I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AE,IAAI,EACV,SAAS,EAAE,eAAe,EAC1B,KAAK,EAAE,KAAK,GACX,QAAQ,CAwDV;AAED,wBAAgB,GAAG,CACjB,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,eAAe,EAC1B,KAAK,EAAE,KAAK,GACX,QAAQ,CAMV;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,eAAe,EAC1B,KAAK,EAAE,KAAK,GACX,QAAQ,CAIV;AA4XD,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,kBAAkB,GAC/B;IACD,IAAI,EAAE,QAAQ,CAAC;IACf,mBAAmB,EAAE,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAC;CAC/D,CA2BA;AAED,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,kBAAkB,GAC/B;IACD;QACE,KAAK,EAAE,KAAK,CAAC;QACb,WAAW,EAAE,WAAW,CAAC;QACzB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;KAC3B;IACD;QAAC,KAAK,EAAE,KAAK,CAAC;QAAC,WAAW,EAAE,WAAW,CAAC;QAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;KAAC;CACpE,CAsBA;AA8ED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAMhE"}
|
package/out/z2s/src/compiler.js
CHANGED
|
@@ -306,8 +306,10 @@ function relationshipSubquery(spec, relationship, format, parentTable) {
|
|
|
306
306
|
function where(spec, condition, table) {
|
|
307
307
|
if (!condition) return sql``;
|
|
308
308
|
switch (condition.type) {
|
|
309
|
-
case "and": return sql`(${sql.join(condition.conditions.map((c) => where(spec, c, table)), " AND ")})`;
|
|
310
|
-
|
|
309
|
+
case "and": if (condition.conditions.length > 0) return sql`(${sql.join(condition.conditions.map((c) => where(spec, c, table)), " AND ")})`;
|
|
310
|
+
else return sql`TRUE`;
|
|
311
|
+
case "or": if (condition.conditions.length > 0) return sql`(${sql.join(condition.conditions.map((c) => where(spec, c, table)), " OR ")})`;
|
|
312
|
+
else return sql`FALSE`;
|
|
311
313
|
case "correlatedSubquery": return exists(spec, condition, table);
|
|
312
314
|
case "simple": return simple(spec, condition, table);
|
|
313
315
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compiler.js","names":["parseBigIntJson"],"sources":["../../../../z2s/src/compiler.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport {last, zip} from '../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {\n parse as parseBigIntJson,\n type JSONValue as BigIntJSONValue,\n} from '../../shared/src/bigint-json.ts';\nimport {hasOwn} from '../../shared/src/has-own.ts';\nimport {type JSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport {isPgTextRepresentedType} from '../../zero-cache/src/types/pg-data-type.ts';\nimport {\n isLikeOperator,\n isNegatedOperator,\n jsonLiteralType,\n type Aggregate,\n type AST,\n type Bound,\n type Condition,\n type CorrelatedSubquery,\n type CorrelatedSubqueryCondition,\n type Correlation,\n type JsonPathReference,\n type LiteralReference,\n type Ordering,\n type SimpleCondition,\n type ValuePosition,\n} from '../../zero-protocol/src/ast.ts';\nimport {\n clientToServer,\n type NameMapper,\n} from '../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../zero-types/src/server-schema.ts';\nimport {groupOrdering} from '../../zql/src/ivm/group-by.ts';\nimport type {Format} from '../../zql/src/ivm/view.ts';\nimport {completeOrdering} from '../../zql/src/query/complete-ordering.ts';\nimport {\n isBuiltinTypeSchema,\n pgTypeForLiteralType,\n sql,\n sqlConvertColumnArg,\n sqlConvertPluralLiteralArg,\n sqlConvertSingularLiteralArg,\n type PluralLiteralType,\n} from './sql.ts';\n\ntype Table = {\n zql: string;\n alias: string;\n};\n\ntype QualifiedColumn = {\n table: Table;\n zql: string;\n};\n\ntype ServerSpec = {\n schema: ServerSchema;\n // maps zql names to server names\n mapper: NameMapper;\n};\n\nexport type Spec = {\n server: ServerSpec;\n zql: Schema['tables'];\n aliasCount: number;\n};\n\nconst ZQL_RESULT_KEY = 'zql_result';\nconst ZQL_RESULT_KEY_IDENT = sql.ident(ZQL_RESULT_KEY);\n\nconst ZQL_RESULT_TABLE_KEY = 'zql_root';\nconst ZQL_RESULT_TABLE_IDENT = sql.ident(ZQL_RESULT_TABLE_KEY);\n\nexport function compile(\n serverSchema: ServerSchema,\n zqlSchema: Schema,\n ast: AST,\n format?: Format,\n): SQLQuery {\n assert(\n ast.groupBy === undefined || ast.aggregate?.distinct === undefined,\n 'a count of distinct values per group is not supported yet',\n );\n // The value would be selected under a group column's name. The query\n // builder rejects such a query; a hand-built AST can still name one.\n assert(\n ast.groupBy === undefined ||\n ast.aggregate === undefined ||\n !ast.groupBy.includes(ast.aggregate.fn),\n () =>\n `groupBy(): the column \"${ast.aggregate?.fn}\" has the same name as the ${ast.aggregate?.fn}() value`,\n );\n // As in the IVM builder: the rows are grouped in the group's order, not the\n // one a bound would be taken in.\n assert(\n (ast.groupBy === undefined && ast.aggregate?.distinct === undefined) ||\n (ast.start === undefined && ast.limit === undefined),\n 'groupBy and a count of distinct values do not support start or limit',\n );\n ast = completeOrdering(\n ast,\n tableName => zqlSchema.tables[tableName].primaryKey,\n );\n const spec: Spec = {\n aliasCount: 0,\n server: {\n schema: serverSchema,\n mapper: clientToServer(zqlSchema.tables),\n },\n zql: zqlSchema.tables,\n };\n if (ast.groupBy) {\n const groups = ast.aggregate\n ? selectGroups(spec, ast, ast.aggregate)\n : selectDistinct(spec, ast);\n return sql`SELECT ${toJSON(ZQL_RESULT_TABLE_KEY)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${groups}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n\n if (ast.aggregate) {\n if (ast.aggregate.distinct) {\n // A count of the distinct combinations counts the rows a distinct()\n // of them gives.\n const groups = selectDistinct(spec, {\n ...ast,\n groupBy: ast.aggregate.distinct,\n aggregate: undefined,\n });\n return sql`SELECT to_json(COUNT(*))::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${groups}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n // Top-level (ungrouped) aggregate: the result is a single scalar, not rows.\n // It reduces the same normalized projection a relationship aggregate does,\n // so values such as timestamps come back in the form ZQL uses. Like the\n // IVM operator, it reduces the rows left after `start`/`limit` and ignores\n // `related`. The order only matters for picking those rows.\n const bounded = ast.limit !== undefined || ast.start !== undefined;\n const inner = select(\n spec,\n {\n ...ast,\n aggregate: undefined,\n related: undefined,\n orderBy: bounded ? ast.orderBy : undefined,\n },\n undefined,\n );\n // An aggregate over no rows (other than COUNT) is SQL NULL, and to_json()\n // of NULL is NULL rather than the JSON text `null` the result parser reads.\n return sql`SELECT COALESCE(to_json(${aggregateExpr(spec, ast.table, ast.aggregate)}), 'null'::json)::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${inner}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n\n return sql`SELECT \n ${toJSON(ZQL_RESULT_TABLE_KEY, format?.singular)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${select(spec, ast, format)}) ${ZQL_RESULT_TABLE_IDENT}`;\n}\n\n/**\n * The groups of `ast.groupBy` among the rows that pass `ast.where`, each with\n * the aggregate under the function's name (`count`, `sum`, …), in the order a\n * grouped query's rows have (see `groupOrdering`). Like a top-level\n * aggregate, it reduces the normalized projection {@link select} gives, so a\n * timestamp comes back in epoch milliseconds, and groups by those values.\n */\nfunction selectGroups(spec: Spec, ast: AST, agg: Aggregate): SQLQuery {\n const inner = select(\n spec,\n {\n ...ast,\n groupBy: undefined,\n aggregate: undefined,\n related: undefined,\n orderBy: undefined,\n },\n undefined,\n );\n const cols = must(ast.groupBy).map(col => sql.ident(col));\n return sql`SELECT ${sql.join(cols, ',')}, ${aggregateExpr(spec, ast.table, agg)} AS ${sql.ident(agg.fn)}\n FROM (${inner}) ${sql.ident('zql_group')}\n GROUP BY ${sql.join(cols, ', ')}\n ORDER BY ${sql.join(\n groupOrdering(ast).map(([col, dir]) => {\n const value = orderedValue(spec, ast.table, col, sql.ident(col));\n return dir === 'asc'\n ? sql`${value} ASC NULLS FIRST`\n : sql`${value} DESC NULLS LAST`;\n }),\n ', ',\n )}`;\n}\n\n/**\n * The distinct values of `ast.groupBy` among the rows that pass `ast.where`,\n * one row of those columns each, in the order a distinct query's rows have\n * (see `groupOrdering`). It groups by the columns rather than selecting\n * DISTINCT, which would need the converted values {@link selectIdent} selects\n * to appear in the ORDER BY too. Like the IVM operator, it ignores `related`.\n */\nfunction selectDistinct(spec: Spec, ast: AST): SQLQuery {\n const table = makeTable(spec, ast.table);\n const columns = must(ast.groupBy).map(zql => ({table, zql}));\n return sql`SELECT ${sql.join(\n columns.map(c => selectIdent(spec.server, c)),\n ',',\n )}\n FROM ${fromIdent(spec.server, table)}\n ${ast.where ? sql`WHERE ${where(spec, ast.where, table)}` : sql``}\n GROUP BY ${sql.join(\n columns.map(c => colIdent(spec.server, c)),\n ', ',\n )}\n ORDER BY ${sql.join(\n groupOrdering(ast).map(([col, dir]) => {\n const value = orderedValue(\n spec,\n ast.table,\n col,\n colIdent(spec.server, {table, zql: col}),\n );\n return dir === 'asc'\n ? sql`${value} ASC NULLS FIRST`\n : sql`${value} DESC NULLS LAST`;\n }),\n ', ',\n )}`;\n}\n\n/**\n * The SQL aggregate for `aggregate`, over a subquery that exposes the\n * aggregated column by its client name (as {@link select} does).\n *\n * `COUNT(*)` is left as Postgres's 64-bit count: the result parser rejects a\n * value outside the safe integer range rather than rounding it.\n *\n * `SUM`/`AVG` add the values as float8, as the IVM operator adds JS numbers:\n * Postgres would otherwise sum a `real` in float4 and a `numeric` exactly.\n *\n * `MIN`/`MAX` of an enum, or of a type Zero represents as text (`uuid`,\n * `inet`, …), compare that text byte by byte, as the IVM operator compares\n * strings. Otherwise an enum would use its declaration order, an `inet` its\n * network order, and a `uuid` would fail (it has no `MIN`).\n */\nfunction aggregateExpr(spec: Spec, zqlTable: string, agg: Aggregate): SQLQuery {\n assert(\n agg.distinct === undefined,\n 'a count of distinct values is not supported in a relationship yet',\n );\n const {fn, field, path} = agg;\n if (path !== undefined) {\n return jsonAggregateExpr(spec, zqlTable, agg, path);\n }\n switch (fn) {\n case 'count':\n return sql`COUNT(*)`;\n case 'sum':\n return sql`SUM(${sql.ident(must(field))}::float8)`;\n case 'avg':\n return sql`AVG(${sql.ident(must(field))}::float8)`;\n case 'min':\n return sql`MIN(${orderedAggregateArg(spec, zqlTable, must(field))})`;\n case 'max':\n return sql`MAX(${orderedAggregateArg(spec, zqlTable, must(field))})`;\n default:\n unreachable(fn);\n }\n}\n\n/**\n * The SQL aggregate over the JSON leaf at `path` inside the (client-named)\n * json column `field` of the subquery. Only leaves the aggregate takes count\n * (see `aggregateValue`): numbers for `sum`/`avg`, numbers and strings for\n * `min`/`max`, each gated on `jsonb_typeof` so a mismatched leaf is SQL NULL\n * (skipped) rather than a cast error.\n *\n * `min`/`max` reduce numbers and strings separately and combine them with the\n * client's cross-type order, numbers before strings (`compareAggregateValues`),\n * instead of Postgres's jsonb order, which puts strings first. The result is\n * jsonb so either type comes back as itself.\n */\nfunction jsonAggregateExpr(\n spec: Spec,\n zqlTable: string,\n {fn, field}: Aggregate,\n path: readonly (string | number)[],\n): SQLQuery {\n const name = must(field);\n const {type, isArray} = getServerColumn(\n spec.server,\n {zql: zqlTable, alias: zqlTable},\n name,\n );\n assert(\n isArray || type === 'json' || type === 'jsonb',\n () => `JSON path on non-JSON column \"${name}\" of type ${type}`,\n );\n const {raw, jsonType} = jsonNavigate(\n jsonBase(sql.ident(name), type, isArray),\n path,\n );\n const num = sql`(CASE WHEN ${jsonType} = 'number' THEN ${raw}::float8 END)`;\n const str = sql`(CASE WHEN ${jsonType} = 'string' THEN ${raw} END)`;\n switch (fn) {\n case 'sum':\n return sql`SUM(${num})::float8`;\n case 'avg':\n return sql`AVG(${num})::float8`;\n case 'min':\n return sql`COALESCE(to_jsonb(MIN(${num})), to_jsonb(MIN(${str})))`;\n case 'max':\n return sql`COALESCE(to_jsonb(MAX(${str})), to_jsonb(MAX(${num})))`;\n case 'count':\n throw new Error('count() takes no JSON path');\n default:\n unreachable(fn);\n }\n}\n\nfunction orderedAggregateArg(\n spec: Spec,\n zqlTable: string,\n field: string,\n): SQLQuery {\n return orderedValue(spec, zqlTable, field, sql.ident(field));\n}\n\n/**\n * `value`, the value of `zqlTable`'s column `field`, in a form Postgres\n * orders as the IVM does: an enum, or a type Zero represents as text, by that\n * text byte by byte. Otherwise an enum would use its declaration order and an\n * `inet` its network order.\n */\nfunction orderedValue(\n spec: Spec,\n zqlTable: string,\n field: string,\n value: SQLQuery,\n): SQLQuery {\n const {server} = spec;\n const column =\n server.schema[server.mapper.tableName(zqlTable)][\n server.mapper.columnName(zqlTable, field)\n ];\n // `format` gives the type's own text: `::text` adds the netmask to an `inet`.\n return column.isEnum || isPgTextRepresentedType(column.type)\n ? sql`format('%s', ${value}) COLLATE \"C\"`\n : value;\n}\n\nfunction select(\n spec: Spec,\n ast: AST,\n format: Format | undefined,\n correlate?: (childTable: Table) => SQLQuery,\n): SQLQuery {\n const table = makeTable(spec, ast.table);\n const selectionSet = related(spec, ast.related ?? [], format, table);\n const tableSchema = spec.zql[ast.table];\n const usedAliases = new Set<string>(\n ast.related?.map(r => r.subquery.alias ?? ''),\n );\n for (const column of Object.keys(tableSchema.columns)) {\n if (!usedAliases.has(column)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table,\n zql: column,\n }),\n );\n }\n }\n\n let appliedWhere = false;\n function maybeWhere(test: unknown) {\n if (!test) {\n return sql``;\n }\n\n const ret = appliedWhere ? sql`AND` : sql`WHERE`;\n appliedWhere = true;\n return ret;\n }\n\n return sql`SELECT ${sql.join(selectionSet, ',')}\n FROM ${fromIdent(spec.server, table)}\n ${maybeWhere(ast.where)} ${where(spec, ast.where, table)}${\n ast.start\n ? sql`\n ${maybeWhere(ast.start)} ${start(spec, ast.start, ast.orderBy, table)}`\n : sql``\n }\n ${maybeWhere(correlate)} ${correlate ? correlate(table) : sql``}\n ${orderBy(spec, ast.orderBy, table)}\n ${limit(ast.limit, format?.singular)}`;\n}\n\nexport function limit(\n limit: number | undefined,\n singular: boolean | undefined,\n): SQLQuery {\n if (limit === 0) {\n return sql`LIMIT 0`;\n }\n if (singular) {\n return sql`LIMIT 1`;\n }\n if (limit === undefined) {\n return sql``;\n }\n return sql`LIMIT ${sqlConvertSingularLiteralArg(limit)}`;\n}\n\nfunction makeTable(spec: Spec, zql: string, alias?: string): Table {\n alias = alias ?? zql + '_' + spec.aliasCount++;\n return {\n zql,\n alias,\n };\n}\n\nexport function orderBy(\n spec: Spec,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!orderBy) {\n return sql``;\n }\n return sql`ORDER BY ${sql.join(\n orderBy.map(([col, dir]) =>\n dir === 'asc'\n ? // Oh postgres. The table must be referred to by client name but the column by server name.\n // E.g., `SELECT server_col as client_col FROM server_table as client_table ORDER BY client_Table.server_col`\n sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} ASC NULLS FIRST`\n : sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} DESC NULLS LAST`,\n ),\n ', ',\n )}`;\n}\n\nexport function start(\n spec: Spec,\n bound: Bound | undefined,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!bound) {\n return sql``;\n }\n assert(\n orderBy !== undefined && orderBy.length > 0,\n 'start requires ordering',\n );\n\n const constraints: SQLQuery[] = [];\n for (let i = 0; i < orderBy.length; i++) {\n const group: SQLQuery[] = [];\n const [iField, iDirection] = orderBy[i];\n for (let j = 0; j <= i; j++) {\n const [field] = orderBy[j];\n if (j === i) {\n group.push(\n startRangeComparison(\n spec,\n table,\n iField,\n bound.row[iField] ?? null,\n iDirection === 'asc' ? '>' : '<',\n ),\n );\n } else {\n group.push(startEquality(spec, table, field, bound.row[field] ?? null));\n }\n }\n constraints.push(sql`(${sql.join(group, ' AND ')})`);\n }\n\n if (!bound.exclusive) {\n constraints.push(\n sql`(${sql.join(\n orderBy.map(([field]) =>\n startEquality(spec, table, field, bound.row[field] ?? null),\n ),\n ' AND ',\n )})`,\n );\n }\n\n return sql`(${sql.join(constraints, ' OR ')})`;\n}\n\nfunction related(\n spec: Spec,\n relationships: readonly CorrelatedSubquery[],\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery[] {\n return relationships.map(relationship =>\n relationshipSubquery(\n spec,\n relationship,\n format?.relationships[must(relationship.subquery.alias)],\n parentTable,\n ),\n );\n}\n\nfunction relationshipSubquery(\n spec: Spec,\n relationship: CorrelatedSubquery,\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery {\n const innerAlias = `inner_${relationship.subquery.alias}`;\n if (relationship.aggregate) {\n // Aggregate relationship: emit a correlated scalar subquery returning the\n // aggregate over the matching child rows, instead of aggregating the rows\n // to JSON. No rows are materialized. The inner subquery exposes columns by\n // their client names, so the aggregated field is referenced as-is.\n const {field} = relationship.aggregate;\n const isJunction = !!relationship.subquery.related?.length;\n const aggExpr = aggregateExpr(\n spec,\n isJunction\n ? must(relationship.subquery.related)[0].subquery.table\n : relationship.subquery.table,\n relationship.aggregate,\n );\n\n let inner: SQLQuery;\n if (isJunction) {\n // Junction (many-to-many) aggregate: the value lives on the destination,\n // one hop past the junction. Aggregate over the junction join, exposing\n // the destination field by its client name so `aggExpr` references it. A\n // `where` on the destination filters the joined rows before aggregating.\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n const destWhere = relationship.subquery.related[0].subquery.where;\n inner = sql`SELECT ${\n field\n ? selectIdent(spec.server, {table: lastTable, zql: field})\n : sql`NULL`\n } FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)})${\n destWhere ? sql` AND (${where(spec, destWhere, lastTable)})` : sql``\n }`;\n } else {\n // As for a top-level aggregate, the order only matters for picking the\n // rows a `limit`/`start` keeps; otherwise it is a needless sort per parent.\n const {subquery} = relationship;\n const bounded =\n subquery.limit !== undefined || subquery.start !== undefined;\n inner = select(\n spec,\n bounded ? subquery : {...subquery, orderBy: undefined},\n undefined,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n );\n }\n return sql`(\n SELECT ${aggExpr} FROM (${inner}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n if (relationship.hidden) {\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n\n assert(\n relationship.subquery.related,\n 'hidden relationship must be a junction',\n );\n const nestedAst = relationship.subquery.related[0].subquery;\n const selectionSet = related(\n spec,\n nestedAst.related ?? [],\n format,\n lastTable,\n );\n const tableSchema = spec.zql[nestedAst.table];\n for (const column of Object.keys(tableSchema.columns)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table: lastTable,\n zql: column,\n }),\n );\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (SELECT ${sql.join(\n selectionSet,\n ',',\n )} FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)}) ${\n nestedAst.where\n ? sql`AND ${where(spec, nestedAst.where, lastTable)}`\n : sql``\n }${\n nestedAst.start\n ? sql` AND ${start(\n spec,\n nestedAst.start,\n nestedAst.orderBy,\n lastTable,\n )}`\n : sql``\n } ${orderBy(spec, nestedAst.orderBy, lastTable)} ${limit(\n last(participatingTables)?.limit,\n format?.singular,\n )} ) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (${select(\n spec,\n relationship.subquery,\n format,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n )}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n}\n\nfunction where(\n spec: Spec,\n condition: Condition | undefined,\n table: Table,\n): SQLQuery {\n if (!condition) {\n return sql``;\n }\n\n switch (condition.type) {\n case 'and':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' AND ',\n )})`;\n case 'or':\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' OR ',\n )})`;\n case 'correlatedSubquery':\n // `scalar` is deliberately ignored here. It is a planner hint for the\n // IVM engines, which have no cost-based planner and benefit from\n // pre-resolving an at-most-one-row subquery to a literal comparison\n // (see zqlite's `resolveSimpleScalarSubqueries`). Postgres decorrelates\n // EXISTS into a semi-join on its own, so the hint buys nothing here —\n // and honoring it as `parentField = (SELECT childField … LIMIT 1)` is\n // only sound when the subquery matches at most one row *globally*.\n // Applying it unconditionally silently dropped rows whenever the\n // subquery was not pinned to a unique key.\n return exists(spec, condition, table);\n case 'simple':\n return simple(spec, condition, table);\n }\n}\n\nfunction exists(\n spec: Spec,\n condition: CorrelatedSubqueryCondition,\n parentTable: Table,\n): SQLQuery {\n switch (condition.op) {\n case 'EXISTS':\n return sql`EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n case 'NOT EXISTS':\n return sql`NOT EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n }\n}\n\nexport function makeCorrelator(\n spec: Spec,\n parentFields: readonly QualifiedColumn[],\n childZqlFields: readonly string[],\n): (childTable: Table) => SQLQuery {\n return (childTable: Table) => {\n const childFields = childZqlFields.map(zqlField => ({\n table: childTable,\n zql: zqlField,\n }));\n return sql.join(\n zip(parentFields, childFields).map(\n ([parentColumn, childColumn]) =>\n sql`${colIdent(spec.server, parentColumn)} = ${colIdent(\n spec.server,\n childColumn,\n )}`,\n ),\n ' AND ',\n );\n };\n}\n\nexport function simple(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n if (condition.left.type === 'json') {\n const special = jsonPathCondition(spec, condition.left, condition, table);\n if (special) {\n return special;\n }\n }\n switch (condition.op) {\n case 'ILIKE':\n case 'LIKE':\n case 'NOT ILIKE':\n case 'NOT LIKE': {\n // The pattern is a string, not a value of the column's type. Converted\n // to the `bpchar` of a `char(n)` column it would lose its trailing\n // spaces. Like ZQL's own LIKE, non-string patterns match as strings.\n const {right} = condition;\n assert(\n right.type === 'literal',\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${sqlConvertSingularLiteralArg(\n right.value === null ? null : String(right.value),\n )}`;\n }\n case '!=':\n case '<':\n case '<=':\n case '=':\n case '>':\n case '>=':\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n condition.right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${valueComparison(\n spec,\n condition.right,\n table,\n condition.left,\n false,\n )}`;\n case 'NOT IN':\n case 'IN':\n return any(spec, condition, table);\n case 'IS':\n case 'IS NOT':\n return distinctFrom(spec, condition, table);\n }\n}\n\nexport function any(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${condition.op === 'NOT IN' ? sql`NOT` : sql``}\n (\n ${valueComparison(spec, condition.left, table, condition.right, false)} = ANY \n (${valueComparison(spec, condition.right, table, condition.left, true)})\n )`;\n}\n\nexport function distinctFrom(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${valueComparison(spec, condition.left, table, condition.right, false)} ${\n condition.op === 'IS' ? sql`IS NOT DISTINCT FROM` : sql`IS DISTINCT FROM`\n } ${valueComparison(spec, condition.right, table, condition.left, false)}`;\n}\n\nfunction startEquality(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sql`${colIdent(spec.server, {\n table,\n zql: field,\n })} IS NOT DISTINCT FROM ${startValue(spec, table, field, value)}`;\n}\n\nfunction startRangeComparison(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n operator: '>' | '<',\n): SQLQuery {\n const column = colIdent(spec.server, {table, zql: field});\n if (value === null) {\n return operator === '>' ? sql`${column} IS NOT NULL` : sql`FALSE`;\n }\n const typedValue = startValue(spec, table, field, value);\n return operator === '>'\n ? sql`${column} > ${typedValue}`\n : sql`(${column} IS NULL OR ${column} < ${typedValue})`;\n}\n\nfunction startValue(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, field),\n value,\n false,\n true,\n );\n}\n\nfunction valueComparison(\n spec: Spec,\n valuePos: ValuePosition,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const valuePosType = valuePos.type;\n switch (valuePosType) {\n case 'column': {\n const qualified: QualifiedColumn = {\n table,\n zql: valuePos.name,\n };\n return colIdent(spec.server, qualified);\n }\n case 'json':\n return jsonPathLeaf(spec, valuePos, table, otherValuePos);\n case 'literal':\n return literalValueComparison(\n spec,\n valuePos,\n table,\n otherValuePos,\n plural,\n );\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(valuePosType);\n }\n}\n\nfunction literalValueComparison(\n spec: Spec,\n valuePos: LiteralReference,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const otherType = otherValuePos.type;\n switch (otherType) {\n case 'column':\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, otherValuePos.name),\n valuePos.value,\n plural,\n true,\n );\n case 'json': {\n // The other side is a JSON path leaf, which is dynamically typed. Render\n // this literal by its OWN JS type so its cast matches the leaf's cast in\n // `jsonPathLeaf` (`leafType`). LiteralValue is primitives or a\n // homogeneous primitive list (enforced at the wire and by the builder).\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n const {value} = valuePos;\n if (Array.isArray(value)) {\n return sqlConvertPluralLiteralArg(\n jsonLiteralType(value) ?? 'string',\n value as PluralLiteralType[],\n );\n }\n // `Array.isArray` does not narrow a `readonly` array out of the union.\n return sqlConvertSingularLiteralArg(\n value as string | number | boolean | null,\n );\n }\n case 'literal': {\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n if (Array.isArray(valuePos.value)) {\n if (valuePos.value.length > 0) {\n // If the array is non-empty base its type on its first\n // element\n return sqlConvertPluralLiteralArg(\n typeof valuePos.value[0] as PluralLiteralType,\n valuePos.value as PluralLiteralType[],\n );\n }\n // If the array is empty, base its type on the other value\n // position's type (as long as the other value position is non-null,\n // cannot have a null[]).\n if (otherValuePos.value !== null) {\n return sqlConvertPluralLiteralArg(\n typeof otherValuePos.value as PluralLiteralType,\n [],\n );\n }\n // If the other value position is null, it can be compared to any\n // type of empty array, chose 'string' arbitrarily.\n return sqlConvertPluralLiteralArg('string', []);\n }\n if (\n typeof valuePos.value === 'string' ||\n typeof valuePos.value === 'number' ||\n typeof valuePos.value === 'boolean'\n ) {\n return sqlConvertSingularLiteralArg(valuePos.value);\n }\n throw new Error(`Literal of unexpected type: ${typeof valuePos.value}`);\n }\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(otherType);\n }\n}\n\n/**\n * The two SQL pieces every JSON path comparison is built from: the leaf's text\n * (`raw`, SQL NULL for a missing key or a JSON null) and its JSON type\n * (`jsonType`, via `jsonb_typeof`).\n *\n * Navigation chains `->` with a *typed* operand per segment (a text operand\n * for an object key, an integer operand for an array index), so Postgres\n * applies the same strict rule as the in-memory reader and SQLite: a string\n * segment never indexes an array and a number never reads an object key. (A\n * `#>>` text[] path would instead resolve a digit string by the container's\n * runtime type, including `'-1'` from the end.) The last step uses `->>` for\n * the text form.\n *\n * The base is the column as jsonb: a `json` column is cast, and a Postgres\n * array column (which zero maps to a `json()` column and the replica stores\n * as JSON text) is converted with `to_jsonb`.\n */\nfunction jsonPathParts(\n spec: Spec,\n ref: JsonPathReference,\n table: Table,\n): {value: SQLQuery; raw: SQLQuery; jsonType: SQLQuery} {\n const {name} = ref.value;\n const col = colIdent(spec.server, {table, zql: name});\n const {type, isArray} = getServerColumn(spec.server, table, name);\n assert(\n isArray || type === 'json' || type === 'jsonb',\n () => `JSON path on non-JSON column \"${name}\" of type ${type}`,\n );\n return jsonNavigate(jsonBase(col, type, isArray), ref.path);\n}\n\n/** A json/jsonb/array column (or an expression of one) as jsonb. */\nfunction jsonBase(col: SQLQuery, type: string, isArray: boolean): SQLQuery {\n return isArray\n ? sql`to_jsonb(${col})`\n : type === 'json'\n ? sql`${col}::jsonb`\n : col;\n}\n\n/** Navigates `path` from the jsonb `base`; see {@link jsonPathParts}. */\nfunction jsonNavigate(\n base: SQLQuery,\n path: readonly (string | number)[],\n): {value: SQLQuery; raw: SQLQuery; jsonType: SQLQuery} {\n let obj = base;\n const operand = (seg: string | number): SQLQuery =>\n typeof seg === 'number'\n ? // A validated non-negative int32 (see isValidJsonPathIndex), so it is\n // safe to inline; `->` needs an integer operand to index an array.\n sql.__dangerous__rawValue(String(seg))\n : sqlConvertSingularLiteralArg(seg);\n const last = path.length - 1;\n for (let i = 0; i < last; i++) {\n obj = sql`(${obj} -> ${operand(path[i])})`;\n }\n const leaf = operand(path[last]);\n return {\n // The leaf as jsonb; `raw` is its text form.\n value: sql`(${obj} -> ${leaf})`,\n raw: sql`(${obj} ->> ${leaf})`,\n jsonType: sql`jsonb_typeof(${obj} -> ${leaf})`,\n };\n}\n\n/**\n * The JS type the leaf must have to be compared against the literal on the\n * other side (`jsonLiteralType`, shared across engines). It is also the\n * `jsonb_typeof` name and the key into `pgTypeForLiteralType` for the cast, so\n * the leaf's cast and the literal's own cast cannot drift. `undefined` for a\n * `null` literal (`IS NULL`: a missing key and a JSON null must both read as\n * SQL NULL), an empty list, or a non-literal.\n */\nfunction leafType(other: ValuePosition): PluralLiteralType | undefined {\n return other.type === 'literal' ? jsonLiteralType(other.value) : undefined;\n}\n\n/**\n * Compiles a JSON path reference to its text form, cast to the comparison type\n * derived from the literal on the other side (`leafType`) so it lines up with\n * that literal's own cast.\n *\n * `->>` maps **both** a missing key and a JSON `null` to SQL `NULL`, matching\n * the SQLite `json_extract` pushdown and the in-memory predicate, so `IS NULL`\n * agrees across all three.\n *\n * The cast is gated on the leaf's JSON type (`CASE WHEN jsonb_typeof(...)`), so a\n * leaf of a different type than the literal is SQL NULL, i.e. a non-match. This\n * is the type-strict comparison documented on {@link JsonPathReference}: `->>`\n * renders a numeric `42` as the text `'42'`, so an ungated text comparison\n * would wrongly match it against the string `'42'`. For `number`/`boolean` the\n * gate is also what keeps the cast from throwing: Postgres errors when casting\n * non-conforming text (a string `\"n/a\"`, an object's JSON text) to\n * `double precision`/`boolean`, which would fail the whole query on one\n * mismatched row. Negated operators need a different form; see\n * `jsonPathCondition`.\n */\nfunction jsonPathLeaf(\n spec: Spec,\n ref: JsonPathReference,\n table: Table,\n other: ValuePosition,\n): SQLQuery {\n const {raw, jsonType} = jsonPathParts(spec, ref, table);\n const t = leafType(other);\n if (t === undefined) {\n return raw;\n }\n return sql`(CASE WHEN ${jsonType} = ${sqlConvertSingularLiteralArg(\n t,\n )} THEN ${raw}::${sql.__dangerous__rawValue(pgTypeForLiteralType(t))} END)`;\n}\n\n/**\n * The comparisons on a JSON path left operand that cannot go through the\n * generic operator rendering with the gated leaf (`jsonPathLeaf`); returns\n * `undefined` for the ones that can.\n *\n * - `IN`/`NOT IN` with a `null` literal is constant-false, as in the\n * in-memory predicate (the generic forms would assert, or match every\n * non-null leaf).\n * - `=`/`IN` against a string or boolean literal compare the leaf *as jsonb*:\n * jsonb equality is type-strict by itself (`\"42\"` never equals `42`, a JSON\n * `null` never equals a string) and a missing key is SQL NULL, so the\n * `jsonb_typeof` gate is unnecessary. Without the `CASE` around the\n * extraction, an expression index on `(col -> 'key')` can serve the\n * predicate. Numbers keep the gated `double precision` form: jsonb compares\n * numbers exactly (`numeric`), which would diverge from the client's and\n * SQLite's IEEE-754 equality above 2^53 or beyond double precision.\n * - An empty `NOT IN` list matches every non-null leaf: SQL's\n * `NOT (x = ANY('{}'))` is TRUE even for a NULL leaf, whereas the\n * predicate's null guard excludes it.\n * - The LIKE family compares text, so the leaf must be a string whatever the\n * literal's type, and the pattern is the literal's text form, as in the\n * in-memory predicate (`String(pattern)`) and SQLite. Deriving the leaf type\n * from a numeric or boolean literal instead would cast the leaf to\n * `double precision`/`boolean` and hand Postgres a LIKE it cannot execute.\n * - The negated operators (`!=`, `NOT LIKE`, `NOT ILIKE`, `NOT IN`): the gate\n * makes a mismatched leaf SQL NULL, which a positive comparison correctly\n * excludes. But NULL also excludes under a negated operator, where a\n * mismatch must *match* (JS `42 !== '42'` is true). `jsonb_typeof` is NULL\n * for a missing key and `'null'` for a JSON null, so one `COALESCE` covers\n * the null guard without a second extraction: a null/missing leaf is\n * false, the same type is the real (negated) comparison, another type is\n * true.\n */\nfunction jsonPathCondition(\n spec: Spec,\n left: JsonPathReference,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery | undefined {\n const {op} = condition;\n let {right} = condition;\n if (\n (op === 'IN' || op === 'NOT IN') &&\n right.type === 'literal' &&\n right.value === null\n ) {\n return sql`false`;\n }\n if (\n isLikeOperator(op) &&\n right.type === 'literal' &&\n right.value !== null &&\n !Array.isArray(right.value)\n ) {\n right = {type: 'literal', value: String(right.value)};\n if (!isNegatedOperator(op)) {\n return sql`${valueComparison(\n spec,\n left,\n table,\n right,\n false,\n )} ${sql.__dangerous__rawValue(op)} ${valueComparison(\n spec,\n right,\n table,\n left,\n false,\n )}`;\n }\n }\n if ((op === '=' || op === 'IN') && right.type === 'literal') {\n const t = leafType(right);\n if (t === 'string' || t === 'boolean') {\n const {value} = jsonPathParts(spec, left, table);\n const lit = valueComparison(spec, right, table, left, op === 'IN');\n return op === 'IN'\n ? sql`${value} = ANY (ARRAY(SELECT to_jsonb(v) FROM unnest(${lit}) AS v))`\n : sql`${value} = to_jsonb(${lit})`;\n }\n }\n // A non-literal (an unbound static parameter) falls through to the generic\n // rendering, which rejects it; it must not be mistaken for an empty list.\n if (!isNegatedOperator(op) || right.type !== 'literal') {\n return undefined;\n }\n const t = leafType(right);\n const {raw, jsonType} = jsonPathParts(spec, left, table);\n if (t === undefined) {\n // Only an empty NOT IN list reaches here: `!=`/`NOT LIKE` against null\n // are constant-false through the generic NULL comparison.\n return op === 'NOT IN' ? sql`${raw} IS NOT NULL` : undefined;\n }\n const leaf = sql`${raw}::${sql.__dangerous__rawValue(pgTypeForLiteralType(t))}`;\n const plural = op === 'NOT IN';\n const lit = valueComparison(spec, right, table, left, plural);\n const cmp = plural\n ? sql`NOT (${leaf} = ANY (${lit}))`\n : sql`${leaf} ${sql.__dangerous__rawValue(op)} ${lit}`;\n return sql`(CASE COALESCE(${jsonType}, 'null') WHEN 'null' THEN false WHEN ${sqlConvertSingularLiteralArg(\n t,\n )} THEN ${cmp} ELSE true END)`;\n}\n\nexport function makeJunctionJoin(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): {\n join: SQLQuery;\n participatingTables: ReturnType<typeof pullTablesForJunction>;\n} {\n const participatingTables = pullTablesForJunction(spec, relationship);\n const joins: SQLQuery[] = [];\n\n for (const {table} of participatingTables) {\n if (joins.length === 0) {\n joins.push(fromIdent(spec.server, table));\n continue;\n }\n joins.push(\n sql` JOIN ${fromIdent(spec.server, table)} ON ${makeCorrelator(\n spec,\n participatingTables[joins.length].correlation.parentField.map(f => ({\n table: participatingTables[joins.length - 1].table,\n zql: f,\n })),\n participatingTables[joins.length].correlation.childField,\n )(participatingTables[joins.length].table)}`,\n );\n }\n\n return {\n join: sql`${sql.join(joins, '')}`,\n participatingTables,\n // lastTable: participatingTables[participatingTables.length - 1].table,\n // lastLimit: participatingTables[participatingTables.length - 1].limit,\n };\n}\n\nexport function pullTablesForJunction(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): [\n {\n table: Table;\n correlation: Correlation;\n limit: number | undefined;\n },\n {table: Table; correlation: Correlation; limit: number | undefined},\n] {\n assert(\n relationship.subquery.related?.length === 1,\n 'Too many related tables for a junction edge',\n );\n const otherRelationship = relationship.subquery.related[0];\n assert(\n !otherRelationship.hidden,\n 'Expected junction edge relationship to not be hidden',\n );\n return [\n {\n table: makeTable(spec, relationship.subquery.table),\n correlation: relationship.correlation,\n limit: relationship.subquery.limit,\n },\n {\n table: makeTable(spec, otherRelationship.subquery.table),\n correlation: otherRelationship.correlation,\n limit: otherRelationship.subquery.limit,\n },\n ];\n}\n\nfunction toJSON(table: string, singular = false): SQLQuery {\n return sql`${\n singular ? sql`` : sql`COALESCE(json_agg`\n }(row_to_json(${sql.ident(table)}))${singular ? sql`` : sql`, '[]'::json)`}`;\n}\n\nfunction selectIdent(server: ServerSpec, column: QualifiedColumn): SQLQuery {\n const serverColumnSchema =\n server.schema[server.mapper.tableName(column.table.zql)][\n server.mapper.columnName(column.table.zql, column.zql)\n ];\n const serverType = serverColumnSchema.type;\n // A user-defined type can have a built-in name such as `timestamp`; only\n // convert the values of the built-in types.\n if (\n !serverColumnSchema.isEnum &&\n isBuiltinTypeSchema(serverColumnSchema.typeSchema)\n ) {\n let needsNormalization = false;\n switch (serverType) {\n case 'timetz':\n // @ts-expect-error Fallthrough intended\n case 'time with time zone':\n needsNormalization = true;\n // fallthrough\n\n case 'date':\n case 'time':\n case 'time without time zone':\n case 'timestamp':\n case 'timestamp without time zone':\n case 'timestamptz':\n case 'timestamp with time zone': {\n // EXTRACT(EPOCH FROM timetz) can be negative when the UTC offset is\n // positive (e.g. 01:00+02 = 23:00 UTC prev day = -3600s). Wrap with\n // modular arithmetic to normalize to 0..86400000.\n const toMs = (epochExpr: SQLQuery): SQLQuery =>\n needsNormalization\n ? sql`((${epochExpr})::bigint + 86400000) % 86400000`\n : epochExpr;\n\n if (serverColumnSchema.isArray) {\n const col = colIdent(server, column);\n return sql`CASE WHEN ${col} IS NULL THEN NULL ELSE ARRAY(SELECT ${toMs(\n sql`EXTRACT(EPOCH FROM unnest(${col})) * 1000`,\n )}) END as ${sql.ident(column.zql)}`;\n }\n\n return sql`${toMs(\n sql`EXTRACT(EPOCH FROM ${colIdent(server, column)}) * 1000`,\n )} as ${sql.ident(column.zql)}`;\n }\n }\n }\n\n return sql`${colIdent(server, column)} as ${sql.ident(column.zql)}`;\n}\n\nfunction colIdent(server: ServerSpec, column: QualifiedColumn) {\n return sql.ident(\n column.table.alias,\n server.mapper.columnName(column.table.zql, column.zql),\n );\n}\n\nfunction fromIdent(server: ServerSpec, table: Table) {\n return sql`${sql.ident(server.mapper.tableName(table.zql))} AS ${sql.ident(table.alias)}`;\n}\n\nfunction getServerColumn(spec: ServerSpec, table: Table, zqlColumn: string) {\n return spec.schema[spec.mapper.tableName(table.zql)][\n spec.mapper.columnName(table.zql, zqlColumn)\n ];\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractZqlResult(pgResult: Array<any>): JSONValue {\n const bigIntJson: BigIntJSONValue = parseBigIntJson(\n pgResult[0][ZQL_RESULT_KEY],\n );\n assertJSONValue(bigIntJson);\n return bigIntJson;\n}\n\nfunction assertJSONValue(v: BigIntJSONValue): asserts v is JSONValue {\n const path = findPathToBigInt(v);\n if (path) {\n throw new Error(`Value exceeds safe Number range. ${path}`);\n }\n}\n\nfunction findPathToBigInt(v: BigIntJSONValue): string | undefined {\n const typeOfV = typeof v;\n switch (typeOfV) {\n case 'bigint':\n return ` = ${v}`;\n case 'object': {\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n for (let i = 0; i < v.length; i++) {\n const path = findPathToBigInt(v[i]);\n if (path) {\n return `[${i}]${path}`;\n }\n }\n return undefined;\n }\n\n const o = v as Record<string, BigIntJSONValue>;\n for (const k in o) {\n if (hasOwn(o, k)) {\n const path = findPathToBigInt(o[k]);\n if (path) {\n return `['${k}']${path}`;\n }\n }\n }\n return undefined;\n }\n case 'number':\n return undefined;\n case 'boolean':\n return undefined;\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqEA,IAAM,iBAAiB;AACvB,IAAM,uBAAuB,IAAI,MAAM,cAAc;AAErD,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB,IAAI,MAAM,oBAAoB;AAE7D,SAAgB,QACd,cACA,WACA,KACA,QACU;CACV,OACE,IAAI,YAAY,KAAA,KAAa,IAAI,WAAW,aAAa,KAAA,GACzD,2DACF;CAGA,OACE,IAAI,YAAY,KAAA,KACd,IAAI,cAAc,KAAA,KAClB,CAAC,IAAI,QAAQ,SAAS,IAAI,UAAU,EAAE,SAEtC,0BAA0B,IAAI,WAAW,GAAG,6BAA6B,IAAI,WAAW,GAAG,SAC/F;CAGA,OACG,IAAI,YAAY,KAAA,KAAa,IAAI,WAAW,aAAa,KAAA,KACvD,IAAI,UAAU,KAAA,KAAa,IAAI,UAAU,KAAA,GAC5C,sEACF;CACA,MAAM,iBACJ,MACA,cAAa,UAAU,OAAO,UAAU,CAAC,UAC3C;CACA,MAAM,OAAa;EACjB,YAAY;EACZ,QAAQ;GACN,QAAQ;GACR,QAAQ,eAAe,UAAU,MAAM;EACzC;EACA,KAAK,UAAU;CACjB;CACA,IAAI,IAAI,SAAS;EACf,MAAM,SAAS,IAAI,YACf,aAAa,MAAM,KAAK,IAAI,SAAS,IACrC,eAAe,MAAM,GAAG;EAC5B,OAAO,GAAG,UAAU,OAAO,oBAAoB,EAAE,YAAY,qBAAqB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MAAM,aAA8BA,MAClC,SAAS,EAAE,CAAC,eACd;CACA,gBAAgB,UAAU;CAC1B,OAAO;AACT;AAEA,SAAS,gBAAgB,GAA4C;CACnE,MAAM,OAAO,iBAAiB,CAAC;CAC/B,IAAI,MACF,MAAM,IAAI,MAAM,oCAAoC,MAAM;AAE9D;AAEA,SAAS,iBAAiB,GAAwC;CAEhE,QAAQ,OADe,GACvB;EACE,KAAK,UACH,OAAO,MAAM;EACf,KAAK,UAAU;GACb,IAAI,MAAM,MACR;GAEF,IAAI,MAAM,QAAQ,CAAC,GAAG;IACpB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;KACjC,MAAM,OAAO,iBAAiB,EAAE,EAAE;KAClC,IAAI,MACF,OAAO,IAAI,EAAE,GAAG;IAEpB;IACA;GACF;GAEA,MAAM,IAAI;GACV,KAAK,MAAM,KAAK,GACd,IAAI,OAAO,GAAG,CAAC,GAAG;IAChB,MAAM,OAAO,iBAAiB,EAAE,EAAE;IAClC,IAAI,MACF,OAAO,KAAK,EAAE,IAAI;GAEtB;GAEF;EACF;EACA,KAAK,UACH;EACF,KAAK,WACH;EACF,SACE;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"compiler.js","names":["parseBigIntJson"],"sources":["../../../../z2s/src/compiler.ts"],"sourcesContent":["import type {SQLQuery} from '@databases/sql';\nimport {last, zip} from '../../shared/src/arrays.ts';\nimport {assert, unreachable} from '../../shared/src/asserts.ts';\nimport {\n parse as parseBigIntJson,\n type JSONValue as BigIntJSONValue,\n} from '../../shared/src/bigint-json.ts';\nimport {hasOwn} from '../../shared/src/has-own.ts';\nimport {type JSONValue} from '../../shared/src/json.ts';\nimport {must} from '../../shared/src/must.ts';\nimport {isPgTextRepresentedType} from '../../zero-cache/src/types/pg-data-type.ts';\nimport {\n isLikeOperator,\n isNegatedOperator,\n jsonLiteralType,\n type Aggregate,\n type AST,\n type Bound,\n type Condition,\n type CorrelatedSubquery,\n type CorrelatedSubqueryCondition,\n type Correlation,\n type JsonPathReference,\n type LiteralReference,\n type Ordering,\n type SimpleCondition,\n type ValuePosition,\n} from '../../zero-protocol/src/ast.ts';\nimport {\n clientToServer,\n type NameMapper,\n} from '../../zero-schema/src/name-mapper.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../zero-types/src/server-schema.ts';\nimport {groupOrdering} from '../../zql/src/ivm/group-by.ts';\nimport type {Format} from '../../zql/src/ivm/view.ts';\nimport {completeOrdering} from '../../zql/src/query/complete-ordering.ts';\nimport {\n isBuiltinTypeSchema,\n pgTypeForLiteralType,\n sql,\n sqlConvertColumnArg,\n sqlConvertPluralLiteralArg,\n sqlConvertSingularLiteralArg,\n type PluralLiteralType,\n} from './sql.ts';\n\ntype Table = {\n zql: string;\n alias: string;\n};\n\ntype QualifiedColumn = {\n table: Table;\n zql: string;\n};\n\ntype ServerSpec = {\n schema: ServerSchema;\n // maps zql names to server names\n mapper: NameMapper;\n};\n\nexport type Spec = {\n server: ServerSpec;\n zql: Schema['tables'];\n aliasCount: number;\n};\n\nconst ZQL_RESULT_KEY = 'zql_result';\nconst ZQL_RESULT_KEY_IDENT = sql.ident(ZQL_RESULT_KEY);\n\nconst ZQL_RESULT_TABLE_KEY = 'zql_root';\nconst ZQL_RESULT_TABLE_IDENT = sql.ident(ZQL_RESULT_TABLE_KEY);\n\nexport function compile(\n serverSchema: ServerSchema,\n zqlSchema: Schema,\n ast: AST,\n format?: Format,\n): SQLQuery {\n assert(\n ast.groupBy === undefined || ast.aggregate?.distinct === undefined,\n 'a count of distinct values per group is not supported yet',\n );\n // The value would be selected under a group column's name. The query\n // builder rejects such a query; a hand-built AST can still name one.\n assert(\n ast.groupBy === undefined ||\n ast.aggregate === undefined ||\n !ast.groupBy.includes(ast.aggregate.fn),\n () =>\n `groupBy(): the column \"${ast.aggregate?.fn}\" has the same name as the ${ast.aggregate?.fn}() value`,\n );\n // As in the IVM builder: the rows are grouped in the group's order, not the\n // one a bound would be taken in.\n assert(\n (ast.groupBy === undefined && ast.aggregate?.distinct === undefined) ||\n (ast.start === undefined && ast.limit === undefined),\n 'groupBy and a count of distinct values do not support start or limit',\n );\n ast = completeOrdering(\n ast,\n tableName => zqlSchema.tables[tableName].primaryKey,\n );\n const spec: Spec = {\n aliasCount: 0,\n server: {\n schema: serverSchema,\n mapper: clientToServer(zqlSchema.tables),\n },\n zql: zqlSchema.tables,\n };\n if (ast.groupBy) {\n const groups = ast.aggregate\n ? selectGroups(spec, ast, ast.aggregate)\n : selectDistinct(spec, ast);\n return sql`SELECT ${toJSON(ZQL_RESULT_TABLE_KEY)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${groups}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n\n if (ast.aggregate) {\n if (ast.aggregate.distinct) {\n // A count of the distinct combinations counts the rows a distinct()\n // of them gives.\n const groups = selectDistinct(spec, {\n ...ast,\n groupBy: ast.aggregate.distinct,\n aggregate: undefined,\n });\n return sql`SELECT to_json(COUNT(*))::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${groups}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n // Top-level (ungrouped) aggregate: the result is a single scalar, not rows.\n // It reduces the same normalized projection a relationship aggregate does,\n // so values such as timestamps come back in the form ZQL uses. Like the\n // IVM operator, it reduces the rows left after `start`/`limit` and ignores\n // `related`. The order only matters for picking those rows.\n const bounded = ast.limit !== undefined || ast.start !== undefined;\n const inner = select(\n spec,\n {\n ...ast,\n aggregate: undefined,\n related: undefined,\n orderBy: bounded ? ast.orderBy : undefined,\n },\n undefined,\n );\n // An aggregate over no rows (other than COUNT) is SQL NULL, and to_json()\n // of NULL is NULL rather than the JSON text `null` the result parser reads.\n return sql`SELECT COALESCE(to_json(${aggregateExpr(spec, ast.table, ast.aggregate)}), 'null'::json)::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${inner}) ${ZQL_RESULT_TABLE_IDENT}`;\n }\n\n return sql`SELECT \n ${toJSON(ZQL_RESULT_TABLE_KEY, format?.singular)}::text AS ${ZQL_RESULT_KEY_IDENT}\n FROM (${select(spec, ast, format)}) ${ZQL_RESULT_TABLE_IDENT}`;\n}\n\n/**\n * The groups of `ast.groupBy` among the rows that pass `ast.where`, each with\n * the aggregate under the function's name (`count`, `sum`, …), in the order a\n * grouped query's rows have (see `groupOrdering`). Like a top-level\n * aggregate, it reduces the normalized projection {@link select} gives, so a\n * timestamp comes back in epoch milliseconds, and groups by those values.\n */\nfunction selectGroups(spec: Spec, ast: AST, agg: Aggregate): SQLQuery {\n const inner = select(\n spec,\n {\n ...ast,\n groupBy: undefined,\n aggregate: undefined,\n related: undefined,\n orderBy: undefined,\n },\n undefined,\n );\n const cols = must(ast.groupBy).map(col => sql.ident(col));\n return sql`SELECT ${sql.join(cols, ',')}, ${aggregateExpr(spec, ast.table, agg)} AS ${sql.ident(agg.fn)}\n FROM (${inner}) ${sql.ident('zql_group')}\n GROUP BY ${sql.join(cols, ', ')}\n ORDER BY ${sql.join(\n groupOrdering(ast).map(([col, dir]) => {\n const value = orderedValue(spec, ast.table, col, sql.ident(col));\n return dir === 'asc'\n ? sql`${value} ASC NULLS FIRST`\n : sql`${value} DESC NULLS LAST`;\n }),\n ', ',\n )}`;\n}\n\n/**\n * The distinct values of `ast.groupBy` among the rows that pass `ast.where`,\n * one row of those columns each, in the order a distinct query's rows have\n * (see `groupOrdering`). It groups by the columns rather than selecting\n * DISTINCT, which would need the converted values {@link selectIdent} selects\n * to appear in the ORDER BY too. Like the IVM operator, it ignores `related`.\n */\nfunction selectDistinct(spec: Spec, ast: AST): SQLQuery {\n const table = makeTable(spec, ast.table);\n const columns = must(ast.groupBy).map(zql => ({table, zql}));\n return sql`SELECT ${sql.join(\n columns.map(c => selectIdent(spec.server, c)),\n ',',\n )}\n FROM ${fromIdent(spec.server, table)}\n ${ast.where ? sql`WHERE ${where(spec, ast.where, table)}` : sql``}\n GROUP BY ${sql.join(\n columns.map(c => colIdent(spec.server, c)),\n ', ',\n )}\n ORDER BY ${sql.join(\n groupOrdering(ast).map(([col, dir]) => {\n const value = orderedValue(\n spec,\n ast.table,\n col,\n colIdent(spec.server, {table, zql: col}),\n );\n return dir === 'asc'\n ? sql`${value} ASC NULLS FIRST`\n : sql`${value} DESC NULLS LAST`;\n }),\n ', ',\n )}`;\n}\n\n/**\n * The SQL aggregate for `aggregate`, over a subquery that exposes the\n * aggregated column by its client name (as {@link select} does).\n *\n * `COUNT(*)` is left as Postgres's 64-bit count: the result parser rejects a\n * value outside the safe integer range rather than rounding it.\n *\n * `SUM`/`AVG` add the values as float8, as the IVM operator adds JS numbers:\n * Postgres would otherwise sum a `real` in float4 and a `numeric` exactly.\n *\n * `MIN`/`MAX` of an enum, or of a type Zero represents as text (`uuid`,\n * `inet`, …), compare that text byte by byte, as the IVM operator compares\n * strings. Otherwise an enum would use its declaration order, an `inet` its\n * network order, and a `uuid` would fail (it has no `MIN`).\n */\nfunction aggregateExpr(spec: Spec, zqlTable: string, agg: Aggregate): SQLQuery {\n assert(\n agg.distinct === undefined,\n 'a count of distinct values is not supported in a relationship yet',\n );\n const {fn, field, path} = agg;\n if (path !== undefined) {\n return jsonAggregateExpr(spec, zqlTable, agg, path);\n }\n switch (fn) {\n case 'count':\n return sql`COUNT(*)`;\n case 'sum':\n return sql`SUM(${sql.ident(must(field))}::float8)`;\n case 'avg':\n return sql`AVG(${sql.ident(must(field))}::float8)`;\n case 'min':\n return sql`MIN(${orderedAggregateArg(spec, zqlTable, must(field))})`;\n case 'max':\n return sql`MAX(${orderedAggregateArg(spec, zqlTable, must(field))})`;\n default:\n unreachable(fn);\n }\n}\n\n/**\n * The SQL aggregate over the JSON leaf at `path` inside the (client-named)\n * json column `field` of the subquery. Only leaves the aggregate takes count\n * (see `aggregateValue`): numbers for `sum`/`avg`, numbers and strings for\n * `min`/`max`, each gated on `jsonb_typeof` so a mismatched leaf is SQL NULL\n * (skipped) rather than a cast error.\n *\n * `min`/`max` reduce numbers and strings separately and combine them with the\n * client's cross-type order, numbers before strings (`compareAggregateValues`),\n * instead of Postgres's jsonb order, which puts strings first. The result is\n * jsonb so either type comes back as itself.\n */\nfunction jsonAggregateExpr(\n spec: Spec,\n zqlTable: string,\n {fn, field}: Aggregate,\n path: readonly (string | number)[],\n): SQLQuery {\n const name = must(field);\n const {type, isArray} = getServerColumn(\n spec.server,\n {zql: zqlTable, alias: zqlTable},\n name,\n );\n assert(\n isArray || type === 'json' || type === 'jsonb',\n () => `JSON path on non-JSON column \"${name}\" of type ${type}`,\n );\n const {raw, jsonType} = jsonNavigate(\n jsonBase(sql.ident(name), type, isArray),\n path,\n );\n const num = sql`(CASE WHEN ${jsonType} = 'number' THEN ${raw}::float8 END)`;\n const str = sql`(CASE WHEN ${jsonType} = 'string' THEN ${raw} END)`;\n switch (fn) {\n case 'sum':\n return sql`SUM(${num})::float8`;\n case 'avg':\n return sql`AVG(${num})::float8`;\n case 'min':\n return sql`COALESCE(to_jsonb(MIN(${num})), to_jsonb(MIN(${str})))`;\n case 'max':\n return sql`COALESCE(to_jsonb(MAX(${str})), to_jsonb(MAX(${num})))`;\n case 'count':\n throw new Error('count() takes no JSON path');\n default:\n unreachable(fn);\n }\n}\n\nfunction orderedAggregateArg(\n spec: Spec,\n zqlTable: string,\n field: string,\n): SQLQuery {\n return orderedValue(spec, zqlTable, field, sql.ident(field));\n}\n\n/**\n * `value`, the value of `zqlTable`'s column `field`, in a form Postgres\n * orders as the IVM does: an enum, or a type Zero represents as text, by that\n * text byte by byte. Otherwise an enum would use its declaration order and an\n * `inet` its network order.\n */\nfunction orderedValue(\n spec: Spec,\n zqlTable: string,\n field: string,\n value: SQLQuery,\n): SQLQuery {\n const {server} = spec;\n const column =\n server.schema[server.mapper.tableName(zqlTable)][\n server.mapper.columnName(zqlTable, field)\n ];\n // `format` gives the type's own text: `::text` adds the netmask to an `inet`.\n return column.isEnum || isPgTextRepresentedType(column.type)\n ? sql`format('%s', ${value}) COLLATE \"C\"`\n : value;\n}\n\nfunction select(\n spec: Spec,\n ast: AST,\n format: Format | undefined,\n correlate?: (childTable: Table) => SQLQuery,\n): SQLQuery {\n const table = makeTable(spec, ast.table);\n const selectionSet = related(spec, ast.related ?? [], format, table);\n const tableSchema = spec.zql[ast.table];\n const usedAliases = new Set<string>(\n ast.related?.map(r => r.subquery.alias ?? ''),\n );\n for (const column of Object.keys(tableSchema.columns)) {\n if (!usedAliases.has(column)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table,\n zql: column,\n }),\n );\n }\n }\n\n let appliedWhere = false;\n function maybeWhere(test: unknown) {\n if (!test) {\n return sql``;\n }\n\n const ret = appliedWhere ? sql`AND` : sql`WHERE`;\n appliedWhere = true;\n return ret;\n }\n\n return sql`SELECT ${sql.join(selectionSet, ',')}\n FROM ${fromIdent(spec.server, table)}\n ${maybeWhere(ast.where)} ${where(spec, ast.where, table)}${\n ast.start\n ? sql`\n ${maybeWhere(ast.start)} ${start(spec, ast.start, ast.orderBy, table)}`\n : sql``\n }\n ${maybeWhere(correlate)} ${correlate ? correlate(table) : sql``}\n ${orderBy(spec, ast.orderBy, table)}\n ${limit(ast.limit, format?.singular)}`;\n}\n\nexport function limit(\n limit: number | undefined,\n singular: boolean | undefined,\n): SQLQuery {\n if (limit === 0) {\n return sql`LIMIT 0`;\n }\n if (singular) {\n return sql`LIMIT 1`;\n }\n if (limit === undefined) {\n return sql``;\n }\n return sql`LIMIT ${sqlConvertSingularLiteralArg(limit)}`;\n}\n\nfunction makeTable(spec: Spec, zql: string, alias?: string): Table {\n alias = alias ?? zql + '_' + spec.aliasCount++;\n return {\n zql,\n alias,\n };\n}\n\nexport function orderBy(\n spec: Spec,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!orderBy) {\n return sql``;\n }\n return sql`ORDER BY ${sql.join(\n orderBy.map(([col, dir]) =>\n dir === 'asc'\n ? // Oh postgres. The table must be referred to by client name but the column by server name.\n // E.g., `SELECT server_col as client_col FROM server_table as client_table ORDER BY client_Table.server_col`\n sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} ASC NULLS FIRST`\n : sql`${colIdent(spec.server, {\n table,\n zql: col,\n })} DESC NULLS LAST`,\n ),\n ', ',\n )}`;\n}\n\nexport function start(\n spec: Spec,\n bound: Bound | undefined,\n orderBy: Ordering | undefined,\n table: Table,\n): SQLQuery {\n if (!bound) {\n return sql``;\n }\n assert(\n orderBy !== undefined && orderBy.length > 0,\n 'start requires ordering',\n );\n\n const constraints: SQLQuery[] = [];\n for (let i = 0; i < orderBy.length; i++) {\n const group: SQLQuery[] = [];\n const [iField, iDirection] = orderBy[i];\n for (let j = 0; j <= i; j++) {\n const [field] = orderBy[j];\n if (j === i) {\n group.push(\n startRangeComparison(\n spec,\n table,\n iField,\n bound.row[iField] ?? null,\n iDirection === 'asc' ? '>' : '<',\n ),\n );\n } else {\n group.push(startEquality(spec, table, field, bound.row[field] ?? null));\n }\n }\n constraints.push(sql`(${sql.join(group, ' AND ')})`);\n }\n\n if (!bound.exclusive) {\n constraints.push(\n sql`(${sql.join(\n orderBy.map(([field]) =>\n startEquality(spec, table, field, bound.row[field] ?? null),\n ),\n ' AND ',\n )})`,\n );\n }\n\n return sql`(${sql.join(constraints, ' OR ')})`;\n}\n\nfunction related(\n spec: Spec,\n relationships: readonly CorrelatedSubquery[],\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery[] {\n return relationships.map(relationship =>\n relationshipSubquery(\n spec,\n relationship,\n format?.relationships[must(relationship.subquery.alias)],\n parentTable,\n ),\n );\n}\n\nfunction relationshipSubquery(\n spec: Spec,\n relationship: CorrelatedSubquery,\n format: Format | undefined,\n parentTable: Table,\n): SQLQuery {\n const innerAlias = `inner_${relationship.subquery.alias}`;\n if (relationship.aggregate) {\n // Aggregate relationship: emit a correlated scalar subquery returning the\n // aggregate over the matching child rows, instead of aggregating the rows\n // to JSON. No rows are materialized. The inner subquery exposes columns by\n // their client names, so the aggregated field is referenced as-is.\n const {field} = relationship.aggregate;\n const isJunction = !!relationship.subquery.related?.length;\n const aggExpr = aggregateExpr(\n spec,\n isJunction\n ? must(relationship.subquery.related)[0].subquery.table\n : relationship.subquery.table,\n relationship.aggregate,\n );\n\n let inner: SQLQuery;\n if (isJunction) {\n // Junction (many-to-many) aggregate: the value lives on the destination,\n // one hop past the junction. Aggregate over the junction join, exposing\n // the destination field by its client name so `aggExpr` references it. A\n // `where` on the destination filters the joined rows before aggregating.\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n const destWhere = relationship.subquery.related[0].subquery.where;\n inner = sql`SELECT ${\n field\n ? selectIdent(spec.server, {table: lastTable, zql: field})\n : sql`NULL`\n } FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)})${\n destWhere ? sql` AND (${where(spec, destWhere, lastTable)})` : sql``\n }`;\n } else {\n // As for a top-level aggregate, the order only matters for picking the\n // rows a `limit`/`start` keeps; otherwise it is a needless sort per parent.\n const {subquery} = relationship;\n const bounded =\n subquery.limit !== undefined || subquery.start !== undefined;\n inner = select(\n spec,\n bounded ? subquery : {...subquery, orderBy: undefined},\n undefined,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n );\n }\n return sql`(\n SELECT ${aggExpr} FROM (${inner}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n if (relationship.hidden) {\n const {join, participatingTables} = makeJunctionJoin(spec, relationship);\n const lastTable = must(last(participatingTables)).table;\n\n assert(\n relationship.subquery.related,\n 'hidden relationship must be a junction',\n );\n const nestedAst = relationship.subquery.related[0].subquery;\n const selectionSet = related(\n spec,\n nestedAst.related ?? [],\n format,\n lastTable,\n );\n const tableSchema = spec.zql[nestedAst.table];\n for (const column of Object.keys(tableSchema.columns)) {\n selectionSet.push(\n selectIdent(spec.server, {\n table: lastTable,\n zql: column,\n }),\n );\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (SELECT ${sql.join(\n selectionSet,\n ',',\n )} FROM ${join} WHERE (${makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n )(participatingTables[0].table)}) ${\n nestedAst.where\n ? sql`AND ${where(spec, nestedAst.where, lastTable)}`\n : sql``\n }${\n nestedAst.start\n ? sql` AND ${start(\n spec,\n nestedAst.start,\n nestedAst.orderBy,\n lastTable,\n )}`\n : sql``\n } ${orderBy(spec, nestedAst.orderBy, lastTable)} ${limit(\n last(participatingTables)?.limit,\n format?.singular,\n )} ) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n }\n\n return sql`(\n SELECT ${toJSON(innerAlias, format?.singular)} FROM (${select(\n spec,\n relationship.subquery,\n format,\n makeCorrelator(\n spec,\n relationship.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n relationship.correlation.childField,\n ),\n )}) ${sql.ident(innerAlias)}\n ) as ${sql.ident(relationship.subquery.alias)}`;\n}\n\nfunction where(\n spec: Spec,\n condition: Condition | undefined,\n table: Table,\n): SQLQuery {\n if (!condition) {\n return sql``;\n }\n\n switch (condition.type) {\n case 'and':\n if (condition.conditions.length > 0) {\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' AND ',\n )})`;\n } else {\n return sql`TRUE`;\n }\n case 'or':\n if (condition.conditions.length > 0) {\n return sql`(${sql.join(\n condition.conditions.map(c => where(spec, c, table)),\n ' OR ',\n )})`;\n } else {\n return sql`FALSE`;\n }\n case 'correlatedSubquery':\n // `scalar` is deliberately ignored here. It is a planner hint for the\n // IVM engines, which have no cost-based planner and benefit from\n // pre-resolving an at-most-one-row subquery to a literal comparison\n // (see zqlite's `resolveSimpleScalarSubqueries`). Postgres decorrelates\n // EXISTS into a semi-join on its own, so the hint buys nothing here —\n // and honoring it as `parentField = (SELECT childField … LIMIT 1)` is\n // only sound when the subquery matches at most one row *globally*.\n // Applying it unconditionally silently dropped rows whenever the\n // subquery was not pinned to a unique key.\n return exists(spec, condition, table);\n case 'simple':\n return simple(spec, condition, table);\n }\n}\n\nfunction exists(\n spec: Spec,\n condition: CorrelatedSubqueryCondition,\n parentTable: Table,\n): SQLQuery {\n switch (condition.op) {\n case 'EXISTS':\n return sql`EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n case 'NOT EXISTS':\n return sql`NOT EXISTS (${select(\n spec,\n condition.related.subquery,\n undefined,\n makeCorrelator(\n spec,\n condition.related.correlation.parentField.map(f => ({\n table: parentTable,\n zql: f,\n })),\n condition.related.correlation.childField,\n ),\n )})`;\n }\n}\n\nexport function makeCorrelator(\n spec: Spec,\n parentFields: readonly QualifiedColumn[],\n childZqlFields: readonly string[],\n): (childTable: Table) => SQLQuery {\n return (childTable: Table) => {\n const childFields = childZqlFields.map(zqlField => ({\n table: childTable,\n zql: zqlField,\n }));\n return sql.join(\n zip(parentFields, childFields).map(\n ([parentColumn, childColumn]) =>\n sql`${colIdent(spec.server, parentColumn)} = ${colIdent(\n spec.server,\n childColumn,\n )}`,\n ),\n ' AND ',\n );\n };\n}\n\nexport function simple(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n if (condition.left.type === 'json') {\n const special = jsonPathCondition(spec, condition.left, condition, table);\n if (special) {\n return special;\n }\n }\n switch (condition.op) {\n case 'ILIKE':\n case 'LIKE':\n case 'NOT ILIKE':\n case 'NOT LIKE': {\n // The pattern is a string, not a value of the column's type. Converted\n // to the `bpchar` of a `char(n)` column it would lose its trailing\n // spaces. Like ZQL's own LIKE, non-string patterns match as strings.\n const {right} = condition;\n assert(\n right.type === 'literal',\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${sqlConvertSingularLiteralArg(\n right.value === null ? null : String(right.value),\n )}`;\n }\n case '!=':\n case '<':\n case '<=':\n case '=':\n case '>':\n case '>=':\n return sql`${valueComparison(\n spec,\n condition.left,\n table,\n condition.right,\n false,\n )} ${sql.__dangerous__rawValue(condition.op)} ${valueComparison(\n spec,\n condition.right,\n table,\n condition.left,\n false,\n )}`;\n case 'NOT IN':\n case 'IN':\n return any(spec, condition, table);\n case 'IS':\n case 'IS NOT':\n return distinctFrom(spec, condition, table);\n }\n}\n\nexport function any(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${condition.op === 'NOT IN' ? sql`NOT` : sql``}\n (\n ${valueComparison(spec, condition.left, table, condition.right, false)} = ANY \n (${valueComparison(spec, condition.right, table, condition.left, true)})\n )`;\n}\n\nexport function distinctFrom(\n spec: Spec,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery {\n return sql`${valueComparison(spec, condition.left, table, condition.right, false)} ${\n condition.op === 'IS' ? sql`IS NOT DISTINCT FROM` : sql`IS DISTINCT FROM`\n } ${valueComparison(spec, condition.right, table, condition.left, false)}`;\n}\n\nfunction startEquality(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sql`${colIdent(spec.server, {\n table,\n zql: field,\n })} IS NOT DISTINCT FROM ${startValue(spec, table, field, value)}`;\n}\n\nfunction startRangeComparison(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n operator: '>' | '<',\n): SQLQuery {\n const column = colIdent(spec.server, {table, zql: field});\n if (value === null) {\n return operator === '>' ? sql`${column} IS NOT NULL` : sql`FALSE`;\n }\n const typedValue = startValue(spec, table, field, value);\n return operator === '>'\n ? sql`${column} > ${typedValue}`\n : sql`(${column} IS NULL OR ${column} < ${typedValue})`;\n}\n\nfunction startValue(\n spec: Spec,\n table: Table,\n field: string,\n value: unknown,\n): SQLQuery {\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, field),\n value,\n false,\n true,\n );\n}\n\nfunction valueComparison(\n spec: Spec,\n valuePos: ValuePosition,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const valuePosType = valuePos.type;\n switch (valuePosType) {\n case 'column': {\n const qualified: QualifiedColumn = {\n table,\n zql: valuePos.name,\n };\n return colIdent(spec.server, qualified);\n }\n case 'json':\n return jsonPathLeaf(spec, valuePos, table, otherValuePos);\n case 'literal':\n return literalValueComparison(\n spec,\n valuePos,\n table,\n otherValuePos,\n plural,\n );\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(valuePosType);\n }\n}\n\nfunction literalValueComparison(\n spec: Spec,\n valuePos: LiteralReference,\n table: Table,\n otherValuePos: ValuePosition,\n plural: boolean,\n): SQLQuery {\n const otherType = otherValuePos.type;\n switch (otherType) {\n case 'column':\n return sqlConvertColumnArg(\n getServerColumn(spec.server, table, otherValuePos.name),\n valuePos.value,\n plural,\n true,\n );\n case 'json': {\n // The other side is a JSON path leaf, which is dynamically typed. Render\n // this literal by its OWN JS type so its cast matches the leaf's cast in\n // `jsonPathLeaf` (`leafType`). LiteralValue is primitives or a\n // homogeneous primitive list (enforced at the wire and by the builder).\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n const {value} = valuePos;\n if (Array.isArray(value)) {\n return sqlConvertPluralLiteralArg(\n jsonLiteralType(value) ?? 'string',\n value as PluralLiteralType[],\n );\n }\n // `Array.isArray` does not narrow a `readonly` array out of the union.\n return sqlConvertSingularLiteralArg(\n value as string | number | boolean | null,\n );\n }\n case 'literal': {\n assert(\n plural === Array.isArray(valuePos.value),\n 'Expected plural flag to match whether value is an array',\n );\n if (Array.isArray(valuePos.value)) {\n if (valuePos.value.length > 0) {\n // If the array is non-empty base its type on its first\n // element\n return sqlConvertPluralLiteralArg(\n typeof valuePos.value[0] as PluralLiteralType,\n valuePos.value as PluralLiteralType[],\n );\n }\n // If the array is empty, base its type on the other value\n // position's type (as long as the other value position is non-null,\n // cannot have a null[]).\n if (otherValuePos.value !== null) {\n return sqlConvertPluralLiteralArg(\n typeof otherValuePos.value as PluralLiteralType,\n [],\n );\n }\n // If the other value position is null, it can be compared to any\n // type of empty array, chose 'string' arbitrarily.\n return sqlConvertPluralLiteralArg('string', []);\n }\n if (\n typeof valuePos.value === 'string' ||\n typeof valuePos.value === 'number' ||\n typeof valuePos.value === 'boolean'\n ) {\n return sqlConvertSingularLiteralArg(valuePos.value);\n }\n throw new Error(`Literal of unexpected type: ${typeof valuePos.value}`);\n }\n case 'static':\n throw new Error(\n 'Static parameters must be bound to a value before compiling to SQL',\n );\n default:\n unreachable(otherType);\n }\n}\n\n/**\n * The two SQL pieces every JSON path comparison is built from: the leaf's text\n * (`raw`, SQL NULL for a missing key or a JSON null) and its JSON type\n * (`jsonType`, via `jsonb_typeof`).\n *\n * Navigation chains `->` with a *typed* operand per segment (a text operand\n * for an object key, an integer operand for an array index), so Postgres\n * applies the same strict rule as the in-memory reader and SQLite: a string\n * segment never indexes an array and a number never reads an object key. (A\n * `#>>` text[] path would instead resolve a digit string by the container's\n * runtime type, including `'-1'` from the end.) The last step uses `->>` for\n * the text form.\n *\n * The base is the column as jsonb: a `json` column is cast, and a Postgres\n * array column (which zero maps to a `json()` column and the replica stores\n * as JSON text) is converted with `to_jsonb`.\n */\nfunction jsonPathParts(\n spec: Spec,\n ref: JsonPathReference,\n table: Table,\n): {value: SQLQuery; raw: SQLQuery; jsonType: SQLQuery} {\n const {name} = ref.value;\n const col = colIdent(spec.server, {table, zql: name});\n const {type, isArray} = getServerColumn(spec.server, table, name);\n assert(\n isArray || type === 'json' || type === 'jsonb',\n () => `JSON path on non-JSON column \"${name}\" of type ${type}`,\n );\n return jsonNavigate(jsonBase(col, type, isArray), ref.path);\n}\n\n/** A json/jsonb/array column (or an expression of one) as jsonb. */\nfunction jsonBase(col: SQLQuery, type: string, isArray: boolean): SQLQuery {\n return isArray\n ? sql`to_jsonb(${col})`\n : type === 'json'\n ? sql`${col}::jsonb`\n : col;\n}\n\n/** Navigates `path` from the jsonb `base`; see {@link jsonPathParts}. */\nfunction jsonNavigate(\n base: SQLQuery,\n path: readonly (string | number)[],\n): {value: SQLQuery; raw: SQLQuery; jsonType: SQLQuery} {\n let obj = base;\n const operand = (seg: string | number): SQLQuery =>\n typeof seg === 'number'\n ? // A validated non-negative int32 (see isValidJsonPathIndex), so it is\n // safe to inline; `->` needs an integer operand to index an array.\n sql.__dangerous__rawValue(String(seg))\n : sqlConvertSingularLiteralArg(seg);\n const last = path.length - 1;\n for (let i = 0; i < last; i++) {\n obj = sql`(${obj} -> ${operand(path[i])})`;\n }\n const leaf = operand(path[last]);\n return {\n // The leaf as jsonb; `raw` is its text form.\n value: sql`(${obj} -> ${leaf})`,\n raw: sql`(${obj} ->> ${leaf})`,\n jsonType: sql`jsonb_typeof(${obj} -> ${leaf})`,\n };\n}\n\n/**\n * The JS type the leaf must have to be compared against the literal on the\n * other side (`jsonLiteralType`, shared across engines). It is also the\n * `jsonb_typeof` name and the key into `pgTypeForLiteralType` for the cast, so\n * the leaf's cast and the literal's own cast cannot drift. `undefined` for a\n * `null` literal (`IS NULL`: a missing key and a JSON null must both read as\n * SQL NULL), an empty list, or a non-literal.\n */\nfunction leafType(other: ValuePosition): PluralLiteralType | undefined {\n return other.type === 'literal' ? jsonLiteralType(other.value) : undefined;\n}\n\n/**\n * Compiles a JSON path reference to its text form, cast to the comparison type\n * derived from the literal on the other side (`leafType`) so it lines up with\n * that literal's own cast.\n *\n * `->>` maps **both** a missing key and a JSON `null` to SQL `NULL`, matching\n * the SQLite `json_extract` pushdown and the in-memory predicate, so `IS NULL`\n * agrees across all three.\n *\n * The cast is gated on the leaf's JSON type (`CASE WHEN jsonb_typeof(...)`), so a\n * leaf of a different type than the literal is SQL NULL, i.e. a non-match. This\n * is the type-strict comparison documented on {@link JsonPathReference}: `->>`\n * renders a numeric `42` as the text `'42'`, so an ungated text comparison\n * would wrongly match it against the string `'42'`. For `number`/`boolean` the\n * gate is also what keeps the cast from throwing: Postgres errors when casting\n * non-conforming text (a string `\"n/a\"`, an object's JSON text) to\n * `double precision`/`boolean`, which would fail the whole query on one\n * mismatched row. Negated operators need a different form; see\n * `jsonPathCondition`.\n */\nfunction jsonPathLeaf(\n spec: Spec,\n ref: JsonPathReference,\n table: Table,\n other: ValuePosition,\n): SQLQuery {\n const {raw, jsonType} = jsonPathParts(spec, ref, table);\n const t = leafType(other);\n if (t === undefined) {\n return raw;\n }\n return sql`(CASE WHEN ${jsonType} = ${sqlConvertSingularLiteralArg(\n t,\n )} THEN ${raw}::${sql.__dangerous__rawValue(pgTypeForLiteralType(t))} END)`;\n}\n\n/**\n * The comparisons on a JSON path left operand that cannot go through the\n * generic operator rendering with the gated leaf (`jsonPathLeaf`); returns\n * `undefined` for the ones that can.\n *\n * - `IN`/`NOT IN` with a `null` literal is constant-false, as in the\n * in-memory predicate (the generic forms would assert, or match every\n * non-null leaf).\n * - `=`/`IN` against a string or boolean literal compare the leaf *as jsonb*:\n * jsonb equality is type-strict by itself (`\"42\"` never equals `42`, a JSON\n * `null` never equals a string) and a missing key is SQL NULL, so the\n * `jsonb_typeof` gate is unnecessary. Without the `CASE` around the\n * extraction, an expression index on `(col -> 'key')` can serve the\n * predicate. Numbers keep the gated `double precision` form: jsonb compares\n * numbers exactly (`numeric`), which would diverge from the client's and\n * SQLite's IEEE-754 equality above 2^53 or beyond double precision.\n * - An empty `NOT IN` list matches every non-null leaf: SQL's\n * `NOT (x = ANY('{}'))` is TRUE even for a NULL leaf, whereas the\n * predicate's null guard excludes it.\n * - The LIKE family compares text, so the leaf must be a string whatever the\n * literal's type, and the pattern is the literal's text form, as in the\n * in-memory predicate (`String(pattern)`) and SQLite. Deriving the leaf type\n * from a numeric or boolean literal instead would cast the leaf to\n * `double precision`/`boolean` and hand Postgres a LIKE it cannot execute.\n * - The negated operators (`!=`, `NOT LIKE`, `NOT ILIKE`, `NOT IN`): the gate\n * makes a mismatched leaf SQL NULL, which a positive comparison correctly\n * excludes. But NULL also excludes under a negated operator, where a\n * mismatch must *match* (JS `42 !== '42'` is true). `jsonb_typeof` is NULL\n * for a missing key and `'null'` for a JSON null, so one `COALESCE` covers\n * the null guard without a second extraction: a null/missing leaf is\n * false, the same type is the real (negated) comparison, another type is\n * true.\n */\nfunction jsonPathCondition(\n spec: Spec,\n left: JsonPathReference,\n condition: SimpleCondition,\n table: Table,\n): SQLQuery | undefined {\n const {op} = condition;\n let {right} = condition;\n if (\n (op === 'IN' || op === 'NOT IN') &&\n right.type === 'literal' &&\n right.value === null\n ) {\n return sql`false`;\n }\n if (\n isLikeOperator(op) &&\n right.type === 'literal' &&\n right.value !== null &&\n !Array.isArray(right.value)\n ) {\n right = {type: 'literal', value: String(right.value)};\n if (!isNegatedOperator(op)) {\n return sql`${valueComparison(\n spec,\n left,\n table,\n right,\n false,\n )} ${sql.__dangerous__rawValue(op)} ${valueComparison(\n spec,\n right,\n table,\n left,\n false,\n )}`;\n }\n }\n if ((op === '=' || op === 'IN') && right.type === 'literal') {\n const t = leafType(right);\n if (t === 'string' || t === 'boolean') {\n const {value} = jsonPathParts(spec, left, table);\n const lit = valueComparison(spec, right, table, left, op === 'IN');\n return op === 'IN'\n ? sql`${value} = ANY (ARRAY(SELECT to_jsonb(v) FROM unnest(${lit}) AS v))`\n : sql`${value} = to_jsonb(${lit})`;\n }\n }\n // A non-literal (an unbound static parameter) falls through to the generic\n // rendering, which rejects it; it must not be mistaken for an empty list.\n if (!isNegatedOperator(op) || right.type !== 'literal') {\n return undefined;\n }\n const t = leafType(right);\n const {raw, jsonType} = jsonPathParts(spec, left, table);\n if (t === undefined) {\n // Only an empty NOT IN list reaches here: `!=`/`NOT LIKE` against null\n // are constant-false through the generic NULL comparison.\n return op === 'NOT IN' ? sql`${raw} IS NOT NULL` : undefined;\n }\n const leaf = sql`${raw}::${sql.__dangerous__rawValue(pgTypeForLiteralType(t))}`;\n const plural = op === 'NOT IN';\n const lit = valueComparison(spec, right, table, left, plural);\n const cmp = plural\n ? sql`NOT (${leaf} = ANY (${lit}))`\n : sql`${leaf} ${sql.__dangerous__rawValue(op)} ${lit}`;\n return sql`(CASE COALESCE(${jsonType}, 'null') WHEN 'null' THEN false WHEN ${sqlConvertSingularLiteralArg(\n t,\n )} THEN ${cmp} ELSE true END)`;\n}\n\nexport function makeJunctionJoin(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): {\n join: SQLQuery;\n participatingTables: ReturnType<typeof pullTablesForJunction>;\n} {\n const participatingTables = pullTablesForJunction(spec, relationship);\n const joins: SQLQuery[] = [];\n\n for (const {table} of participatingTables) {\n if (joins.length === 0) {\n joins.push(fromIdent(spec.server, table));\n continue;\n }\n joins.push(\n sql` JOIN ${fromIdent(spec.server, table)} ON ${makeCorrelator(\n spec,\n participatingTables[joins.length].correlation.parentField.map(f => ({\n table: participatingTables[joins.length - 1].table,\n zql: f,\n })),\n participatingTables[joins.length].correlation.childField,\n )(participatingTables[joins.length].table)}`,\n );\n }\n\n return {\n join: sql`${sql.join(joins, '')}`,\n participatingTables,\n // lastTable: participatingTables[participatingTables.length - 1].table,\n // lastLimit: participatingTables[participatingTables.length - 1].limit,\n };\n}\n\nexport function pullTablesForJunction(\n spec: Spec,\n relationship: CorrelatedSubquery,\n): [\n {\n table: Table;\n correlation: Correlation;\n limit: number | undefined;\n },\n {table: Table; correlation: Correlation; limit: number | undefined},\n] {\n assert(\n relationship.subquery.related?.length === 1,\n 'Too many related tables for a junction edge',\n );\n const otherRelationship = relationship.subquery.related[0];\n assert(\n !otherRelationship.hidden,\n 'Expected junction edge relationship to not be hidden',\n );\n return [\n {\n table: makeTable(spec, relationship.subquery.table),\n correlation: relationship.correlation,\n limit: relationship.subquery.limit,\n },\n {\n table: makeTable(spec, otherRelationship.subquery.table),\n correlation: otherRelationship.correlation,\n limit: otherRelationship.subquery.limit,\n },\n ];\n}\n\nfunction toJSON(table: string, singular = false): SQLQuery {\n return sql`${\n singular ? sql`` : sql`COALESCE(json_agg`\n }(row_to_json(${sql.ident(table)}))${singular ? sql`` : sql`, '[]'::json)`}`;\n}\n\nfunction selectIdent(server: ServerSpec, column: QualifiedColumn): SQLQuery {\n const serverColumnSchema =\n server.schema[server.mapper.tableName(column.table.zql)][\n server.mapper.columnName(column.table.zql, column.zql)\n ];\n const serverType = serverColumnSchema.type;\n // A user-defined type can have a built-in name such as `timestamp`; only\n // convert the values of the built-in types.\n if (\n !serverColumnSchema.isEnum &&\n isBuiltinTypeSchema(serverColumnSchema.typeSchema)\n ) {\n let needsNormalization = false;\n switch (serverType) {\n case 'timetz':\n // @ts-expect-error Fallthrough intended\n case 'time with time zone':\n needsNormalization = true;\n // fallthrough\n\n case 'date':\n case 'time':\n case 'time without time zone':\n case 'timestamp':\n case 'timestamp without time zone':\n case 'timestamptz':\n case 'timestamp with time zone': {\n // EXTRACT(EPOCH FROM timetz) can be negative when the UTC offset is\n // positive (e.g. 01:00+02 = 23:00 UTC prev day = -3600s). Wrap with\n // modular arithmetic to normalize to 0..86400000.\n const toMs = (epochExpr: SQLQuery): SQLQuery =>\n needsNormalization\n ? sql`((${epochExpr})::bigint + 86400000) % 86400000`\n : epochExpr;\n\n if (serverColumnSchema.isArray) {\n const col = colIdent(server, column);\n return sql`CASE WHEN ${col} IS NULL THEN NULL ELSE ARRAY(SELECT ${toMs(\n sql`EXTRACT(EPOCH FROM unnest(${col})) * 1000`,\n )}) END as ${sql.ident(column.zql)}`;\n }\n\n return sql`${toMs(\n sql`EXTRACT(EPOCH FROM ${colIdent(server, column)}) * 1000`,\n )} as ${sql.ident(column.zql)}`;\n }\n }\n }\n\n return sql`${colIdent(server, column)} as ${sql.ident(column.zql)}`;\n}\n\nfunction colIdent(server: ServerSpec, column: QualifiedColumn) {\n return sql.ident(\n column.table.alias,\n server.mapper.columnName(column.table.zql, column.zql),\n );\n}\n\nfunction fromIdent(server: ServerSpec, table: Table) {\n return sql`${sql.ident(server.mapper.tableName(table.zql))} AS ${sql.ident(table.alias)}`;\n}\n\nfunction getServerColumn(spec: ServerSpec, table: Table, zqlColumn: string) {\n return spec.schema[spec.mapper.tableName(table.zql)][\n spec.mapper.columnName(table.zql, zqlColumn)\n ];\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractZqlResult(pgResult: Array<any>): JSONValue {\n const bigIntJson: BigIntJSONValue = parseBigIntJson(\n pgResult[0][ZQL_RESULT_KEY],\n );\n assertJSONValue(bigIntJson);\n return bigIntJson;\n}\n\nfunction assertJSONValue(v: BigIntJSONValue): asserts v is JSONValue {\n const path = findPathToBigInt(v);\n if (path) {\n throw new Error(`Value exceeds safe Number range. ${path}`);\n }\n}\n\nfunction findPathToBigInt(v: BigIntJSONValue): string | undefined {\n const typeOfV = typeof v;\n switch (typeOfV) {\n case 'bigint':\n return ` = ${v}`;\n case 'object': {\n if (v === null) {\n return;\n }\n if (Array.isArray(v)) {\n for (let i = 0; i < v.length; i++) {\n const path = findPathToBigInt(v[i]);\n if (path) {\n return `[${i}]${path}`;\n }\n }\n return undefined;\n }\n\n const o = v as Record<string, BigIntJSONValue>;\n for (const k in o) {\n if (hasOwn(o, k)) {\n const path = findPathToBigInt(o[k]);\n if (path) {\n return `['${k}']${path}`;\n }\n }\n }\n return undefined;\n }\n case 'number':\n return undefined;\n case 'boolean':\n return undefined;\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqEA,IAAM,iBAAiB;AACvB,IAAM,uBAAuB,IAAI,MAAM,cAAc;AAErD,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB,IAAI,MAAM,oBAAoB;AAE7D,SAAgB,QACd,cACA,WACA,KACA,QACU;CACV,OACE,IAAI,YAAY,KAAA,KAAa,IAAI,WAAW,aAAa,KAAA,GACzD,2DACF;CAGA,OACE,IAAI,YAAY,KAAA,KAC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KAAK,GACd,IAAI,OAAO,GAAG,CAAC,GAAG;IAChB,MAAM,OAAO,iBAAiB,EAAE,EAAE;IAClC,IAAI,MACF,OAAO,KAAK,EAAE,IAAI;GAEtB;GAEF;EACF;EACA,KAAK,UACH;EACF,KAAK,WACH;EACF,SACE;CACJ;AACF"}
|
package/out/zero/package.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region package.json
|
|
2
2
|
var name = "@rocicorp/zero";
|
|
3
|
-
var version = "1.13.0-canary.
|
|
3
|
+
var version = "1.13.0-canary.2";
|
|
4
4
|
var description = "Zero is a web framework for serverless web development.";
|
|
5
5
|
var homepage = "https://zero.rocicorp.dev";
|
|
6
6
|
var bugs = { "url": "https://bugs.rocicorp.dev" };
|
|
@@ -134,7 +134,7 @@ var dependencies = {
|
|
|
134
134
|
"@postgresql-typed/oids": "^0.2.0",
|
|
135
135
|
"@rocicorp/lock": "^2.0.1",
|
|
136
136
|
"@rocicorp/logger": "^6.1.0",
|
|
137
|
-
"@rocicorp/zero-sqlite3": "^1.
|
|
137
|
+
"@rocicorp/zero-sqlite3": "^1.2.0",
|
|
138
138
|
"@standard-schema/spec": "^1.1.0",
|
|
139
139
|
"@types/basic-auth": "^1.1.8",
|
|
140
140
|
"@types/ws": "^8.18.1",
|
package/out/zero/package.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.13.0-canary.
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.13.0-canary.2\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/kysely\": {\n \"types\": \"./out/zero/src/adapters/kysely.d.ts\",\n \"default\": \"./out/zero/src/adapters/kysely.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --quiet --config ../../oxlint.config.ts src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.5.5\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.66.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.1.0\",\n \"@fastify/websocket\": \"^11.2.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"1.9.1\",\n \"@opentelemetry/api-logs\": \"0.223.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"0.81.2\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"0.223.0\",\n \"@opentelemetry/resources\": \"2.12.0\",\n \"@opentelemetry/sdk-metrics\": \"2.12.0\",\n \"@opentelemetry/sdk-node\": \"0.223.0\",\n \"@opentelemetry/sdk-trace-node\": \"2.12.0\",\n \"@opentelemetry/semantic-conventions\": \"1.43.0\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^2.0.1\",\n \"@rocicorp/logger\": \"^6.1.0\",\n \"@rocicorp/zero-sqlite3\": \"^1.2.0\",\n \"@standard-schema/spec\": \"^1.1.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.18.1\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.2\",\n \"chokidar\": \"^4.0.3\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.2\",\n \"command-line-usage\": \"^7.0.4\",\n \"compare-utf8\": \"^0.2.3\",\n \"defu\": \"^6.1.7\",\n \"eventemitter3\": \"^5.0.4\",\n \"fastify\": \"^5.12.7\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.10.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.2\",\n \"nanoid\": \"^5.1.16\",\n \"oxc-parser\": \"^0.129.0\",\n \"oxfmt\": \"^0.74.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.8.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.22.0\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \"^18.2.5\",\n \"analyze-query\": \"workspace:*\",\n \"ast-to-zql\": \"workspace:*\",\n \"expo\": \"^58.0.14\",\n \"expo-sqlite\": \"^58.0.13\",\n \"react-native\": \"^0.88.0\",\n \"replicache\": \"workspace:*\",\n \"shared\": \"workspace:*\",\n \"syncpack\": \"^14.3.1\",\n \"typedoc\": \"^0.28.19\",\n \"typescript\": \"~7.0.2\",\n \"vite\": \"^8.3.4\",\n \"vitest\": \"^5.0.5\",\n \"zero-cache\": \"workspace:*\",\n \"zero-client\": \"workspace:*\",\n \"zero-pg\": \"workspace:*\",\n \"zero-react\": \"workspace:*\",\n \"zero-server\": \"workspace:*\",\n \"zero-solid\": \"workspace:*\",\n \"zqlite\": \"workspace:*\"\n },\n \"engines\": {\n \"node\": \">=22\"\n },\n \"packageManager\": \"pnpm@11.11.0\"\n}\n"],"mappings":""}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert } from "../../../shared/src/asserts.js";
|
|
2
|
+
import { assignProperty, getOwnProperty } from "../../../shared/src/objects.js";
|
|
2
3
|
import { parse } from "../../../shared/src/valita.js";
|
|
3
4
|
import { must } from "../../../shared/src/must.js";
|
|
4
|
-
import { assignProperty, getOwnProperty } from "../../../shared/src/objects.js";
|
|
5
5
|
import { consume } from "../../../zql/src/ivm/stream.js";
|
|
6
6
|
import { simplifyCondition } from "../../../zql/src/query/expression.js";
|
|
7
7
|
import { asQueryInternals } from "../../../zql/src/query/query-internals.js";
|