joist-core 2.4.0-next.40 → 2.4.0-next.41

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.
@@ -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/** 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,KAAK,IAAI,KAAK,MAAM,0BAA0B,GAAG,GAAG,CAAC;CAAE;MACzE,IAAI,QAAQ,QAAQ,KAAK,IAC9B,OAAO;EAAE,GAAG;EAAM,IAAI,KAAK,GAAG,KAAK,M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;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"}
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/**\n * An infix operator between two expressions, i.e. `(pg.\"embedding\" <=> ?)`.\n *\n * A literal right-hand side is bound through the left expression's codec, and Postgres infers\n * the parameter's type from the operator, so no cast is needed.\n */\nexport class OperatorExpr extends BaseExpr {\n private right: BaseExpr;\n\n constructor(\n private left: BaseExpr,\n private op: string,\n right: unknown,\n private opts: { outputType?: TypeInfo } = {},\n ) {\n super();\n this.right = isExpr(right) ? asNode(right) : new BindingExpr(left.encode(right));\n }\n\n get outputType(): TypeInfo | undefined {\n return this.opts.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n const { left, right } = this;\n if (left.sqlNullable || right.sqlNullable) return true;\n return left.sqlNullable === false && right.sqlNullable === false ? false : undefined;\n }\n\n get sqlSource(): object | undefined {\n return this.left.sqlSource;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const joined = joinFragments([this.left.toSql(ctx), this.right.toSql(ctx)], ` ${this.op} `);\n return { ...joined, sql: `(${joined.sql})` };\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":";;;;;;;;;;;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AK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,QACH,OAAO;EACT,SACE;CACJ;AACF;;AAGA,SAAS,aAAa,OAAyB;CAC7C,OAAO,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;AACrD;;AAGA,SAAgB,aAAa,GAAsB,KAA2C;CAC5F,IAAI,EAAE,EAAE,gBAAgB,WACtB,OAAO,KAAK,+FAA+F;CAE7G,IAAI,OAAO,KAAK,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"}
@@ -228,6 +228,15 @@ var PrimitiveColumnImpl = class extends TableColumn {
228
228
  value: [v1, v2]
229
229
  });
230
230
  }
