joist-core 2.3.0-next.99 → 2.4.0
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/build/EntityManager.cjs +1 -1
- package/build/EntityManager.cjs.map +1 -1
- package/build/EntityManager.d.cts +9 -8
- package/build/EntityManager.d.cts.map +1 -1
- package/build/EntityManager.d.mts +9 -8
- package/build/EntityManager.d.mts.map +1 -1
- package/build/EntityManager.js +1 -1
- package/build/EntityManager.js.map +1 -1
- package/build/dataloaders/findCountDataLoader.cjs +2 -0
- package/build/dataloaders/findCountDataLoader.cjs.map +1 -1
- package/build/dataloaders/findCountDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findCountDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findCountDataLoader.js +2 -0
- package/build/dataloaders/findCountDataLoader.js.map +1 -1
- package/build/dataloaders/findDataLoader.cjs +1 -0
- package/build/dataloaders/findDataLoader.cjs.map +1 -1
- package/build/dataloaders/findDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findDataLoader.js +2 -1
- package/build/dataloaders/findDataLoader.js.map +1 -1
- package/build/dataloaders/findIdsDataLoader.cjs +2 -0
- package/build/dataloaders/findIdsDataLoader.cjs.map +1 -1
- package/build/dataloaders/findIdsDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findIdsDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findIdsDataLoader.js +2 -0
- package/build/dataloaders/findIdsDataLoader.js.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.cjs +2 -0
- package/build/dataloaders/findPaginatedDataLoader.cjs.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.js +2 -0
- package/build/dataloaders/findPaginatedDataLoader.js.map +1 -1
- package/build/index.cjs +6 -3
- package/build/index.cjs.map +1 -1
- package/build/index.d.cts +6 -4
- package/build/index.d.cts.map +1 -1
- package/build/index.d.mts +6 -4
- package/build/index.d.mts.map +1 -1
- package/build/index.js +6 -5
- package/build/index.js.map +1 -1
- package/build/keys.cjs +6 -1
- package/build/keys.cjs.map +1 -1
- package/build/keys.d.cts +3 -1
- package/build/keys.d.cts.map +1 -1
- package/build/keys.d.mts +3 -1
- package/build/keys.d.mts.map +1 -1
- package/build/keys.js +6 -2
- package/build/keys.js.map +1 -1
- package/build/queries/find/QueryParser.cjs +1 -2
- package/build/queries/find/QueryParser.cjs.map +1 -1
- package/build/queries/find/QueryParser.d.cts.map +1 -1
- package/build/queries/find/QueryParser.d.mts.map +1 -1
- package/build/queries/find/QueryParser.js +2 -3
- package/build/queries/find/QueryParser.js.map +1 -1
- package/build/queries/find/QueryVisitor.cjs +17 -0
- package/build/queries/find/QueryVisitor.cjs.map +1 -1
- package/build/queries/find/QueryVisitor.d.cts +3 -1
- package/build/queries/find/QueryVisitor.d.cts.map +1 -1
- package/build/queries/find/QueryVisitor.d.mts +3 -1
- package/build/queries/find/QueryVisitor.d.mts.map +1 -1
- package/build/queries/find/QueryVisitor.js +17 -1
- package/build/queries/find/QueryVisitor.js.map +1 -1
- package/build/queries/sql/Expr.cjs +18 -1
- package/build/queries/sql/Expr.cjs.map +1 -1
- package/build/queries/sql/Expr.d.cts +13 -3
- package/build/queries/sql/Expr.d.cts.map +1 -1
- package/build/queries/sql/Expr.d.mts +13 -3
- package/build/queries/sql/Expr.d.mts.map +1 -1
- package/build/queries/sql/Expr.js +18 -2
- package/build/queries/sql/Expr.js.map +1 -1
- package/build/queries/sql/JoinTree.cjs +72 -0
- package/build/queries/sql/JoinTree.cjs.map +1 -0
- package/build/queries/sql/JoinTree.d.cts +107 -0
- package/build/queries/sql/JoinTree.d.cts.map +1 -0
- package/build/queries/sql/JoinTree.d.mts +107 -0
- package/build/queries/sql/JoinTree.d.mts.map +1 -0
- package/build/queries/sql/JoinTree.js +71 -0
- package/build/queries/sql/JoinTree.js.map +1 -0
- package/build/queries/sql/Tables.cjs +103 -6
- package/build/queries/sql/Tables.cjs.map +1 -1
- package/build/queries/sql/Tables.d.cts +72 -13
- package/build/queries/sql/Tables.d.cts.map +1 -1
- package/build/queries/sql/Tables.d.mts +72 -13
- package/build/queries/sql/Tables.d.mts.map +1 -1
- package/build/queries/sql/Tables.js +101 -10
- package/build/queries/sql/Tables.js.map +1 -1
- package/build/queries/sql/custom.cjs +52 -0
- package/build/queries/sql/custom.cjs.map +1 -0
- package/build/queries/sql/custom.d.cts +85 -0
- package/build/queries/sql/custom.d.cts.map +1 -0
- package/build/queries/sql/custom.d.mts +85 -0
- package/build/queries/sql/custom.d.mts.map +1 -0
- package/build/queries/sql/custom.js +49 -0
- package/build/queries/sql/custom.js.map +1 -0
- package/build/queries/sql/execute.cjs +68 -28
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts +110 -11
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts +110 -11
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +69 -29
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/expressions/types.d.cts +5 -5
- package/build/queries/sql/expressions/types.d.cts.map +1 -1
- package/build/queries/sql/expressions/types.d.mts +5 -5
- package/build/queries/sql/expressions/types.d.mts.map +1 -1
- package/build/queries/sql/keywords.cjs +1 -1
- package/build/queries/sql/keywords.cjs.map +1 -1
- package/build/queries/sql/keywords.d.cts +1 -1
- package/build/queries/sql/keywords.d.mts +1 -1
- package/build/queries/sql/keywords.js +1 -1
- package/build/queries/sql/keywords.js.map +1 -1
- package/build/queries/sql/query.cjs +100 -38
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +96 -46
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +96 -46
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +102 -40
- package/build/queries/sql/query.js.map +1 -1
- package/build/queries/valueFilters.cjs +28 -36
- package/build/queries/valueFilters.cjs.map +1 -1
- package/build/queries/valueFilters.d.cts +2 -4
- package/build/queries/valueFilters.d.cts.map +1 -1
- package/build/queries/valueFilters.d.mts +2 -4
- package/build/queries/valueFilters.d.mts.map +1 -1
- package/build/queries/valueFilters.js +29 -36
- package/build/queries/valueFilters.js.map +1 -1
- package/build/serde/serde.cjs.map +1 -1
- package/build/serde/serde.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Expr.js","names":[],"sources":["../../../src/queries/sql/Expr.ts"],"sourcesContent":["import type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type ConditionInput, type PredicateBrand, type SqlCondition, brandPredicate } from \"src/queries/conditions.ts\";\nimport type { RawCondition } from \"src/queries/parsedConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport { safeKq } from \"src/queries/sql/keywords.ts\";\nimport type { ExpressionOrderBy, QueryCondition } from \"src/queries/sql/query.ts\";\nimport { type TypeInfo, arrayOutputType } from \"src/serde/TypeInfo.ts\";\n\n/**\n * The shared expression protocol for `em.query`.\n *\n * Table columns (`a.first_name`), aggregates (`b.id.count()`), `sql` templates, subquery columns\n * (`bookStats.bookCount`), and scalar subqueries all implement it, so any of them can appear in\n * `select`, `where`, `groupBy`, `having`, `orderBy`, and inside other expressions.\n *\n * This module is a leaf on purpose: `Tables.ts` extends `BaseExpr` at load time, so nothing here may\n * import (at runtime) a module that leads back to `Tables.ts`. Anything that needs metadata, alias\n * binding, or SQL generation for conditions is reached through the `ExprContext` the query parser passes in.\n */\n\nexport const exprBrand: unique symbol = Symbol(\"joist.expr\");\n\n/**\n * Phantom type information carried by every `Expr`.\n *\n * `R` is the decoded result type.\n *\n * `Src` is the expression's *source key*: the type-level identity of the table it reads from. An entity\n * table's key is its type name (`table(Author)` gives `\"Author\"`) or the explicit name in\n * `table(Author, \"m\")`; a subquery's key is its `as: \"book_stats\"`, or the shared sentinel `\"?\"` when it\n * has no `as`. Exactly two questions are asked of a source key, and nothing else:\n *\n * - `MaybeNull` asks \"is my source key among the LEFT-joined sources in this query's join list?\" If yes,\n * the value can be `null`.\n * - `CheckScope` asks \"is my source key among `from` + `join` at all?\" If no, the query reads from a\n * table it never joined.\n *\n * Two special keys opt out of both questions:\n *\n * - `Expr<number, never>` reads from nothing that can be left-joined away, i.e. `b.id.count()`\n * - `Expr<number, string>` (the default) is untracked, i.e. `sql.ref` on an unknown table\n */\nexport interface ExprBrand<R, Src extends string> {\n readonly __result: R;\n readonly __source: Src;\n}\n\n/**\n * \"Any expression whose result is `R`\", checked by brand alone.\n *\n * Method parameters use this instead of `Expr<R>` so that `Expr` stays covariant in `R`: checking\n * `Expr<AuthorId>` against `Expr<AuthorId | null>` then only compares the phantom `__result`, not every\n * method's parameter list (which would make `Expr` invariant, and break `select: b.author_id` dispatch and\n * polymorphic joins).\n */\nexport type ExprLike<R> = { readonly [exprBrand]: ExprBrand<R, any> };\n\n/** Controls which values enter an array aggregate and their order within the array. */\nexport interface ArrayAggOptions {\n distinct?: boolean;\n /** With DISTINCT, PostgreSQL requires ordering expressions to match the aggregate argument. */\n orderBy?: readonly (ExpressionOrderBy | undefined)[];\n /** Undefined conditions are pruned, as in a query's where clause. */\n filter?: QueryCondition;\n}\n\n/**\n * A typed SQL expression: a table column, an aggregate, a `sql` template, or a scalar subquery.\n *\n * Conditions and SQL functions are methods, so they need no import. Aggregates keep `Src` so scope\n * checking still sees through `bs.x.max()`; `count` is source-less because `count(x)` is 0, not null,\n * when `x`'s table is left-joined away; `coalesce` drops `Src` on purpose, since its whole job is to\n * remove the nullability a left join adds.\n */\nexport interface Expr<R, Src extends string = string> {\n readonly [exprBrand]: ExprBrand<R, Src>;\n eq(value: R | ExprLike<R> | undefined): SqlCondition;\n ne(value: R | ExprLike<R> | undefined): SqlCondition;\n gt(value: R | ExprLike<R> | undefined): SqlCondition;\n gte(value: R | ExprLike<R> | undefined): SqlCondition;\n lt(value: R | ExprLike<R> | undefined): SqlCondition;\n lte(value: R | ExprLike<R> | undefined): SqlCondition;\n // A list subquery may select a nullable column; NULLs in the set never match, so that is fine.\n in(values: readonly R[] | ExprLike<R | null> | undefined): SqlCondition;\n nin(values: readonly R[] | ExprLike<R | null> | undefined): SqlCondition;\n\n /** Prefixes this expression and a space to a raw predicate; write .is`IS NULL`, not .is`NULL`. */\n is(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition;\n\n /** `count(x)::int`; `count(a.id)` is `count(*)` for the FROM table, and the matched-row count for a left-joined one. */\n count(): Expr<number, never>;\n countDistinct(): Expr<number, never>;\n sum(this: Expr<number | null, Src>): Expr<number | null, Src>;\n avg(this: Expr<number | null, Src>): Expr<number | null, Src>;\n min(): Expr<R | null, Src>;\n max(): Expr<R | null, Src>;\n /** PG keeps element NULLs (a left-joined empty group aggregates as `[null]`), and zero rows aggregate as NULL. */\n arrayAgg(options?: ArrayAggOptions): Expr<R[] | null, Src>;\n stringAgg(this: Expr<string | null, Src>, delimiter: string): Expr<string | null, Src>;\n coalesce(fallback: NonNullable<R>): Expr<NonNullable<R>, never>;\n}\n\n/**\n * A join entry: the join kind is the key, the joined source is the value, plus `on`. `inner?: never` /\n * `left?: never` keep an entry to one kind (the `SqlCondition` `and`/`or` trick).\n *\n * `on` is required. A join is pruned when nothing references it anymore, not by an `undefined` ON;\n * `keep: true` pins a join that would otherwise prune, i.e. an inner join used as an existence filter,\n * the way em.find's `keepAliases` does. It is a boolean so callers can pass a flag.\n *\n * Declared here (not `query.ts`) so the relation join factories in `Tables.ts` (i.e. `a.books.as(b)`) can\n * return them without importing `query.ts`; `query.ts` re-constrains `A` to its `QuerySource`.\n */\nexport interface InnerJoin<A, C = SqlCondition> {\n readonly inner: A;\n readonly left?: never;\n readonly on: C;\n readonly keep?: boolean;\n}\n\nexport interface LeftJoin<A, C = SqlCondition> {\n readonly left: A;\n readonly inner?: never;\n readonly on: C;\n readonly keep?: boolean;\n}\n\n/** SQL plus its `?` bindings plus the SQL aliases it references, i.e. for join pruning. */\nexport interface SqlFragment {\n sql: string;\n bindings: any[];\n refs: string[];\n}\n\n/**\n * What an expression needs from the query it is generating SQL for: the SQL alias assigned to each\n * source, and a way to turn nested conditions into SQL (which needs `ConditionBuilder`, so it lives in `query.ts`).\n */\nexport interface ExprContext {\n /** Returns the SQL alias for a table's `TableMgmt` or a subquery handle, searching enclosing queries. */\n aliasFor(handle: object): string;\n /** Turns a user-facing condition into SQL; `undefined` if it pruned away entirely. */\n conditionToSql(cond: QueryCondition): SqlFragment | undefined;\n}\n\nexport function isExpr(value: unknown): value is ExprLike<any> {\n return typeof value === \"object\" && value !== null && exprBrand in value;\n}\n\n/** Every `Expr` is a `BaseExpr` at runtime; this cast keeps `isExpr` a plain type guard so unions narrow. */\nexport function asNode(expr: ExprLike<any>): BaseExpr {\n return expr as any as BaseExpr;\n}\n\nexport const deferredSym: unique symbol = Symbol(\"joist.deferredCondition\");\n\n/**\n * A condition whose SQL depends on aliases that are only known once the query is parsed, i.e.\n * `bookStats.bookCount.gt(1)` or `bs.authorId.eq(a.id)`.\n *\n * It is shaped like a `RawCondition` with a SQL brand so it can sit in any `SqlCondition`; `resolveDeferredConditions`\n * snapshots `condition`, `bindings`, and `aliases` before the filter is parsed. Domain alias conditions\n * use a separate protocol in the `em.find` parser.\n */\nexport interface DeferredCondition extends RawCondition, PredicateBrand<\"sql\"> {\n [deferredSym]: (ctx: ExprContext) => RawCondition;\n}\n\nexport function isDeferredCondition(cond: unknown): cond is DeferredCondition {\n return typeof cond === \"object\" && cond !== null && deferredSym in cond;\n}\n\n/** Creates a `DeferredCondition` that generates its SQL with `fn` once the query's aliases are known. */\nexport function deferredCondition(fn: (ctx: ExprContext) => SqlFragment): DeferredCondition {\n const cond: DeferredCondition = brandPredicate(\n {\n kind: \"raw\",\n aliases: [],\n condition: \"<unresolved>\",\n bindings: [],\n pruneable: false,\n [deferredSym]: (ctx: ExprContext): RawCondition => {\n const { sql, bindings, refs } = fn(ctx);\n return { ...cond, condition: sql, bindings, aliases: refs };\n },\n },\n \"sql\",\n );\n return cond;\n}\n\n/**\n * Resolve each condition occurrence and snapshot it before resolving the next one. A nested subquery\n * may reuse the same condition under another alias; it must not overwrite this occurrence's SQL.\n */\nexport function resolveDeferredConditions(\n cond: ConditionInput | undefined,\n ctx: ExprContext,\n): ConditionInput | undefined {\n if (cond === undefined || cond === null) return cond;\n if (isDeferredCondition(cond)) {\n return cond[deferredSym](ctx);\n } else if (\"and\" in cond && cond.and) {\n return { ...cond, and: cond.and.map((c) => resolveDeferredConditions(c, ctx)) };\n } else if (\"or\" in cond && cond.or) {\n return { ...cond, or: cond.or.map((c) => resolveDeferredConditions(c, ctx)) };\n }\n return cond;\n}\n\n/** Concatenates SQL fragments with `sep`, keeping bindings and refs in order. */\nexport function joinFragments(parts: SqlFragment[], sep: string): SqlFragment {\n return {\n sql: parts.map((p) => p.sql).join(sep),\n bindings: parts.flatMap((p) => p.bindings),\n refs: parts.flatMap((p) => p.refs),\n };\n}\n\n/**\n * The methods every expression shares. Subclasses provide `toSql`, and usually `decode`/`encode`.\n *\n * Table columns can override comparisons to apply column-specific conversions. Domain aliases do not\n * implement this protocol.\n */\nexport abstract class BaseExpr {\n readonly [exprBrand]: any = this;\n\n /** Produces this expression's SQL so it can be embedded in a larger expression, i.e. a subquery gets parens. */\n abstract toSql(ctx: ExprContext): SqlFragment;\n\n /** Only an actual scalar/IN subquery exposes its selected expression, not an ordinary ID expression. */\n get subquerySelect(): BaseExpr | undefined {\n return undefined;\n }\n\n /** Known SQL representation and logical domain; raw SQL and unmodeled refs remain unknown. */\n get outputType(): TypeInfo | undefined {\n return undefined;\n }\n\n /** Physical SQL nullability; undefined means unknown, not a NOT NULL guarantee. */\n get sqlNullable(): boolean | undefined {\n return undefined;\n }\n\n /** The source of a direct column reference, whose value becomes NULL under an unmatched LEFT join. */\n get sqlSource(): object | undefined {\n return undefined;\n }\n\n /** Produces the SQL without the outer parens a subquery normally gets; only differs for subqueries. */\n toSqlBare(ctx: ExprContext): SqlFragment {\n return this.toSql(ctx);\n }\n\n /** Converts a result-set value into the domain value, i.e. an int into a tagged id. */\n decode(value: unknown): unknown {\n return value;\n }\n\n /** Converts a domain value into the database value, i.e. a tagged id into an int, for bindings. */\n encode(value: unknown): unknown {\n return value;\n }\n\n eq(value: unknown): SqlCondition {\n return this.compare(\"=\", value);\n }\n\n ne(value: unknown): SqlCondition {\n return this.compare(\"!=\", value);\n }\n\n gt(value: unknown): SqlCondition {\n return this.compare(\">\", value);\n }\n\n gte(value: unknown): SqlCondition {\n return this.compare(\">=\", value);\n }\n\n lt(value: unknown): SqlCondition {\n return this.compare(\"<\", value);\n }\n\n lte(value: unknown): SqlCondition {\n return this.compare(\"<=\", value);\n }\n\n in(values: unknown): SqlCondition {\n return this.inList(\"IN\", values);\n }\n\n nin(values: unknown): SqlCondition {\n return this.inList(\"NOT IN\", values);\n }\n\n /** Prefixes this expression to a SQL template, retaining bindings and referenced aliases. */\n is(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition {\n const suffix = new TemplateExpr(strings, values);\n return deferredCondition((ctx) => joinFragments([this.toSql(ctx), suffix.toSql(ctx)], \" \"));\n }\n\n count(): Expr<number, never> {\n return new FnExpr(\"count\", [this], {\n suffix: \"::int\",\n decode: decodeNumber,\n encode: identity,\n outputType: { dbType: \"int4\", domain: Number, arrayElementSafe: true },\n }) as any;\n }\n\n countDistinct(): Expr<number, never> {\n return new FnExpr(\"count\", [this], {\n prefix: \"DISTINCT \",\n suffix: \"::int\",\n decode: decodeNumber,\n encode: identity,\n outputType: { dbType: \"int4\", domain: Number, arrayElementSafe: true },\n }) as any;\n }\n\n sum(): Expr<number | null, any> {\n return new FnExpr(\"sum\", [this], {\n decode: decodeNumber,\n encode: identity,\n outputType: numericAggregateOutputType(\"sum\", this.outputType),\n }) as any;\n }\n\n avg(): Expr<number | null, any> {\n return new FnExpr(\"avg\", [this], {\n decode: decodeNumber,\n encode: identity,\n outputType: numericAggregateOutputType(\"avg\", this.outputType),\n }) as any;\n }\n\n min(): Expr<any, any> {\n return new FnExpr(\"min\", [this], {\n decode: (v) => this.decode(v),\n outputType: minMaxOutputType(this.outputType),\n }) as any;\n }\n\n max(): Expr<any, any> {\n return new FnExpr(\"max\", [this], {\n decode: (v) => this.decode(v),\n outputType: minMaxOutputType(this.outputType),\n }) as any;\n }\n\n arrayAgg(options?: ArrayAggOptions): Expr<any, any> {\n // Values are arrays while the argument encodes/decodes *elements*, i.e. a `.coalesce([\"b:1\"])`\n // fallback must encode each tagged id, not hand the whole array to the id column's encoder\n return new FnExpr(\"array_agg\", [this], {\n prefix: options?.distinct ? \"DISTINCT \" : undefined,\n aggregate: options,\n decode: (v) => (Array.isArray(v) ? v.map((e) => this.decode(e)) : v),\n encode: (v) => (Array.isArray(v) ? v.map((e) => this.encode(e)) : v),\n outputType: arrayOutputType(this.outputType),\n }) as any;\n }\n\n stringAgg(delimiter: string): Expr<string | null, any> {\n return new FnExpr(\"string_agg\", [this, new BindingExpr(delimiter)], {\n outputType:\n this.outputType?.domain === String ? { dbType: \"text\", domain: String, arrayElementSafe: true } : undefined,\n }) as any;\n }\n\n coalesce(fallback: unknown): Expr<any, never> {\n return new FnExpr(\"coalesce\", [this, new BindingExpr(this.encode(fallback))], {\n decode: (v) => this.decode(v),\n outputType: this.outputType,\n }) as any;\n }\n\n /** `this op value`, where `value` may be `undefined` (pruned), `null`, another expression, or a literal. */\n protected compare(op: string, value: unknown): SqlCondition {\n if (value === undefined) return skipCondition;\n if (value === null) {\n const not = op === \"=\" ? \"\" : op === \"!=\" ? \"NOT \" : fail(`Cannot compare ${op} to null`);\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { ...left, sql: `${left.sql} IS ${not}NULL` };\n });\n }\n if (isExpr(value)) {\n return deferredCondition((ctx) => joinFragments([this.toSql(ctx), asNode(value).toSql(ctx)], ` ${op} `));\n }\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { sql: `${left.sql} ${op} ?`, bindings: [...left.bindings, this.encode(value)], refs: left.refs };\n });\n }\n\n /** `this IN (subquery)` or `this = ANY(?)` for a list; `NOT IN` / `!= ALL(?)` for `nin`. */\n protected inList(op: \"IN\" | \"NOT IN\", values: unknown): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) {\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n const right = asNode(values).toSqlBare(ctx);\n return joinFragments([left, { ...right, sql: `(${right.sql})` }], ` ${op} `);\n });\n }\n if (!Array.isArray(values)) fail(`Expected an array or subquery for ${op}, got ${values}`);\n const fn = op === \"IN\" ? \"= ANY(?)\" : \"!= ALL(?)\";\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return {\n sql: `${left.sql} ${fn}`,\n bindings: [...left.bindings, values.map((v) => this.encode(v))],\n refs: left.refs,\n };\n });\n }\n}\n\n/**\n * A SQL function applied to expressions, i.e. `count(a.\"id\")::int` or `coalesce(bs.\"n\", ?)`.\n *\n * By default decoding is identity and encoding follows the first argument. Callers explicitly supply\n * a decoder and output type when needed (`max(a.id)` is still an id); numeric aggregates supply their\n * own decoder/encoder, since `count(a.id)` is a number, not an id. Unknown functions have no output type.\n */\nexport class FnExpr extends BaseExpr {\n constructor(\n private name: string,\n private args: BaseExpr[],\n private opts: {\n prefix?: string;\n suffix?: string;\n decode?: (value: unknown) => unknown;\n encode?: (value: unknown) => unknown;\n outputType?: TypeInfo;\n aggregate?: ArrayAggOptions;\n },\n ) {\n super();\n }\n\n get outputType(): TypeInfo | undefined {\n return this.opts.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n switch (this.name) {\n case \"count\":\n return false;\n case \"sum\":\n case \"avg\":\n case \"min\":\n case \"max\":\n case \"array_agg\":\n case \"string_agg\":\n return true;\n case \"coalesce\":\n // Only the fallback is independent of an outer query's LEFT joins.\n return this.args[1]?.sqlNullable === false ? false : undefined;\n default:\n return undefined;\n }\n }\n\n /**\n * Renders function arguments, aggregate ordering, and the filter in SQL binding order.\n * Keep references from all three so aggregate-only joins are retained.\n */\n toSql(ctx: ExprContext): SqlFragment {\n const args = joinFragments(\n this.args.map((a) => a.toSql(ctx)),\n \", \",\n );\n const ordering = joinFragments(\n (this.opts.aggregate?.orderBy ?? []).flatMap((entry) => {\n if (entry === undefined) return [];\n const fragment = orderByToSql(entry, ctx);\n return fragment ? [fragment] : [];\n }),\n \", \",\n );\n const filter = this.opts.aggregate?.filter;\n const condition = filter === undefined ? undefined : ctx.conditionToSql(filter);\n return {\n sql: `${this.name}(${this.opts.prefix ?? \"\"}${args.sql}${ordering.sql ? ` ORDER BY ${ordering.sql}` : \"\"})${condition ? ` FILTER (WHERE ${condition.sql})` : \"\"}${this.opts.suffix ?? \"\"}`,\n bindings: [...args.bindings, ...ordering.bindings, ...(condition?.bindings ?? [])],\n refs: [...args.refs, ...ordering.refs, ...(condition?.refs ?? [])],\n };\n }\n\n decode(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n return this.opts.decode ? this.opts.decode(value) : value;\n }\n\n encode(value: unknown): unknown {\n return this.opts.encode ? this.opts.encode(value) : this.args[0].encode(value);\n }\n}\n\n/** A bound literal, i.e. the `?` in `coalesce(x, ?)`. */\nexport class BindingExpr extends BaseExpr {\n constructor(private value: unknown) {\n super();\n }\n\n get sqlNullable(): boolean {\n return this.value === null || this.value === undefined;\n }\n\n toSql(): SqlFragment {\n return { sql: \"?\", bindings: [this.value], refs: [] };\n }\n}\n\n/** An unmodeled column on a known source, i.e. `sql.ref(a, \"ts_search\")`; untracked at the type level. */\nexport class RefExpr extends BaseExpr {\n constructor(\n private handle: object,\n private column: string,\n ) {\n super();\n }\n\n get sqlSource(): object {\n return this.handle;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.handle);\n // safeKq for both halves: sql.ref takes user strings, and a subquery alias is its `as` name\n return { sql: `${safeKq(alias)}.${safeKq(this.column)}`, bindings: [], refs: [alias] };\n }\n}\n\n/**\n * A `sql` tagged template.\n *\n * For an Author table `a` assigned the SQL alias `a1`:\n *\n * ```ts\n * sql`${a.age} * 2` // Expression: a1.age * 2\n * sql`${a.age.gte(18)}` // Condition: (a1.age >= ?), bindings [18]\n * sql`${\"Alice\"}` // Value: ?, bindings [\"Alice\"]\n * ```\n */\nexport class TemplateExpr extends BaseExpr {\n constructor(\n private strings: TemplateStringsArray,\n private values: unknown[],\n ) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const parts: SqlFragment[] = [];\n this.strings.forEach((s, i) => {\n parts.push({ sql: s, bindings: [], refs: [] });\n if (i < this.values.length) parts.push(interpolationToSql(this.values[i], ctx));\n });\n return joinFragments(parts, \"\");\n }\n}\n\n/** Turns one `${...}` of a `sql` template into SQL: an expression, a condition, or a bound value. */\nexport function interpolationToSql(value: unknown, ctx: ExprContext): SqlFragment {\n if (isExpr(value)) {\n return asNode(value).toSql(ctx);\n } else if (isConditionLike(value)) {\n return ctx.conditionToSql(value as SqlCondition) ?? { sql: \"true\", bindings: [], refs: [] };\n } else {\n return { sql: \"?\", bindings: [value], refs: [] };\n }\n}\n\n/** True for the user-facing condition shapes: `{ and }`, `{ or }`, `ColumnCondition`, `RawCondition`. */\nexport function isConditionLike(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as any;\n return \"and\" in v || \"or\" in v || v.kind === \"column\" || v.kind === \"raw\" || v.kind === \"exists\";\n}\n\n/**\n * Resolves the SQL result type of supported numeric aggregates; other overloads remain unknown.\n *\n * I.e. `a.age.sum()` has `dbType: \"int8\"` and Number conversion, while `a.age` has `dbType: \"int4\"`\n * and identity conversion. Their number domains agree, but SQL types reject a union in either order.\n */\nfunction numericAggregateOutputType(name: \"sum\" | \"avg\", outputType: TypeInfo | undefined): TypeInfo | undefined {\n switch (outputType?.dbType) {\n case \"int2\":\n case \"int4\":\n return { dbType: name === \"sum\" ? \"int8\" : \"numeric\", domain: Number, arrayElementSafe: true };\n case \"int8\":\n case \"numeric\":\n return { dbType: \"numeric\", domain: Number, arrayElementSafe: true };\n case \"float4\":\n return { dbType: name === \"sum\" ? \"float4\" : \"float8\", domain: Number, arrayElementSafe: true };\n case \"float8\":\n return { dbType: \"float8\", domain: Number, arrayElementSafe: true };\n default:\n return undefined;\n }\n}\n\n/** Only known MIN/MAX overloads have predictable output types; varchar/name use the text overload. */\nfunction minMaxOutputType(outputType: TypeInfo | undefined): TypeInfo | undefined {\n switch (outputType?.dbType) {\n case \"varchar\":\n case \"name\":\n return { ...outputType, dbType: \"text\" };\n case \"int2\":\n case \"int4\":\n case \"int8\":\n case \"numeric\":\n case \"float4\":\n case \"float8\":\n case \"text\":\n case \"bpchar\":\n case \"date\":\n case \"time\":\n case \"timetz\":\n case \"timestamp\":\n case \"timestamptz\":\n case \"interval\":\n case \"money\":\n case \"inet\":\n return outputType;\n default:\n return undefined;\n }\n}\n\n/** Decodes `count`/`sum`/`avg` results, which Postgres returns as strings for bigint/numeric. */\nfunction decodeNumber(value: unknown): unknown {\n return typeof value === \"string\" ? Number(value) : value;\n}\n\n/** Renders an expression order for either a query or an aggregate, or prunes an undefined order. */\nexport function orderByToSql(o: ExpressionOrderBy, ctx: ExprContext): SqlFragment | undefined {\n if (!(o.sort instanceof BaseExpr)) {\n return fail(\"orderBy must be an expression, i.e. a table column, aggregate, sql`...`, or scalar query(...)\");\n }\n if (Object.keys(o).some((key) => key !== \"sort\" && key !== \"order\" && key !== \"nulls\")) {\n return fail(\"Expression orderBy entries only accept sort, order, and nulls\");\n }\n if (o.order === undefined) return undefined;\n if (o.order !== \"ASC\" && o.order !== \"DESC\") {\n return fail(`Invalid orderBy direction '${o.order}'`);\n }\n // `nulls` is interpolated into the SQL, so never trust it, i.e. it might cross an `any` boundary\n if (o.nulls !== undefined && o.nulls !== \"first\" && o.nulls !== \"last\") {\n return fail(`Invalid orderBy nulls '${o.nulls}'`);\n }\n const fragment = o.sort.toSql(ctx);\n const nulls = o.nulls ? ` NULLS ${o.nulls.toUpperCase()}` : \"\";\n return { ...fragment, sql: `${fragment.sql} ${o.order}${nulls}` };\n}\n\nfunction identity(value: unknown): unknown {\n return value;\n}\n\nfunction fail(message: string): never {\n throw new Error(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,YAA2B,OAAO,YAAY;AA6H3D,SAAgB,OAAO,OAAwC;CAC7D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;AACrE;;AAGA,SAAgB,OAAO,MAA+B;CACpD,OAAO;AACT;AAEA,MAAa,cAA6B,OAAO,yBAAyB;AAc1E,SAAgB,oBAAoB,MAA0C;CAC5E,OAAO,OAAO,SAAS,YAAY,SAAS,QAAQ,eAAe;AACrE;;AAGA,SAAgB,kBAAkB,IAA0D;CAC1F,MAAM,OAA0B,eAC9B;EACE,MAAM;EACN,SAAS,CAAC;EACV,WAAW;EACX,UAAU,CAAC;EACX,WAAW;GACV,eAAe,QAAmC;GACjD,MAAM,EAAE,KAAK,UAAU,SAAS,GAAG,GAAG;GACtC,OAAO;IAAE,GAAG;IAAM,WAAW;IAAK;IAAU,SAAS;GAAK;EAC5D;CACF,GACA,KACF;CACA,OAAO;AACT;;;;;AAMA,SAAgB,0BACd,MACA,KAC4B;CAC5B,IAAI,SAAS,KAAA,KAAa,SAAS,MAAM,OAAO;CAChD,IAAI,oBAAoB,IAAI,GAC1B,OAAO,KAAK,YAAY,CAAC,GAAG;MACvB,IAAI,SAAS,QAAQ,KAAK,KAC/B,OAAO;EAAE,GAAG;EAAM,KAAK,KAAK,IAAI,KAAK,MAAM,0BAA0B,GAAG,GAAG,CAAC;CAAE;MACzE,IAAI,QAAQ,QAAQ,KAAK,IAC9B,OAAO;EAAE,GAAG;EAAM,IAAI,KAAK,GAAG,KAAK,MAAM,0BAA0B,GAAG,GAAG,CAAC;CAAE;CAE9E,OAAO;AACT;;AAGA,SAAgB,cAAc,OAAsB,KAA0B;CAC5E,OAAO;EACL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AAM,GAAG;CACjC,MAAM,QAAQ,EAAE,QAAQ,UAAU,EAAE,MAAM,YAAY,MAAM;CAC5D,OAAO;EAAE,GAAG;EAAU,KAAK,GAAG,SAAS,IAAI,GAAG,EAAE,QAAQ;CAAQ;AAClE;AAEA,SAAS,SAAS,OAAyB;CACzC,OAAO;AACT;AAEA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,OAAO;AACzB"}
|
|
1
|
+
{"version":3,"file":"Expr.js","names":[],"sources":["../../../src/queries/sql/Expr.ts"],"sourcesContent":["import type { EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type ConditionInput, type PredicateBrand, type SqlCondition, brandPredicate } from \"src/queries/conditions.ts\";\nimport type { RawCondition } from \"src/queries/parsedConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport { safeKq } from \"src/queries/sql/keywords.ts\";\nimport type { ExpressionOrderBy, QueryCondition } from \"src/queries/sql/query.ts\";\nimport { type TypeInfo, arrayOutputType } from \"src/serde/TypeInfo.ts\";\n\n/**\n * The shared expression protocol for `em.query`.\n *\n * Table columns (`a.first_name`), aggregates (`b.id.count()`), `sql` templates, subquery columns\n * (`bookStats.bookCount`), and scalar subqueries all implement it, so any of them can appear in\n * `select`, `where`, `groupBy`, `having`, `orderBy`, and inside other expressions.\n *\n * This module is a leaf on purpose: `Tables.ts` extends `BaseExpr` at load time, so nothing here may\n * import (at runtime) a module that leads back to `Tables.ts`. Anything that needs metadata, alias\n * binding, or SQL generation for conditions is reached through the `ExprContext` the query parser passes in.\n */\n\nexport const exprBrand: unique symbol = Symbol(\"joist.expr\");\n/** Carries a column's table property name so array selects can infer and decode named result rows. */\nexport const selectKeyBrand: unique symbol = Symbol(\"joist.selectKey\");\n\n/**\n * Phantom type information carried by every `Expr`.\n *\n * `R` is the decoded result type.\n *\n * `Src` is the expression's *source key*: the type-level identity of the table it reads from. An entity\n * table's key is its type name (`table(Author)` gives `\"Author\"`) or the explicit name in\n * `table(Author, \"m\")`; a subquery's key is its `as: \"book_stats\"`, or the shared sentinel `\"?\"` when it\n * has no `as`. Exactly two questions are asked of a source key, and nothing else:\n *\n * - `MaybeNull` asks \"is my source key among the LEFT-joined sources in this query's join list?\" If yes,\n * the value can be `null`.\n * - `CheckScope` asks \"is my source key among `from` + `join` at all?\" If no, the query reads from a\n * table it never joined.\n *\n * Two special keys opt out of both questions:\n *\n * - `Expr<number, never>` reads from nothing that can be left-joined away, i.e. `b.id.count()`\n * - `Expr<number, string>` (the default) is untracked, i.e. a table whose entity type is not statically known\n */\nexport interface ExprBrand<R, Src extends string> {\n readonly __result: R;\n readonly __source: Src;\n}\n\n/**\n * \"Any expression whose result is `R`\", checked by brand alone.\n *\n * Method parameters use this instead of `Expr<R>` so that `Expr` stays covariant in `R`: checking\n * `Expr<AuthorId>` against `Expr<AuthorId | null>` then only compares the phantom `__result`, not every\n * method's parameter list (which would make `Expr` invariant, and break `select: b.author_id` dispatch and\n * polymorphic joins).\n */\nexport type ExprLike<R> = { readonly [exprBrand]: ExprBrand<R, any> };\n\n/** Controls which values enter an array aggregate and their order within the array. */\nexport interface ArrayAggOptions {\n distinct?: boolean;\n /** With DISTINCT, PostgreSQL requires ordering expressions to match the aggregate argument. */\n orderBy?: readonly (ExpressionOrderBy | undefined)[];\n /** Undefined conditions are pruned, as in a query's where clause. */\n filter?: QueryCondition;\n}\n\n/**\n * A typed SQL expression: a table column, an aggregate, a `sql` template, or a scalar subquery.\n *\n * Conditions and SQL functions are methods, so they need no import. Aggregates keep `Src` so scope\n * checking still sees through `bs.x.max()`; `count` is source-less because `count(x)` is 0, not null,\n * when `x`'s table is left-joined away; `coalesce` drops `Src` on purpose, since its whole job is to\n * remove the nullability a left join adds.\n */\nexport interface Expr<R, Src extends string = string> {\n readonly [exprBrand]: ExprBrand<R, Src>;\n eq(value: R | ExprLike<R> | undefined): SqlCondition;\n ne(value: R | ExprLike<R> | undefined): SqlCondition;\n gt(value: R | ExprLike<R> | undefined): SqlCondition;\n gte(value: R | ExprLike<R> | undefined): SqlCondition;\n lt(value: R | ExprLike<R> | undefined): SqlCondition;\n lte(value: R | ExprLike<R> | undefined): SqlCondition;\n // A list subquery may select a nullable column; NULLs in the set never match, so that is fine.\n in(values: readonly R[] | ExprLike<R | null> | undefined): SqlCondition;\n nin(values: readonly R[] | ExprLike<R | null> | undefined): SqlCondition;\n\n /** Prefixes this expression and a space to a raw predicate; write .is`IS NULL`, not .is`NULL`. */\n is(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition;\n\n /** Orders by this expression in ascending order. */\n asc(): ExpressionOrderBy;\n /** Orders by this expression in descending order. */\n desc(): ExpressionOrderBy;\n\n /** `count(x)::int`; `count(a.id)` is `count(*)` for the FROM table, and the matched-row count for a left-joined one. */\n count(): Expr<number, never>;\n countDistinct(): Expr<number, never>;\n sum(this: Expr<number | null, Src>): Expr<number | null, Src>;\n avg(this: Expr<number | null, Src>): Expr<number | null, Src>;\n min(): Expr<R | null, Src>;\n max(): Expr<R | null, Src>;\n /** PG keeps element NULLs (a left-joined empty group aggregates as `[null]`), and zero rows aggregate as NULL. */\n arrayAgg(options?: ArrayAggOptions): Expr<R[] | null, Src>;\n stringAgg(this: Expr<string | null, Src>, delimiter: string): Expr<string | null, Src>;\n coalesce(fallback: NonNullable<R>): Expr<NonNullable<R>, never>;\n}\n\n/**\n * A join entry: the join kind is the key, the joined source is the value, plus `on`. `inner?: never` /\n * `left?: never` keep an entry to one kind (the `SqlCondition` `and`/`or` trick).\n *\n * `on` is required. A join is pruned when nothing references it anymore, not by an `undefined` ON;\n * `keep: true` pins a join that would otherwise prune, i.e. an inner join used as an existence filter,\n * the way em.find's `keepAliases` does. It is a boolean so callers can pass a flag.\n *\n * Declared here (not `query.ts`) so the relation join factories in `Tables.ts` (i.e. `a.books.as(b)`) can\n * return them without importing `query.ts`; `query.ts` re-constrains `A` to its `QuerySource`.\n */\nexport interface InnerJoin<A, C = SqlCondition> {\n readonly inner: A;\n readonly left?: never;\n readonly on: C;\n readonly keep?: boolean;\n}\n\nexport interface LeftJoin<A, C = SqlCondition> {\n readonly left: A;\n readonly inner?: never;\n readonly on: C;\n readonly keep?: boolean;\n}\n\n/** SQL plus its `?` bindings plus the SQL aliases it references, i.e. for join pruning. */\nexport interface SqlFragment {\n sql: string;\n bindings: any[];\n refs: string[];\n}\n\n/**\n * What an expression needs from the query it is generating SQL for: the SQL alias assigned to each\n * source, and a way to turn nested conditions into SQL (which needs `ConditionBuilder`, so it lives in `query.ts`).\n */\nexport interface ExprContext {\n /** Returns the SQL alias for a table's `TableMgmt` or a subquery handle, searching enclosing queries. */\n aliasFor(handle: object): string;\n /** Turns a user-facing condition into SQL; `undefined` if it pruned away entirely. */\n conditionToSql(cond: QueryCondition): SqlFragment | undefined;\n}\n\nexport function isExpr(value: unknown): value is ExprLike<any> {\n return typeof value === \"object\" && value !== null && exprBrand in value;\n}\n\n/** Every `Expr` is a `BaseExpr` at runtime; this cast keeps `isExpr` a plain type guard so unions narrow. */\nexport function asNode(expr: ExprLike<any>): BaseExpr {\n return expr as any as BaseExpr;\n}\n\nexport const deferredSym: unique symbol = Symbol(\"joist.deferredCondition\");\n\n/**\n * A condition whose SQL depends on aliases that are only known once the query is parsed, i.e.\n * `bookStats.bookCount.gt(1)` or `bs.authorId.eq(a.id)`.\n *\n * It is shaped like a `RawCondition` with a SQL brand so it can sit in any `SqlCondition`; `resolveDeferredConditions`\n * snapshots `condition`, `bindings`, and `aliases` before the filter is parsed. Domain alias conditions\n * use a separate protocol in the `em.find` parser.\n */\nexport interface DeferredCondition extends RawCondition, PredicateBrand<\"sql\"> {\n [deferredSym]: (ctx: ExprContext) => RawCondition;\n}\n\nexport function isDeferredCondition(cond: unknown): cond is DeferredCondition {\n return typeof cond === \"object\" && cond !== null && deferredSym in cond;\n}\n\n/** Creates a `DeferredCondition` that generates its SQL with `fn` once the query's aliases are known. */\nexport function deferredCondition(fn: (ctx: ExprContext) => SqlFragment): DeferredCondition {\n const cond: DeferredCondition = brandPredicate(\n {\n kind: \"raw\",\n aliases: [],\n condition: \"<unresolved>\",\n bindings: [],\n pruneable: false,\n [deferredSym]: (ctx: ExprContext): RawCondition => {\n const { sql, bindings, refs } = fn(ctx);\n return { ...cond, condition: sql, bindings, aliases: refs };\n },\n },\n \"sql\",\n );\n return cond;\n}\n\n/**\n * Resolve each condition occurrence and snapshot it before resolving the next one. A nested subquery\n * may reuse the same condition under another alias; it must not overwrite this occurrence's SQL.\n */\nexport function resolveDeferredConditions(\n cond: ConditionInput | undefined,\n ctx: ExprContext,\n): ConditionInput | undefined {\n if (cond === undefined || cond === null) return cond;\n if (isDeferredCondition(cond)) {\n return cond[deferredSym](ctx);\n } else if (\"and\" in cond && cond.and) {\n return { ...cond, and: cond.and.map((c) => resolveDeferredConditions(c, ctx)) };\n } else if (\"or\" in cond && cond.or) {\n return { ...cond, or: cond.or.map((c) => resolveDeferredConditions(c, ctx)) };\n }\n return cond;\n}\n\n/** Concatenates SQL fragments with `sep`, keeping bindings and refs in order. */\nexport function joinFragments(parts: SqlFragment[], sep: string): SqlFragment {\n return {\n sql: parts.map((p) => p.sql).join(sep),\n bindings: parts.flatMap((p) => p.bindings),\n refs: parts.flatMap((p) => p.refs),\n };\n}\n\n/**\n * The methods every expression shares. Subclasses provide `toSql`, and usually `decode`/`encode`.\n *\n * Table columns can override comparisons to apply column-specific conversions. Domain aliases do not\n * implement this protocol.\n */\nexport abstract class BaseExpr {\n readonly [exprBrand]: any = this;\n\n /** Produces this expression's SQL so it can be embedded in a larger expression, i.e. a subquery gets parens. */\n abstract toSql(ctx: ExprContext): SqlFragment;\n\n /** Only an actual scalar/IN subquery exposes its selected expression, not an ordinary ID expression. */\n get subquerySelect(): BaseExpr | undefined {\n return undefined;\n }\n\n /** Known SQL representation and logical domain; raw SQL and unmodeled refs remain unknown. */\n get outputType(): TypeInfo | undefined {\n return undefined;\n }\n\n /** Physical SQL nullability; undefined means unknown, not a NOT NULL guarantee. */\n get sqlNullable(): boolean | undefined {\n return undefined;\n }\n\n /** The source of a direct column reference, whose value becomes NULL under an unmatched LEFT join. */\n get sqlSource(): object | undefined {\n return undefined;\n }\n\n /** Produces the SQL without the outer parens a subquery normally gets; only differs for subqueries. */\n toSqlBare(ctx: ExprContext): SqlFragment {\n return this.toSql(ctx);\n }\n\n /** Converts a result-set value into the domain value, i.e. an int into a tagged id. */\n decode(value: unknown): unknown {\n return value;\n }\n\n /** Converts a domain value into the database value, i.e. a tagged id into an int, for bindings. */\n encode(value: unknown): unknown {\n return value;\n }\n\n eq(value: unknown): SqlCondition {\n return this.compare(\"=\", value);\n }\n\n ne(value: unknown): SqlCondition {\n return this.compare(\"!=\", value);\n }\n\n gt(value: unknown): SqlCondition {\n return this.compare(\">\", value);\n }\n\n gte(value: unknown): SqlCondition {\n return this.compare(\">=\", value);\n }\n\n lt(value: unknown): SqlCondition {\n return this.compare(\"<\", value);\n }\n\n lte(value: unknown): SqlCondition {\n return this.compare(\"<=\", value);\n }\n\n in(values: unknown): SqlCondition {\n return this.inList(\"IN\", values);\n }\n\n nin(values: unknown): SqlCondition {\n return this.inList(\"NOT IN\", values);\n }\n\n /** Prefixes this expression to a SQL template, retaining bindings and referenced aliases. */\n is(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition {\n const suffix = new TemplateExpr(strings, values);\n return deferredCondition((ctx) => joinFragments([this.toSql(ctx), suffix.toSql(ctx)], \" \"));\n }\n\n /** Orders by this expression in ascending order. */\n asc(): ExpressionOrderBy {\n return { sort: this, order: \"ASC\" };\n }\n\n /** Orders by this expression in descending order. */\n desc(): ExpressionOrderBy {\n return { sort: this, order: \"DESC\" };\n }\n\n count(): Expr<number, never> {\n return new FnExpr(\"count\", [this], {\n suffix: \"::int\",\n decode: decodeNumber,\n encode: identity,\n outputType: { dbType: \"int4\", domain: Number, arrayElementSafe: true },\n }) as any;\n }\n\n countDistinct(): Expr<number, never> {\n return new FnExpr(\"count\", [this], {\n prefix: \"DISTINCT \",\n suffix: \"::int\",\n decode: decodeNumber,\n encode: identity,\n outputType: { dbType: \"int4\", domain: Number, arrayElementSafe: true },\n }) as any;\n }\n\n sum(): Expr<number | null, any> {\n return new FnExpr(\"sum\", [this], {\n decode: decodeNumber,\n encode: identity,\n outputType: numericAggregateOutputType(\"sum\", this.outputType),\n }) as any;\n }\n\n avg(): Expr<number | null, any> {\n return new FnExpr(\"avg\", [this], {\n decode: decodeNumber,\n encode: identity,\n outputType: numericAggregateOutputType(\"avg\", this.outputType),\n }) as any;\n }\n\n min(): Expr<any, any> {\n return new FnExpr(\"min\", [this], {\n decode: (v) => this.decode(v),\n outputType: minMaxOutputType(this.outputType),\n }) as any;\n }\n\n max(): Expr<any, any> {\n return new FnExpr(\"max\", [this], {\n decode: (v) => this.decode(v),\n outputType: minMaxOutputType(this.outputType),\n }) as any;\n }\n\n arrayAgg(options?: ArrayAggOptions): Expr<any, any> {\n // Values are arrays while the argument encodes/decodes *elements*, i.e. a `.coalesce([\"b:1\"])`\n // fallback must encode each tagged id, not hand the whole array to the id column's encoder\n return new FnExpr(\"array_agg\", [this], {\n prefix: options?.distinct ? \"DISTINCT \" : undefined,\n aggregate: options,\n decode: (v) => (Array.isArray(v) ? v.map((e) => this.decode(e)) : v),\n encode: (v) => (Array.isArray(v) ? v.map((e) => this.encode(e)) : v),\n outputType: arrayOutputType(this.outputType),\n }) as any;\n }\n\n stringAgg(delimiter: string): Expr<string | null, any> {\n return new FnExpr(\"string_agg\", [this, new BindingExpr(delimiter)], {\n outputType:\n this.outputType?.domain === String ? { dbType: \"text\", domain: String, arrayElementSafe: true } : undefined,\n }) as any;\n }\n\n coalesce(fallback: unknown): Expr<any, never> {\n return new FnExpr(\"coalesce\", [this, new BindingExpr(this.encode(fallback))], {\n decode: (v) => this.decode(v),\n outputType: this.outputType,\n }) as any;\n }\n\n /** `this op value`, where `value` may be `undefined` (pruned), `null`, another expression, or a literal. */\n protected compare(op: string, value: unknown): SqlCondition {\n if (value === undefined) return skipCondition;\n if (value === null) {\n const not = op === \"=\" ? \"\" : op === \"!=\" ? \"NOT \" : fail(`Cannot compare ${op} to null`);\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { ...left, sql: `${left.sql} IS ${not}NULL` };\n });\n }\n if (isExpr(value)) {\n return deferredCondition((ctx) => joinFragments([this.toSql(ctx), asNode(value).toSql(ctx)], ` ${op} `));\n }\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { sql: `${left.sql} ${op} ?`, bindings: [...left.bindings, this.encode(value)], refs: left.refs };\n });\n }\n\n /** `this IN (subquery)` or `this = ANY(?)` for a list; `NOT IN` / `!= ALL(?)` for `nin`. */\n protected inList(op: \"IN\" | \"NOT IN\", values: unknown): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) {\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n const right = asNode(values).toSqlBare(ctx);\n return joinFragments([left, { ...right, sql: `(${right.sql})` }], ` ${op} `);\n });\n }\n if (!Array.isArray(values)) fail(`Expected an array or subquery for ${op}, got ${values}`);\n const fn = op === \"IN\" ? \"= ANY(?)\" : \"!= ALL(?)\";\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return {\n sql: `${left.sql} ${fn}`,\n bindings: [...left.bindings, values.map((v) => this.encode(v))],\n refs: left.refs,\n };\n });\n }\n}\n\n/**\n * A SQL function applied to expressions, i.e. `count(a.\"id\")::int` or `coalesce(bs.\"n\", ?)`.\n *\n * By default decoding is identity and encoding follows the first argument. Callers explicitly supply\n * a decoder and output type when needed (`max(a.id)` is still an id); numeric aggregates supply their\n * own decoder/encoder, since `count(a.id)` is a number, not an id. Unknown functions have no output type.\n */\nexport class FnExpr extends BaseExpr {\n constructor(\n private name: string,\n private args: BaseExpr[],\n private opts: {\n prefix?: string;\n suffix?: string;\n decode?: (value: unknown) => unknown;\n encode?: (value: unknown) => unknown;\n outputType?: TypeInfo;\n aggregate?: ArrayAggOptions;\n },\n ) {\n super();\n }\n\n get outputType(): TypeInfo | undefined {\n return this.opts.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n switch (this.name) {\n case \"count\":\n return false;\n case \"sum\":\n case \"avg\":\n case \"min\":\n case \"max\":\n case \"array_agg\":\n case \"string_agg\":\n return true;\n case \"coalesce\":\n // Only the fallback is independent of an outer query's LEFT joins.\n return this.args[1]?.sqlNullable === false ? false : undefined;\n default:\n return undefined;\n }\n }\n\n /**\n * Renders function arguments, aggregate ordering, and the filter in SQL binding order.\n * Keep references from all three so aggregate-only joins are retained.\n */\n toSql(ctx: ExprContext): SqlFragment {\n const args = joinFragments(\n this.args.map((a) => a.toSql(ctx)),\n \", \",\n );\n const ordering = joinFragments(\n (this.opts.aggregate?.orderBy ?? []).flatMap((entry) => {\n if (entry === undefined) return [];\n const fragment = orderByToSql(entry, ctx);\n return fragment ? [fragment] : [];\n }),\n \", \",\n );\n const filter = this.opts.aggregate?.filter;\n const condition = filter === undefined ? undefined : ctx.conditionToSql(filter);\n return {\n sql: `${this.name}(${this.opts.prefix ?? \"\"}${args.sql}${ordering.sql ? ` ORDER BY ${ordering.sql}` : \"\"})${condition ? ` FILTER (WHERE ${condition.sql})` : \"\"}${this.opts.suffix ?? \"\"}`,\n bindings: [...args.bindings, ...ordering.bindings, ...(condition?.bindings ?? [])],\n refs: [...args.refs, ...ordering.refs, ...(condition?.refs ?? [])],\n };\n }\n\n decode(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n return this.opts.decode ? this.opts.decode(value) : value;\n }\n\n encode(value: unknown): unknown {\n return this.opts.encode ? this.opts.encode(value) : this.args[0].encode(value);\n }\n}\n\n/** A bound literal, i.e. the `?` in `coalesce(x, ?)`. */\nexport class BindingExpr extends BaseExpr {\n constructor(private value: unknown) {\n super();\n }\n\n get sqlNullable(): boolean {\n return this.value === null || this.value === undefined;\n }\n\n toSql(): SqlFragment {\n return { sql: \"?\", bindings: [this.value], refs: [] };\n }\n}\n\n/** An unmodeled column on a known source, i.e. `a.column(\"ts_search\")`. */\nexport class RefExpr extends BaseExpr {\n constructor(\n private handle: object,\n private column: string,\n ) {\n super();\n }\n\n get sqlSource(): object {\n return this.handle;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.handle);\n // safeKq for both halves: an unmodeled column is a user string, and a subquery alias is its `as` name\n return { sql: `${safeKq(alias)}.${safeKq(this.column)}`, bindings: [], refs: [alias] };\n }\n}\n\n/**\n * A `sql` tagged template.\n *\n * For an Author table `a` assigned the SQL alias `a1`:\n *\n * ```ts\n * sql`${a.age} * 2` // Expression: a1.age * 2\n * sql`${a.age.gte(18)}` // Condition: (a1.age >= ?), bindings [18]\n * sql`${\"Alice\"}` // Value: ?, bindings [\"Alice\"]\n * ```\n */\nexport class TemplateExpr extends BaseExpr {\n constructor(\n private strings: TemplateStringsArray,\n private values: unknown[],\n ) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const parts: SqlFragment[] = [];\n this.strings.forEach((s, i) => {\n parts.push({ sql: s, bindings: [], refs: [] });\n if (i < this.values.length) parts.push(interpolationToSql(this.values[i], ctx));\n });\n return joinFragments(parts, \"\");\n }\n}\n\n/** Turns one `${...}` of a `sql` template into SQL: an expression, a condition, or a bound value. */\nexport function interpolationToSql(value: unknown, ctx: ExprContext): SqlFragment {\n if (isExpr(value)) {\n return asNode(value).toSql(ctx);\n } else if (isConditionLike(value)) {\n return ctx.conditionToSql(value as SqlCondition) ?? { sql: \"true\", bindings: [], refs: [] };\n } else {\n return { sql: \"?\", bindings: [value], refs: [] };\n }\n}\n\n/** True for the user-facing condition shapes: `{ and }`, `{ or }`, `ColumnCondition`, `RawCondition`. */\nexport function isConditionLike(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as any;\n return \"and\" in v || \"or\" in v || v.kind === \"column\" || v.kind === \"raw\" || v.kind === \"exists\";\n}\n\n/**\n * Resolves the SQL result type of supported numeric aggregates; other overloads remain unknown.\n *\n * I.e. `a.age.sum()` has `dbType: \"int8\"` and Number conversion, while `a.age` has `dbType: \"int4\"`\n * and identity conversion. Their number domains agree, but SQL types reject a union in either order.\n */\nfunction numericAggregateOutputType(name: \"sum\" | \"avg\", outputType: TypeInfo | undefined): TypeInfo | undefined {\n switch (outputType?.dbType) {\n case \"int2\":\n case \"int4\":\n return { dbType: name === \"sum\" ? \"int8\" : \"numeric\", domain: Number, arrayElementSafe: true };\n case \"int8\":\n case \"numeric\":\n return { dbType: \"numeric\", domain: Number, arrayElementSafe: true };\n case \"float4\":\n return { dbType: name === \"sum\" ? \"float4\" : \"float8\", domain: Number, arrayElementSafe: true };\n case \"float8\":\n return { dbType: \"float8\", domain: Number, arrayElementSafe: true };\n default:\n return undefined;\n }\n}\n\n/** Only known MIN/MAX overloads have predictable output types; varchar/name use the text overload. */\nfunction minMaxOutputType(outputType: TypeInfo | undefined): TypeInfo | undefined {\n switch (outputType?.dbType) {\n case \"varchar\":\n case \"name\":\n return { ...outputType, dbType: \"text\" };\n case \"int2\":\n case \"int4\":\n case \"int8\":\n case \"numeric\":\n case \"float4\":\n case \"float8\":\n case \"text\":\n case \"bpchar\":\n case \"date\":\n case \"time\":\n case \"timetz\":\n case \"timestamp\":\n case \"timestamptz\":\n case \"interval\":\n case \"money\":\n case \"inet\":\n return outputType;\n default:\n return undefined;\n }\n}\n\n/** Decodes `count`/`sum`/`avg` results, which Postgres returns as strings for bigint/numeric. */\nfunction decodeNumber(value: unknown): unknown {\n return typeof value === \"string\" ? Number(value) : value;\n}\n\n/** Renders an expression order for either a query or an aggregate, or prunes an undefined order. */\nexport function orderByToSql(o: ExpressionOrderBy, ctx: ExprContext): SqlFragment | undefined {\n if (!(o.sort instanceof BaseExpr)) {\n return fail(\"orderBy must be an expression, i.e. a table column, aggregate, sql`...`, or scalar query(...)\");\n }\n if (Object.keys(o).some((key) => key !== \"sort\" && key !== \"order\" && key !== \"nulls\")) {\n return fail(\"Expression orderBy entries only accept sort, order, and nulls\");\n }\n if (o.order === undefined) return undefined;\n if (o.order !== \"ASC\" && o.order !== \"DESC\") {\n return fail(`Invalid orderBy direction '${o.order}'`);\n }\n // `nulls` is interpolated into the SQL, so never trust it, i.e. it might cross an `any` boundary\n if (o.nulls !== undefined && o.nulls !== \"first\" && o.nulls !== \"last\") {\n return fail(`Invalid orderBy nulls '${o.nulls}'`);\n }\n const fragment = o.sort.toSql(ctx);\n const nulls = o.nulls ? ` NULLS ${o.nulls.toUpperCase()}` : \"\";\n return { ...fragment, sql: `${fragment.sql} ${o.order}${nulls}` };\n}\n\nfunction identity(value: unknown): unknown {\n return value;\n}\n\nfunction fail(message: string): never {\n throw new Error(message);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,YAA2B,OAAO,YAAY;;AAE3D,MAAa,iBAAgC,OAAO,iBAAiB;AAkIrE,SAAgB,OAAO,OAAwC;CAC7D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;AACrE;;AAGA,SAAgB,OAAO,MAA+B;CACpD,OAAO;AACT;AAEA,MAAa,cAA6B,OAAO,yBAAyB;AAc1E,SAAgB,oBAAoB,MAA0C;CAC5E,OAAO,OAAO,SAAS,YAAY,SAAS,QAAQ,eAAe;AACrE;;AAGA,SAAgB,kBAAkB,IAA0D;CAC1F,MAAM,OAA0B,eAC9B;EACE,MAAM;EACN,SAAS,CAAC;EACV,WAAW;EACX,UAAU,CAAC;EACX,WAAW;GACV,eAAe,QAAmC;GACjD,MAAM,EAAE,KAAK,UAAU,SAAS,GAAG,GAAG;GACtC,OAAO;IAAE,GAAG;IAAM,WAAW;IAAK;IAAU,SAAS;GAAK;EAC5D;CACF,GACA,KACF;CACA,OAAO;AACT;;;;;AAMA,SAAgB,0BACd,MACA,KAC4B;CAC5B,IAAI,SAAS,KAAA,KAAa,SAAS,MAAM,OAAO;CAChD,IAAI,oBAAoB,IAAI,GAC1B,OAAO,KAAK,YAAY,CAAC,GAAG;MACvB,IAAI,SAAS,QAAQ,KAAK,KAC/B,OAAO;EAAE,GAAG;EAAM,KAAK,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CAAC,CAAC,CAAC,MAAM,QAAQ,QAAQ,UAAU,QAAQ,WAAW,QAAQ,OAAO,GACnF,OAAO,KAAK,+DAA+D;CAE7E,IAAI,EAAE,UAAU,KAAA,GAAW,OAAO,KAAA;CAClC,IAAI,EAAE,UAAU,SAAS,EAAE,UAAU,QACnC,OAAO,KAAK,8BAA8B,EAAE,MAAM,EAAE;CAGtD,IAAI,EAAE,UAAU,KAAA,KAAa,EAAE,UAAU,WAAW,EAAE,UAAU,QAC9D,OAAO,KAAK,0BAA0B,EAAE,MAAM,EAAE;CAElD,MAAM,WAAW,EAAE,KAAK,MAAM,GAAG;CACjC,MAAM,QAAQ,EAAE,QAAQ,UAAU,EAAE,MAAM,YAAY,MAAM;CAC5D,OAAO;EAAE,GAAG;EAAU,KAAK,GAAG,SAAS,IAAI,GAAG,EAAE,QAAQ;CAAQ;AAClE;AAEA,SAAS,SAAS,OAAyB;CACzC,OAAO;AACT;AAEA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,OAAO;AACzB"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_utils = require("../../utils.cjs");
|
|
3
|
+
const require_queries_sql_Tables = require("./Tables.cjs");
|
|
4
|
+
const require_Entity = require("../../Entity.cjs");
|
|
5
|
+
//#region src/queries/sql/JoinTree.ts
|
|
6
|
+
/**
|
|
7
|
+
* Walks domain relationship filters into ordinary SQL joins and WHERE predicates.
|
|
8
|
+
* Handles remain query-local; no SQL aliases or caller objects are changed.
|
|
9
|
+
* I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.
|
|
10
|
+
*/
|
|
11
|
+
function compileJoinTree(from, tree) {
|
|
12
|
+
if (!require_queries_sql_Tables.isEntityTable(from)) require_utils.fail("Join trees require an entity table in from");
|
|
13
|
+
const joins = [];
|
|
14
|
+
const conditions = [];
|
|
15
|
+
visitTree(from, tree, joins, conditions, /* @__PURE__ */ new Set([require_queries_sql_Tables.getTableMgmt(from)]));
|
|
16
|
+
return {
|
|
17
|
+
joins,
|
|
18
|
+
condition: { and: conditions }
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Compiles one node, leaving relationship conditions in WHERE rather than ON.
|
|
23
|
+
* Each relationship gets one target handle; reusing a bound handle would merge distinct paths.
|
|
24
|
+
* Owning-reference ID filters stay on the FK, while collection ID filters use the joined primary key.
|
|
25
|
+
*/
|
|
26
|
+
function visitTree(source, tree, joins, conditions, bound) {
|
|
27
|
+
if (!isTreeObject(tree)) require_utils.fail("Expected a join tree object");
|
|
28
|
+
const mgmt = require_queries_sql_Tables.getTableMgmt(source);
|
|
29
|
+
if (tree.as !== void 0 && tree.as !== source) require_utils.fail("Join tree root as must be the same table handle as from");
|
|
30
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
31
|
+
if (key === "as") continue;
|
|
32
|
+
const field = mgmt.meta.allFields[key] ?? require_utils.fail(`Unknown join tree field ${mgmt.meta.type}.${key}`);
|
|
33
|
+
if (!(key in mgmt.meta.fields)) require_utils.fail(`Join trees do not support inherited field ${mgmt.meta.type}.${key}`);
|
|
34
|
+
if (field.kind === "poly") require_utils.fail(`Join trees do not support polymorphic field ${mgmt.meta.type}.${key}`);
|
|
35
|
+
if ([
|
|
36
|
+
"m2o",
|
|
37
|
+
"o2m",
|
|
38
|
+
"lo2m",
|
|
39
|
+
"m2m",
|
|
40
|
+
"o2o"
|
|
41
|
+
].includes(field.kind)) {
|
|
42
|
+
if (value === void 0) continue;
|
|
43
|
+
if (field.kind === "m2o" && !isTreeObject(value)) {
|
|
44
|
+
conditions.push(require_queries_sql_Tables.tableWhere(mgmt, { [key]: value }));
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (field.kind === "m2o" && isTreeObject(value) && Object.hasOwn(value, "ne")) {
|
|
48
|
+
conditions.push(require_queries_sql_Tables.tableWhere(mgmt, { [key]: value }));
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (!("otherMetadata" in field)) require_utils.fail(`Unsupported join tree field ${mgmt.meta.type}.${key}`);
|
|
52
|
+
const meta = field.otherMetadata();
|
|
53
|
+
const target = isTreeObject(value) && value.as !== void 0 ? value.as : require_queries_sql_Tables.newTableProxy(meta.cstr);
|
|
54
|
+
if (!require_queries_sql_Tables.isEntityTable(target) || require_queries_sql_Tables.getTableMgmt(target).meta !== meta) require_utils.fail(`Join tree binding for ${mgmt.meta.type}.${key} must be a ${meta.type} table`);
|
|
55
|
+
const identity = require_queries_sql_Tables.getTableMgmt(target);
|
|
56
|
+
if (bound.has(identity)) require_utils.fail(`Join tree table ${meta.type} is bound more than once; create a separate table handle`);
|
|
57
|
+
bound.add(identity);
|
|
58
|
+
const relation = source[key];
|
|
59
|
+
joins.push(relation.as(target));
|
|
60
|
+
if (isTreeObject(value) && !Object.hasOwn(value, "ne")) visitTree(target, value, joins, conditions, bound);
|
|
61
|
+
else conditions.push(require_queries_sql_Tables.tableEntityWhere(identity, value));
|
|
62
|
+
} else conditions.push(require_queries_sql_Tables.tableWhere(mgmt, { [key]: value }));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Separates nested relationship objects from entity, ID, and list filters. */
|
|
66
|
+
function isTreeObject(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !require_Entity.isEntity(value);
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
exports.compileJoinTree = compileJoinTree;
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=JoinTree.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JoinTree.cjs","names":["isEntityTable","getTableMgmt","fail","tableWhere","newTableProxy","tableEntityWhere","isEntity"],"sources":["../../../src/queries/sql/JoinTree.ts"],"sourcesContent":["import { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { InnerJoin, LeftJoin } from \"src/queries/sql/Expr.ts\";\nimport type { QueryCondition, QueryJoin, QueryJoinInput } from \"src/queries/sql/query.ts\";\nimport {\n type CollectionJoin,\n type TableFilter,\n type TableFor,\n getTableMgmt,\n isEntityTable,\n newTableProxy,\n tableEntityWhere,\n tableWhere,\n} from \"src/queries/sql/Tables.ts\";\nimport type { FieldsOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** Domain filters and optional table bindings for one node in a relationship tree. */\nexport type JoinTree<T extends Entity> = Omit<TableFilter<T>, RelationNames<T>> & {\n readonly as?: TableFor<T>;\n} & {\n readonly [K in RelationNames<T>]?: FieldsOf<T>[K] extends {\n kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\";\n type: infer U extends Entity;\n }\n ? JoinTree<U> | (K extends keyof TableFilter<T> ? TableFilter<T>[K] : JoinedEntityFilter<U>)\n : never;\n};\n\n/**\n * Filters entities, e.g. `{ books: \"b:1\" }` filters Book.id to 1.\n *\n * Adapted from `em.find`s EntityFilter, rather than a direct copy:\n *\n * - Keeps entity/ID, list, boolean, and `ne` filters, but omits scopes, find aliases, nested objects, and logical groups.\n * - JoinTree supplies nested objects and table bindings separately.\n * - Lists can mix entities and IDs, unlike EntityFilter's separate entity[] and ID[] alternatives.\n * - Null is always allowed because these relationships use LEFT joins.\n * - undefined comes from JoinTree's optional relationship keys.\n */\ntype JoinedEntityFilter<T extends Entity> =\n | IdOf<T>\n | T\n | readonly (IdOf<T> | T)[]\n | boolean\n | null\n | { ne: IdOf<T> | T | null | undefined };\n\ntype RelationNames<T extends Entity> = {\n [K in keyof FieldsOf<T>]: FieldsOf<T>[K] extends { kind: \"m2o\" | \"poly\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\" }\n ? K\n : never;\n}[keyof FieldsOf<T>];\n\n/**\n * Validates a join tree against the entity in `from`, preserving its exact table bindings.\n *\n * I.e. given:\n *\n * ```ts\n * const [a, b] = tables(Author, Book);\n * em.query({\n * from: a,\n * join: { books: { as: b, title: \"One\" } },\n * select: { title: b.title },\n * });\n * // F = typeof a\n * // J = { books: { as: typeof b; title: string } }\n * ```\n *\n * We:\n *\n * - Infer `T = Author` from `F`,\n * - Validate `books` against `Author`,\n * - Validate `title` against `Book`, and\n * - Retain `typeof b` for result typing.\n */\nexport type CheckJoinInput<F, J> =\n // If J accepts the entire list-or-tree union, its annotation erased the join shape.\n // Queries with no join infer [] and use the list branch below.\n QueryJoinInput extends J\n ? { join?: \"join was typed too generically; use `satisfies Query` instead of `: Query`\" }\n : // If J is an array, then it's a QueryJoinList and we can return unknown\n [J] extends [readonly unknown[]]\n ? unknown\n : F extends TableFor<infer T extends Entity>\n ? // Validate domain filters and bindings, including extra keys on variables and nested trees.\n { join?: JoinTree<T> & CheckTree<T, J> }\n : // This incompatible type reports why a tree can't start at a non-entity source.\n { join?: \"join trees require an entity table in from\" };\n\n/**\n * Determines which tables a join tree binds and whether each uses an INNER or LEFT join.\n *\n * Query result types use these entries to identify available tables and columns that can be null.\n *\n * I.e. Author.books.author uses LEFT joins for both Book and its Author because an Author may have no Books.\n */\nexport type TreeEntries<T extends Entity, J, Nullable extends boolean = false> =\n // If every string is valid keyof J, then we've lost our literal type (i.e. as const) and were\n // passed an opaque type like Record<string, unknown> that doesn't expose its specific relationship\n // keys or table bindings to collect, so just return never.\n string extends keyof J\n ? never\n : // If J has an `as` key, it might be the general JoinTree<T> type, which we check for in the next ternary.\n // If J doesn't have `as`, it can't be the general `JoinTree<T>` so we can jump straight to TreeEntriesImpl.\n \"as\" extends keyof J\n ? // If `JoinTree<T> extends J`, then we again have a board type. CheckTree will reject this input, but\n // here we stop instead of following every relationship in the domain graph.\n JoinTree<T> extends J\n ? never\n : TreeEntriesImpl<T, J, Nullable>\n : TreeEntriesImpl<T, J, Nullable>;\n\n/** Collects join entries from the relationship keys supplied in this tree node. */\ntype TreeEntriesImpl<T extends Entity, J, Nullable extends boolean> = {\n [K in keyof J & keyof FieldsOf<T>]: FieldsOf<T>[K] extends {\n kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\";\n type: infer U extends Entity;\n }\n ? TreeNodeJoins<\n U,\n Exclude<J[K], undefined>,\n Nullable extends true ? true : FieldsOf<T>[K] extends { kind: \"m2o\"; nullable: never } ? false : true\n >\n : never;\n}[keyof J & keyof FieldsOf<T>];\n\n/**\n * Collects the join entries for this node's table binding and its nested relationships.\n *\n * An `as` binding contributes a LeftJoin or InnerJoin according to Nullable.\n * Without a binding, only nested relationship entries are included; entity, ID, and list filters add none.\n */\ntype TreeNodeJoins<T extends Entity, J, Nullable extends boolean> =\n // If `J extends Entity | unknown[]`, then it's a leaf entity/id filter, so stop recursing\n J extends Entity | readonly unknown[]\n ? never\n : // If `J extends object`, look for an `as` binding and nested relationships.\n // If `J extends object` is false, this is a scalar filter like \"b:1\" in `{ books: \"b:1\" }` and we stop here.\n J extends object\n ?\n | (J extends { readonly as: infer A extends TableFor<T> }\n ? Nullable extends true\n ? LeftJoin<A>\n : InnerJoin<A>\n : never)\n | TreeEntries<T, J, Nullable>\n : never;\n\n/** Rejects broad tree annotations before checking their supplied keys and values. */\ntype CheckTree<T extends Entity, J> =\n // An entity or a list of entities/IDs is a filter value, so don't check its properties as tree keys.\n J extends Entity | readonly unknown[]\n ? unknown\n : \"as\" extends keyof J\n ? JoinTree<T> extends J\n ? \"join tree bindings were typed too generically; use `satisfies JoinTree<T>` instead of `: JoinTree<T>`\"\n : CheckTreeKeys<T, J>\n : CheckTreeKeys<T, J>;\n\n/** Rejects unknown tree keys, including extra properties on objects stored in variables. */\ntype CheckTreeKeys<T extends Entity, J> = [Exclude<keyof J, keyof JoinTree<T>>] extends [never]\n ? {\n [K in keyof J]: K extends \"as\"\n ? J[K] extends TableFor<T> | undefined\n ? unknown\n : never\n : K extends keyof JoinTree<T>\n ? K extends keyof FieldsOf<T>\n ? FieldsOf<T>[K] extends { kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\"; type: infer U extends Entity }\n ? (J[K] extends JoinTree<T>[K] ? unknown : never) & CheckRelationTree<U, J[K]>\n : J[K] extends JoinTree<T>[K]\n ? unknown\n : never\n : unknown\n : never;\n // Report the error on the tree object; intersecting a message with a boolean field would collapse to never.\n }\n : `unknown join tree field '${Exclude<keyof J, keyof JoinTree<T>> & string}'`;\n\n/** Checks each optional relationship alternative without treating entities or exclusion filters as trees. */\ntype CheckRelationTree<T extends Entity, J> = J extends object\n ? \"ne\" extends keyof J\n ? unknown\n : CheckTree<T, J>\n : unknown;\n\n/**\n * Walks domain relationship filters into ordinary SQL joins and WHERE predicates.\n * Handles remain query-local; no SQL aliases or caller objects are changed.\n * I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.\n */\nexport function compileJoinTree(from: unknown, tree: unknown): { joins: QueryJoin[]; condition: QueryCondition } {\n if (!isEntityTable(from)) fail(\"Join trees require an entity table in from\");\n const joins: QueryJoin[] = [];\n const conditions: QueryCondition[] = [];\n const bound = new Set<object>([getTableMgmt(from)]);\n visitTree(from, tree, joins, conditions, bound);\n return { joins, condition: { and: conditions } };\n}\n\n/**\n * Compiles one node, leaving relationship conditions in WHERE rather than ON.\n * Each relationship gets one target handle; reusing a bound handle would merge distinct paths.\n * Owning-reference ID filters stay on the FK, while collection ID filters use the joined primary key.\n */\nfunction visitTree(\n source: TableFor<Entity>,\n tree: unknown,\n joins: QueryJoin[],\n conditions: QueryCondition[],\n bound: Set<object>,\n): void {\n if (!isTreeObject(tree)) fail(\"Expected a join tree object\");\n const mgmt = getTableMgmt(source);\n if (tree.as !== undefined && tree.as !== source) fail(\"Join tree root as must be the same table handle as from\");\n for (const [key, value] of Object.entries(tree)) {\n if (key === \"as\") continue;\n const field = mgmt.meta.allFields[key] ?? fail(`Unknown join tree field ${mgmt.meta.type}.${key}`);\n if (!(key in mgmt.meta.fields)) fail(`Join trees do not support inherited field ${mgmt.meta.type}.${key}`);\n if (field.kind === \"poly\") fail(`Join trees do not support polymorphic field ${mgmt.meta.type}.${key}`);\n if ([\"m2o\", \"o2m\", \"lo2m\", \"m2m\", \"o2o\"].includes(field.kind)) {\n if (value === undefined) continue;\n if (field.kind === \"m2o\" && !isTreeObject(value)) {\n // Avoid joining the related table; add the condition directly to the FK column.\n conditions.push(tableWhere(mgmt, { [key]: value }));\n continue;\n }\n if (field.kind === \"m2o\" && isTreeObject(value) && Object.hasOwn(value, \"ne\")) {\n // Exclusion filters also apply directly to the FK column without joining the related table.\n conditions.push(tableWhere(mgmt, { [key]: value }));\n continue;\n }\n // The field-kind check above establishes the relationship metadata and factory shape.\n if (!(\"otherMetadata\" in field)) fail(`Unsupported join tree field ${mgmt.meta.type}.${key}`);\n const meta = field.otherMetadata();\n const target = isTreeObject(value) && value.as !== undefined ? value.as : newTableProxy(meta.cstr);\n if (!isEntityTable(target) || getTableMgmt(target).meta !== meta) {\n fail(`Join tree binding for ${mgmt.meta.type}.${key} must be a ${meta.type} table`);\n }\n const identity = getTableMgmt(target);\n if (bound.has(identity))\n fail(`Join tree table ${meta.type} is bound more than once; create a separate table handle`);\n bound.add(identity);\n const relation = (source as unknown as Record<string, CollectionJoin<Entity>>)[key];\n joins.push(relation.as(target));\n // Recurse into nested relationship filters, e.g. `{ books: { title: \"One\" } }`.\n // A `{ ne: ... }` object instead filters the joined entity's ID, so handle it like an ID or entity value.\n // We don't have to handle other keys like `gt`, etc. b/c we know this is an entity filter, not a value filter.\n if (isTreeObject(value) && !Object.hasOwn(value, \"ne\")) {\n visitTree(target, value, joins, conditions, bound);\n } else {\n conditions.push(tableEntityWhere(identity, value));\n }\n } else {\n conditions.push(tableWhere(mgmt, { [key]: value }));\n }\n }\n}\n\n/** Separates nested relationship objects from entity, ID, and list filters. */\nfunction isTreeObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !isEntity(value);\n}\n"],"mappings":";;;;;;;;;;AAiMA,SAAgB,gBAAgB,MAAe,MAAkE;CAC/G,IAAI,C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C,CAAC;IAClD;GACF;GAEA,IAAI,EAAE,mBAAmB,QAAQ,cAAA,KAAK,+BAA+B,KAAK,KAAK,KAAK,GAAG,KAAK;GAC5F,MAAM,OAAO,MAAM,cAAc;GACjC,MAAM,SAAS,aAAa,KAAK,KAAK,MAAM,OAAO,KAAA,IAAY,MAAM,KAAKC,2BAAAA,cAAc,KAAK,IAAI;GACjG,IAAI,CAACJ,2BAAAA,cAAc,MAAM,KAAKC,2BAAAA,aAAa,MAAM,CAAC,CAAC,SAAS,MAC1D,cAAA,KAAK,yBAAyB,KAAK,KAAK,KAAK,GAAG,IAAI,aAAa,KAAK,KAAK,OAAO;GAEpF,MAAM,WAAWA,2BAAAA,aAAa,MAAM;GACpC,IAAI,MAAM,IAAI,QAAQ,GACpB,cAAA,KAAK,mBAAmB,KAAK,KAAK,yDAAyD;GAC7F,MAAM,IAAI,QAAQ;GAClB,MAAM,WAAY,OAA6D;GAC/E,MAAM,KAAK,SAAS,GAAG,MAAM,CAAC;GAI9B,IAAI,aAAa,KAAK,KAAK,CAAC,OAAO,OAAO,OAAO,IAAI,GACnD,UAAU,QAAQ,OAAO,OAAO,YAAY,KAAK;QAEjD,WAAW,KAAKI,2BAAAA,iBAAiB,UAAU,KAAK,CAAC;EAErD,OACE,WAAW,KAAKF,2BAAAA,WAAW,MAAM,GAAG,MAAM,MAAM,CAAC,CAAC;CAEtD;AACF;;AAGA,SAAS,aAAa,OAAkD;CACtE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,CAACG,eAAAA,SAAS,KAAK;AAChG"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { FieldsOf } from "../../typeMap.cjs";
|
|
2
|
+
import { TableFilter, TableFor } from "./Tables.cjs";
|
|
3
|
+
import { QueryCondition, QueryJoin, QueryJoinInput } from "./query.cjs";
|
|
4
|
+
import { InnerJoin, LeftJoin } from "./Expr.cjs";
|
|
5
|
+
import { IdOf } from "../../EntityManager.cjs";
|
|
6
|
+
import { Entity } from "../../Entity.cjs";
|
|
7
|
+
//#region src/queries/sql/JoinTree.d.ts
|
|
8
|
+
/** Domain filters and optional table bindings for one node in a relationship tree. */
|
|
9
|
+
type JoinTree<T extends Entity> = Omit<TableFilter<T>, RelationNames<T>> & {
|
|
10
|
+
readonly as?: TableFor<T>;
|
|
11
|
+
} & { readonly [K in RelationNames<T>]?: FieldsOf<T>[K] extends {
|
|
12
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
13
|
+
type: infer U extends Entity;
|
|
14
|
+
} ? JoinTree<U> | (K extends keyof TableFilter<T> ? TableFilter<T>[K] : JoinedEntityFilter<U>) : never; };
|
|
15
|
+
/**
|
|
16
|
+
* Filters entities, e.g. `{ books: "b:1" }` filters Book.id to 1.
|
|
17
|
+
*
|
|
18
|
+
* Adapted from `em.find`s EntityFilter, rather than a direct copy:
|
|
19
|
+
*
|
|
20
|
+
* - Keeps entity/ID, list, boolean, and `ne` filters, but omits scopes, find aliases, nested objects, and logical groups.
|
|
21
|
+
* - JoinTree supplies nested objects and table bindings separately.
|
|
22
|
+
* - Lists can mix entities and IDs, unlike EntityFilter's separate entity[] and ID[] alternatives.
|
|
23
|
+
* - Null is always allowed because these relationships use LEFT joins.
|
|
24
|
+
* - undefined comes from JoinTree's optional relationship keys.
|
|
25
|
+
*/
|
|
26
|
+
type JoinedEntityFilter<T extends Entity> = IdOf<T> | T | readonly (IdOf<T> | T)[] | boolean | null | {
|
|
27
|
+
ne: IdOf<T> | T | null | undefined;
|
|
28
|
+
};
|
|
29
|
+
type RelationNames<T extends Entity> = { [K in keyof FieldsOf<T>]: FieldsOf<T>[K] extends {
|
|
30
|
+
kind: "m2o" | "poly" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
31
|
+
} ? K : never; }[keyof FieldsOf<T>];
|
|
32
|
+
/**
|
|
33
|
+
* Validates a join tree against the entity in `from`, preserving its exact table bindings.
|
|
34
|
+
*
|
|
35
|
+
* I.e. given:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* const [a, b] = tables(Author, Book);
|
|
39
|
+
* em.query({
|
|
40
|
+
* from: a,
|
|
41
|
+
* join: { books: { as: b, title: "One" } },
|
|
42
|
+
* select: { title: b.title },
|
|
43
|
+
* });
|
|
44
|
+
* // F = typeof a
|
|
45
|
+
* // J = { books: { as: typeof b; title: string } }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* We:
|
|
49
|
+
*
|
|
50
|
+
* - Infer `T = Author` from `F`,
|
|
51
|
+
* - Validate `books` against `Author`,
|
|
52
|
+
* - Validate `title` against `Book`, and
|
|
53
|
+
* - Retain `typeof b` for result typing.
|
|
54
|
+
*/
|
|
55
|
+
type CheckJoinInput<F, J> = QueryJoinInput extends J ? {
|
|
56
|
+
join?: "join was typed too generically; use `satisfies Query` instead of `: Query`";
|
|
57
|
+
} : [J] extends [readonly unknown[]] ? unknown : F extends TableFor<infer T extends Entity> ? {
|
|
58
|
+
join?: JoinTree<T> & CheckTree<T, J>;
|
|
59
|
+
} : {
|
|
60
|
+
join?: "join trees require an entity table in from";
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Determines which tables a join tree binds and whether each uses an INNER or LEFT join.
|
|
64
|
+
*
|
|
65
|
+
* Query result types use these entries to identify available tables and columns that can be null.
|
|
66
|
+
*
|
|
67
|
+
* I.e. Author.books.author uses LEFT joins for both Book and its Author because an Author may have no Books.
|
|
68
|
+
*/
|
|
69
|
+
type TreeEntries<T extends Entity, J, Nullable extends boolean = false> = string extends keyof J ? never : "as" extends keyof J ? JoinTree<T> extends J ? never : TreeEntriesImpl<T, J, Nullable> : TreeEntriesImpl<T, J, Nullable>;
|
|
70
|
+
/** Collects join entries from the relationship keys supplied in this tree node. */
|
|
71
|
+
type TreeEntriesImpl<T extends Entity, J, Nullable extends boolean> = { [K in keyof J & keyof FieldsOf<T>]: FieldsOf<T>[K] extends {
|
|
72
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
73
|
+
type: infer U extends Entity;
|
|
74
|
+
} ? TreeNodeJoins<U, Exclude<J[K], undefined>, Nullable extends true ? true : FieldsOf<T>[K] extends {
|
|
75
|
+
kind: "m2o";
|
|
76
|
+
nullable: never;
|
|
77
|
+
} ? false : true> : never; }[keyof J & keyof FieldsOf<T>];
|
|
78
|
+
/**
|
|
79
|
+
* Collects the join entries for this node's table binding and its nested relationships.
|
|
80
|
+
*
|
|
81
|
+
* An `as` binding contributes a LeftJoin or InnerJoin according to Nullable.
|
|
82
|
+
* Without a binding, only nested relationship entries are included; entity, ID, and list filters add none.
|
|
83
|
+
*/
|
|
84
|
+
type TreeNodeJoins<T extends Entity, J, Nullable extends boolean> = J extends Entity | readonly unknown[] ? never : J extends object ? (J extends {
|
|
85
|
+
readonly as: infer A extends TableFor<T>;
|
|
86
|
+
} ? Nullable extends true ? LeftJoin<A> : InnerJoin<A> : never) | TreeEntries<T, J, Nullable> : never;
|
|
87
|
+
/** Rejects broad tree annotations before checking their supplied keys and values. */
|
|
88
|
+
type CheckTree<T extends Entity, J> = J extends Entity | readonly unknown[] ? unknown : "as" extends keyof J ? JoinTree<T> extends J ? "join tree bindings were typed too generically; use `satisfies JoinTree<T>` instead of `: JoinTree<T>`" : CheckTreeKeys<T, J> : CheckTreeKeys<T, J>;
|
|
89
|
+
/** Rejects unknown tree keys, including extra properties on objects stored in variables. */
|
|
90
|
+
type CheckTreeKeys<T extends Entity, J> = [Exclude<keyof J, keyof JoinTree<T>>] extends [never] ? { [K in keyof J]: K extends "as" ? J[K] extends TableFor<T> | undefined ? unknown : never : K extends keyof JoinTree<T> ? K extends keyof FieldsOf<T> ? FieldsOf<T>[K] extends {
|
|
91
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
92
|
+
type: infer U extends Entity;
|
|
93
|
+
} ? (J[K] extends JoinTree<T>[K] ? unknown : never) & CheckRelationTree<U, J[K]> : J[K] extends JoinTree<T>[K] ? unknown : never : unknown : never; } : `unknown join tree field '${Exclude<keyof J, keyof JoinTree<T>> & string}'`;
|
|
94
|
+
/** Checks each optional relationship alternative without treating entities or exclusion filters as trees. */
|
|
95
|
+
type CheckRelationTree<T extends Entity, J> = J extends object ? "ne" extends keyof J ? unknown : CheckTree<T, J> : unknown;
|
|
96
|
+
/**
|
|
97
|
+
* Walks domain relationship filters into ordinary SQL joins and WHERE predicates.
|
|
98
|
+
* Handles remain query-local; no SQL aliases or caller objects are changed.
|
|
99
|
+
* I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.
|
|
100
|
+
*/
|
|
101
|
+
declare function compileJoinTree(from: unknown, tree: unknown): {
|
|
102
|
+
joins: QueryJoin[];
|
|
103
|
+
condition: QueryCondition;
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
export { CheckJoinInput, JoinTree, TreeEntries, compileJoinTree };
|
|
107
|
+
//# sourceMappingURL=JoinTree.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JoinTree.d.cts","names":[],"sources":["../../../src/queries/sql/JoinTree.ts"],"mappings":";;;;;;;;KAkBY,SAAS,UAAU,UAAU,KAAK,YAAY,IAAI,cAAc;WACjE,KAAK,SAAS;gBAEb,KAAK,cAAc,MAAM,SAAS,GAAG;EAC7C;EACA,YAAY,UAAU;IAEpB,SAAS,MAAM,gBAAgB,YAAY,KAAK,YAAY,GAAG,KAAK,mBAAmB;;;;;;;;;;;;KAexF,mBAAmB,UAAU,UAC9B,KAAK,KACL,cACU,KAAK,KAAK;EAGlB,IAAI,KAAK,KAAK;;KAEf,cAAc,UAAU,aAC1B,WAAW,SAAS,KAAK,SAAS,GAAG;EAAa;IAC/C,mBAEE,SAAS;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,eAAe,GAAG,KAG5B,uBAAuB;EACjB;KAED,4CAEC,UAAU,eAAe,UAAU;EAE/B,OAAO,SAAS,KAAK,UAAU,GAAG;;EAElC;;;;;;;;;KASA,YAAY,UAAU,QAAQ,GAAG,yDAItB,+BAIE,IAGjB,SAAS,WAAW,YAElB,gBAAgB,GAAG,GAAG,YACxB,gBAAgB,GAAG,GAAG;;KAGzB,gBAAgB,UAAU,QAAQ,GAAG,+BACvC,WAAW,UAAU,SAAS,KAAK,SAAS,GAAG;EAC9C;EACA,YAAY,UAAU;IAEpB,cACE,GACA,QAAQ,EAAE,gBACV,+BAA+B,SAAS,GAAG;EAAa;EAAa;mCAGrE,UAAU,SAAS;;;;;;;KAQtB,cAAc,UAAU,QAAQ,GAAG,4BAEtC,UAAU,sCAIN,oBAEO;WAAqB,UAAU,UAAU,SAAS;IAC/C,wBACE,SAAS,KACT,UAAU,cAEhB,YAAY,GAAG,GAAG;;KAIzB,UAAU,UAAU,QAAQ,KAE/B,UAAU,2DAEa,IACjB,SAAS,WAAW,8GAElB,cAAc,GAAG,KACnB,cAAc,GAAG;;KAGpB,cAAc,UAAU,QAAQ,MAAM,cAAc,SAAS,SAAS,0BAEpE,WAAW,IAAI,iBACZ,EAAE,WAAW,SAAS,mCAGtB,gBAAgB,SAAS,KACvB,gBAAgB,SAAS,KACvB,SAAS,GAAG;EAAa;EAA8C,YAAY,UAAU;KAC1F,EAAE,WAAW,SAAS,GAAG,wBAAwB,kBAAkB,GAAG,EAAE,MACzE,EAAE,WAAW,SAAS,GAAG,wEAOT,cAAc,SAAS,SAAS;;KAG3D,kBAAkB,UAAU,QAAQ,KAAK,sCACvB,cAEjB,UAAU,GAAG;;;;;;iBAQH,gBAAgB,eAAe;EAAkB,OAAO;EAAa,WAAW"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { FieldsOf } from "../../typeMap.mjs";
|
|
2
|
+
import { TableFilter, TableFor } from "./Tables.mjs";
|
|
3
|
+
import { QueryCondition, QueryJoin, QueryJoinInput } from "./query.mjs";
|
|
4
|
+
import { InnerJoin, LeftJoin } from "./Expr.mjs";
|
|
5
|
+
import { IdOf } from "../../EntityManager.mjs";
|
|
6
|
+
import { Entity } from "../../Entity.mjs";
|
|
7
|
+
//#region src/queries/sql/JoinTree.d.ts
|
|
8
|
+
/** Domain filters and optional table bindings for one node in a relationship tree. */
|
|
9
|
+
type JoinTree<T extends Entity> = Omit<TableFilter<T>, RelationNames<T>> & {
|
|
10
|
+
readonly as?: TableFor<T>;
|
|
11
|
+
} & { readonly [K in RelationNames<T>]?: FieldsOf<T>[K] extends {
|
|
12
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
13
|
+
type: infer U extends Entity;
|
|
14
|
+
} ? JoinTree<U> | (K extends keyof TableFilter<T> ? TableFilter<T>[K] : JoinedEntityFilter<U>) : never; };
|
|
15
|
+
/**
|
|
16
|
+
* Filters entities, e.g. `{ books: "b:1" }` filters Book.id to 1.
|
|
17
|
+
*
|
|
18
|
+
* Adapted from `em.find`s EntityFilter, rather than a direct copy:
|
|
19
|
+
*
|
|
20
|
+
* - Keeps entity/ID, list, boolean, and `ne` filters, but omits scopes, find aliases, nested objects, and logical groups.
|
|
21
|
+
* - JoinTree supplies nested objects and table bindings separately.
|
|
22
|
+
* - Lists can mix entities and IDs, unlike EntityFilter's separate entity[] and ID[] alternatives.
|
|
23
|
+
* - Null is always allowed because these relationships use LEFT joins.
|
|
24
|
+
* - undefined comes from JoinTree's optional relationship keys.
|
|
25
|
+
*/
|
|
26
|
+
type JoinedEntityFilter<T extends Entity> = IdOf<T> | T | readonly (IdOf<T> | T)[] | boolean | null | {
|
|
27
|
+
ne: IdOf<T> | T | null | undefined;
|
|
28
|
+
};
|
|
29
|
+
type RelationNames<T extends Entity> = { [K in keyof FieldsOf<T>]: FieldsOf<T>[K] extends {
|
|
30
|
+
kind: "m2o" | "poly" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
31
|
+
} ? K : never; }[keyof FieldsOf<T>];
|
|
32
|
+
/**
|
|
33
|
+
* Validates a join tree against the entity in `from`, preserving its exact table bindings.
|
|
34
|
+
*
|
|
35
|
+
* I.e. given:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* const [a, b] = tables(Author, Book);
|
|
39
|
+
* em.query({
|
|
40
|
+
* from: a,
|
|
41
|
+
* join: { books: { as: b, title: "One" } },
|
|
42
|
+
* select: { title: b.title },
|
|
43
|
+
* });
|
|
44
|
+
* // F = typeof a
|
|
45
|
+
* // J = { books: { as: typeof b; title: string } }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* We:
|
|
49
|
+
*
|
|
50
|
+
* - Infer `T = Author` from `F`,
|
|
51
|
+
* - Validate `books` against `Author`,
|
|
52
|
+
* - Validate `title` against `Book`, and
|
|
53
|
+
* - Retain `typeof b` for result typing.
|
|
54
|
+
*/
|
|
55
|
+
type CheckJoinInput<F, J> = QueryJoinInput extends J ? {
|
|
56
|
+
join?: "join was typed too generically; use `satisfies Query` instead of `: Query`";
|
|
57
|
+
} : [J] extends [readonly unknown[]] ? unknown : F extends TableFor<infer T extends Entity> ? {
|
|
58
|
+
join?: JoinTree<T> & CheckTree<T, J>;
|
|
59
|
+
} : {
|
|
60
|
+
join?: "join trees require an entity table in from";
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Determines which tables a join tree binds and whether each uses an INNER or LEFT join.
|
|
64
|
+
*
|
|
65
|
+
* Query result types use these entries to identify available tables and columns that can be null.
|
|
66
|
+
*
|
|
67
|
+
* I.e. Author.books.author uses LEFT joins for both Book and its Author because an Author may have no Books.
|
|
68
|
+
*/
|
|
69
|
+
type TreeEntries<T extends Entity, J, Nullable extends boolean = false> = string extends keyof J ? never : "as" extends keyof J ? JoinTree<T> extends J ? never : TreeEntriesImpl<T, J, Nullable> : TreeEntriesImpl<T, J, Nullable>;
|
|
70
|
+
/** Collects join entries from the relationship keys supplied in this tree node. */
|
|
71
|
+
type TreeEntriesImpl<T extends Entity, J, Nullable extends boolean> = { [K in keyof J & keyof FieldsOf<T>]: FieldsOf<T>[K] extends {
|
|
72
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
73
|
+
type: infer U extends Entity;
|
|
74
|
+
} ? TreeNodeJoins<U, Exclude<J[K], undefined>, Nullable extends true ? true : FieldsOf<T>[K] extends {
|
|
75
|
+
kind: "m2o";
|
|
76
|
+
nullable: never;
|
|
77
|
+
} ? false : true> : never; }[keyof J & keyof FieldsOf<T>];
|
|
78
|
+
/**
|
|
79
|
+
* Collects the join entries for this node's table binding and its nested relationships.
|
|
80
|
+
*
|
|
81
|
+
* An `as` binding contributes a LeftJoin or InnerJoin according to Nullable.
|
|
82
|
+
* Without a binding, only nested relationship entries are included; entity, ID, and list filters add none.
|
|
83
|
+
*/
|
|
84
|
+
type TreeNodeJoins<T extends Entity, J, Nullable extends boolean> = J extends Entity | readonly unknown[] ? never : J extends object ? (J extends {
|
|
85
|
+
readonly as: infer A extends TableFor<T>;
|
|
86
|
+
} ? Nullable extends true ? LeftJoin<A> : InnerJoin<A> : never) | TreeEntries<T, J, Nullable> : never;
|
|
87
|
+
/** Rejects broad tree annotations before checking their supplied keys and values. */
|
|
88
|
+
type CheckTree<T extends Entity, J> = J extends Entity | readonly unknown[] ? unknown : "as" extends keyof J ? JoinTree<T> extends J ? "join tree bindings were typed too generically; use `satisfies JoinTree<T>` instead of `: JoinTree<T>`" : CheckTreeKeys<T, J> : CheckTreeKeys<T, J>;
|
|
89
|
+
/** Rejects unknown tree keys, including extra properties on objects stored in variables. */
|
|
90
|
+
type CheckTreeKeys<T extends Entity, J> = [Exclude<keyof J, keyof JoinTree<T>>] extends [never] ? { [K in keyof J]: K extends "as" ? J[K] extends TableFor<T> | undefined ? unknown : never : K extends keyof JoinTree<T> ? K extends keyof FieldsOf<T> ? FieldsOf<T>[K] extends {
|
|
91
|
+
kind: "m2o" | "o2m" | "lo2m" | "m2m" | "o2o";
|
|
92
|
+
type: infer U extends Entity;
|
|
93
|
+
} ? (J[K] extends JoinTree<T>[K] ? unknown : never) & CheckRelationTree<U, J[K]> : J[K] extends JoinTree<T>[K] ? unknown : never : unknown : never; } : `unknown join tree field '${Exclude<keyof J, keyof JoinTree<T>> & string}'`;
|
|
94
|
+
/** Checks each optional relationship alternative without treating entities or exclusion filters as trees. */
|
|
95
|
+
type CheckRelationTree<T extends Entity, J> = J extends object ? "ne" extends keyof J ? unknown : CheckTree<T, J> : unknown;
|
|
96
|
+
/**
|
|
97
|
+
* Walks domain relationship filters into ordinary SQL joins and WHERE predicates.
|
|
98
|
+
* Handles remain query-local; no SQL aliases or caller objects are changed.
|
|
99
|
+
* I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.
|
|
100
|
+
*/
|
|
101
|
+
declare function compileJoinTree(from: unknown, tree: unknown): {
|
|
102
|
+
joins: QueryJoin[];
|
|
103
|
+
condition: QueryCondition;
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
export { CheckJoinInput, JoinTree, TreeEntries, compileJoinTree };
|
|
107
|
+
//# sourceMappingURL=JoinTree.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JoinTree.d.mts","names":[],"sources":["../../../src/queries/sql/JoinTree.ts"],"mappings":";;;;;;;;KAkBY,SAAS,UAAU,UAAU,KAAK,YAAY,IAAI,cAAc;WACjE,KAAK,SAAS;gBAEb,KAAK,cAAc,MAAM,SAAS,GAAG;EAC7C;EACA,YAAY,UAAU;IAEpB,SAAS,MAAM,gBAAgB,YAAY,KAAK,YAAY,GAAG,KAAK,mBAAmB;;;;;;;;;;;;KAexF,mBAAmB,UAAU,UAC9B,KAAK,KACL,cACU,KAAK,KAAK;EAGlB,IAAI,KAAK,KAAK;;KAEf,cAAc,UAAU,aAC1B,WAAW,SAAS,KAAK,SAAS,GAAG;EAAa;IAC/C,mBAEE,SAAS;;;;;;;;;;;;;;;;;;;;;;;;KAyBL,eAAe,GAAG,KAG5B,uBAAuB;EACjB;KAED,4CAEC,UAAU,eAAe,UAAU;EAE/B,OAAO,SAAS,KAAK,UAAU,GAAG;;EAElC;;;;;;;;;KASA,YAAY,UAAU,QAAQ,GAAG,yDAItB,+BAIE,IAGjB,SAAS,WAAW,YAElB,gBAAgB,GAAG,GAAG,YACxB,gBAAgB,GAAG,GAAG;;KAGzB,gBAAgB,UAAU,QAAQ,GAAG,+BACvC,WAAW,UAAU,SAAS,KAAK,SAAS,GAAG;EAC9C;EACA,YAAY,UAAU;IAEpB,cACE,GACA,QAAQ,EAAE,gBACV,+BAA+B,SAAS,GAAG;EAAa;EAAa;mCAGrE,UAAU,SAAS;;;;;;;KAQtB,cAAc,UAAU,QAAQ,GAAG,4BAEtC,UAAU,sCAIN,oBAEO;WAAqB,UAAU,UAAU,SAAS;IAC/C,wBACE,SAAS,KACT,UAAU,cAEhB,YAAY,GAAG,GAAG;;KAIzB,UAAU,UAAU,QAAQ,KAE/B,UAAU,2DAEa,IACjB,SAAS,WAAW,8GAElB,cAAc,GAAG,KACnB,cAAc,GAAG;;KAGpB,cAAc,UAAU,QAAQ,MAAM,cAAc,SAAS,SAAS,0BAEpE,WAAW,IAAI,iBACZ,EAAE,WAAW,SAAS,mCAGtB,gBAAgB,SAAS,KACvB,gBAAgB,SAAS,KACvB,SAAS,GAAG;EAAa;EAA8C,YAAY,UAAU;KAC1F,EAAE,WAAW,SAAS,GAAG,wBAAwB,kBAAkB,GAAG,EAAE,MACzE,EAAE,WAAW,SAAS,GAAG,wEAOT,cAAc,SAAS,SAAS;;KAG3D,kBAAkB,UAAU,QAAQ,KAAK,sCACvB,cAEjB,UAAU,GAAG;;;;;;iBAQH,gBAAgB,eAAe;EAAkB,OAAO;EAAa,WAAW"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { fail } from "../../utils.js";
|
|
2
|
+
import { getTableMgmt, isEntityTable, newTableProxy, tableEntityWhere, tableWhere } from "./Tables.js";
|
|
3
|
+
import { isEntity } from "../../Entity.js";
|
|
4
|
+
//#region src/queries/sql/JoinTree.ts
|
|
5
|
+
/**
|
|
6
|
+
* Walks domain relationship filters into ordinary SQL joins and WHERE predicates.
|
|
7
|
+
* Handles remain query-local; no SQL aliases or caller objects are changed.
|
|
8
|
+
* I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.
|
|
9
|
+
*/
|
|
10
|
+
function compileJoinTree(from, tree) {
|
|
11
|
+
if (!isEntityTable(from)) fail("Join trees require an entity table in from");
|
|
12
|
+
const joins = [];
|
|
13
|
+
const conditions = [];
|
|
14
|
+
visitTree(from, tree, joins, conditions, /* @__PURE__ */ new Set([getTableMgmt(from)]));
|
|
15
|
+
return {
|
|
16
|
+
joins,
|
|
17
|
+
condition: { and: conditions }
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Compiles one node, leaving relationship conditions in WHERE rather than ON.
|
|
22
|
+
* Each relationship gets one target handle; reusing a bound handle would merge distinct paths.
|
|
23
|
+
* Owning-reference ID filters stay on the FK, while collection ID filters use the joined primary key.
|
|
24
|
+
*/
|
|
25
|
+
function visitTree(source, tree, joins, conditions, bound) {
|
|
26
|
+
if (!isTreeObject(tree)) fail("Expected a join tree object");
|
|
27
|
+
const mgmt = getTableMgmt(source);
|
|
28
|
+
if (tree.as !== void 0 && tree.as !== source) fail("Join tree root as must be the same table handle as from");
|
|
29
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
30
|
+
if (key === "as") continue;
|
|
31
|
+
const field = mgmt.meta.allFields[key] ?? fail(`Unknown join tree field ${mgmt.meta.type}.${key}`);
|
|
32
|
+
if (!(key in mgmt.meta.fields)) fail(`Join trees do not support inherited field ${mgmt.meta.type}.${key}`);
|
|
33
|
+
if (field.kind === "poly") fail(`Join trees do not support polymorphic field ${mgmt.meta.type}.${key}`);
|
|
34
|
+
if ([
|
|
35
|
+
"m2o",
|
|
36
|
+
"o2m",
|
|
37
|
+
"lo2m",
|
|
38
|
+
"m2m",
|
|
39
|
+
"o2o"
|
|
40
|
+
].includes(field.kind)) {
|
|
41
|
+
if (value === void 0) continue;
|
|
42
|
+
if (field.kind === "m2o" && !isTreeObject(value)) {
|
|
43
|
+
conditions.push(tableWhere(mgmt, { [key]: value }));
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (field.kind === "m2o" && isTreeObject(value) && Object.hasOwn(value, "ne")) {
|
|
47
|
+
conditions.push(tableWhere(mgmt, { [key]: value }));
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (!("otherMetadata" in field)) fail(`Unsupported join tree field ${mgmt.meta.type}.${key}`);
|
|
51
|
+
const meta = field.otherMetadata();
|
|
52
|
+
const target = isTreeObject(value) && value.as !== void 0 ? value.as : newTableProxy(meta.cstr);
|
|
53
|
+
if (!isEntityTable(target) || getTableMgmt(target).meta !== meta) fail(`Join tree binding for ${mgmt.meta.type}.${key} must be a ${meta.type} table`);
|
|
54
|
+
const identity = getTableMgmt(target);
|
|
55
|
+
if (bound.has(identity)) fail(`Join tree table ${meta.type} is bound more than once; create a separate table handle`);
|
|
56
|
+
bound.add(identity);
|
|
57
|
+
const relation = source[key];
|
|
58
|
+
joins.push(relation.as(target));
|
|
59
|
+
if (isTreeObject(value) && !Object.hasOwn(value, "ne")) visitTree(target, value, joins, conditions, bound);
|
|
60
|
+
else conditions.push(tableEntityWhere(identity, value));
|
|
61
|
+
} else conditions.push(tableWhere(mgmt, { [key]: value }));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Separates nested relationship objects from entity, ID, and list filters. */
|
|
65
|
+
function isTreeObject(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !isEntity(value);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
export { compileJoinTree };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=JoinTree.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JoinTree.js","names":[],"sources":["../../../src/queries/sql/JoinTree.ts"],"sourcesContent":["import { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf } from \"src/EntityManager.ts\";\nimport type { InnerJoin, LeftJoin } from \"src/queries/sql/Expr.ts\";\nimport type { QueryCondition, QueryJoin, QueryJoinInput } from \"src/queries/sql/query.ts\";\nimport {\n type CollectionJoin,\n type TableFilter,\n type TableFor,\n getTableMgmt,\n isEntityTable,\n newTableProxy,\n tableEntityWhere,\n tableWhere,\n} from \"src/queries/sql/Tables.ts\";\nimport type { FieldsOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** Domain filters and optional table bindings for one node in a relationship tree. */\nexport type JoinTree<T extends Entity> = Omit<TableFilter<T>, RelationNames<T>> & {\n readonly as?: TableFor<T>;\n} & {\n readonly [K in RelationNames<T>]?: FieldsOf<T>[K] extends {\n kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\";\n type: infer U extends Entity;\n }\n ? JoinTree<U> | (K extends keyof TableFilter<T> ? TableFilter<T>[K] : JoinedEntityFilter<U>)\n : never;\n};\n\n/**\n * Filters entities, e.g. `{ books: \"b:1\" }` filters Book.id to 1.\n *\n * Adapted from `em.find`s EntityFilter, rather than a direct copy:\n *\n * - Keeps entity/ID, list, boolean, and `ne` filters, but omits scopes, find aliases, nested objects, and logical groups.\n * - JoinTree supplies nested objects and table bindings separately.\n * - Lists can mix entities and IDs, unlike EntityFilter's separate entity[] and ID[] alternatives.\n * - Null is always allowed because these relationships use LEFT joins.\n * - undefined comes from JoinTree's optional relationship keys.\n */\ntype JoinedEntityFilter<T extends Entity> =\n | IdOf<T>\n | T\n | readonly (IdOf<T> | T)[]\n | boolean\n | null\n | { ne: IdOf<T> | T | null | undefined };\n\ntype RelationNames<T extends Entity> = {\n [K in keyof FieldsOf<T>]: FieldsOf<T>[K] extends { kind: \"m2o\" | \"poly\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\" }\n ? K\n : never;\n}[keyof FieldsOf<T>];\n\n/**\n * Validates a join tree against the entity in `from`, preserving its exact table bindings.\n *\n * I.e. given:\n *\n * ```ts\n * const [a, b] = tables(Author, Book);\n * em.query({\n * from: a,\n * join: { books: { as: b, title: \"One\" } },\n * select: { title: b.title },\n * });\n * // F = typeof a\n * // J = { books: { as: typeof b; title: string } }\n * ```\n *\n * We:\n *\n * - Infer `T = Author` from `F`,\n * - Validate `books` against `Author`,\n * - Validate `title` against `Book`, and\n * - Retain `typeof b` for result typing.\n */\nexport type CheckJoinInput<F, J> =\n // If J accepts the entire list-or-tree union, its annotation erased the join shape.\n // Queries with no join infer [] and use the list branch below.\n QueryJoinInput extends J\n ? { join?: \"join was typed too generically; use `satisfies Query` instead of `: Query`\" }\n : // If J is an array, then it's a QueryJoinList and we can return unknown\n [J] extends [readonly unknown[]]\n ? unknown\n : F extends TableFor<infer T extends Entity>\n ? // Validate domain filters and bindings, including extra keys on variables and nested trees.\n { join?: JoinTree<T> & CheckTree<T, J> }\n : // This incompatible type reports why a tree can't start at a non-entity source.\n { join?: \"join trees require an entity table in from\" };\n\n/**\n * Determines which tables a join tree binds and whether each uses an INNER or LEFT join.\n *\n * Query result types use these entries to identify available tables and columns that can be null.\n *\n * I.e. Author.books.author uses LEFT joins for both Book and its Author because an Author may have no Books.\n */\nexport type TreeEntries<T extends Entity, J, Nullable extends boolean = false> =\n // If every string is valid keyof J, then we've lost our literal type (i.e. as const) and were\n // passed an opaque type like Record<string, unknown> that doesn't expose its specific relationship\n // keys or table bindings to collect, so just return never.\n string extends keyof J\n ? never\n : // If J has an `as` key, it might be the general JoinTree<T> type, which we check for in the next ternary.\n // If J doesn't have `as`, it can't be the general `JoinTree<T>` so we can jump straight to TreeEntriesImpl.\n \"as\" extends keyof J\n ? // If `JoinTree<T> extends J`, then we again have a board type. CheckTree will reject this input, but\n // here we stop instead of following every relationship in the domain graph.\n JoinTree<T> extends J\n ? never\n : TreeEntriesImpl<T, J, Nullable>\n : TreeEntriesImpl<T, J, Nullable>;\n\n/** Collects join entries from the relationship keys supplied in this tree node. */\ntype TreeEntriesImpl<T extends Entity, J, Nullable extends boolean> = {\n [K in keyof J & keyof FieldsOf<T>]: FieldsOf<T>[K] extends {\n kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\";\n type: infer U extends Entity;\n }\n ? TreeNodeJoins<\n U,\n Exclude<J[K], undefined>,\n Nullable extends true ? true : FieldsOf<T>[K] extends { kind: \"m2o\"; nullable: never } ? false : true\n >\n : never;\n}[keyof J & keyof FieldsOf<T>];\n\n/**\n * Collects the join entries for this node's table binding and its nested relationships.\n *\n * An `as` binding contributes a LeftJoin or InnerJoin according to Nullable.\n * Without a binding, only nested relationship entries are included; entity, ID, and list filters add none.\n */\ntype TreeNodeJoins<T extends Entity, J, Nullable extends boolean> =\n // If `J extends Entity | unknown[]`, then it's a leaf entity/id filter, so stop recursing\n J extends Entity | readonly unknown[]\n ? never\n : // If `J extends object`, look for an `as` binding and nested relationships.\n // If `J extends object` is false, this is a scalar filter like \"b:1\" in `{ books: \"b:1\" }` and we stop here.\n J extends object\n ?\n | (J extends { readonly as: infer A extends TableFor<T> }\n ? Nullable extends true\n ? LeftJoin<A>\n : InnerJoin<A>\n : never)\n | TreeEntries<T, J, Nullable>\n : never;\n\n/** Rejects broad tree annotations before checking their supplied keys and values. */\ntype CheckTree<T extends Entity, J> =\n // An entity or a list of entities/IDs is a filter value, so don't check its properties as tree keys.\n J extends Entity | readonly unknown[]\n ? unknown\n : \"as\" extends keyof J\n ? JoinTree<T> extends J\n ? \"join tree bindings were typed too generically; use `satisfies JoinTree<T>` instead of `: JoinTree<T>`\"\n : CheckTreeKeys<T, J>\n : CheckTreeKeys<T, J>;\n\n/** Rejects unknown tree keys, including extra properties on objects stored in variables. */\ntype CheckTreeKeys<T extends Entity, J> = [Exclude<keyof J, keyof JoinTree<T>>] extends [never]\n ? {\n [K in keyof J]: K extends \"as\"\n ? J[K] extends TableFor<T> | undefined\n ? unknown\n : never\n : K extends keyof JoinTree<T>\n ? K extends keyof FieldsOf<T>\n ? FieldsOf<T>[K] extends { kind: \"m2o\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\"; type: infer U extends Entity }\n ? (J[K] extends JoinTree<T>[K] ? unknown : never) & CheckRelationTree<U, J[K]>\n : J[K] extends JoinTree<T>[K]\n ? unknown\n : never\n : unknown\n : never;\n // Report the error on the tree object; intersecting a message with a boolean field would collapse to never.\n }\n : `unknown join tree field '${Exclude<keyof J, keyof JoinTree<T>> & string}'`;\n\n/** Checks each optional relationship alternative without treating entities or exclusion filters as trees. */\ntype CheckRelationTree<T extends Entity, J> = J extends object\n ? \"ne\" extends keyof J\n ? unknown\n : CheckTree<T, J>\n : unknown;\n\n/**\n * Walks domain relationship filters into ordinary SQL joins and WHERE predicates.\n * Handles remain query-local; no SQL aliases or caller objects are changed.\n * I.e. Author.books.author emits Book before its Author, even if only the final Author has an as binding.\n */\nexport function compileJoinTree(from: unknown, tree: unknown): { joins: QueryJoin[]; condition: QueryCondition } {\n if (!isEntityTable(from)) fail(\"Join trees require an entity table in from\");\n const joins: QueryJoin[] = [];\n const conditions: QueryCondition[] = [];\n const bound = new Set<object>([getTableMgmt(from)]);\n visitTree(from, tree, joins, conditions, bound);\n return { joins, condition: { and: conditions } };\n}\n\n/**\n * Compiles one node, leaving relationship conditions in WHERE rather than ON.\n * Each relationship gets one target handle; reusing a bound handle would merge distinct paths.\n * Owning-reference ID filters stay on the FK, while collection ID filters use the joined primary key.\n */\nfunction visitTree(\n source: TableFor<Entity>,\n tree: unknown,\n joins: QueryJoin[],\n conditions: QueryCondition[],\n bound: Set<object>,\n): void {\n if (!isTreeObject(tree)) fail(\"Expected a join tree object\");\n const mgmt = getTableMgmt(source);\n if (tree.as !== undefined && tree.as !== source) fail(\"Join tree root as must be the same table handle as from\");\n for (const [key, value] of Object.entries(tree)) {\n if (key === \"as\") continue;\n const field = mgmt.meta.allFields[key] ?? fail(`Unknown join tree field ${mgmt.meta.type}.${key}`);\n if (!(key in mgmt.meta.fields)) fail(`Join trees do not support inherited field ${mgmt.meta.type}.${key}`);\n if (field.kind === \"poly\") fail(`Join trees do not support polymorphic field ${mgmt.meta.type}.${key}`);\n if ([\"m2o\", \"o2m\", \"lo2m\", \"m2m\", \"o2o\"].includes(field.kind)) {\n if (value === undefined) continue;\n if (field.kind === \"m2o\" && !isTreeObject(value)) {\n // Avoid joining the related table; add the condition directly to the FK column.\n conditions.push(tableWhere(mgmt, { [key]: value }));\n continue;\n }\n if (field.kind === \"m2o\" && isTreeObject(value) && Object.hasOwn(value, \"ne\")) {\n // Exclusion filters also apply directly to the FK column without joining the related table.\n conditions.push(tableWhere(mgmt, { [key]: value }));\n continue;\n }\n // The field-kind check above establishes the relationship metadata and factory shape.\n if (!(\"otherMetadata\" in field)) fail(`Unsupported join tree field ${mgmt.meta.type}.${key}`);\n const meta = field.otherMetadata();\n const target = isTreeObject(value) && value.as !== undefined ? value.as : newTableProxy(meta.cstr);\n if (!isEntityTable(target) || getTableMgmt(target).meta !== meta) {\n fail(`Join tree binding for ${mgmt.meta.type}.${key} must be a ${meta.type} table`);\n }\n const identity = getTableMgmt(target);\n if (bound.has(identity))\n fail(`Join tree table ${meta.type} is bound more than once; create a separate table handle`);\n bound.add(identity);\n const relation = (source as unknown as Record<string, CollectionJoin<Entity>>)[key];\n joins.push(relation.as(target));\n // Recurse into nested relationship filters, e.g. `{ books: { title: \"One\" } }`.\n // A `{ ne: ... }` object instead filters the joined entity's ID, so handle it like an ID or entity value.\n // We don't have to handle other keys like `gt`, etc. b/c we know this is an entity filter, not a value filter.\n if (isTreeObject(value) && !Object.hasOwn(value, \"ne\")) {\n visitTree(target, value, joins, conditions, bound);\n } else {\n conditions.push(tableEntityWhere(identity, value));\n }\n } else {\n conditions.push(tableWhere(mgmt, { [key]: value }));\n }\n }\n}\n\n/** Separates nested relationship objects from entity, ID, and list filters. */\nfunction isTreeObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !isEntity(value);\n}\n"],"mappings":";;;;;;;;;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