231
+ cosineDistance(vector) {
232
+ if (this.column.dbType !== "vector") require_utils.fail(`${this.column.columnName} is not a vector column`);
233
+ const outputType = {
234
+ dbType: "float8",
235
+ domain: Number,
236
+ arrayElementSafe: true
237
+ };
238
+ return new require_queries_sql_Expr.OperatorExpr(this, "<=>", vector, { outputType });
239
+ }
231
240
  like(value) {
232
241
  if (value === void 0) return require_queries_skipCondition.skipCondition;
233
242
  return this.addCondition({
@@ -1 +1 @@
1
- {"version":3,"file":"Tables.cjs","names":["isCustomTableDefinition","safeKq","kq","getMetadata","RefExpr","fail","getCustomTableDefinition","BaseExpr","selectKeyBrand","kqDot","toIdOf","mapToDb","deferredCondition","buildValueCondition","isExpr","skipCondition","makeLike","taggedIdPrefix","groupBy","getConstructorFromTaggedId","maybeResolveReferenceToId","asNode","getBaseAndSelfMetas","getBaseSelfAndSubMetas","getBaseMeta","parseEntityFilter","parseValueFilter","isEntity"],"sources":["../../../src/queries/sql/Tables.ts"],"sourcesContent":["import { groupBy } from \"joist-utils\";\n// Load configure first: otherwise the built cjs/esm module graph evaluates relations/* before their\n// base classes exist (\"Class extends value undefined\").\nimport { getConstructorFromTaggedId } from \"src/configure.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf, MaybeAbstractEntityConstructor, TaggedId } from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type LargeOneToManyField,\n type ManyToManyField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PolymorphicFieldComponent,\n getBaseAndSelfMetas,\n getBaseMeta,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"src/EntityMetadata.ts\";\nimport { maybeResolveReferenceToId, taggedIdPrefix, toIdOf } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport type { ParsedValueFilter } from \"src/queries/parsedConditions.ts\";\nimport { buildValueCondition } from \"src/queries/renderConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport {\n type CustomColumnInputs,\n type CustomTable,\n type CustomTableDefinition,\n type CustomTableFor,\n type CustomTableMgmt,\n getCustomTableDefinition,\n isCustomTableDefinition,\n} from \"src/queries/sql/custom.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n RefExpr,\n type SqlFragment,\n asNode,\n deferredCondition,\n isExpr,\n selectKeyBrand,\n} from \"src/queries/sql/Expr.ts\";\nimport { kq, kqDot, safeKq } from \"src/queries/sql/keywords.ts\";\nimport type { QueryArg, QueryJoinInput, QuerySource } from \"src/queries/sql/query.ts\";\nimport { makeLike, mapToDb, parseEntityFilter, parseValueFilter } from \"src/queries/valueFilters.ts\";\nimport type { Column } from \"src/serde/columns.ts\";\nimport type { TypeInfo } from \"src/serde/TypeInfo.ts\";\nimport type { ColumnsOf, FieldsOf, FilterOf, TypeMap, TypeNameOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** Creates physical column expressions and relationship joins for `T`. */\nexport function table<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): Table<T>;\n/** Creates a typed physical handle for a table declared with `declareTable`. */\nexport function table<TableName extends string, C extends CustomColumnInputs>(\n definition: CustomTableDefinition<TableName, C>,\n): CustomTable<C, TableName>;\n/**\n * Creates a table with an explicit type-level name, i.e. `table(Author, \"m\")` for a self-join.\n *\n * The name is the table's source key in `em.query`: two bare `table(Author)`s share the key `\"Author\"`,\n * so a left-joined mentor would also mark the mentee's columns nullable; a named alias has its own key.\n */\nexport function table<T extends Entity, Name extends string>(\n cstr: MaybeAbstractEntityConstructor<T>,\n name: Name,\n): Table<T, Name>;\n/** Creates a named custom-table handle for joins and self-joins. */\nexport function table<C extends CustomColumnInputs, TableName extends string, Name extends string>(\n definition: CustomTableDefinition<TableName, C>,\n name: Name,\n): CustomTable<C, Name>;\nexport function table<T extends Entity>(\n cstr: MaybeAbstractEntityConstructor<T> | CustomTableDefinition<string, CustomColumnInputs>,\n _name?: string,\n): unknown {\n // The name only exists at the type level; the SQL alias is still assigned by the query parser\n return isCustomTableDefinition(cstr) ? newCustomTableProxy(cstr) : newTableProxy(cstr);\n}\n\n/** Creates multiple physical table handles. */\nexport function tables<T extends readonly MaybeAbstractEntityConstructor<any>[]>(\n ...type: T\n): { [P in keyof T]: T[P] extends MaybeAbstractEntityConstructor<infer E extends Entity> ? Table<E> : never } {\n return type.map((t) => newTableProxy(t)) as any;\n}\n\n/**\n * The runtime management interface plus phantom type information for `em.query`.\n *\n * `__entity` lets `QueryRow` recover `T` for entity mode (you cannot `infer T` back out of a mapped\n * type), and `__name` is the table's source key (see `Expr`).\n */\nexport interface TableSourceBrand<Name extends string> extends TableSourceMgmt {\n readonly __name: Name;\n}\n\n/** A modeled table source that can hydrate its generated entity type. */\nexport interface TableBrand<T, Name extends string> extends TableSourceBrand<Name>, TableMgmt {\n readonly __entity: T;\n}\n\n/**\n * A physical table for `T`: one expression per SQL column, with relationship names as join factories.\n * Selecting the table itself retains entity hydration; selecting columns returns decoded SQL values.\n *\n * Unlike an Alias, a Table is an explicit SQL source, not a place to bind in an em.find relationship\n * tree. I.e. with `a = table(Author)`, `{ from: a }` registers that handle in the query's scope.\n * Its columns already know their physical column and codec, but their SQL name still depends on the\n * query: the same Author handle might be `a` in one query and `a1` in a nested query.\n *\n * Each predicate occurrence renders through ExprContext.aliasFor using the current scope (or an\n * enclosing scope for a correlation). Rendering returns SQL, ordered bindings, and source references\n * together. A comparison records both sides' references; templates and subqueries carry their\n * references too. Join pruning follows these references and join dependencies, rather than guessing\n * which tables a SQL string mentions. It also accounts for select/order/group expressions and keep.\n *\n * I.e. if a joined Author is used only by `a.firstName.eq(name)`, supplying undefined removes that\n * predicate and lets the unused join prune. Both APIs share this undefined-condition pruning rule;\n * they differ in how they get the references: Alias resolves domain conditions against a relationship\n * tree, while Table renders SQL expressions against explicit sources. Neither caches SQL names on\n * the reusable handle or predicate, so one parse cannot overwrite another parse's bindings.\n *\n * `Name` is the table's type-level source key, defaulting to the entity's own type name, so a\n * LEFT-joined SmallPublisher does not make Publisher columns nullable. `table(Author, \"m\")`\n * gives a self-join table its own key.\n */\nexport type Table<T extends Entity, Name extends string = TableNameOf<T>> = TableShape<T, Name> &\n (\"where\" extends keyof TableShape<T, Name>\n ? {}\n : {\n /** Builds an AND condition from local domain fields, without implicit joins. */\n where(filter: TableFilter<T>): SqlCondition;\n }) &\n (\"column\" extends keyof TableShape<T, Name>\n ? {}\n : {\n /**\n * References a column Joist does not model, i.e. `a.column<string>(\"ts_search\")`.\n *\n * The expression keeps this table's source key, so it is scope-checked and nullified by a\n * LEFT join like any modeled column. `R` is unchecked: it asserts what the database returns,\n * and the value is not decoded through a codec.\n *\n * A schema that has its own `column` column or relation keeps that meaning, and then has no\n * escape hatch for unmodeled columns.\n */\n column<R = unknown>(column: string): Expr<R, Name>;\n });\n\n/** Domain filters for fields stored on this physical table, without relationship traversal. */\nexport type TableFilter<T extends Entity> = {\n [K in LocalFieldNames<T> & keyof FieldsOf<T>]?: FieldsOf<T>[K] extends {\n kind: \"m2o\";\n type: infer U extends Entity;\n nullable: infer N;\n }\n ? TableReferenceFilter<U, N extends undefined ? null : never>\n : FilterOf<T>[K];\n};\n\n/** Generated column ownership excludes CTI base fields and polymorphic components. */\ntype LocalFieldNames<T> = ColumnsOf<T>[keyof ColumnsOf<T>] extends { fieldName: infer F }\n ? Extract<F, keyof FilterOf<T>>\n : never;\n\n/** The owning-reference subset of find filters that only compares a foreign key. */\ntype TableReferenceFilter<T extends Entity, N> =\n | T\n | IdOf<T>\n | readonly (T | IdOf<T>)[]\n | boolean\n | N\n | undefined\n | { ne: T | IdOf<T> | N | undefined };\n\n/** Maps an entity's columns and relationships to expressions and joins for one typed table handle. */\ntype TableShape<T extends Entity, Name extends string> = {\n readonly [tableMgmt]: TableBrand<T, Name>;\n} & {\n // Add typed expressions for each physical column, including its property name for array selects.\n [P in keyof ColumnsOf<T> & string]: P extends \"id\"\n ? EntityColumn<T, never, Name, P>\n : ColumnsOf<T>[P] extends { entity: infer U extends Entity; nullable: infer N }\n ? ReferenceColumn<U, N extends true ? null : never, Name, P>\n : ColumnsOf<T>[P] extends { type: infer V; nullable: infer N }\n ? PrimitiveColumn<V, N extends true ? null : never, Name, P>\n : never;\n} & {\n // Add relation join sugar such as `a.books.as(b)` for fields that are not physical columns.\n [\n P in keyof FieldsOf<T> as P extends keyof ColumnsOf<T>\n ? never\n : FieldsOf<T>[P] extends { kind: \"m2o\" | \"poly\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\" }\n ? P\n : never\n ]: FieldsOf<T>[P] extends { kind: \"m2o\"; type: infer U extends Entity; nullable: infer N }\n ? ReferenceJoin<U, N extends undefined ? null : never, Name>\n : FieldsOf<T>[P] extends { kind: \"poly\"; type: infer U extends Entity; nullable: infer N }\n ? PolyReference<U, N extends undefined ? null : never, Name>\n : FieldsOf<T>[P] extends { kind: \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\"; type: infer U extends Entity }\n ? CollectionJoin<U>\n : never;\n} & {\n // Add subtype join sugar such as `p.smallPublisher(sp)` for entities whose __type root is T.\n // CTI joins the physical tables by ID; STI self-joins the shared table by ID plus its discriminator.\n [\n K in keyof TypeMap as TypeMap[K] extends {\n entityType: infer U extends Entity & { __type: { 0: TypeNameOf<T>; 1: string } };\n }\n ? Uncapitalize<TypeNameOf<U> & string>\n : never\n ]: TypeMap[K] extends { entityType: infer U extends Entity } ? SubtypeJoin<U> : never;\n};\n\n/** Keeps explicit base and subtype sources independent, with generic entities untracked. */\ntype TableNameOf<T> = T extends { __type: { 0: string } } ? TypeNameOf<T> & string : string;\n\n/** Provides fluent methods for creating joins through an owning reference relationship. */\nexport interface ReferenceJoin<U extends Entity, N extends null | never, Src extends string = string> {\n /**\n * Required reference joins like `b.author.as(a)` are INNER unless `b` is already a LEFT-joined alias.\n * Nullable references are always LEFT joined.\n */\n as<A extends TableFor<U>>(other: A): [N] extends [never] ? DefaultReferenceJoin<A, Src> : LeftJoin<A>;\n inner<A extends TableFor<U>>(other: A): InnerJoin<A>;\n left<A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/** The source of a default reference join, used to inherit optional paths within each query. */\nexport const referenceJoinSource: unique symbol = Symbol(\"joist.referenceJoinSource\");\n\n/** A required reference defaults to INNER unless its source was LEFT joined. */\nexport type DefaultReferenceJoin<A, Src extends string> = InnerJoin<A> & {\n readonly [referenceJoinSource]: Src;\n};\n\n/** Any table whose entity is (a subtype of) `U`, i.e. what a relation join factory accepts. */\nexport type TableFor<U> = { readonly [tableMgmt]: TableBrand<U, string> };\n\n/**\n * A collection relation (o2m/o2o/m2m) as a join factory: `a.books.as(b)` returns the same\n * `{ left: b, on: ... }` entry the expanded form writes, with the FK condition built from metadata, so\n * join-list inference, nullability, scope checking, and pruning are unchanged and both forms mix freely.\n *\n * `as` binds the joined alias, the same way em.find's `{ books: { as: b } }` does. The default is LEFT\n * (a collection may be empty, and a LEFT join never filters rows, so pruning it is always safe);\n * `.inner(b)` opts into filtering. An m2m entry carries a hidden second join through the join table,\n * which the parser expands; the pair prunes together.\n */\nexport interface CollectionJoin<U extends Entity> {\n as<A extends TableFor<U>>(other: A): LeftJoin<A>;\n inner<A extends TableFor<U>>(other: A): InnerJoin<A>;\n left<A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/** A named subtype join, defaulting to LEFT because a root row may belong to another subtype. */\ninterface SubtypeJoin<U extends Entity> extends CollectionJoin<U> {\n <A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/**\n * A physical FK column expression (`b.authorId` selects/compares the `author_id` FK) plus a join factory\n * (`b.authorId.as(a)` joins). The default join kind follows physical column nullability:\n * a NOT NULL FK is INNER unless its source was LEFT joined, a nullable one is LEFT, and the row type reflects it.\n */\nexport interface ReferenceColumn<\n U extends Entity,\n N extends null | never,\n Src extends string,\n Key extends string = string,\n>\n extends EntityColumn<U, N, Src, Key>, ReferenceJoin<U, N, Src> {}\n\n/**\n * A polymorphic reference: condition methods (each resolving the component column from the value), plus\n * a join factory that picks the component from the argument's entity, i.e. `c.parent.as(a)` joins\n * through `parent_author_id`, like an explicit join with `on: c.parent.eq(a.id)`.\n */\nexport interface PolyReference<\n U extends Entity,\n N extends null | never,\n Src extends string = string,\n> extends ReferenceJoin<U, N, Src> {\n eq(value: U | TaggedId | ExprLike<IdOf<U> | null> | null | undefined): SqlCondition;\n ne(value: U | TaggedId | ExprLike<IdOf<U> | null> | null | undefined): SqlCondition;\n in(values: readonly (U | TaggedId)[] | ExprLike<IdOf<U> | null> | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (U | TaggedId)[] | undefined): SqlCondition;\n}\n\nexport interface PrimitiveColumn<\n V,\n N extends null | never,\n Src extends string = string,\n Key extends string = string,\n> extends Expr<V | N, Src> {\n readonly [selectKeyBrand]: Key;\n eq(value: V | ExprLike<V | N> | N | undefined): SqlCondition;\n ne(value: V | ExprLike<V | N> | N | undefined): SqlCondition;\n in(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (V | null)[] | undefined): SqlCondition;\n nin(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition;\n gt(value: V | ExprLike<V | N> | undefined): SqlCondition;\n gte(value: V | ExprLike<V | N> | undefined): SqlCondition;\n lt(value: V | ExprLike<V | N> | undefined): SqlCondition;\n lte(value: V | ExprLike<V | N> | undefined): SqlCondition;\n like(value: V | undefined): SqlCondition;\n ilike(value: V | undefined): SqlCondition;\n search(value: V | undefined): SqlCondition;\n between(v1: V | undefined, v2: V | undefined): SqlCondition;\n // need to move to ArrayColumn\n // ...added the `string` to support jsonb contains like `WHERE profile @> '{\"age\": 25}'`\n // Ideally this would go in a JsonbColumn\n contains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n ncontains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n overlaps(value: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n noverlaps(value: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n\n /**\n * Adds a JSON path existence condition, using the `@?` operator.\n *\n * Any values should be embedded directly within the `jsonPath`, because postgres does not\n * support parameterized JSON path expressions. The entire `jsonPath` is treated as a parameter,\n * so this is safe from SQL injection.\n */\n pathExists(jsonPath: string | undefined): SqlCondition;\n\n /**\n * Adds a JSON path predicate condition, using the `@@` operator.\n *\n * Any values should be embedded directly within the `jsonPath`, because postgres does not\n * support parameterized JSON path expressions. The entire `jsonPath` is treated as a parameter,\n * so this is safe from SQL injection.\n */\n pathIsTrue(jsonPath: string | undefined): SqlCondition;\n\n /**\n * Add `exp` to the query, which should include the operator & expression and any\n * bound parameters (but not include the column name).\n *\n * We use knex-style placeholders, i.e. `?` and `\\\\?` to escape question marks, i.e.\n *\n * ```ts\n * a.address.raw(\"@\\\\? ?\", ['$.street ? (@ == \"rr2\")'])`\n * ```\n */\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition;\n}\n\nexport interface EntityColumn<\n T,\n N extends null | never = never,\n Src extends string = string,\n Key extends string = string,\n> extends Expr<IdOf<T> | N, Src> {\n readonly [selectKeyBrand]: Key;\n /** Produces the tagged ID as SQL text, preserving NULL and the column's source. */\n taggedId(): Expr<string | N, Src>;\n eq(value: T | IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n ne(value: T | IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n // Adding `| null` for GraphQL support\n in<\n F extends QuerySource,\n const S extends ExprLike<IdOf<T> | null>,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n >(\n value: QueryArg<F, S, J, Name>,\n ): SqlCondition;\n in(value: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty, null, or undefined. */\n inNonEmpty(value: readonly (T | IdOf<T> | null)[] | null | undefined): SqlCondition;\n nin(value: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n gt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n gte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n lt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n lte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition;\n}\n\nexport const tableMgmt = Symbol(\"tableMgmt\");\nexport const inQueryCondition: unique symbol = Symbol(\"joist.inQueryCondition\");\n\n/** Defers a direct IN query literal to query.ts, which owns query pruning and SQL generation. */\nexport interface InQueryCondition {\n readonly [inQueryCondition]: { column: BaseExpr; query: object };\n}\n\nexport function getTableMgmt<T extends Entity>(table: TableFor<T>): TableMgmt;\nexport function getTableMgmt(table: CustomTableFor): CustomTableMgmt;\nexport function getTableMgmt(table: TableFor<Entity> | CustomTableFor): TableSourceMgmt;\nexport function getTableMgmt(table: TableFor<Entity> | CustomTableFor): TableSourceMgmt {\n return table[tableMgmt];\n}\n\n/** The identity SQL queries bind a table by, plus its original entity metadata. */\nexport interface TableSourceMgmt {\n tableName: string;\n schema?: string;\n}\n\n/** Qualifies custom tables without changing SQL for tables on the default search path. */\nexport function tableSqlName(table: TableSourceMgmt): string {\n return table.schema ? `${safeKq(table.schema)}.${kq(table.tableName)}` : kq(table.tableName);\n}\n\n/** The identity and generated metadata of a modeled entity table. */\nexport interface TableMgmt extends TableSourceMgmt {\n /**\n * The metadata this table was created with, i.e. `table(TaskNew)` keeps `taskNewMeta`.\n *\n * It cannot be re-derived from `tableName`: STI subtypes share their base's table (`Task`, `TaskNew`,\n * and `TaskOld` are all `tasks`), so a `getMetadataForTable(\"tasks\")` lookup can only return the base\n * `Task`, and the alias would lose its subtype identity for explicit subtype joins and entity hydration.\n */\n meta: EntityMetadata;\n}\n\n/** Returns the metadata for the entity that `table` is bound to. */\nexport function getTableMetadata<T extends Entity>(table: TableFor<T>): EntityMetadata<T> {\n const mgmt = table[tableMgmt];\n return mgmt.meta as EntityMetadata<T>;\n}\n\nexport function newTableProxy<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): Table<T> {\n const meta = getMetadata(cstr);\n // The identity SQL queries bind to a source, retaining STI subtype metadata.\n const mgmt: TableMgmt = { tableName: meta.tableName, meta };\n const subtypes = new Map(meta.subTypes.map((m) => [m.type[0].toLowerCase() + m.type.slice(1), m]));\n const proxy: any = new Proxy(cstr, {\n /** Create a physical column expression or a relation join factory. */\n get(_, key: PropertyKey): any {\n if (key === tableMgmt) {\n return mgmt;\n }\n if (typeof key !== \"string\") return undefined;\n const descriptor = Object.hasOwn(meta.columns, key) ? meta.columns[key] : undefined;\n if (descriptor) {\n return descriptor.idMetadata\n ? new EntityColumnImpl(meta, descriptor, mgmt, key)\n : new PrimitiveColumnImpl(meta, descriptor, mgmt, key);\n }\n const subtype = subtypes.get(key);\n if (subtype) {\n const join = new SubtypeJoinImpl(proxy, subtype);\n return Object.assign(join.as.bind(join), {\n as: join.as.bind(join),\n inner: join.inner.bind(join),\n left: join.left.bind(join),\n });\n }\n const relation = physicalRelation(meta, key);\n if (key === \"where\" && !isRelation(meta.allFields[key])) {\n return (filter: TableFilter<T>) => tableWhere(mgmt, filter);\n }\n if (key === \"column\" && !isRelation(meta.allFields[key])) {\n return (column: string) => new RefExpr(mgmt, column);\n }\n const field = relation ?? fail(`No physical field ${key} on ${cstr.name}; join its base table explicitly`);\n switch (field.kind) {\n case \"m2o\":\n return new ReferenceJoinImpl(new EntityColumnImpl(meta, field.serde.columns[0].column, mgmt));\n case \"poly\":\n return new PolyReferenceImpl(meta, mgmt, field);\n case \"o2m\":\n case \"o2o\":\n case \"lo2m\":\n return new OneToManyJoinImpl(proxy, field);\n case \"m2m\":\n return new ManyToManyJoinImpl(proxy, field);\n default:\n throw new Error(`Unsupported table field kind ${field.kind}`);\n }\n },\n\n has(_, key) {\n return (\n key === tableMgmt ||\n (typeof key === \"string\" &&\n (key === \"where\" ||\n key === \"column\" ||\n Object.hasOwn(meta.columns, key) ||\n !!physicalRelation(meta, key) ||\n subtypes.has(key)))\n );\n },\n });\n return proxy;\n}\n\n/** Creates a typed handle for primitive columns declared outside Joist codegen. */\nfunction newCustomTableProxy<TableName extends string, C extends CustomColumnInputs>(\n definition: CustomTableDefinition<TableName, C>,\n): CustomTable<C, TableName> {\n const { tableName, schema, columns } = getCustomTableDefinition(definition);\n const mgmt: CustomTableMgmt = { tableName, schema, columns };\n return new Proxy(\n {},\n {\n get(_, key: PropertyKey): unknown {\n if (key === tableMgmt) return mgmt;\n if (typeof key !== \"string\") return undefined;\n const descriptor = Object.hasOwn(columns, key) ? columns[key] : undefined;\n if (descriptor) return new PrimitiveColumnImpl(undefined, descriptor, mgmt, key);\n if (key === \"column\") return (column: string) => new RefExpr(mgmt, column);\n return fail(`Custom table ${tableName} has no declared column ${key}; use .column(\"${key}\")`);\n },\n has(_, key): boolean {\n return key === tableMgmt || key === \"column\" || (typeof key === \"string\" && Object.hasOwn(columns, key));\n },\n },\n ) as CustomTable<C, TableName>;\n}\n\nexport function isTable(obj: unknown): obj is Table<any, any> | CustomTableFor {\n return (typeof obj === \"function\" || (typeof obj === \"object\" && obj !== null)) && tableMgmt in obj;\n}\n\n/** Whether a physical table has generated entity metadata. */\nexport function isEntityTable(obj: unknown): obj is Table<any, any> {\n return isTable(obj) && \"meta\" in obj[tableMgmt];\n}\n\n/** Whether a physical table has columns declared through `declareTable`. */\nexport function isCustomTable(obj: unknown): obj is CustomTableFor {\n return isTable(obj) && \"columns\" in obj[tableMgmt];\n}\n\n/**\n * A physical table column implements `Expr`: it renders as `alias.\"column\"`, decodes result\n * values through the column's shared scalar codec, and inherits aggregate methods from `BaseExpr`.\n */\nclass TableColumn extends BaseExpr {\n public constructor(\n readonly meta: EntityMetadata | undefined,\n readonly column: Column,\n readonly mgmt: TableSourceMgmt,\n private readonly selectKey: string = column.columnName,\n ) {\n super();\n }\n\n get [selectKeyBrand](): string {\n return this.selectKey;\n }\n\n /** Author.id, Book.authorId, and Comment.parentAuthorId use the same Author ID domain. */\n get outputType(): TypeInfo | undefined {\n return this.column.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.column.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.mgmt;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.mgmt);\n return { sql: kqDot(alias, this.column.columnName), bindings: [], refs: [alias] };\n }\n\n /** Decodes result-set values with public PK/FK ids, while hydration keeps internal tagged ids. */\n decode(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n const idMeta = this.idMetadata;\n if (idMeta) return toIdOf(idMeta, this.column.mapFromDb(value) as TaggedId | undefined);\n return this.column.mapFromDb(value);\n }\n\n encode(value: unknown): unknown {\n return this.column.mapToDb(value);\n }\n\n /** Identifies the ID domain of a primary key, FK, or physical polymorphic component. */\n get idMetadata(): EntityMetadata | undefined {\n return this.column.idMetadata?.();\n }\n\n /** Encodes literals when the condition is created and renders with each query's aliases. */\n addCondition(value: ParsedValueFilter<unknown>): SqlCondition {\n const encoded = mapToDb(this.column, value);\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n const [sql, bindings] = buildValueCondition(left.sql, encoded);\n return { sql, bindings: [...left.bindings, ...bindings], refs: left.refs };\n });\n }\n\n /** Renders raw operators against the same quoted column SQL as other expressions. */\n protected addRawCondition(exp: string, bindings: readonly any[]): SqlCondition {\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { sql: `${left.sql} ${exp}`, bindings: [...left.bindings, ...bindings], refs: left.refs };\n });\n }\n\n /** Uses column filter conversions for literals and shared comparisons for expressions and null equality. */\n protected compare(op: string, value: unknown): SqlCondition {\n if (value === undefined || isExpr(value) || (value === null && (op === \"=\" || op === \"!=\"))) {\n return super.compare(op, value);\n }\n // Primitive relational comparisons historically bind null through mapToDb.\n const kind = ({ \"=\": \"eq\", \"!=\": \"ne\", \">\": \"gt\", \">=\": \"gte\", \"<\": \"lt\", \"<=\": \"lte\" } as const)[op];\n if (!kind) return fail(`Invalid operator ${op}`);\n return this.addCondition({ kind, value });\n }\n\n /**\n * Compares this column to another expression.\n *\n * Table columns, aggregates, subquery columns, and `sql` templates use the expression context\n * to render their complete SQL.\n * Negated array operators wrap the complete comparison in NOT.\n */\n protected compareToExpr(op: string, value: ExprLike<any>, negate = false): SqlCondition {\n if (negate) {\n return deferredCondition((ctx) => {\n const comparison = ctx.conditionToSql(this.compareToExpr(op, value))!;\n return { ...comparison, sql: `NOT (${comparison.sql})` };\n });\n }\n return super.compare(op, value);\n }\n}\n\nclass PrimitiveColumnImpl<V, N extends null | never> extends TableColumn implements PrimitiveColumn<V, N> {\n between(v1: V | undefined, v2: V | undefined): SqlCondition {\n if (v1 === undefined || v2 === undefined) return skipCondition;\n return this.addCondition({ kind: \"between\", value: [v1, v2] });\n }\n\n like(value: V | undefined): SqlCondition {\n if (value === undefined) return skipCondition;\n return this.addCondition({ kind: \"like\", value });\n }\n\n ilike(value: V | undefined): SqlCondition {\n if (value === undefined) return skipCondition;\n return this.addCondition({ kind: \"ilike\", value });\n }\n\n search(value: V | undefined): SqlCondition {\n // Check !value so that empty strings are pruned\n if (!value) return skipCondition;\n return this.addCondition({ kind: \"ilike\", value: makeLike(value) });\n }\n\n in(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inList(\"IN\", values);\n if (values.includes(null)) {\n const isNull = this.addCondition({ kind: \"is-null\" });\n const hasValue = this.addCondition({ kind: \"in\", value: values.filter((v) => v !== null) });\n return { or: [isNull, hasValue] };\n } else {\n return this.addCondition({ kind: \"in\", value: values as V[] });\n }\n }\n\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (V | null)[] | undefined): SqlCondition {\n return values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n nin(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inList(\"NOT IN\", values);\n return this.addCondition({ kind: \"nin\", value: values.filter((v) => v !== null) as V[] });\n }\n\n // V will already be an array\n contains(v1: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"@>\", v1);\n return this.addCondition({ kind: \"contains\", value: v1 as any });\n }\n\n // V will already be an array\n ncontains(v1: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"@>\", v1, true);\n return this.addCondition({ kind: \"ncontains\", value: v1 as any });\n }\n\n // V will already be an array\n overlaps(v1: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"&&\", v1);\n return this.addCondition({ kind: \"overlaps\", value: v1 as any });\n }\n\n noverlaps(v1: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"&&\", v1, true);\n return this.addCondition({ kind: \"noverlaps\", value: v1 as any });\n }\n\n pathExists(jsonPath: string | undefined): SqlCondition {\n if (jsonPath === undefined) return skipCondition;\n return this.addCondition({ kind: \"jsonPathExists\", value: jsonPath });\n }\n\n pathIsTrue(jsonPath: string | undefined): SqlCondition {\n if (jsonPath === undefined) return skipCondition;\n return this.addCondition({ kind: \"jsonPathPredicate\", value: jsonPath });\n }\n\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition {\n if (bindings === undefined) return skipCondition;\n return this.addRawCondition(exp, bindings);\n }\n}\n\nclass EntityColumnImpl<T> extends TableColumn implements EntityColumn<T> {\n /** Uses the ID target's tag, including for foreign keys and polymorphic components. */\n taggedId(): Expr<string, string> {\n return new TaggedIdExpr(this) as unknown as Expr<string, string>;\n }\n\n in<\n F extends QuerySource,\n const S extends ExprLike<IdOf<T> | null>,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n >(values: QueryArg<F, S, J, Name>): SqlCondition;\n in(values: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n in(values: object | readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n if (values === undefined) {\n return skipCondition;\n } else if (values === null) {\n throw new Error(\"Unsupported\");\n } else if (isExpr(values)) {\n return this.inList(\"IN\", values);\n } else if (!Array.isArray(values)) {\n return { [inQueryCondition]: { column: this, query: values } } as unknown as SqlCondition;\n } else if (values.includes(null)) {\n // Like `PrimitiveColumn.in`, split `[a1, null]` into `IS NULL OR IN (...)`\n const isNull = this.addCondition({ kind: \"is-null\" });\n const hasValue = this.addCondition({ kind: \"in\", value: values.filter((v) => v !== null) as any });\n return { or: [isNull, hasValue] };\n } else {\n return this.addCondition({ kind: \"in\", value: values as any });\n }\n }\n\n /** Applies an IN condition unless the list is empty, null, or undefined. */\n inNonEmpty(values: readonly (T | IdOf<T> | null)[] | null | undefined): SqlCondition {\n return values === null || values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n nin(values: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n if (values === undefined) {\n return skipCondition;\n } else if (values === null) {\n throw new Error(\"Unsupported\");\n } else if (isExpr(values)) {\n return this.inList(\"NOT IN\", values);\n } else {\n return this.addCondition({ kind: \"nin\", value: values.filter((v) => v !== null) as any });\n }\n }\n\n gt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\">\", \"gt\", value);\n }\n\n gte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\">=\", \"gte\", value);\n }\n\n lt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\"<\", \"lt\", value);\n }\n\n lte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\"<=\", \"lte\", value);\n }\n\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition {\n if (bindings === undefined) return skipCondition;\n return this.addRawCondition(exp, bindings);\n }\n\n /** Joins via this FK, inheriting the source's LEFT join for otherwise required references. */\n as(other: object): object {\n return {\n ...this.joinEntry(this.sqlNullable === false ? \"inner\" : \"left\", other),\n [referenceJoinSource]: this.mgmt,\n };\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", other);\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", other);\n }\n\n private joinEntry(kind: JoinKind, other: object): object {\n return { [kind]: requireTable(other), on: this.eq(idColumnOf(other)) };\n }\n\n private compareId(op: string, kind: \"gt\" | \"gte\" | \"lt\" | \"lte\", value: unknown): SqlCondition {\n if (value === undefined) return skipCondition;\n if (value === null) throw new Error(\"Unsupported\");\n if (isExpr(value)) return this.compareToExpr(op, value);\n return this.addCondition({ kind, value: value as any });\n }\n}\n\n/** Converts a physical ID to SQL text so nested SQL expressions also receive the tag. */\nclass TaggedIdExpr extends BaseExpr {\n constructor(private column: TableColumn) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const fragment = this.column.toSql(ctx);\n const meta = this.column.idMetadata ?? fail(\"Tagged IDs require an ID column\");\n return {\n ...fragment,\n sql: `(? || ${fragment.sql}::text)`,\n bindings: [taggedIdPrefix(meta), ...fragment.bindings],\n };\n }\n\n get outputType(): TypeInfo {\n return { dbType: \"text\", domain: String, arrayElementSafe: true };\n }\n\n get sqlNullable(): boolean | undefined {\n return this.column.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.column.sqlSource;\n }\n}\n\nclass PolyReferenceImpl<T extends Entity> {\n public constructor(\n private meta: EntityMetadata,\n private mgmt: TableMgmt,\n private field: PolymorphicField,\n ) {}\n\n /** Compares to a tagged id, an entity, or another table's id column, which picks the component (`c.parent.eq(a.id)`). */\n eq(value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.addEqOrNe(\"eq\", value);\n }\n\n ne(value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.addEqOrNe(\"ne\", value);\n }\n\n // We required tagged ids for polys\n in(values: readonly (T | TaggedId)[] | ExprLike<IdOf<T> | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inSubquery(values);\n // Split up the ids by constructor\n const idsByConstructor = groupBy(values, (id) => getConstructorFromTaggedId(maybeResolveReferenceToId(id)!).name);\n // Or together `parent_book_id in (1,2,3) OR parent_author_id IN (4,5,6)`\n return {\n or: Object.entries(idsByConstructor).map(([cstrName, ids]) => {\n const comp =\n this.field.components.find((p) => p.otherMetadata().cstr.name === cstrName) ??\n fail(`No component for ${cstrName}`);\n return this.componentColumn(comp).addCondition({ kind: \"in\", value: ids });\n }),\n };\n }\n\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (T | TaggedId)[] | undefined): SqlCondition {\n return values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n /** Joins via this poly's component, inheriting the source's LEFT join when the poly is required. */\n as(other: object): object {\n return { ...this.joinEntry(this.field.required ? \"inner\" : \"left\", other), [referenceJoinSource]: this.mgmt };\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", other);\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", other);\n }\n\n private joinEntry(kind: JoinKind, other: object): object {\n return { [kind]: requireTable(other), on: this.eq(idColumnOf(other) as any) };\n }\n\n /**\n * i.e. `c.parent.in(query({ from: a, ..., select: a.id }))`: like `eq` against a table column, the\n * subquery's agreed ID domain picks the component, i.e. authors pick `parent_author_id`.\n */\n private inSubquery(values: ExprLike<any>): SqlCondition {\n // Only actual subqueries expose this getter; importing query.ts would create a load-order cycle.\n const selected = asNode(values).subquerySelect;\n const outputType = selected?.outputType;\n let otherMeta = outputType?.idMeta;\n if (!otherMeta) {\n // Ordinary reads can select an unknown key serde. Compounds validate codecs before exposing a select.\n if (!outputType && selected instanceof TableColumn) {\n otherMeta = selected.idMetadata;\n }\n if (!otherMeta) {\n return fail(\n selected instanceof TableColumn\n ? `${this.field.fieldName} \\`in\\` needs an id or FK column, got ${selected.column.columnName}`\n : `${this.field.fieldName} is polymorphic, so \\`in\\` needs a subquery selecting an id or FK column`,\n );\n }\n }\n const comp =\n this.field.components.find((p) => getBaseAndSelfMetas(otherMeta).includes(p.otherMetadata())) ??\n fail(`${this.field.fieldName} has no component for ${otherMeta.type}`);\n return this.componentColumn(comp).in(values);\n }\n\n private addEqOrNe(\n kind: \"eq\" | \"ne\",\n value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined,\n ): SqlCondition {\n if (value === undefined) {\n return skipCondition;\n } else if (value instanceof TableColumn) {\n // Joining through the poly, i.e. `c.parent.eq(a.id)`: the other table column's ID domain picks the component\n const otherMeta = value.idMetadata ?? fail(`${this.field.fieldName} needs an id or FK column`);\n const comp =\n this.field.components.find((p) => getBaseAndSelfMetas(otherMeta).includes(p.otherMetadata())) ??\n fail(`${this.field.fieldName} has no component for ${otherMeta.type}`);\n return this.componentColumn(comp)[kind](value);\n } else if (isExpr(value)) {\n return fail(\n `${this.field.fieldName} is polymorphic, so it can only be compared to tagged ids or entity table columns`,\n );\n } else if (value === null) {\n // We can AND each of the components as many conditions\n const value = kind === \"eq\" ? ({ kind: \"is-null\" } as const) : ({ kind: \"not-null\" } as const);\n return {\n and: this.field.components.map((p) => this.componentColumn(p).addCondition(value)),\n };\n } else {\n // If we have a value, we can find the component\n const comp =\n this.field.components.find(\n (p) => p.otherMetadata().cstr === getConstructorFromTaggedId(maybeResolveReferenceToId(value) as string),\n ) || fail(`Could not find component for ${value}`);\n return this.componentColumn(comp)[kind](value);\n }\n }\n\n /** Returns the physical FK expression for one polymorphic target. */\n private componentColumn(comp: PolymorphicFieldComponent): EntityColumnImpl<T> {\n const descriptor = comp.column;\n return new EntityColumnImpl<T>(this.meta, descriptor, this.mgmt);\n }\n}\n\n/**\n * Marks a sugar join entry whose target is a *collection* (o2m/m2m), which filter soft-deletes like\n * em.find's \"collections filter out soft-deletes, but m2o/o2o references still return them\"; see\n * `QueryParser.addSoftDeleteCondition`'s call site. Reference joins and explicit joins are unmarked.\n */\nexport const collectionJoin: unique symbol = Symbol(\"joist.collectionJoin\");\n\n/** Marks a sugar m2m join entry (`a.tags.as(t)`) with its hidden join-table join; `parseQuery` expands it. */\nexport const m2mJoinTable: unique symbol = Symbol(\"joist.m2mJoinTable\");\n\nexport interface M2mJoinTable {\n handle: JoinTableHandle;\n on: SqlCondition;\n}\n\n/** The runtime identity of an m2m join table in a query, i.e. `authors_to_tags`; it has no entity. */\nexport class JoinTableHandle {\n constructor(readonly joinTableName: string) {}\n}\n\ntype JoinKind = \"inner\" | \"left\";\n\n/**\n * The `as`/`inner`/`left` join factory for collection relations, i.e. `a.books.as(b)` joins with the\n * relation's default kind (LEFT: a collection may be empty) and `.inner`/`.left` override. m2o/poly\n * relations implement the same three methods on their join factories. Physical FKs such as\n * `b.author_id` are expressions that also expose a join factory.\n */\nabstract class CollectionJoinImpl {\n as(other: object): object {\n return this.joinEntry(\"left\", requireTable(other));\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", requireTable(other));\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", requireTable(other));\n }\n\n protected abstract joinEntry(kind: JoinKind, other: TableFor<Entity>): object;\n}\n\n/** Joins a named subtype explicitly; only STI subtype sugar adds a discriminator to its ON. */\nclass SubtypeJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: TableFor<Entity>,\n private subtype: EntityMetadata,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n if (getTableMetadata(other) !== this.subtype) {\n return fail(`Expected table(${this.subtype.type}) for the explicit subtype join`);\n }\n const on = idColumnOf(this.proxy).eq(idColumnOf(other));\n if (this.subtype.inheritanceType !== \"sti\" || this.subtype.stiDiscriminatorValue === undefined) {\n return { [kind]: other, on };\n }\n const base = this.subtype.baseTypes.find((m) => m.stiDiscriminatorField !== undefined)!;\n const columnName = base.fields[base.stiDiscriminatorField!].serde!.columns[0].columnName;\n // Discriminator values are database enum ids, not domain enum values to pass through the field codec.\n const discriminator = deferredCondition((ctx) => {\n const alias = ctx.aliasFor(other[tableMgmt]);\n return {\n sql: `${kqDot(alias, columnName)} = ?`,\n bindings: [this.subtype.stiDiscriminatorValue],\n refs: [alias],\n };\n });\n return { [kind]: other, on: { and: [on, discriminator] } };\n }\n}\n\n/** An o2m/lo2m/o2o relation: the ON is the other side's FK (an m2o or a poly component) back to our id. */\nclass OneToManyJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: any,\n private field: OneToManyField | LargeOneToManyField | OneToOneField,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n const { field } = this;\n const otherMeta = getTableMetadata(other);\n const descriptor = Object.values(otherMeta.columns).find((column) => column.columnName === field.otherColumnName);\n if (!descriptor) {\n return fail(\n `Cannot join ${getTableMetadata(this.proxy).type}.${field.fieldName} to ${otherMeta.type}: ` +\n `${field.otherColumnName} is not physically present on ${otherMeta.tableName}; join the base table explicitly`,\n );\n }\n const column = new EntityColumnImpl(otherMeta, descriptor, other[tableMgmt]);\n const on = column.eq(this.proxy.id);\n // Collections (o2m/lo2m) filter soft-deletes like em.find; o2o references resolve them\n const filtered = field.kind === \"o2m\" ? field.softDeletes !== \"include\" : field.kind === \"lo2m\";\n return { [kind]: other, on, [collectionJoin]: filtered };\n }\n}\n\n/**\n * An m2m relation, i.e. `a.tags.as(t)`.\n *\n * The entry's own ON is `t.id = att.tag_id`, and the hidden `[m2mJoinTable]` half is\n * `att.author_id = a.id`; only the target's ON references the join table, so reference pruning keeps\n * or drops the pair together. Both are deferred conditions: the join table has no entity metadata, so\n * its alias only exists once the parser registers it.\n */\nclass ManyToManyJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: any,\n private field: ManyToManyField,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n const { joinTableName, columnNames } = this.field;\n const [ourColumn, otherColumn] = columnNames;\n const jt = new JoinTableHandle(joinTableName);\n const ourId = idColumnOf(this.proxy);\n const otherId = idColumnOf(other);\n const jtOn = deferredCondition((ctx) => {\n const jtAlias = ctx.aliasFor(jt);\n const id = ourId.toSql(ctx);\n return { sql: `${kqDot(jtAlias, ourColumn)} = ${id.sql}`, bindings: id.bindings, refs: id.refs };\n });\n const on = deferredCondition((ctx) => {\n const jtAlias = ctx.aliasFor(jt);\n const id = otherId.toSql(ctx);\n return { sql: `${id.sql} = ${kqDot(jtAlias, otherColumn)}`, bindings: id.bindings, refs: [...id.refs, jtAlias] };\n });\n const filtered = this.field.softDeletes !== \"include\";\n return {\n [kind]: other,\n on,\n [collectionJoin]: filtered,\n [m2mJoinTable]: { handle: jt, on: jtOn } satisfies M2mJoinTable,\n };\n }\n}\n\n/** Fails fast when a join factory is passed something other than a table. */\nfunction requireTable(other: object): TableFor<Entity> {\n if (!isEntityTable(other)) return fail(`Expected an entity table to join, got ${other}`);\n return other;\n}\n\n/** The id column of a joined table, for building sugar ON conditions. */\nfunction idColumnOf(other: object): TableColumn {\n return (other as any).id;\n}\n\n/** Keeps relation names join-only; physical FK columns retain expression methods. */\nclass ReferenceJoinImpl {\n constructor(private column: EntityColumnImpl<unknown>) {}\n\n as(other: object): object {\n return this.column.as(other);\n }\n\n inner(other: object): object {\n return this.column.inner(other);\n }\n\n left(other: object): object {\n return this.column.left(other);\n }\n}\n\n/** Identifies domain relationship keys exposed alongside physical columns. */\nfunction isRelation(field: Field | undefined): boolean {\n return field !== undefined && [\"m2o\", \"poly\", \"o2m\", \"lo2m\", \"m2m\", \"o2o\"].includes(field.kind);\n}\n\n/** Resolves relationship sugar only from domain fields owned by this physical table. */\nfunction physicalRelation(meta: EntityMetadata, key: string): Field | undefined {\n const owners = [meta, ...getBaseSelfAndSubMetas(getBaseMeta(meta))];\n const owner = owners.find((owner) => owner.tableName === meta.tableName && Object.hasOwn(owner.fields, key));\n const field = owner?.fields[key];\n if (!isRelation(field)) return undefined;\n // I.e. TaskNew.copiedFrom uses Task's original FK domain, not its specialized TaskNew target.\n if (field?.kind === \"m2o\" || field?.kind === \"poly\") {\n if (!field.serde.columns.every((binding) => Object.values(meta.columns).includes(binding.column))) return undefined;\n return field.kind === \"poly\"\n ? {\n ...field,\n components: field.components.map((component) => ({\n column: component.column,\n columnName: component.columnName,\n otherFieldName: component.otherFieldName,\n otherMetadata: component.column.idMetadata!,\n })),\n }\n : field;\n }\n return field;\n}\n\n/**\n * Maps local domain fields to table-bound conditions, encoding each leaf once.\n * I.e. Author.firstName uses the first_name column but resolves its alias in each query scope.\n * Collections, polymorphic references, and inherited nonlocal fields require explicit expressions.\n */\nexport function tableWhere(mgmt: TableMgmt, filter: object): SqlCondition {\n const { meta } = mgmt;\n const conditions: SqlCondition[] = [];\n if (!filter || typeof filter !== \"object\" || Array.isArray(filter)) {\n throw new Error(`Expected a domain field filter for ${meta.type}`);\n }\n for (const [key, value] of Object.entries(filter)) {\n // CTI allFields.id points at the base key; the subtype has its own physical key.\n const field = key === \"id\" ? meta.fields.id : Object.hasOwn(meta.allFields, key) ? meta.allFields[key] : undefined;\n if (\n !field ||\n ![\"primaryKey\", \"primitive\", \"enum\", \"m2o\"].includes(field.kind) ||\n !field.serde ||\n field.serde.columns.length !== 1 ||\n !field.serde.columns.every((binding) => Object.values(meta.columns).includes(binding.column))\n ) {\n throw new Error(`Unsupported table filter field ${meta.type}.${key}; use an explicit join`);\n }\n const column = new TableColumn(meta, field.serde.columns[0].column, mgmt);\n let leaves: ParsedValueFilter<unknown>[];\n if (field.kind === \"m2o\") {\n if (!isTableReferenceFilter(value)) {\n throw new Error(`Unsupported table reference filter ${meta.type}.${key}; use an entity or ID`);\n }\n const parsed = parseEntityFilter(field.otherMetadata(), value);\n if (parsed?.kind === \"join\") {\n throw new Error(`Unsupported table reference filter ${meta.type}.${key}; use an entity or ID`);\n }\n leaves = parsed ? [parsed] : [];\n } else {\n leaves = parseValueFilter(value);\n }\n for (const leaf of leaves) {\n if (leaf.kind === \"between\" && leaf.value.some((v) => v === undefined)) {\n if (leaf.value[0] !== undefined) conditions.push(column.addCondition({ kind: \"gte\", value: leaf.value[0] }));\n if (leaf.value[1] !== undefined) conditions.push(column.addCondition({ kind: \"lte\", value: leaf.value[1] }));\n } else if (leaf.kind === \"in\" && !column.column.isArray && leaf.value.includes(null)) {\n conditions.push({\n or: [\n column.addCondition({ kind: \"is-null\" }),\n column.addCondition({ kind: \"in\", value: leaf.value.filter((v) => v !== null) }),\n ],\n });\n } else {\n conditions.push(column.addCondition(leaf));\n }\n }\n }\n return conditions.length === 0 ? skipCondition : { and: conditions };\n}\n\n/**\n * Converts relationship filters into conditions on the joined table's id column.\n * I.e. Author's `join: { books: \"b:1\" }` filters Book.id to 1; `{ books: book }` uses book.id.\n * Lists match any supplied ID, `true` requires a Book, and `null` or `false` requires no Book.\n */\nexport function tableEntityWhere(mgmt: TableMgmt, value: unknown): SqlCondition {\n const parsed = parseEntityFilter(mgmt.meta, value);\n if (!parsed) return skipCondition;\n if (parsed.kind === \"join\") fail(`Expected an entity or ID filter for ${mgmt.meta.type}`);\n return new TableColumn(mgmt.meta, mgmt.meta.fields.id.serde!.columns[0].column, mgmt).addCondition(parsed);\n}\n\n/** Rejects nested relations, scopes, and aliases before parsing owning-reference values. */\nfunction isTableReferenceFilter(value: unknown): boolean {\n if (value == null || typeof value === \"boolean\" || isTableReferenceValue(value)) return true;\n if (Array.isArray(value)) return value.every(isTableReferenceValue);\n if (typeof value === \"object\" && Object.keys(value).length === 1 && Object.hasOwn(value, \"ne\")) {\n const excluded = (value as { ne: unknown }).ne;\n return excluded == null || isTableReferenceValue(excluded);\n }\n return false;\n}\n\n/** Recognizes an entity or public ID without accepting another filter object. */\nfunction isTableReferenceValue(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || isEntity(value);\n}\n"],"mappings":";;;;;;;;;;;;;;AA6EA,SAAgB,MACd,MACA,OACS;CAET,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AOA,SAAgB,iBAAiB,MAAiB,OAA8B;CAC9E,MAAM,SAASU,6BAAAA,kBAAkB,KAAK,MAAM,KAAK;CACjD,IAAI,CAAC,QAAQ,OAAOV,8BAAAA;CACpB,IAAI,OAAO,SAAS,QAAQ,cAAA,KAAK,uCAAuC,KAAK,KAAK,MAAM;CACxF,OAAO,IAAI,YAAY,KAAK,MAAM,KAAK,KAAK,OAAO,GAAG,MAAO,QAAQ,EAAE,CAAC,QAAQ,IAAI,CAAC,CAAC,aAAa,MAAM;AAC3G;;AAGA,SAAS,uBAAuB,OAAyB;CACvD,IAAI,SAAS,QAAQ,OAAO,UAAU,aAAa,sBAAsB,KAAK,GAAG,OAAO;CACxF,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,MAAM,qBAAqB;CAClE,IAAI,OAAO,UAAU,YAAY,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,OAAO,OAAO,OAAO,IAAI,GAAG;EAC9F,MAAM,WAAY,MAA0B;EAC5C,OAAO,YAAY,QAAQ,sBAAsB,QAAQ;CAC3D;CACA,OAAO;AACT;;AAGA,SAAS,sBAAsB,OAAyB;CACtD,OAAO,OAAO,UAAU,YAAY,OAAO,UAAU,YAAYY,eAAAA,SAAS,KAAK;AACjF"}
1
+ {"version":3,"file":"Tables.cjs","names":["isCustomTableDefinition","safeKq","kq","getMetadata","RefExpr","fail","getCustomTableDefinition","BaseExpr","selectKeyBrand","kqDot","toIdOf","mapToDb","deferredCondition","buildValueCondition","isExpr","skipCondition","OperatorExpr","makeLike","taggedIdPrefix","groupBy","getConstructorFromTaggedId","maybeResolveReferenceToId","asNode","getBaseAndSelfMetas","getBaseSelfAndSubMetas","getBaseMeta","parseEntityFilter","parseValueFilter","isEntity"],"sources":["../../../src/queries/sql/Tables.ts"],"sourcesContent":["import { groupBy } from \"joist-utils\";\n// Load configure first: otherwise the built cjs/esm module graph evaluates relations/* before their\n// base classes exist (\"Class extends value undefined\").\nimport { getConstructorFromTaggedId } from \"src/configure.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport type { IdOf, MaybeAbstractEntityConstructor, TaggedId } from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type LargeOneToManyField,\n type ManyToManyField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PolymorphicFieldComponent,\n getBaseAndSelfMetas,\n getBaseMeta,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"src/EntityMetadata.ts\";\nimport { maybeResolveReferenceToId, taggedIdPrefix, toIdOf } from \"src/keys.ts\";\nimport type { SqlCondition } from \"src/queries/conditions.ts\";\nimport type { ParsedValueFilter } from \"src/queries/parsedConditions.ts\";\nimport { buildValueCondition } from \"src/queries/renderConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport {\n type CustomColumnInputs,\n type CustomTable,\n type CustomTableDefinition,\n type CustomTableFor,\n type CustomTableMgmt,\n getCustomTableDefinition,\n isCustomTableDefinition,\n} from \"src/queries/sql/custom.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n OperatorExpr,\n RefExpr,\n type SqlFragment,\n asNode,\n deferredCondition,\n isExpr,\n selectKeyBrand,\n} from \"src/queries/sql/Expr.ts\";\nimport { kq, kqDot, safeKq } from \"src/queries/sql/keywords.ts\";\nimport type { QueryArg, QueryJoinInput, QuerySource } from \"src/queries/sql/query.ts\";\nimport { makeLike, mapToDb, parseEntityFilter, parseValueFilter } from \"src/queries/valueFilters.ts\";\nimport type { Column } from \"src/serde/columns.ts\";\nimport type { TypeInfo } from \"src/serde/TypeInfo.ts\";\nimport type { ColumnsOf, FieldsOf, FilterOf, TypeMap, TypeNameOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\n/** Creates physical column expressions and relationship joins for `T`. */\nexport function table<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): Table<T>;\n/** Creates a typed physical handle for a table declared with `declareTable`. */\nexport function table<TableName extends string, C extends CustomColumnInputs>(\n definition: CustomTableDefinition<TableName, C>,\n): CustomTable<C, TableName>;\n/**\n * Creates a table with an explicit type-level name, i.e. `table(Author, \"m\")` for a self-join.\n *\n * The name is the table's source key in `em.query`: two bare `table(Author)`s share the key `\"Author\"`,\n * so a left-joined mentor would also mark the mentee's columns nullable; a named alias has its own key.\n */\nexport function table<T extends Entity, Name extends string>(\n cstr: MaybeAbstractEntityConstructor<T>,\n name: Name,\n): Table<T, Name>;\n/** Creates a named custom-table handle for joins and self-joins. */\nexport function table<C extends CustomColumnInputs, TableName extends string, Name extends string>(\n definition: CustomTableDefinition<TableName, C>,\n name: Name,\n): CustomTable<C, Name>;\nexport function table<T extends Entity>(\n cstr: MaybeAbstractEntityConstructor<T> | CustomTableDefinition<string, CustomColumnInputs>,\n _name?: string,\n): unknown {\n // The name only exists at the type level; the SQL alias is still assigned by the query parser\n return isCustomTableDefinition(cstr) ? newCustomTableProxy(cstr) : newTableProxy(cstr);\n}\n\n/** Creates multiple physical table handles. */\nexport function tables<T extends readonly MaybeAbstractEntityConstructor<any>[]>(\n ...type: T\n): { [P in keyof T]: T[P] extends MaybeAbstractEntityConstructor<infer E extends Entity> ? Table<E> : never } {\n return type.map((t) => newTableProxy(t)) as any;\n}\n\n/**\n * The runtime management interface plus phantom type information for `em.query`.\n *\n * `__entity` lets `QueryRow` recover `T` for entity mode (you cannot `infer T` back out of a mapped\n * type), and `__name` is the table's source key (see `Expr`).\n */\nexport interface TableSourceBrand<Name extends string> extends TableSourceMgmt {\n readonly __name: Name;\n}\n\n/** A modeled table source that can hydrate its generated entity type. */\nexport interface TableBrand<T, Name extends string> extends TableSourceBrand<Name>, TableMgmt {\n readonly __entity: T;\n}\n\n/**\n * A physical table for `T`: one expression per SQL column, with relationship names as join factories.\n * Selecting the table itself retains entity hydration; selecting columns returns decoded SQL values.\n *\n * Unlike an Alias, a Table is an explicit SQL source, not a place to bind in an em.find relationship\n * tree. I.e. with `a = table(Author)`, `{ from: a }` registers that handle in the query's scope.\n * Its columns already know their physical column and codec, but their SQL name still depends on the\n * query: the same Author handle might be `a` in one query and `a1` in a nested query.\n *\n * Each predicate occurrence renders through ExprContext.aliasFor using the current scope (or an\n * enclosing scope for a correlation). Rendering returns SQL, ordered bindings, and source references\n * together. A comparison records both sides' references; templates and subqueries carry their\n * references too. Join pruning follows these references and join dependencies, rather than guessing\n * which tables a SQL string mentions. It also accounts for select/order/group expressions and keep.\n *\n * I.e. if a joined Author is used only by `a.firstName.eq(name)`, supplying undefined removes that\n * predicate and lets the unused join prune. Both APIs share this undefined-condition pruning rule;\n * they differ in how they get the references: Alias resolves domain conditions against a relationship\n * tree, while Table renders SQL expressions against explicit sources. Neither caches SQL names on\n * the reusable handle or predicate, so one parse cannot overwrite another parse's bindings.\n *\n * `Name` is the table's type-level source key, defaulting to the entity's own type name, so a\n * LEFT-joined SmallPublisher does not make Publisher columns nullable. `table(Author, \"m\")`\n * gives a self-join table its own key.\n */\nexport type Table<T extends Entity, Name extends string = TableNameOf<T>> = TableShape<T, Name> &\n (\"where\" extends keyof TableShape<T, Name>\n ? {}\n : {\n /** Builds an AND condition from local domain fields, without implicit joins. */\n where(filter: TableFilter<T>): SqlCondition;\n }) &\n (\"column\" extends keyof TableShape<T, Name>\n ? {}\n : {\n /**\n * References a column Joist does not model, i.e. `a.column<string>(\"ts_search\")`.\n *\n * The expression keeps this table's source key, so it is scope-checked and nullified by a\n * LEFT join like any modeled column. `R` is unchecked: it asserts what the database returns,\n * and the value is not decoded through a codec.\n *\n * A schema that has its own `column` column or relation keeps that meaning, and then has no\n * escape hatch for unmodeled columns.\n */\n column<R = unknown>(column: string): Expr<R, Name>;\n });\n\n/** Domain filters for fields stored on this physical table, without relationship traversal. */\nexport type TableFilter<T extends Entity> = {\n [K in LocalFieldNames<T> & keyof FieldsOf<T>]?: FieldsOf<T>[K] extends {\n kind: \"m2o\";\n type: infer U extends Entity;\n nullable: infer N;\n }\n ? TableReferenceFilter<U, N extends undefined ? null : never>\n : FilterOf<T>[K];\n};\n\n/** Generated column ownership excludes CTI base fields and polymorphic components. */\ntype LocalFieldNames<T> = ColumnsOf<T>[keyof ColumnsOf<T>] extends { fieldName: infer F }\n ? Extract<F, keyof FilterOf<T>>\n : never;\n\n/** The owning-reference subset of find filters that only compares a foreign key. */\ntype TableReferenceFilter<T extends Entity, N> =\n | T\n | IdOf<T>\n | readonly (T | IdOf<T>)[]\n | boolean\n | N\n | undefined\n | { ne: T | IdOf<T> | N | undefined };\n\n/** Maps an entity's columns and relationships to expressions and joins for one typed table handle. */\ntype TableShape<T extends Entity, Name extends string> = {\n readonly [tableMgmt]: TableBrand<T, Name>;\n} & {\n // Add typed expressions for each physical column, including its property name for array selects.\n [P in keyof ColumnsOf<T> & string]: P extends \"id\"\n ? EntityColumn<T, never, Name, P>\n : ColumnsOf<T>[P] extends { entity: infer U extends Entity; nullable: infer N }\n ? ReferenceColumn<U, N extends true ? null : never, Name, P>\n : ColumnsOf<T>[P] extends { type: infer V; nullable: infer N }\n ? PrimitiveColumn<V, N extends true ? null : never, Name, P>\n : never;\n} & {\n // Add relation join sugar such as `a.books.as(b)` for fields that are not physical columns.\n [\n P in keyof FieldsOf<T> as P extends keyof ColumnsOf<T>\n ? never\n : FieldsOf<T>[P] extends { kind: \"m2o\" | \"poly\" | \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\" }\n ? P\n : never\n ]: FieldsOf<T>[P] extends { kind: \"m2o\"; type: infer U extends Entity; nullable: infer N }\n ? ReferenceJoin<U, N extends undefined ? null : never, Name>\n : FieldsOf<T>[P] extends { kind: \"poly\"; type: infer U extends Entity; nullable: infer N }\n ? PolyReference<U, N extends undefined ? null : never, Name>\n : FieldsOf<T>[P] extends { kind: \"o2m\" | \"lo2m\" | \"m2m\" | \"o2o\"; type: infer U extends Entity }\n ? CollectionJoin<U>\n : never;\n} & {\n // Add subtype join sugar such as `p.smallPublisher(sp)` for entities whose __type root is T.\n // CTI joins the physical tables by ID; STI self-joins the shared table by ID plus its discriminator.\n [\n K in keyof TypeMap as TypeMap[K] extends {\n entityType: infer U extends Entity & { __type: { 0: TypeNameOf<T>; 1: string } };\n }\n ? Uncapitalize<TypeNameOf<U> & string>\n : never\n ]: TypeMap[K] extends { entityType: infer U extends Entity } ? SubtypeJoin<U> : never;\n};\n\n/** Keeps explicit base and subtype sources independent, with generic entities untracked. */\ntype TableNameOf<T> = T extends { __type: { 0: string } } ? TypeNameOf<T> & string : string;\n\n/** Provides fluent methods for creating joins through an owning reference relationship. */\nexport interface ReferenceJoin<U extends Entity, N extends null | never, Src extends string = string> {\n /**\n * Required reference joins like `b.author.as(a)` are INNER unless `b` is already a LEFT-joined alias.\n * Nullable references are always LEFT joined.\n */\n as<A extends TableFor<U>>(other: A): [N] extends [never] ? DefaultReferenceJoin<A, Src> : LeftJoin<A>;\n inner<A extends TableFor<U>>(other: A): InnerJoin<A>;\n left<A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/** The source of a default reference join, used to inherit optional paths within each query. */\nexport const referenceJoinSource: unique symbol = Symbol(\"joist.referenceJoinSource\");\n\n/** A required reference defaults to INNER unless its source was LEFT joined. */\nexport type DefaultReferenceJoin<A, Src extends string> = InnerJoin<A> & {\n readonly [referenceJoinSource]: Src;\n};\n\n/** Any table whose entity is (a subtype of) `U`, i.e. what a relation join factory accepts. */\nexport type TableFor<U> = { readonly [tableMgmt]: TableBrand<U, string> };\n\n/**\n * A collection relation (o2m/o2o/m2m) as a join factory: `a.books.as(b)` returns the same\n * `{ left: b, on: ... }` entry the expanded form writes, with the FK condition built from metadata, so\n * join-list inference, nullability, scope checking, and pruning are unchanged and both forms mix freely.\n *\n * `as` binds the joined alias, the same way em.find's `{ books: { as: b } }` does. The default is LEFT\n * (a collection may be empty, and a LEFT join never filters rows, so pruning it is always safe);\n * `.inner(b)` opts into filtering. An m2m entry carries a hidden second join through the join table,\n * which the parser expands; the pair prunes together.\n */\nexport interface CollectionJoin<U extends Entity> {\n as<A extends TableFor<U>>(other: A): LeftJoin<A>;\n inner<A extends TableFor<U>>(other: A): InnerJoin<A>;\n left<A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/** A named subtype join, defaulting to LEFT because a root row may belong to another subtype. */\ninterface SubtypeJoin<U extends Entity> extends CollectionJoin<U> {\n <A extends TableFor<U>>(other: A): LeftJoin<A>;\n}\n\n/**\n * A physical FK column expression (`b.authorId` selects/compares the `author_id` FK) plus a join factory\n * (`b.authorId.as(a)` joins). The default join kind follows physical column nullability:\n * a NOT NULL FK is INNER unless its source was LEFT joined, a nullable one is LEFT, and the row type reflects it.\n */\nexport interface ReferenceColumn<\n U extends Entity,\n N extends null | never,\n Src extends string,\n Key extends string = string,\n>\n extends EntityColumn<U, N, Src, Key>, ReferenceJoin<U, N, Src> {}\n\n/**\n * A polymorphic reference: condition methods (each resolving the component column from the value), plus\n * a join factory that picks the component from the argument's entity, i.e. `c.parent.as(a)` joins\n * through `parent_author_id`, like an explicit join with `on: c.parent.eq(a.id)`.\n */\nexport interface PolyReference<\n U extends Entity,\n N extends null | never,\n Src extends string = string,\n> extends ReferenceJoin<U, N, Src> {\n eq(value: U | TaggedId | ExprLike<IdOf<U> | null> | null | undefined): SqlCondition;\n ne(value: U | TaggedId | ExprLike<IdOf<U> | null> | null | undefined): SqlCondition;\n in(values: readonly (U | TaggedId)[] | ExprLike<IdOf<U> | null> | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (U | TaggedId)[] | undefined): SqlCondition;\n}\n\nexport interface PrimitiveColumn<\n V,\n N extends null | never,\n Src extends string = string,\n Key extends string = string,\n> extends Expr<V | N, Src> {\n readonly [selectKeyBrand]: Key;\n eq(value: V | ExprLike<V | N> | N | undefined): SqlCondition;\n ne(value: V | ExprLike<V | N> | N | undefined): SqlCondition;\n in(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (V | null)[] | undefined): SqlCondition;\n nin(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition;\n gt(value: V | ExprLike<V | N> | undefined): SqlCondition;\n gte(value: V | ExprLike<V | N> | undefined): SqlCondition;\n lt(value: V | ExprLike<V | N> | undefined): SqlCondition;\n lte(value: V | ExprLike<V | N> | undefined): SqlCondition;\n like(value: V | undefined): SqlCondition;\n ilike(value: V | undefined): SqlCondition;\n search(value: V | undefined): SqlCondition;\n between(v1: V | undefined, v2: V | undefined): SqlCondition;\n /**\n * The cosine distance (pgvector's `<=>`) between this `vector` column and `vector`, from 0 for the same direction\n * to 2 for opposite directions; NULL when the column is NULL.\n *\n * Only `vector` columns support it, so other `number[]` (i.e. pg array) columns fail when the query is built.\n */\n cosineDistance(\n this: PrimitiveColumn<number[], N, Src, Key>,\n vector: number[] | ExprLike<number[] | N>,\n ): Expr<number | N, Src>;\n // need to move to ArrayColumn\n // ...added the `string` to support jsonb contains like `WHERE profile @> '{\"age\": 25}'`\n // Ideally this would go in a JsonbColumn\n contains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n ncontains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n overlaps(value: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n noverlaps(value: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;\n\n /**\n * Adds a JSON path existence condition, using the `@?` operator.\n *\n * Any values should be embedded directly within the `jsonPath`, because postgres does not\n * support parameterized JSON path expressions. The entire `jsonPath` is treated as a parameter,\n * so this is safe from SQL injection.\n */\n pathExists(jsonPath: string | undefined): SqlCondition;\n\n /**\n * Adds a JSON path predicate condition, using the `@@` operator.\n *\n * Any values should be embedded directly within the `jsonPath`, because postgres does not\n * support parameterized JSON path expressions. The entire `jsonPath` is treated as a parameter,\n * so this is safe from SQL injection.\n */\n pathIsTrue(jsonPath: string | undefined): SqlCondition;\n\n /**\n * Add `exp` to the query, which should include the operator & expression and any\n * bound parameters (but not include the column name).\n *\n * We use knex-style placeholders, i.e. `?` and `\\\\?` to escape question marks, i.e.\n *\n * ```ts\n * a.address.raw(\"@\\\\? ?\", ['$.street ? (@ == \"rr2\")'])`\n * ```\n */\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition;\n}\n\nexport interface EntityColumn<\n T,\n N extends null | never = never,\n Src extends string = string,\n Key extends string = string,\n> extends Expr<IdOf<T> | N, Src> {\n readonly [selectKeyBrand]: Key;\n /** Produces the tagged ID as SQL text, preserving NULL and the column's source. */\n taggedId(): Expr<string | N, Src>;\n eq(value: T | IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n ne(value: T | IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n // Adding `| null` for GraphQL support\n in<\n F extends QuerySource,\n const S extends ExprLike<IdOf<T> | null>,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n >(\n value: QueryArg<F, S, J, Name>,\n ): SqlCondition;\n in(value: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n /** Applies an IN condition unless the list is empty, null, or undefined. */\n inNonEmpty(value: readonly (T | IdOf<T> | null)[] | null | undefined): SqlCondition;\n nin(value: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n gt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n gte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n lt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n lte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition;\n}\n\nexport const tableMgmt = Symbol(\"tableMgmt\");\nexport const inQueryCondition: unique symbol = Symbol(\"joist.inQueryCondition\");\n\n/** Defers a direct IN query literal to query.ts, which owns query pruning and SQL generation. */\nexport interface InQueryCondition {\n readonly [inQueryCondition]: { column: BaseExpr; query: object };\n}\n\nexport function getTableMgmt<T extends Entity>(table: TableFor<T>): TableMgmt;\nexport function getTableMgmt(table: CustomTableFor): CustomTableMgmt;\nexport function getTableMgmt(table: TableFor<Entity> | CustomTableFor): TableSourceMgmt;\nexport function getTableMgmt(table: TableFor<Entity> | CustomTableFor): TableSourceMgmt {\n return table[tableMgmt];\n}\n\n/** The identity SQL queries bind a table by, plus its original entity metadata. */\nexport interface TableSourceMgmt {\n tableName: string;\n schema?: string;\n}\n\n/** Qualifies custom tables without changing SQL for tables on the default search path. */\nexport function tableSqlName(table: TableSourceMgmt): string {\n return table.schema ? `${safeKq(table.schema)}.${kq(table.tableName)}` : kq(table.tableName);\n}\n\n/** The identity and generated metadata of a modeled entity table. */\nexport interface TableMgmt extends TableSourceMgmt {\n /**\n * The metadata this table was created with, i.e. `table(TaskNew)` keeps `taskNewMeta`.\n *\n * It cannot be re-derived from `tableName`: STI subtypes share their base's table (`Task`, `TaskNew`,\n * and `TaskOld` are all `tasks`), so a `getMetadataForTable(\"tasks\")` lookup can only return the base\n * `Task`, and the alias would lose its subtype identity for explicit subtype joins and entity hydration.\n */\n meta: EntityMetadata;\n}\n\n/** Returns the metadata for the entity that `table` is bound to. */\nexport function getTableMetadata<T extends Entity>(table: TableFor<T>): EntityMetadata<T> {\n const mgmt = table[tableMgmt];\n return mgmt.meta as EntityMetadata<T>;\n}\n\nexport function newTableProxy<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): Table<T> {\n const meta = getMetadata(cstr);\n // The identity SQL queries bind to a source, retaining STI subtype metadata.\n const mgmt: TableMgmt = { tableName: meta.tableName, meta };\n const subtypes = new Map(meta.subTypes.map((m) => [m.type[0].toLowerCase() + m.type.slice(1), m]));\n const proxy: any = new Proxy(cstr, {\n /** Create a physical column expression or a relation join factory. */\n get(_, key: PropertyKey): any {\n if (key === tableMgmt) {\n return mgmt;\n }\n if (typeof key !== \"string\") return undefined;\n const descriptor = Object.hasOwn(meta.columns, key) ? meta.columns[key] : undefined;\n if (descriptor) {\n return descriptor.idMetadata\n ? new EntityColumnImpl(meta, descriptor, mgmt, key)\n : new PrimitiveColumnImpl(meta, descriptor, mgmt, key);\n }\n const subtype = subtypes.get(key);\n if (subtype) {\n const join = new SubtypeJoinImpl(proxy, subtype);\n return Object.assign(join.as.bind(join), {\n as: join.as.bind(join),\n inner: join.inner.bind(join),\n left: join.left.bind(join),\n });\n }\n const relation = physicalRelation(meta, key);\n if (key === \"where\" && !isRelation(meta.allFields[key])) {\n return (filter: TableFilter<T>) => tableWhere(mgmt, filter);\n }\n if (key === \"column\" && !isRelation(meta.allFields[key])) {\n return (column: string) => new RefExpr(mgmt, column);\n }\n const field = relation ?? fail(`No physical field ${key} on ${cstr.name}; join its base table explicitly`);\n switch (field.kind) {\n case \"m2o\":\n return new ReferenceJoinImpl(new EntityColumnImpl(meta, field.serde.columns[0].column, mgmt));\n case \"poly\":\n return new PolyReferenceImpl(meta, mgmt, field);\n case \"o2m\":\n case \"o2o\":\n case \"lo2m\":\n return new OneToManyJoinImpl(proxy, field);\n case \"m2m\":\n return new ManyToManyJoinImpl(proxy, field);\n default:\n throw new Error(`Unsupported table field kind ${field.kind}`);\n }\n },\n\n has(_, key) {\n return (\n key === tableMgmt ||\n (typeof key === \"string\" &&\n (key === \"where\" ||\n key === \"column\" ||\n Object.hasOwn(meta.columns, key) ||\n !!physicalRelation(meta, key) ||\n subtypes.has(key)))\n );\n },\n });\n return proxy;\n}\n\n/** Creates a typed handle for primitive columns declared outside Joist codegen. */\nfunction newCustomTableProxy<TableName extends string, C extends CustomColumnInputs>(\n definition: CustomTableDefinition<TableName, C>,\n): CustomTable<C, TableName> {\n const { tableName, schema, columns } = getCustomTableDefinition(definition);\n const mgmt: CustomTableMgmt = { tableName, schema, columns };\n return new Proxy(\n {},\n {\n get(_, key: PropertyKey): unknown {\n if (key === tableMgmt) return mgmt;\n if (typeof key !== \"string\") return undefined;\n const descriptor = Object.hasOwn(columns, key) ? columns[key] : undefined;\n if (descriptor) return new PrimitiveColumnImpl(undefined, descriptor, mgmt, key);\n if (key === \"column\") return (column: string) => new RefExpr(mgmt, column);\n return fail(`Custom table ${tableName} has no declared column ${key}; use .column(\"${key}\")`);\n },\n has(_, key): boolean {\n return key === tableMgmt || key === \"column\" || (typeof key === \"string\" && Object.hasOwn(columns, key));\n },\n },\n ) as CustomTable<C, TableName>;\n}\n\nexport function isTable(obj: unknown): obj is Table<any, any> | CustomTableFor {\n return (typeof obj === \"function\" || (typeof obj === \"object\" && obj !== null)) && tableMgmt in obj;\n}\n\n/** Whether a physical table has generated entity metadata. */\nexport function isEntityTable(obj: unknown): obj is Table<any, any> {\n return isTable(obj) && \"meta\" in obj[tableMgmt];\n}\n\n/** Whether a physical table has columns declared through `declareTable`. */\nexport function isCustomTable(obj: unknown): obj is CustomTableFor {\n return isTable(obj) && \"columns\" in obj[tableMgmt];\n}\n\n/**\n * A physical table column implements `Expr`: it renders as `alias.\"column\"`, decodes result\n * values through the column's shared scalar codec, and inherits aggregate methods from `BaseExpr`.\n */\nclass TableColumn extends BaseExpr {\n public constructor(\n readonly meta: EntityMetadata | undefined,\n readonly column: Column,\n readonly mgmt: TableSourceMgmt,\n private readonly selectKey: string = column.columnName,\n ) {\n super();\n }\n\n get [selectKeyBrand](): string {\n return this.selectKey;\n }\n\n /** Author.id, Book.authorId, and Comment.parentAuthorId use the same Author ID domain. */\n get outputType(): TypeInfo | undefined {\n return this.column.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.column.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.mgmt;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.mgmt);\n return { sql: kqDot(alias, this.column.columnName), bindings: [], refs: [alias] };\n }\n\n /** Decodes result-set values with public PK/FK ids, while hydration keeps internal tagged ids. */\n decode(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n const idMeta = this.idMetadata;\n if (idMeta) return toIdOf(idMeta, this.column.mapFromDb(value) as TaggedId | undefined);\n return this.column.mapFromDb(value);\n }\n\n encode(value: unknown): unknown {\n return this.column.mapToDb(value);\n }\n\n /** Identifies the ID domain of a primary key, FK, or physical polymorphic component. */\n get idMetadata(): EntityMetadata | undefined {\n return this.column.idMetadata?.();\n }\n\n /** Encodes literals when the condition is created and renders with each query's aliases. */\n addCondition(value: ParsedValueFilter<unknown>): SqlCondition {\n const encoded = mapToDb(this.column, value);\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n const [sql, bindings] = buildValueCondition(left.sql, encoded);\n return { sql, bindings: [...left.bindings, ...bindings], refs: left.refs };\n });\n }\n\n /** Renders raw operators against the same quoted column SQL as other expressions. */\n protected addRawCondition(exp: string, bindings: readonly any[]): SqlCondition {\n return deferredCondition((ctx) => {\n const left = this.toSql(ctx);\n return { sql: `${left.sql} ${exp}`, bindings: [...left.bindings, ...bindings], refs: left.refs };\n });\n }\n\n /** Uses column filter conversions for literals and shared comparisons for expressions and null equality. */\n protected compare(op: string, value: unknown): SqlCondition {\n if (value === undefined || isExpr(value) || (value === null && (op === \"=\" || op === \"!=\"))) {\n return super.compare(op, value);\n }\n // Primitive relational comparisons historically bind null through mapToDb.\n const kind = ({ \"=\": \"eq\", \"!=\": \"ne\", \">\": \"gt\", \">=\": \"gte\", \"<\": \"lt\", \"<=\": \"lte\" } as const)[op];\n if (!kind) return fail(`Invalid operator ${op}`);\n return this.addCondition({ kind, value });\n }\n\n /**\n * Compares this column to another expression.\n *\n * Table columns, aggregates, subquery columns, and `sql` templates use the expression context\n * to render their complete SQL.\n * Negated array operators wrap the complete comparison in NOT.\n */\n protected compareToExpr(op: string, value: ExprLike<any>, negate = false): SqlCondition {\n if (negate) {\n return deferredCondition((ctx) => {\n const comparison = ctx.conditionToSql(this.compareToExpr(op, value))!;\n return { ...comparison, sql: `NOT (${comparison.sql})` };\n });\n }\n return super.compare(op, value);\n }\n}\n\nclass PrimitiveColumnImpl<V, N extends null | never> extends TableColumn implements PrimitiveColumn<V, N> {\n between(v1: V | undefined, v2: V | undefined): SqlCondition {\n if (v1 === undefined || v2 === undefined) return skipCondition;\n return this.addCondition({ kind: \"between\", value: [v1, v2] });\n }\n\n cosineDistance(vector: number[] | ExprLike<number[] | N>): Expr<number | N, string> {\n if (this.column.dbType !== \"vector\") fail(`${this.column.columnName} is not a vector column`);\n const outputType: TypeInfo = { dbType: \"float8\", domain: Number, arrayElementSafe: true };\n return new OperatorExpr(this, \"<=>\", vector, { outputType }) as unknown as Expr<number | N, string>;\n }\n\n like(value: V | undefined): SqlCondition {\n if (value === undefined) return skipCondition;\n return this.addCondition({ kind: \"like\", value });\n }\n\n ilike(value: V | undefined): SqlCondition {\n if (value === undefined) return skipCondition;\n return this.addCondition({ kind: \"ilike\", value });\n }\n\n search(value: V | undefined): SqlCondition {\n // Check !value so that empty strings are pruned\n if (!value) return skipCondition;\n return this.addCondition({ kind: \"ilike\", value: makeLike(value) });\n }\n\n in(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inList(\"IN\", values);\n if (values.includes(null)) {\n const isNull = this.addCondition({ kind: \"is-null\" });\n const hasValue = this.addCondition({ kind: \"in\", value: values.filter((v) => v !== null) });\n return { or: [isNull, hasValue] };\n } else {\n return this.addCondition({ kind: \"in\", value: values as V[] });\n }\n }\n\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (V | null)[] | undefined): SqlCondition {\n return values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n nin(values: readonly (V | null)[] | ExprLike<V | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inList(\"NOT IN\", values);\n return this.addCondition({ kind: \"nin\", value: values.filter((v) => v !== null) as V[] });\n }\n\n // V will already be an array\n contains(v1: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"@>\", v1);\n return this.addCondition({ kind: \"contains\", value: v1 as any });\n }\n\n // V will already be an array\n ncontains(v1: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"@>\", v1, true);\n return this.addCondition({ kind: \"ncontains\", value: v1 as any });\n }\n\n // V will already be an array\n overlaps(v1: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"&&\", v1);\n return this.addCondition({ kind: \"overlaps\", value: v1 as any });\n }\n\n noverlaps(v1: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition {\n if (v1 === undefined) return skipCondition;\n if (isExpr(v1)) return this.compareToExpr(\"&&\", v1, true);\n return this.addCondition({ kind: \"noverlaps\", value: v1 as any });\n }\n\n pathExists(jsonPath: string | undefined): SqlCondition {\n if (jsonPath === undefined) return skipCondition;\n return this.addCondition({ kind: \"jsonPathExists\", value: jsonPath });\n }\n\n pathIsTrue(jsonPath: string | undefined): SqlCondition {\n if (jsonPath === undefined) return skipCondition;\n return this.addCondition({ kind: \"jsonPathPredicate\", value: jsonPath });\n }\n\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition {\n if (bindings === undefined) return skipCondition;\n return this.addRawCondition(exp, bindings);\n }\n}\n\nclass EntityColumnImpl<T> extends TableColumn implements EntityColumn<T> {\n /** Uses the ID target's tag, including for foreign keys and polymorphic components. */\n taggedId(): Expr<string, string> {\n return new TaggedIdExpr(this) as unknown as Expr<string, string>;\n }\n\n in<\n F extends QuerySource,\n const S extends ExprLike<IdOf<T> | null>,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n >(values: QueryArg<F, S, J, Name>): SqlCondition;\n in(values: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition;\n in(values: object | readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n if (values === undefined) {\n return skipCondition;\n } else if (values === null) {\n throw new Error(\"Unsupported\");\n } else if (isExpr(values)) {\n return this.inList(\"IN\", values);\n } else if (!Array.isArray(values)) {\n return { [inQueryCondition]: { column: this, query: values } } as unknown as SqlCondition;\n } else if (values.includes(null)) {\n // Like `PrimitiveColumn.in`, split `[a1, null]` into `IS NULL OR IN (...)`\n const isNull = this.addCondition({ kind: \"is-null\" });\n const hasValue = this.addCondition({ kind: \"in\", value: values.filter((v) => v !== null) as any });\n return { or: [isNull, hasValue] };\n } else {\n return this.addCondition({ kind: \"in\", value: values as any });\n }\n }\n\n /** Applies an IN condition unless the list is empty, null, or undefined. */\n inNonEmpty(values: readonly (T | IdOf<T> | null)[] | null | undefined): SqlCondition {\n return values === null || values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n nin(values: readonly (T | IdOf<T> | null)[] | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n if (values === undefined) {\n return skipCondition;\n } else if (values === null) {\n throw new Error(\"Unsupported\");\n } else if (isExpr(values)) {\n return this.inList(\"NOT IN\", values);\n } else {\n return this.addCondition({ kind: \"nin\", value: values.filter((v) => v !== null) as any });\n }\n }\n\n gt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\">\", \"gt\", value);\n }\n\n gte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\">=\", \"gte\", value);\n }\n\n lt(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\"<\", \"lt\", value);\n }\n\n lte(value: IdOf<T> | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.compareId(\"<=\", \"lte\", value);\n }\n\n raw(exp: string, bindings: readonly any[] | undefined): SqlCondition {\n if (bindings === undefined) return skipCondition;\n return this.addRawCondition(exp, bindings);\n }\n\n /** Joins via this FK, inheriting the source's LEFT join for otherwise required references. */\n as(other: object): object {\n return {\n ...this.joinEntry(this.sqlNullable === false ? \"inner\" : \"left\", other),\n [referenceJoinSource]: this.mgmt,\n };\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", other);\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", other);\n }\n\n private joinEntry(kind: JoinKind, other: object): object {\n return { [kind]: requireTable(other), on: this.eq(idColumnOf(other)) };\n }\n\n private compareId(op: string, kind: \"gt\" | \"gte\" | \"lt\" | \"lte\", value: unknown): SqlCondition {\n if (value === undefined) return skipCondition;\n if (value === null) throw new Error(\"Unsupported\");\n if (isExpr(value)) return this.compareToExpr(op, value);\n return this.addCondition({ kind, value: value as any });\n }\n}\n\n/** Converts a physical ID to SQL text so nested SQL expressions also receive the tag. */\nclass TaggedIdExpr extends BaseExpr {\n constructor(private column: TableColumn) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const fragment = this.column.toSql(ctx);\n const meta = this.column.idMetadata ?? fail(\"Tagged IDs require an ID column\");\n return {\n ...fragment,\n sql: `(? || ${fragment.sql}::text)`,\n bindings: [taggedIdPrefix(meta), ...fragment.bindings],\n };\n }\n\n get outputType(): TypeInfo {\n return { dbType: \"text\", domain: String, arrayElementSafe: true };\n }\n\n get sqlNullable(): boolean | undefined {\n return this.column.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.column.sqlSource;\n }\n}\n\nclass PolyReferenceImpl<T extends Entity> {\n public constructor(\n private meta: EntityMetadata,\n private mgmt: TableMgmt,\n private field: PolymorphicField,\n ) {}\n\n /** Compares to a tagged id, an entity, or another table's id column, which picks the component (`c.parent.eq(a.id)`). */\n eq(value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.addEqOrNe(\"eq\", value);\n }\n\n ne(value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined): SqlCondition {\n return this.addEqOrNe(\"ne\", value);\n }\n\n // We required tagged ids for polys\n in(values: readonly (T | TaggedId)[] | ExprLike<IdOf<T> | null> | undefined): SqlCondition {\n if (values === undefined) return skipCondition;\n if (isExpr(values)) return this.inSubquery(values);\n // Split up the ids by constructor\n const idsByConstructor = groupBy(values, (id) => getConstructorFromTaggedId(maybeResolveReferenceToId(id)!).name);\n // Or together `parent_book_id in (1,2,3) OR parent_author_id IN (4,5,6)`\n return {\n or: Object.entries(idsByConstructor).map(([cstrName, ids]) => {\n const comp =\n this.field.components.find((p) => p.otherMetadata().cstr.name === cstrName) ??\n fail(`No component for ${cstrName}`);\n return this.componentColumn(comp).addCondition({ kind: \"in\", value: ids });\n }),\n };\n }\n\n /** Applies an IN condition unless the list is empty or undefined. */\n inNonEmpty(values: readonly (T | TaggedId)[] | undefined): SqlCondition {\n return values === undefined || values.length === 0 ? skipCondition : this.in(values);\n }\n\n /** Joins via this poly's component, inheriting the source's LEFT join when the poly is required. */\n as(other: object): object {\n return { ...this.joinEntry(this.field.required ? \"inner\" : \"left\", other), [referenceJoinSource]: this.mgmt };\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", other);\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", other);\n }\n\n private joinEntry(kind: JoinKind, other: object): object {\n return { [kind]: requireTable(other), on: this.eq(idColumnOf(other) as any) };\n }\n\n /**\n * i.e. `c.parent.in(query({ from: a, ..., select: a.id }))`: like `eq` against a table column, the\n * subquery's agreed ID domain picks the component, i.e. authors pick `parent_author_id`.\n */\n private inSubquery(values: ExprLike<any>): SqlCondition {\n // Only actual subqueries expose this getter; importing query.ts would create a load-order cycle.\n const selected = asNode(values).subquerySelect;\n const outputType = selected?.outputType;\n let otherMeta = outputType?.idMeta;\n if (!otherMeta) {\n // Ordinary reads can select an unknown key serde. Compounds validate codecs before exposing a select.\n if (!outputType && selected instanceof TableColumn) {\n otherMeta = selected.idMetadata;\n }\n if (!otherMeta) {\n return fail(\n selected instanceof TableColumn\n ? `${this.field.fieldName} \\`in\\` needs an id or FK column, got ${selected.column.columnName}`\n : `${this.field.fieldName} is polymorphic, so \\`in\\` needs a subquery selecting an id or FK column`,\n );\n }\n }\n const comp =\n this.field.components.find((p) => getBaseAndSelfMetas(otherMeta).includes(p.otherMetadata())) ??\n fail(`${this.field.fieldName} has no component for ${otherMeta.type}`);\n return this.componentColumn(comp).in(values);\n }\n\n private addEqOrNe(\n kind: \"eq\" | \"ne\",\n value: T | TaggedId | ExprLike<IdOf<T> | null> | null | undefined,\n ): SqlCondition {\n if (value === undefined) {\n return skipCondition;\n } else if (value instanceof TableColumn) {\n // Joining through the poly, i.e. `c.parent.eq(a.id)`: the other table column's ID domain picks the component\n const otherMeta = value.idMetadata ?? fail(`${this.field.fieldName} needs an id or FK column`);\n const comp =\n this.field.components.find((p) => getBaseAndSelfMetas(otherMeta).includes(p.otherMetadata())) ??\n fail(`${this.field.fieldName} has no component for ${otherMeta.type}`);\n return this.componentColumn(comp)[kind](value);\n } else if (isExpr(value)) {\n return fail(\n `${this.field.fieldName} is polymorphic, so it can only be compared to tagged ids or entity table columns`,\n );\n } else if (value === null) {\n // We can AND each of the components as many conditions\n const value = kind === \"eq\" ? ({ kind: \"is-null\" } as const) : ({ kind: \"not-null\" } as const);\n return {\n and: this.field.components.map((p) => this.componentColumn(p).addCondition(value)),\n };\n } else {\n // If we have a value, we can find the component\n const comp =\n this.field.components.find(\n (p) => p.otherMetadata().cstr === getConstructorFromTaggedId(maybeResolveReferenceToId(value) as string),\n ) || fail(`Could not find component for ${value}`);\n return this.componentColumn(comp)[kind](value);\n }\n }\n\n /** Returns the physical FK expression for one polymorphic target. */\n private componentColumn(comp: PolymorphicFieldComponent): EntityColumnImpl<T> {\n const descriptor = comp.column;\n return new EntityColumnImpl<T>(this.meta, descriptor, this.mgmt);\n }\n}\n\n/**\n * Marks a sugar join entry whose target is a *collection* (o2m/m2m), which filter soft-deletes like\n * em.find's \"collections filter out soft-deletes, but m2o/o2o references still return them\"; see\n * `QueryParser.addSoftDeleteCondition`'s call site. Reference joins and explicit joins are unmarked.\n */\nexport const collectionJoin: unique symbol = Symbol(\"joist.collectionJoin\");\n\n/** Marks a sugar m2m join entry (`a.tags.as(t)`) with its hidden join-table join; `parseQuery` expands it. */\nexport const m2mJoinTable: unique symbol = Symbol(\"joist.m2mJoinTable\");\n\nexport interface M2mJoinTable {\n handle: JoinTableHandle;\n on: SqlCondition;\n}\n\n/** The runtime identity of an m2m join table in a query, i.e. `authors_to_tags`; it has no entity. */\nexport class JoinTableHandle {\n constructor(readonly joinTableName: string) {}\n}\n\ntype JoinKind = \"inner\" | \"left\";\n\n/**\n * The `as`/`inner`/`left` join factory for collection relations, i.e. `a.books.as(b)` joins with the\n * relation's default kind (LEFT: a collection may be empty) and `.inner`/`.left` override. m2o/poly\n * relations implement the same three methods on their join factories. Physical FKs such as\n * `b.author_id` are expressions that also expose a join factory.\n */\nabstract class CollectionJoinImpl {\n as(other: object): object {\n return this.joinEntry(\"left\", requireTable(other));\n }\n\n inner(other: object): object {\n return this.joinEntry(\"inner\", requireTable(other));\n }\n\n left(other: object): object {\n return this.joinEntry(\"left\", requireTable(other));\n }\n\n protected abstract joinEntry(kind: JoinKind, other: TableFor<Entity>): object;\n}\n\n/** Joins a named subtype explicitly; only STI subtype sugar adds a discriminator to its ON. */\nclass SubtypeJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: TableFor<Entity>,\n private subtype: EntityMetadata,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n if (getTableMetadata(other) !== this.subtype) {\n return fail(`Expected table(${this.subtype.type}) for the explicit subtype join`);\n }\n const on = idColumnOf(this.proxy).eq(idColumnOf(other));\n if (this.subtype.inheritanceType !== \"sti\" || this.subtype.stiDiscriminatorValue === undefined) {\n return { [kind]: other, on };\n }\n const base = this.subtype.baseTypes.find((m) => m.stiDiscriminatorField !== undefined)!;\n const columnName = base.fields[base.stiDiscriminatorField!].serde!.columns[0].columnName;\n // Discriminator values are database enum ids, not domain enum values to pass through the field codec.\n const discriminator = deferredCondition((ctx) => {\n const alias = ctx.aliasFor(other[tableMgmt]);\n return {\n sql: `${kqDot(alias, columnName)} = ?`,\n bindings: [this.subtype.stiDiscriminatorValue],\n refs: [alias],\n };\n });\n return { [kind]: other, on: { and: [on, discriminator] } };\n }\n}\n\n/** An o2m/lo2m/o2o relation: the ON is the other side's FK (an m2o or a poly component) back to our id. */\nclass OneToManyJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: any,\n private field: OneToManyField | LargeOneToManyField | OneToOneField,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n const { field } = this;\n const otherMeta = getTableMetadata(other);\n const descriptor = Object.values(otherMeta.columns).find((column) => column.columnName === field.otherColumnName);\n if (!descriptor) {\n return fail(\n `Cannot join ${getTableMetadata(this.proxy).type}.${field.fieldName} to ${otherMeta.type}: ` +\n `${field.otherColumnName} is not physically present on ${otherMeta.tableName}; join the base table explicitly`,\n );\n }\n const column = new EntityColumnImpl(otherMeta, descriptor, other[tableMgmt]);\n const on = column.eq(this.proxy.id);\n // Collections (o2m/lo2m) filter soft-deletes like em.find; o2o references resolve them\n const filtered = field.kind === \"o2m\" ? field.softDeletes !== \"include\" : field.kind === \"lo2m\";\n return { [kind]: other, on, [collectionJoin]: filtered };\n }\n}\n\n/**\n * An m2m relation, i.e. `a.tags.as(t)`.\n *\n * The entry's own ON is `t.id = att.tag_id`, and the hidden `[m2mJoinTable]` half is\n * `att.author_id = a.id`; only the target's ON references the join table, so reference pruning keeps\n * or drops the pair together. Both are deferred conditions: the join table has no entity metadata, so\n * its alias only exists once the parser registers it.\n */\nclass ManyToManyJoinImpl extends CollectionJoinImpl {\n constructor(\n private proxy: any,\n private field: ManyToManyField,\n ) {\n super();\n }\n\n protected joinEntry(kind: JoinKind, other: TableFor<Entity>): object {\n const { joinTableName, columnNames } = this.field;\n const [ourColumn, otherColumn] = columnNames;\n const jt = new JoinTableHandle(joinTableName);\n const ourId = idColumnOf(this.proxy);\n const otherId = idColumnOf(other);\n const jtOn = deferredCondition((ctx) => {\n const jtAlias = ctx.aliasFor(jt);\n const id = ourId.toSql(ctx);\n return { sql: `${kqDot(jtAlias, ourColumn)} = ${id.sql}`, bindings: id.bindings, refs: id.refs };\n });\n const on = deferredCondition((ctx) => {\n const jtAlias = ctx.aliasFor(jt);\n const id = otherId.toSql(ctx);\n return { sql: `${id.sql} = ${kqDot(jtAlias, otherColumn)}`, bindings: id.bindings, refs: [...id.refs, jtAlias] };\n });\n const filtered = this.field.softDeletes !== \"include\";\n return {\n [kind]: other,\n on,\n [collectionJoin]: filtered,\n [m2mJoinTable]: { handle: jt, on: jtOn } satisfies M2mJoinTable,\n };\n }\n}\n\n/** Fails fast when a join factory is passed something other than a table. */\nfunction requireTable(other: object): TableFor<Entity> {\n if (!isEntityTable(other)) return fail(`Expected an entity table to join, got ${other}`);\n return other;\n}\n\n/** The id column of a joined table, for building sugar ON conditions. */\nfunction idColumnOf(other: object): TableColumn {\n return (other as any).id;\n}\n\n/** Keeps relation names join-only; physical FK columns retain expression methods. */\nclass ReferenceJoinImpl {\n constructor(private column: EntityColumnImpl<unknown>) {}\n\n as(other: object): object {\n return this.column.as(other);\n }\n\n inner(other: object): object {\n return this.column.inner(other);\n }\n\n left(other: object): object {\n return this.column.left(other);\n }\n}\n\n/** Identifies domain relationship keys exposed alongside physical columns. */\nfunction isRelation(field: Field | undefined): boolean {\n return field !== undefined && [\"m2o\", \"poly\", \"o2m\", \"lo2m\", \"m2m\", \"o2o\"].includes(field.kind);\n}\n\n/** Resolves relationship sugar only from domain fields owned by this physical table. */\nfunction physicalRelation(meta: EntityMetadata, key: string): Field | undefined {\n const owners = [meta, ...getBaseSelfAndSubMetas(getBaseMeta(meta))];\n const owner = owners.find((owner) => owner.tableName === meta.tableName && Object.hasOwn(owner.fields, key));\n const field = owner?.fields[key];\n if (!isRelation(field)) return undefined;\n // I.e. TaskNew.copiedFrom uses Task's original FK domain, not its specialized TaskNew target.\n if (field?.kind === \"m2o\" || field?.kind === \"poly\") {\n if (!field.serde.columns.every((binding) => Object.values(meta.columns).includes(binding.column))) return undefined;\n return field.kind === \"poly\"\n ? {\n ...field,\n components: field.components.map((component) => ({\n column: component.column,\n columnName: component.columnName,\n otherFieldName: component.otherFieldName,\n otherMetadata: component.column.idMetadata!,\n })),\n }\n : field;\n }\n return field;\n}\n\n/**\n * Maps local domain fields to table-bound conditions, encoding each leaf once.\n * I.e. Author.firstName uses the first_name column but resolves its alias in each query scope.\n * Collections, polymorphic references, and inherited nonlocal fields require explicit expressions.\n */\nexport function tableWhere(mgmt: TableMgmt, filter: object): SqlCondition {\n const { meta } = mgmt;\n const conditions: SqlCondition[] = [];\n if (!filter || typeof filter !== \"object\" || Array.isArray(filter)) {\n throw new Error(`Expected a domain field filter for ${meta.type}`);\n }\n for (const [key, value] of Object.entries(filter)) {\n // CTI allFields.id points at the base key; the subtype has its own physical key.\n const field = key === \"id\" ? meta.fields.id : Object.hasOwn(meta.allFields, key) ? meta.allFields[key] : undefined;\n if (\n !field ||\n ![\"primaryKey\", \"primitive\", \"enum\", \"m2o\"].includes(field.kind) ||\n !field.serde ||\n field.serde.columns.length !== 1 ||\n !field.serde.columns.every((binding) => Object.values(meta.columns).includes(binding.column))\n ) {\n throw new Error(`Unsupported table filter field ${meta.type}.${key}; use an explicit join`);\n }\n const column = new TableColumn(meta, field.serde.columns[0].column, mgmt);\n let leaves: ParsedValueFilter<unknown>[];\n if (field.kind === \"m2o\") {\n if (!isTableReferenceFilter(value)) {\n throw new Error(`Unsupported table reference filter ${meta.type}.${key}; use an entity or ID`);\n }\n const parsed = parseEntityFilter(field.otherMetadata(), value);\n if (parsed?.kind === \"join\") {\n throw new Error(`Unsupported table reference filter ${meta.type}.${key}; use an entity or ID`);\n }\n leaves = parsed ? [parsed] : [];\n } else {\n leaves = parseValueFilter(value);\n }\n for (const leaf of leaves) {\n if (leaf.kind === \"between\" && leaf.value.some((v) => v === undefined)) {\n if (leaf.value[0] !== undefined) conditions.push(column.addCondition({ kind: \"gte\", value: leaf.value[0] }));\n if (leaf.value[1] !== undefined) conditions.push(column.addCondition({ kind: \"lte\", value: leaf.value[1] }));\n } else if (leaf.kind === \"in\" && !column.column.isArray && leaf.value.includes(null)) {\n conditions.push({\n or: [\n column.addCondition({ kind: \"is-null\" }),\n column.addCondition({ kind: \"in\", value: leaf.value.filter((v) => v !== null) }),\n ],\n });\n } else {\n conditions.push(column.addCondition(leaf));\n }\n }\n }\n return conditions.length === 0 ? skipCondition : { and: conditions };\n}\n\n/**\n * Converts relationship filters into conditions on the joined table's id column.\n * I.e. Author's `join: { books: \"b:1\" }` filters Book.id to 1; `{ books: book }` uses book.id.\n * Lists match any supplied ID, `true` requires a Book, and `null` or `false` requires no Book.\n */\nexport function tableEntityWhere(mgmt: TableMgmt, value: unknown): SqlCondition {\n const parsed = parseEntityFilter(mgmt.meta, value);\n if (!parsed) return skipCondition;\n if (parsed.kind === \"join\") fail(`Expected an entity or ID filter for ${mgmt.meta.type}`);\n return new TableColumn(mgmt.meta, mgmt.meta.fields.id.serde!.columns[0].column, mgmt).addCondition(parsed);\n}\n\n/** Rejects nested relations, scopes, and aliases before parsing owning-reference values. */\nfunction isTableReferenceFilter(value: unknown): boolean {\n if (value == null || typeof value === \"boolean\" || isTableReferenceValue(value)) return true;\n if (Array.isArray(value)) return value.every(isTableReferenceValue);\n if (typeof value === \"object\" && Object.keys(value).length === 1 && Object.hasOwn(value, \"ne\")) {\n const excluded = (value as { ne: unknown }).ne;\n return excluded == null || isTableReferenceValue(excluded);\n }\n return false;\n}\n\n/** Recognizes an entity or public ID without accepting another filter object. */\nfunction isTableReferenceValue(value: unknown): boolean {\n return typeof value === \"string\" || typeof value === \"number\" || isEntity(value);\n}\n"],"mappings":";;;;;;;;;;;;;;AA8EA,SAAgB,MACd,MACA,OACS;CAET,OAAOA,2BAAAA,wBAAwB,IAAI,IAAI,oBAAoB,IAAI,IAAI,cAAc,IAAI;AACvF;;AAGA,SAAgB,OACd,GAAG,MACy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,CACjF,EACF,CAAC;OAED,WAAW,KAAK,OAAO,aAAa,IAAI,CAAC;CAG/C;CACA,OAAO,WAAW,WAAW,IAAIZ,8BAAAA,gBAAgB,EAAE,KAAK,WAAW;AACrE;;;;;;AAOA,SAAgB,iBAAiB,MAAiB,OAA8B;CAC9E,MAAM,SAASW,6BAAAA,kBAAkB,KAAK,MAAM,KAAK;CACjD,IAAI,CAAC,QAAQ,OAAOX,8BAAAA;CACpB,IAAI,OAAO,SAAS,QAAQ,cAAA,KAAK,uCAAuC,KAAK,KAAK,MAAM;CACxF,OAAO,IAAI,YAAY,KAAK,MAAM,KAAK,KAAK,OAAO,GAAG,MAAO,QAAQ,EAAE,CAAC,QAAQ,IAAI,CAAC,CAAC,aAAa,MAAM;AAC3G;;AAGA,SAAS,uBAAuB,OAAyB;CACvD,IAAI,SAAS,QAAQ,OAAO,UAAU,aAAa,sBAAsB,KAAK,GAAG,OAAO;CACxF,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,MAAM,qBAAqB;CAClE,IAAI,OAAO,UAAU,YAAY,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,OAAO,OAAO,OAAO,IAAI,GAAG;EAC9F,MAAM,WAAY,MAA0B;EAC5C,OAAO,YAAY,QAAQ,sBAAsB,QAAQ;CAC3D;CACA,OAAO;AACT;;AAGA,SAAS,sBAAsB,OAAyB;CACtD,OAAO,OAAO,UAAU,YAAY,OAAO,UAAU,YAAYa,eAAAA,SAAS,KAAK;AACjF"}
@@ -201,6 +201,13 @@ export interface PrimitiveColumn<V, N extends null | never, Src extends string =
201
201
  ilike(value: V | undefined): SqlCondition;
202
202
  search(value: V | undefined): SqlCondition;
203
203
  between(v1: V | undefined, v2: V | undefined): SqlCondition;
204
+ /**
205
+ * The cosine distance (pgvector's `<=>`) between this `vector` column and `vector`, from 0 for the same direction
206
+ * to 2 for opposite directions; NULL when the column is NULL.
207
+ *
208
+ * Only `vector` columns support it, so other `number[]` (i.e. pg array) columns fail when the query is built.
209
+ */
210
+ cosineDistance(this: PrimitiveColumn<number[], N, Src, Key>, vector: number[] | ExprLike<number[] | N>): Expr<number | N, Src>;
204
211
  contains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;
205
212
  ncontains(value: string | V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;
206
213
  overlaps(value: V | PrimitiveColumn<V, any> | N | undefined): SqlCondition;