joist-core 2.3.0-next.75 → 2.3.0-next.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/query.cjs +8 -3
- package/build/query.cjs.map +1 -1
- package/build/query.d.cts +2 -2
- package/build/query.d.cts.map +1 -1
- package/build/query.d.mts +2 -2
- package/build/query.d.mts.map +1 -1
- package/build/query.js +8 -3
- package/build/query.js.map +1 -1
- package/package.json +2 -2
package/build/query.cjs
CHANGED
|
@@ -908,6 +908,7 @@ function conditionToSql(cond, ctx, topLevel) {
|
|
|
908
908
|
checkCondition(cond);
|
|
909
909
|
if (cond === void 0) return void 0;
|
|
910
910
|
const resolved = require_Expr.resolveDeferredConditions(resolveQueryCondition(cond, ctx), ctx);
|
|
911
|
+
if (resolved === void 0) return void 0;
|
|
911
912
|
const filter = isFilter(resolved) ? resolved : { and: [resolved] };
|
|
912
913
|
const cb = new require_ConditionBuilder.ConditionBuilder();
|
|
913
914
|
cb.maybeAddExpression(filter);
|
|
@@ -923,7 +924,8 @@ function conditionToSql(cond, ctx, topLevel) {
|
|
|
923
924
|
}
|
|
924
925
|
/**
|
|
925
926
|
* Rejects malformed predicates throughout a condition tree before pruning can discard a restriction.
|
|
926
|
-
* I.e. an invalid Author-name condition stays invalid even inside a group that would otherwise prune
|
|
927
|
+
* I.e. an invalid Author-name condition stays invalid even inside a group that would otherwise prune,
|
|
928
|
+
* while an explicitly omitted query-valued condition is allowed to prune.
|
|
927
929
|
*/
|
|
928
930
|
function checkCondition(value) {
|
|
929
931
|
if (require_DeferredAlias.isDeferredAliasCondition(value) || value && typeof value === "object" && require_conditions.predicateBrand in value && value[require_conditions.predicateBrand] === "domain") require_utils.fail("Domain alias conditions are only supported by em.find; use table(...) predicates in SQL queries and mutations.");
|
|
@@ -941,6 +943,7 @@ function checkCondition(value) {
|
|
|
941
943
|
const key = "exists" in condition ? "exists" : "notExists";
|
|
942
944
|
checkConditionKeys(condition, [key], "Query existence condition");
|
|
943
945
|
const query = condition[key];
|
|
946
|
+
if (query === void 0) return;
|
|
944
947
|
if (!(query instanceof SubqueryExpr) && !isReadQueryValue(query)) require_utils.fail(`Query ${key} requires a query(...) value`);
|
|
945
948
|
toQuery(query);
|
|
946
949
|
} else if (condition.kind === "raw") {
|
|
@@ -1021,8 +1024,10 @@ function resolveQueryCondition(cond, ctx) {
|
|
|
1021
1024
|
pruneIfUndefined: cond.pruneIfUndefined
|
|
1022
1025
|
};
|
|
1023
1026
|
if ("exists" in cond || "notExists" in cond) {
|
|
1024
|
-
const positive =
|
|
1025
|
-
const
|
|
1027
|
+
const positive = "exists" in cond;
|
|
1028
|
+
const subquery = positive ? cond.exists : cond.notExists;
|
|
1029
|
+
if (subquery === void 0) return void 0;
|
|
1030
|
+
const plan = parseQuery(toQuery(subquery), ctx, ctx.assigner);
|
|
1026
1031
|
return {
|
|
1027
1032
|
kind: "raw",
|
|
1028
1033
|
condition: `${positive ? "EXISTS" : "NOT EXISTS"} (${plan.sql})`,
|
package/build/query.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.cjs","names":["TemplateExpr","deferredCondition","RefExpr","AliasAssigner","safeKq","fail","BaseExpr","isExpr","isTable","getTableMgmt","getTableMetadata","JoinTableHandle","collectionJoin","m2mJoinTable","lazyExcludedSelects","kqStar","kq","filterSoftDeletes","getBaseMeta","asNode","resolveDeferredConditions","ConditionBuilder","buildWhereClause","isDeferredAliasCondition","predicateBrand","skipCondition","deferredSym","deepFindConditions"],"sources":["../src/query.ts"],"sourcesContent":["import { AliasAssigner } from \"./AliasAssigner.ts\";\nimport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nimport {\n type ConditionGroup,\n type ConditionInput,\n type SqlCondition,\n type SqlPredicate,\n type UnbrandedPredicate,\n predicateBrand,\n} from \"./conditions.ts\";\nimport { isDeferredAliasCondition } from \"./DeferredAlias.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityMetadata, getBaseMeta } from \"./EntityMetadata.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprBrand,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n RefExpr,\n type SqlFragment,\n TemplateExpr,\n asNode,\n deferredCondition,\n deferredSym,\n exprBrand,\n isExpr,\n resolveDeferredConditions,\n} from \"./Expr.ts\";\nimport { kq, kqStar, safeKq } from \"./keywords.ts\";\nimport { deepFindConditions } from \"./QueryParser.pruning.ts\";\nimport {\n type ColumnCondition,\n type ParsedExpressionFilter,\n filterSoftDeletes,\n lazyExcludedSelects,\n} from \"./QueryParser.ts\";\nimport { skipCondition } from \"./skipCondition.ts\";\nimport {\n JoinTableHandle,\n type M2mJoinTable,\n type Table,\n type TableBrand,\n type TableMgmt,\n collectionJoin,\n getTableMetadata,\n getTableMgmt,\n isTable,\n m2mJoinTable,\n tableMgmt,\n} from \"./Tables.ts\";\nimport { type TypeInfo } from \"./TypeInfo.ts\";\nimport { type TypeMapEntry } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\n/**\n * `em.query`: SQL-shaped queries as plain object literals.\n *\n * A query is data, a `Query<S, J>` POJO, `{ from, join, where, groupBy, having, select, orderBy, ... }`\n * in SQL evaluation order:\n *\n * const [a, b] = tables(Author, Book);\n * const bookStats = query({ from: b, groupBy: [b.author_id], select: { authorId: b.author_id, n: b.id.count() } });\n * const rows = await em.query({\n * from: a,\n * join: [{ left: bookStats, on: bookStats.authorId.eq(a.id) }],\n * select: { name: a.first_name, n: bookStats.n },\n * orderBy: { n: \"DESC\" },\n * });\n * // rows: { name: string; n: number | null }[] (null because of the LEFT join)\n *\n * `em.query(pojo)` runs it. `select` decides the row type: a bare table returns entities, a\n * `{ key: expr }` object returns typed POJOs, a bare subquery returns that subquery's rows.\n *\n * `query(pojo)` turns the *same* POJO into a value: a derived table with typed columns, a scalar\n * expression, or an entity list. It is the one non-POJO step, and the subquery analog of `table(Author)`:\n * to reference a query's columns, the outer query needs *values* for them, and no POJO can manufacture\n * values keyed off its own `select` keys.\n *\n * `table()`/`tables()` and `query()` are the only free functions a query needs, plus the `sql` tagged\n * template as the escape hatch for SQL with no modeled shape. Everything else is in-DSL: join kinds and\n * sort directions are keyword keys (`{ left: b, on }`, `{ desc: x }`), SQL functions are methods on\n * expressions (`b.id.count()`, `b.title.max()`, `x.coalesce(0)`), conditions are methods\n * (`a.age.gte(18)`), and pruning is `undefined`: an `undefined` condition drops out, and a join nothing\n * references anymore drops with it (see \"Pruning\" below).\n *\n * User documentation: `docs/src/content/docs/features/queries-raw.md`.\n */\n\n// =====================================================================================================\n// Sources, joins, clauses\n// =====================================================================================================\n\nexport const subqueryBrand: unique symbol = Symbol(\"joist.subquery\");\nexport const entityQueryBrand: unique symbol = Symbol(\"joist.entityQuery\");\nexport const scalarQueryBrand: unique symbol = Symbol(\"joist.scalarQuery\");\n\n/** A query(...) value with any projection, for EXISTS and NOT EXISTS predicates. */\nexport type ExistsQuery = Subquery<unknown, string> | EntityQuery<Entity> | { readonly [scalarQueryBrand]: true };\n\n/**\n * A condition for a query's where, having, or join on clause. Combine conditions with and/or,\n * or use exists/notExists to check whether a query(...) value returns any rows.\n *\n * I.e. `{ and: [a.age.gte(18), { exists: booksForAuthor }] }` selects adult Authors with Books,\n * where `booksForAuthor` is `query({ from: b, where: b.author_id.eq(a.id), select: b.id })`.\n */\nexport type QueryCondition =\n | SqlPredicate\n | UnbrandedPredicate\n | ((\n | { and: Array<QueryCondition | undefined>; or?: never; exists?: never; notExists?: never }\n | { or: Array<QueryCondition | undefined>; and?: never; exists?: never; notExists?: never }\n ) & { pruneIfUndefined?: \"any\" | \"all\" })\n | { exists: ExistsQuery; notExists?: never; and?: never; or?: never }\n | { notExists: ExistsQuery; exists?: never; and?: never; or?: never };\n\n/** Phantom type information carried by a table-shaped subquery. */\nexport interface SubqueryBrand<R, Name extends string> {\n readonly __row: R;\n readonly __name: Name;\n}\n\n/** Anything that can be a source or be joined: an entity table or a table-shaped subquery. */\nexport type QuerySource =\n | { readonly [tableMgmt]: TableBrand<any, string> }\n | { readonly [subqueryBrand]: SubqueryBrand<any, string> };\n\n/**\n * A join entry (see `InnerJoin`/`LeftJoin` in `Expr.ts`): the expanded `{ inner: b, on }` form, or the\n * entry a relation join factory returns (`a.books.as(b)`); joins to a subquery are always the expanded\n * form, since a subquery has no FK metadata.\n */\nexport type QueryJoin = InnerJoin<QuerySource, QueryCondition> | LeftJoin<QuerySource, QueryCondition>;\nexport type QueryJoins = readonly (QueryJoin | undefined)[];\n\n/**\n * An expression order-by entry: the direction is the key and the expression is the value, unlike\n * the keyed form's field name and `\"ASC\" | \"DESC\"` value. `never` on the other key keeps an\n * entry to one direction, the same trick `ConditionGroup` uses for `and`/`or`. `nulls` is\n * `NULLS FIRST/LAST`.\n *\n * When select keys are known, exclude them so a keyed sort cannot be silently ignored inside an\n * expression entry. An untyped `Query` has no known keys to exclude.\n */\nexport type QueryOrderBy<S = never> = (\n | { readonly asc: ExprLike<any>; readonly desc?: never }\n | { readonly desc: ExprLike<any>; readonly asc?: never }\n) & { readonly nulls?: \"first\" | \"last\" } & (string extends OrderByKey<S>\n ? unknown\n : { readonly [K in Exclude<OrderByKey<S>, \"asc\" | \"desc\" | \"nulls\">]?: never });\n\nexport type OrderByDirection =\n | \"ASC\"\n | \"DESC\"\n | \"ASC NULLS FIRST\"\n | \"ASC NULLS LAST\"\n | \"DESC NULLS FIRST\"\n | \"DESC NULLS LAST\";\n\n/**\n * A keyed `orderBy` entry, used alone or in an array, like `em.find`'s `orderBy: [{ firstName: \"ASC\" }]`.\n *\n * The keys are the keys of a POJO/subquery `select` (rendered as SQL output-column names, so ordering\n * by an aggregate does not repeat its expression), or the entity's sortable fields in entity mode.\n * An `undefined` direction prunes the entry, like any other condition. For expressions that are not\n * in `select`, mix in `{ asc: expr }` / `{ desc: expr }` entries in the array form.\n */\nexport type OrderByKeys<S> = S extends { readonly [tableMgmt]: { readonly __entity: infer T } }\n ? T extends Entity\n ? { readonly [K in keyof Table<T> as Table<T>[K] extends ExprLike<any> ? K : never]?: OrderByDirection | undefined }\n : never\n : S extends { readonly [exprBrand]: any }\n ? never\n : { readonly [K in keyof S & string]?: OrderByDirection | undefined };\n\n/** All sortable keys across select variants, not just the keys shared by every variant. */\ntype OrderByKey<S> = S extends unknown ? keyof OrderByKeys<S> : never;\n\n/** The three select shapes: entity mode, single-expression mode (scalar/list subqueries), and POJO mode. */\nexport type QuerySelect = QuerySource | ExprLike<any> | Record<string, ExprLike<any>>;\n\n/**\n * Everything but the source, in SQL evaluation order: FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT,\n * ORDER BY, LIMIT.\n *\n * `S` and `J` are generic so callers keep the literal shape of `select` and `join`; the defaults let\n * a standalone object use `satisfies Query` (or `satisfies Clauses` for a source-less fragment).\n */\nexport interface Clauses<S extends QuerySelect = QuerySelect, J extends QueryJoins = QueryJoins> {\n join?: J;\n /** A boolean group, an exists/notExists query, or a bare condition such as `a.age.gte(18)`. */\n where?: QueryCondition;\n groupBy?: readonly ExprLike<any>[];\n having?: QueryCondition;\n select: S & CheckEntitySelect<S>;\n orderBy?: readonly (QueryOrderBy<S> | OrderByKeys<S> | undefined)[] | OrderByKeys<S>;\n limit?: number;\n offset?: number;\n distinct?: boolean;\n /** Defaults to true. `false` keeps every join, em.find's opt-out. */\n pruneJoins?: boolean;\n /**\n * Defaults to `\"exclude\"`, em.find's rule: a soft-deletable entity in `from` gains a\n * `deleted_at IS NULL` condition in WHERE, and a joined one gains it in its join's ON (so a LEFT\n * join nulls its columns out instead of dropping rows). `\"include\"` turns the injection off for\n * this query; subqueries read their own key.\n */\n softDeletes?: \"include\" | \"exclude\";\n}\n\n/** A whole query: `Clauses` plus its source. `query(q)` turns it into a value; `em.query(q)` runs it. */\nexport interface Query<S extends QuerySelect = QuerySelect, J extends QueryJoins = QueryJoins>\n extends Clauses<S, J>, Partial<Record<SetOperation | MutationKey | \"with\" | \"ctes\", never>> {\n from: QuerySource;\n}\n\n/**\n * The six PostgreSQL set operations. Each compound root has exactly one operation.\n *\n * I.e. `union` removes duplicate projected Author names; `unionAll` keeps every copy.\n */\nexport type SetOperation = \"union\" | \"unionAll\" | \"intersect\" | \"intersectAll\" | \"except\" | \"exceptAll\";\n\n/** Mutation clauses are forbidden even on nonliteral read inputs. */\ntype MutationKey = \"insert\" | \"update\" | \"delete\" | \"values\" | \"set\" | \"returning\" | \"allowAll\";\n\n/**\n * For set operations like UNION, this is one read operand with named POJO columns: an ordinary query,\n * a reusable query value, or another compound.\n * Scalar queries, expressions, and entity hydration are excluded.\n *\n * I.e. `{ from: a, select: { id: a.id } }` and its `query(...)` value can contribute Author IDs to a\n * union. `{ from: a, select: a.id }` cannot: even one-column set operands must give that column a name.\n */\nexport type SetOperand =\n | Query<Record<string, ExprLike<unknown>> | Subquery<unknown, string>>\n | Subquery<unknown, string>\n | SetQuery<readonly SetOperand[]>;\n\n/**\n * SQL-shaped compound input; use `satisfies SetQuery` to retain the operands' literal row types.\n *\n * I.e. for Author alias `a` and Book alias `b`:\n * ```ts\n * const names = {\n * union: [\n * { from: a, select: { name: a.first_name } },\n * { from: b, select: { name: b.title } },\n * ],\n * orderBy: { name: \"ASC\" },\n * } satisfies SetQuery;\n * ```\n *\n * The default operand tuple requires at least two reads. `query` and `em.query` also infer dynamically\n * sized arrays; `CheckSetQuery` validates their row types, and runtime validation checks their length.\n * This input shape checks direction values; `CheckSetQuery` checks the inferred output keys in orderBy.\n */\nexport type SetQuery<Operands extends readonly SetOperand[] = readonly [SetOperand, SetOperand, ...SetOperand[]]> = {\n // Each K creates one alternative, i.e. required `union` with the other five operation keys forbidden.\n [K in SetOperation]: { readonly [P in K]: Operands } & { readonly [P in Exclude<SetOperation, K>]?: never };\n}[SetOperation] & {\n // These clauses belong to the combined rows, not to an implicit first SELECT.\n readonly orderBy?:\n | Readonly<Record<string, OrderByDirection | undefined>>\n | readonly (Readonly<Record<string, OrderByDirection | undefined>> | undefined)[];\n readonly limit?: number;\n readonly offset?: number;\n readonly as?: string;\n} & {\n // SELECT clauses and branch policies must stay inside operands or an ordinary outer query.\n readonly [\n K in\n | \"from\"\n | \"select\"\n | \"join\"\n | \"where\"\n | \"groupBy\"\n | \"having\"\n | \"distinct\"\n | \"softDeletes\"\n | \"pruneJoins\"\n | MutationKey\n | \"with\"\n | \"ctes\"\n ]?: never;\n};\n\n/**\n * Extracts the operand collection from each possible compound root, ignoring pagination and ordering.\n *\n * I.e. for `Q = { union: readonly [typeof authorNames, typeof bookNames]; limit: 10 }`, the result is\n * `readonly [typeof authorNames, typeof bookNames]`. Distributing over Q also handles a runtime choice\n * between different operations; Extract discards optional, unused operation keys whose value is undefined.\n */\ntype OperandsOf<Q> = Q extends unknown ? Extract<Q[keyof Q & SetOperation], readonly SetOperand[]> : never;\n\n/**\n * Gets the left operand, which supplies canonical output keys and the retained row type for EXCEPT/INTERSECT.\n *\n * I.e. `FirstOperand<{ except: readonly [typeof authorNames, typeof bookNames] }>` is `typeof authorNames`.\n * For a dynamic array, the exact first element is unknown, so this is the array's element type instead.\n */\ntype FirstOperand<Q> = OperandsOf<Q>[0];\n\n/**\n * Resolves the named rows of an ordinary or compound read operand, including its LEFT join nullability.\n *\n * I.e. a query from Author `a` with a LEFT-joined Book `b` and `select: { title: b.title }` has row type\n * `{ title: string | null }`, even though Book.title is required. A reusable `query(...)` value already\n * stores that row type in its brand; a nested compound combines its own operands recursively.\n */\nexport type ReadQueryRow<Q> = SetOperand extends Q\n ? // Stop at the general, recursive operand type: its projection is unknown, not an empty POJO.\n unknown\n : // Read the brand before inspecting `select`, which could itself be a named column on a query value.\n Q extends { readonly [subqueryBrand]: { readonly __row: infer R } }\n ? R\n : Q extends { select: infer S }\n ? // A declared Query<S, J> has an optional join property that still carries J's LEFT joins.\n QueryRow<S, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoins> : []>\n : [OperandsOf<Q>] extends [never]\n ? never\n : SetQueryRow<Q>;\n\n/**\n * UNION combines each column's values; INTERSECT and EXCEPT conservatively retain the left row.\n *\n * I.e. Author first names projected as `{ name: string }` unioned with LEFT-joined Book titles projected\n * as `{ name: string | null }` produce `{ name: string | null }`. EXCEPT with those Author names on the\n * left retains `{ name: string }`; it neither adds the right side's NULL nor promises narrower values.\n *\n * The outer conditional distributes over a TypeScript union of alternative queries. I.e. a runtime\n * choice between an Author-name UNION and a Book-order EXCEPT must retain `{ name: string } | { order: number }`.\n */\nexport type SetQueryRow<Q> = Q extends unknown\n ? {\n // The first operand supplies keys; const/readonly input projections do not make result rows readonly.\n -readonly [K in keyof ReadQueryRow<FirstOperand<Q>>]: ColumnValue<\n // UNION can return values from any operand; EXCEPT/INTERSECT return values from the left.\n Q extends { union: readonly SetOperand[] } | { unionAll: readonly SetOperand[] }\n ? ReadQueryRow<OperandsOf<Q>[number]>\n : ReadQueryRow<FirstOperand<Q>>,\n K\n >;\n }\n : never;\n\n/**\n * Collects column K's value from each row alternative in R, rather than requiring K on every alternative.\n *\n * I.e. `ColumnValue<{ name: string } | { name: string | null }, \"name\">` is `string | null`.\n * An alternative without K contributes never; `CompatibleRow` separately rejects mismatched operand keys.\n */\ntype ColumnValue<R, K extends PropertyKey> = R extends unknown ? (K extends keyof R ? R[K] : never) : never;\n\n/**\n * Checks whether either non-null value type is assignable to the other, without requiring equal nullability.\n *\n * I.e. `CompatibleValue<number, number | null>` is true, while `CompatibleValue<AuthorId, BookId>` is false.\n * This is only a TypeScript check: Author.age and Author.age.sum() both pass as numbers, but runtime\n * output-type checks must still reject their different int4/int8 representations.\n */\ntype CompatibleValue<L, R> = [NonNullable<L>] extends [NonNullable<R>]\n ? true\n : [NonNullable<R>] extends [NonNullable<L>]\n ? true\n : false;\n\n/**\n * Requires exactly the same output keys and compatible TypeScript values for every column.\n *\n * I.e. `L = { name: string; age: number }` and `R = { age: number | null; name: string }` are compatible despite\n * key order and nullability. `{ name: string }` and `{ title: string }` are not. SQL representations and\n * codec domains still need runtime validation; this boolean does not establish decoder compatibility.\n */\ntype CompatibleRow<L, R> = [keyof L] extends [keyof R]\n ? // Checking both directions rejects missing and extra right-side keys, not just a shared subset.\n [keyof R] extends [keyof L]\n ? // Reduce the per-column flags to a union: any false rejects the complete row.\n false extends { [K in keyof L]: CompatibleValue<L[K], ColumnValue<R, K>> }[keyof L]\n ? false\n : true\n : false\n : false;\n\n/**\n * Produces a constraint for Q: unknown leaves a valid operand unchanged, while a message rejects it.\n *\n * I.e. First can select Author.firstName as `name` and Q can select Book.title as `name`. Both pass.\n * Changing Q's key to `title` produces the key/value diagnostic. A nested compound must also pass its own\n * arity and ordering checks, not merely expose a compatible result row.\n */\ntype CheckOperand<First, Q> =\n CompatibleRow<ReadQueryRow<First>, ReadQueryRow<Q>> extends true\n ? // Validate nested roots too, so an otherwise compatible one-operand UNION cannot hide inside Q.\n Q extends SetQuery<readonly SetOperand[]>\n ? CheckSetQuery<Q>\n : CheckReadQuery<Q>\n : \"set operands must have the same keys and compatible column values\";\n\n/**\n * Checks every operand against O[0] while preserving the collection's tuple shape and readonly modifier.\n *\n * I.e. compatible operands `O = readonly [typeof authorNames, typeof bookNames]` produce\n * `readonly [unknown, unknown]` constraints. Mapping O directly preserves length instead of validating\n * array methods and the length property as though they were additional query operands.\n */\ntype CheckOperands<O extends readonly SetOperand[]> = { readonly [I in keyof O]: CheckOperand<O[0], O[I]> };\n\n/**\n * Restricts each ordering hash to Keys, including hashes supplied through variables or readonly arrays.\n *\n * I.e. with `Keys = \"name\"`, `{ name: \"ASC\" }` and `[undefined, { name: \"DESC\" }]` pass, but a `title`\n * key receives a diagnostic. SetQuery already restricts direction values; this check does not replace them.\n */\ntype CheckSetOrder<O, Keys> = O extends readonly unknown[]\n ? // Preserve each array entry so an invalid hash is reported at its own position.\n { readonly [I in keyof O]: CheckSetOrder<O[I], Keys> }\n : { readonly [K in keyof O]: K extends Keys ? unknown : \"orderBy must name a set output column\" };\n\n/**\n * Validate known tuples and output ordering without widening the inferred operand projections.\n * Preserve optional keys when TypeScript infers a runtime choice between different operations.\n *\n * I.e. `{ union: [authorNames] as const }` fails minimum arity; a `typeof authorNames[]` can pass the\n * static checks but still needs a runtime length check. If authorNames and bookNames both expose only\n * `name`, combining them with `orderBy: { title: \"ASC\" }` fails the output-key check.\n *\n * The result is intersected with the inferred input Q. Unknown constraints leave its literal types\n * intact; error messages make the offending operands or ordering keys incompatible with that input.\n */\nexport type CheckSetQuery<Q extends SetQuery<readonly SetOperand[]>> = Q extends unknown\n ? // A widened first operand has lost the output keys and values needed to validate the remaining reads.\n SetOperand extends FirstOperand<Q>\n ? \"set operands were typed too generically; use `satisfies SetQuery` instead\"\n : {\n // Map Q itself so unused optional operation keys stay optional for UNION-or-EXCEPT input types.\n readonly [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly SetOperand[]\n ? // Dynamic arrays retain their row types but defer minimum arity to runtime.\n number extends Q[K][\"length\"]\n ? CheckOperands<Q[K]>\n : // A known tuple must guarantee two operands before any row comparisons can pass.\n Q[K] extends readonly [SetOperand, SetOperand, ...SetOperand[]]\n ? CheckOperands<Q[K]>\n : \"set operations require at least two operands\"\n : never\n : // Non-operation clauses retain their inferred types; SetQuery already constrains their shapes.\n unknown;\n } & CheckReadQuery<Q> & {\n // Only the inferred output keys are legal here; expression ordering needs an outer SELECT.\n readonly orderBy?: CheckSetOrder<Q[\"orderBy\"], keyof ReadQueryRow<FirstOperand<Q>>>;\n }\n : never;\n\n/**\n * Rejects unknown clauses on concrete read inputs, recursively through compound operands.\n * Intersect this with an inferred Q; a widened annotation cannot reveal keys already erased from its type.\n * I.e. an INSERT source with `select: { title: b.title }` and `ctes: [...]` must not silently discard the CTEs.\n */\nexport type CheckReadQuery<Q> = SetOperand extends Q\n ? unknown\n : Q extends readonly unknown[]\n ? { readonly [I in keyof Q]: CheckReadQuery<Q[I]> }\n : Q extends { readonly [subqueryBrand]: SubqueryBrand<infer R, string> }\n ? { readonly [K in keyof Q]: K extends keyof R | typeof subqueryBrand ? unknown : never }\n : Q extends { readonly [entityQueryBrand]: unknown }\n ? { readonly [K in keyof Q]: K extends typeof entityQueryBrand ? unknown : never }\n : Q extends { readonly from: unknown; readonly select: unknown }\n ? { readonly [K in keyof Q]: K extends keyof Clauses | \"from\" | \"as\" ? unknown : never }\n : {\n readonly [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? CheckReadQuery<Q[K]>\n : unknown\n : K extends \"orderBy\" | \"limit\" | \"offset\" | \"as\"\n ? unknown\n : never;\n };\n\n// =====================================================================================================\n// Result-row types\n// =====================================================================================================\n\n/** The type-level name of a table or subquery, i.e. `\"Author\"` or `\"book_stats\"`. */\nexport type NameOf<A> = A extends { readonly [tableMgmt]: { readonly __name: infer N } }\n ? N\n : A extends { readonly [subqueryBrand]: { readonly __name: infer N } }\n ? N\n : never;\n\n/** The names of every alias that was LEFT JOINed; `X` is a naked type parameter so this distributes. */\ntype LeftJoined<X> = X extends LeftJoin<infer A> ? NameOf<A> : never;\n\n/**\n * Asks: is this expression's source key among the LEFT-joined sources in this query's join list? If\n * yes, the value can be `null`, so `R` becomes `R | null`; if no, `R` is unchanged.\n *\n * I.e. `MaybeNull<number, \"book_stats\", [LeftJoin<typeof bookStats>]>` is `number | null`,\n * because `book_stats` is in `LeftJoined<J[number]>`; with an inner join it stays `number`.\n *\n * Source-less expressions (`Src` is `never`, i.e. `b.id.count()`) are never nullified. Untracked ones\n * (`Src` is `string`, i.e. a `sql.ref` on an unknown table) might come from any left-joined table,\n * so they are conservatively nullified whenever the query has a left join at all.\n *\n * `string` must never be a *table's* name: `Extract<\"Author\", string>` matches, so one left-joined\n * table named `string` would nullify every column in the query. That is why anonymous subqueries\n * share the literal sentinel `\"?\"` instead.\n */\nexport type MaybeNull<R, Src extends string, J extends QueryJoins> = string extends Src\n ? [LeftJoined<J[number]>] extends [never]\n ? R\n : R | null\n : [Extract<Src, LeftJoined<J[number]>>] extends [never]\n ? R\n : R | null;\n\n/**\n * The result row for a query with select `S` and joins `J`.\n *\n * - entity mode (`select: a`) is the entity\n * - subquery mode (`select: bookStats`) is the subquery's row, i.e. `select *`\n * - single expression (`select: b.id.count()`) is that expression's value, used by scalar subqueries\n * - POJO mode is a mapped type over the select keys, with left-join nullability applied\n */\nexport type QueryRow<S, J extends QueryJoins = []> = S extends { readonly [tableMgmt]: { readonly __entity: infer T } }\n ? T\n : S extends { readonly [subqueryBrand]: { readonly __row: infer R } }\n ? R\n : S extends { readonly [exprBrand]: ExprBrand<infer R, infer Src> }\n ? MaybeNull<R, Src, J>\n : {\n [K in keyof S]: S[K] extends { readonly [exprBrand]: ExprBrand<infer R, infer Src> }\n ? MaybeNull<R, Src, J>\n : never;\n };\n\n// =====================================================================================================\n// `query()`: a query POJO becomes a typed table, scalar, or entity list\n// =====================================================================================================\n\n/**\n * A table-shaped query: one `Expr` per select key, each tagged with the table's name as its `Src`,\n * plus a brand carrying the row type. This is the direct analog of `Table<T>`: `Table<T>` maps physical\n * columns to expressions, `Subquery<Row, Name>` maps the inner query's select keys to expressions.\n */\nexport type Subquery<R, Name extends string> = {\n readonly [subqueryBrand]: SubqueryBrand<R, Name>;\n} & { readonly [K in keyof R]: Expr<R[K], Name> };\n\n/** An entity-mode query (`select: a`): runnable, but it has no columns to reference. */\nexport type EntityQuery<T extends Entity> = { readonly [entityQueryBrand]: { readonly __row: T } } & Partial<\n Record<MutationKey | \"with\" | \"ctes\", never>\n>;\n\n/** A scalar/list query that remains distinguishable from ordinary expressions for EXISTS. */\nexport type ScalarQuery<R> = Expr<R | null, never> & { readonly [scalarQueryBrand]: true };\n\n/** Physical inheritance tables cannot supply complete entities; select their columns instead. */\ntype CheckEntitySelect<S> = [\n Extract<\n TypeMapEntry<S extends { readonly [tableMgmt]: { readonly __entity: infer T } } ? T : never, \"inheritanceType\">,\n \"cti\" | \"sti\"\n >,\n] extends [never]\n ? unknown\n : \"Inherited tables cannot be selected as entities; select their columns individually\";\n\n/**\n * Rejects a `select` that a `: Query` annotation widened to the whole `QuerySelect` union.\n *\n * `satisfies Query` checks the shape but keeps the literal type of `select`, so `S` infers as\n * `{ name: Expr<string, \"Author\"> }`. A `: Query` annotation replaces that type with the annotation, so\n * `S` infers as `QuerySelect` itself, and without this guard `query(q)` returned a useless union with no\n * error at all.\n *\n * A widened `S` is the only kind of `S` the whole `QuerySelect` union is assignable to (a POJO, an\n * `Expr`, or a `Table` never is), so `QuerySelect extends S` detects it, and intersecting the parameter\n * with `{ select: \"<message>\" }` fails the call on `select` with that message, for `query()` and\n * `em.query()` alike:\n *\n * const narrow = { from: a, select: { name: a.first_name } } satisfies Query;\n * query(narrow); // Subquery<{ name: string }, \"?\">\n *\n * const widened: Query = { from: a, select: { name: a.first_name } };\n * query(widened);\n * // error: Type 'QuerySelect' is not assignable to type\n * // '\"select was typed too generically; use `satisfies Query` instead of `: Query`\"'\n *\n * `S` also defaults to `never`, so a *missing* `select` is reported as \"Property 'select' is missing\"\n * against `Query<never, []>` instead of tripping this guard.\n */\nexport type NotWidened<S> = QuerySelect extends S\n ? { select: \"select was typed too generically; use `satisfies Query` instead of `: Query`\" }\n : unknown;\n\n/** What `query()` returns, by select shape: an entity list, a scalar/list subquery, or a derived table. */\nexport type QueryValue<S, J extends QueryJoins, Name extends string> = S extends {\n readonly [tableMgmt]: { readonly __entity: infer T extends Entity };\n}\n ? EntityQuery<T>\n : S extends { readonly [exprBrand]: ExprBrand<unknown, any> }\n ? ScalarQuery<QueryRow<S, J>>\n : Subquery<QueryRow<S, J>, Name>;\n\n/** The names of every alias in scope for a query: the source alias plus every joined alias. */\ntype JoinedName<X> = X extends { readonly inner: infer A }\n ? NameOf<A>\n : X extends { readonly left: infer A }\n ? NameOf<A>\n : never;\ntype InScope<F, J extends QueryJoins> = NameOf<F> | JoinedName<J[number]>;\n\n/**\n * Asks, for every column of a POJO select: is its source key among `from` + `join` at all? If no, the\n * query reads from a table it never joined, and that select key's type becomes an error message.\n *\n * Because `Expr` already carries `Src`, this is nearly free: for each select key, if `Src` is tracked\n * and any of its names is outside `InScope`, intersect that key's type with an error string, so the\n * caller sees `Type 'Expr<number, \"book_stats\">' is not assignable to type '... is not in from/join'`.\n * Untracked (`string`) and source-less (`never`) expressions always pass. Tables with the same\n * type-level name (two bare `table(Author)`, or two anonymous tables) cannot be told apart, so a miss\n * there goes unreported; the check never gives a false positive, only false negatives on collisions.\n *\n * `[S] extends [...]` keeps this non-distributive, and `never` is skipped outright: `query()` defaults\n * `S` to `never` when `select` is missing, and a distributive conditional over `never` would swallow the\n * whole parameter type.\n */\nexport type CheckScope<S, F, J extends QueryJoins> = [S] extends [never]\n ? unknown\n : // A source-shaped select (`select: a`, `select: bookStats`) must be the `from`: a joined source's\n // rows would need left-join nullability (and entity hydration) that source-shaped selects don't\n // model. Two same-named sources (unnamed aliases of one entity, anonymous subqueries) pass this\n // check and are caught at runtime instead.\n [S] extends [QuerySource]\n ? NameOf<S> extends NameOf<F>\n ? unknown\n : { select: `'${NameOf<S> & string}' is a joined source, not the from; select its columns individually` }\n : [S] extends [Record<string, ExprLike<any>>]\n ? {\n select: {\n [K in keyof S]: S[K] extends { readonly [exprBrand]: ExprBrand<any, infer Src> }\n ? string extends Src\n ? unknown\n : [Exclude<Src, InScope<F, J>>] extends [never]\n ? unknown\n : `table '${Exclude<Src, InScope<F, J>> & string}' is not in from/join`\n : unknown;\n };\n }\n : unknown;\n\n/** The one argument type `query()` and `em.query()` share: a `Query` POJO plus its source, name, and checks. */\nexport type QueryArg<F extends QuerySource, S extends QuerySelect, J extends QueryJoins, Name extends string> = Query<\n S,\n J\n> & {\n from: F;\n as?: Name;\n} & CheckScope<S, F, J> &\n NotWidened<S>;\n\n/**\n * Turns a `Query` POJO into a value. The select shape decides which (`QueryValue`):\n *\n * - a single expression is a scalar subquery or an IN list (`Expr<R | null>`; a scalar subquery can\n * return no row, so use `.coalesce(0)` when the SQL guarantees a value, i.e. an ungrouped `count`)\n * - an entity table is an entity list, runnable via `em.query`\n * - a POJO is a derived table whose columns are `Expr`s; it can be a source, be joined, or be run\n *\n * `as` is the SQL alias and the type-level identity, the same role the second argument of\n * `table(Author, \"m\")` plays. Without it the SQL alias is generated, like `table(Author)`, and all\n * anonymous tables share the type-level identity `\"?\"`: precise against every named alias, and\n * conservative (a left-joined anonymous table nullifies every anonymous table's columns) only among\n * themselves. This is the same collision two bare `table(Author)` have.\n *\n * Ordinary SELECT shapes share one signature: separate scalar/entity/POJO overloads hid `as` from\n * completions and cost 15-28% check time. The separate compound root has one additional signature;\n * `NotWidened` still rejects a SELECT widened by a `: Query` annotation.\n */\nexport function query<const Q extends SetQuery<readonly SetOperand[]>, Name extends string = \"?\">(\n q: Q & CheckSetQuery<Q> & { as?: Name },\n): Subquery<SetQueryRow<Q>, Name>;\nexport function query<\n F extends QuerySource,\n S extends QuerySelect = never,\n J extends QueryJoins = [],\n Name extends string = \"?\",\n>(q: QueryArg<F, S, J, Name>): QueryValue<S, J, Name>;\nexport function query(q: AnyReadQuery): unknown {\n const handle = new SubqueryHandle(toQuery(q));\n const output = handle.output();\n if (output.kind === \"entity\") {\n return { [entityQueryBrand]: handle } as any;\n } else if (output.kind === \"scalar\") {\n return new SubqueryExpr(handle) as any;\n } else {\n return newSubqueryProxy(handle) as any;\n }\n}\n\n/**\n * Builds a SQL expression from a tagged template.\n *\n * For an Author alias `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 * // Selecting this expression keeps the join to Book b.\n * sql.number`${b.order} * ${2}`\n *\n * // Reference an unmodeled column; it is untracked at the type level.\n * sql.ref<string>(a, \"ts_search\")\n * sql.condition`${sql.ref(a, \"ts_search\")} @@ plainto_tsquery(${term})`\n * ```\n */\nexport function sql<R = unknown>(strings: TemplateStringsArray, ...values: unknown[]): Expr<R, never> {\n return new TemplateExpr(strings, values) as any;\n}\n\n/** Shorthand for `sql<number>`; does not cast or convert the SQL result. */\nsql.number = sql<number>;\n\n/** Shorthand for `sql<number | null>`; does not cast or convert the SQL result. */\nsql.numberOrNull = sql<number | null>;\n\n/** Shorthand for `sql<string>`; does not cast or convert the SQL result. */\nsql.string = sql<string>;\n\n/** Shorthand for `sql<string | null>`; does not cast or convert the SQL result. */\nsql.stringOrNull = sql<string | null>;\n\n/** Shorthand for `sql<boolean>`; does not cast or convert the SQL result. */\nsql.boolean = sql<boolean>;\n\n/** Shorthand for `sql<boolean | null>`; does not cast or convert the SQL result. */\nsql.booleanOrNull = sql<boolean | null>;\n\n/** A raw condition for `where`, `having`, or `on`. */\nsql.condition = function condition(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition {\n return deferredCondition((ctx) => new TemplateExpr(strings, values).toSql(ctx));\n};\n\n/** A column Joist does not model, on a source that is in the query. */\nsql.ref = function ref<R = unknown>(source: QuerySource, column: string): Expr<R, string> {\n return new RefExpr(handleOf(source), column) as any;\n};\n\n/**\n * Parses `arg` (a `Query` POJO or `query(...)` value) into a runnable `Plan`.\n *\n * `EntityManager.query` runs the plan; this module deliberately does not import `EntityManager` (see\n * `EntityHydrator`), so it parses and hands back `{ sql, bindings, decodeRows }` instead of executing.\n */\nexport function parseUserQuery(arg: unknown): Plan {\n if (arg instanceof SubqueryExpr) fail(\"Scalar query values are expressions, not executable read inputs\");\n return parseQuery(toQuery(arg), undefined, new AliasAssigner());\n}\n\n/** Recognizes read brands, including malformed hybrids that must reach read validation rather than mutation execution. */\nexport function isReadQueryValue(arg: unknown): boolean {\n return isSubqueryValue(arg) || isEntityQueryValue(arg);\n}\n\n/**\n * Compiles scalar or nonempty named expression projections, shared by SELECT and mutation RETURNING.\n * Source-shaped values need read hydration/source rules and are deliberately excluded here.\n */\nexport function projectionToSql(\n select: unknown,\n ctx: Ctx,\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const output = projectionOutput(select);\n if (output.kind === \"scalar\") {\n // Scalar mode: one value per row, used by scalar/IN-list subqueries\n const expr = output.columns[0][1];\n const fragment = expr.toSql(ctx);\n const selects = [{ ...fragment, sql: `${fragment.sql} AS value` }];\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => expr.decode(row.value)),\n output,\n };\n }\n // POJO mode\n const entries = output.columns;\n const selects = entries.map((entry) => {\n const [key, expr] = entry;\n const fragment = expr.toSql(ctx);\n return { ...fragment, sql: `${fragment.sql} AS ${safeKq(key)}` };\n });\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => decodeRow(row, entries)),\n output,\n };\n}\n\n/**\n * The one `EntityManager` capability that row decoding needs, typed structurally.\n *\n * Importing `EntityManager.ts` here would complete an `EntityManager.ts` <-> `query.ts` declaration\n * cycle (`EntityManager.query` imports this module's types), which correlated with a tsc 7.0.2\n * incremental-build bug: after tsdown rewrites `build/`, `tsc --build` sporadically reports thousands\n * of phantom \"Module 'joist-orm' has no exported member ...\" errors and caches them in `.tsbuildinfo`.\n */\nexport interface EntityHydrator {\n hydrate(cstr: any, rows: readonly any[]): any[];\n}\n\nexport interface Plan {\n sql: string;\n bindings: any[];\n /** Aliases of enclosing queries this (sub)query referenced. */\n outerRefs: string[];\n /** Ordered SQL output columns and their existing expression codecs, before JS row decoding. */\n output: QueryOutput;\n decodeRows(em: EntityHydrator, rows: any[]): any[];\n}\n\n// =====================================================================================================\n// Runtime: handles, subquery expressions, the proxy\n// =====================================================================================================\n\ntype AnyQuery = Query<any, any> & { as?: string };\ntype AnyReadQuery = AnyQuery | SetQuery<readonly SetOperand[]>;\n\n/** Only POJO outputs can be set operands; ordinary scalar reads also expose an ordered output column. */\nexport interface QueryOutput {\n kind: \"entity\" | \"scalar\" | \"pojo\";\n /** Expressions retain codecs and physical nullability after LEFT joins and set operations. */\n columns: readonly (readonly [string, BaseExpr])[];\n}\n\n/** The runtime identity of a `query(...)` value; `Ctx.aliasFor` keys on it, like a table's `TableMgmt`. */\nexport class SubqueryHandle {\n constructor(readonly q: AnyReadQuery) {}\n\n get name(): string | undefined {\n return this.q.as;\n }\n\n /** The select keys, for `select: <subquery>` and for reporting unknown columns. */\n columnKeys(): string[] {\n const output = this.output();\n if (output.kind === \"pojo\") return output.columns.map(([key]) => key);\n return fail(`A subquery with an entity or scalar select has no columns`);\n }\n\n /** The inner expression behind `key`, for its decoder/encoder. */\n columnExpr(key: string): BaseExpr {\n return (\n this.output().columns.find(([name]) => name === key)?.[1] ??\n fail(`Subquery ${this.describe()} has no column ${key}`)\n );\n }\n\n /** Resolve output metadata without parsing SQL or caching aliases from an enclosing query. */\n output(): QueryOutput {\n return queryOutput(this.q);\n }\n\n column(key: string): SubqueryColumnExpr {\n return new SubqueryColumnExpr(this, key, this.columnExpr(key));\n }\n\n describe(): string {\n return this.q.as ? `'${this.q.as}'` : \"(anonymous)\";\n }\n}\n\n/** A column of a joined/from'd subquery, i.e. `bookStats.bookCount`, which becomes `book_stats.\"bookCount\"`. */\nclass SubqueryColumnExpr extends BaseExpr {\n constructor(\n private handle: SubqueryHandle,\n private key: string,\n private inner: BaseExpr,\n ) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.handle);\n // safeKq for the alias too: a subquery's canonical alias is its user-provided `as` name\n return { sql: `${safeKq(alias)}.${safeKq(this.key)}`, bindings: [], refs: [alias] };\n }\n\n decode(value: unknown): unknown {\n return this.inner.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.inner.encode(value);\n }\n\n get outputType(): TypeInfo | undefined {\n return this.inner.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.inner.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.handle;\n }\n}\n\n/**\n * A scalar (or IN-list) subquery, i.e. `query({ from: b, where: [...], select: b.id.count() })`.\n *\n * It closes over the outer aliases it references, so correlation is free; those references are the\n * subquery's \"free\" aliases and count toward the outer query's join pruning.\n */\nclass SubqueryExpr extends BaseExpr {\n readonly [scalarQueryBrand] = true;\n\n constructor(readonly handle: SubqueryHandle) {\n super();\n }\n\n get subquerySelect(): BaseExpr {\n const expr = this.handle.output().columns[0][1];\n // Polymorphic IN uses the original alias's ID metadata when its key codec is unknown.\n return expr instanceof OutputExpr ? expr.inner : expr;\n }\n\n get outputType(): TypeInfo | undefined {\n return this.subquerySelect.outputType;\n }\n\n get sqlNullable(): boolean {\n // Even a NOT NULL projection becomes NULL when a scalar subquery returns no rows.\n return true;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const bare = this.toSqlBare(ctx);\n return { ...bare, sql: `(${bare.sql})` };\n }\n\n toSqlBare(ctx: ExprContext): SqlFragment {\n const parent = ctx instanceof Ctx ? ctx : fail(\"Subqueries need the query parser's context\");\n const plan = parseQuery(this.handle.q, parent, parent.assigner);\n return { sql: plan.sql, bindings: plan.bindings, refs: plan.outerRefs };\n }\n\n decode(value: unknown): unknown {\n return this.subquerySelect.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.subquerySelect.encode(value);\n }\n}\n\nfunction newSubqueryProxy(handle: SubqueryHandle): object {\n return new Proxy(\n {},\n {\n get(_, key) {\n if (key === subqueryBrand) return handle;\n if (typeof key === \"string\") return handle.column(key);\n return undefined;\n },\n has(_, key) {\n return key === subqueryBrand || (typeof key === \"string\" && handle.columnKeys().includes(key));\n },\n },\n );\n}\n\nfunction isSubqueryValue(value: unknown): value is { [subqueryBrand]: SubqueryHandle } {\n return typeof value === \"object\" && value !== null && subqueryBrand in value;\n}\n\nfunction isEntityQueryValue(value: unknown): value is { [entityQueryBrand]: SubqueryHandle } {\n return typeof value === \"object\" && value !== null && entityQueryBrand in value;\n}\n\nfunction isPlainSelect(select: unknown): select is Record<string, ExprLike<any>> {\n return (\n typeof select === \"object\" &&\n select !== null &&\n !isExpr(select) &&\n !isSubqueryValue(select) &&\n !isEntityQueryValue(select) &&\n (Object.getPrototypeOf(select) === Object.prototype || Object.getPrototypeOf(select) === null)\n );\n}\n\n/** Returns the runtime identity of a source: a table's `TableMgmt` or a subquery's handle. */\nfunction handleOf(source: unknown): TableMgmt | SubqueryHandle {\n if (isTable(source)) return getTableMgmt(source);\n if (isSubqueryValue(source)) return readValueHandle(source);\n return fail(`Expected a table or a query(...) value, got ${source}`);\n}\n\n// =====================================================================================================\n// Runtime: parse -> prune -> SQL -> decode\n// =====================================================================================================\n\nfunction toQuery(arg: unknown): AnyReadQuery {\n if (isReadQueryValue(arg)) return toQuery(readValueHandle(arg).q);\n if (arg instanceof SubqueryExpr) return toQuery(arg.handle.q);\n validateReadQuery(arg);\n return arg;\n}\n\n/** Virtual subquery columns are not own clauses; attached properties on the value are always rejected. */\nfunction readValueHandle(arg: unknown): SubqueryHandle {\n if (!isSubqueryValue(arg) && !isEntityQueryValue(arg)) return fail(\"Expected a branded read query value\");\n const brand = isSubqueryValue(arg) ? subqueryBrand : entityQueryBrand;\n validateQueryKeys(arg, [brand], \"Read query values\");\n const handle = isSubqueryValue(arg) ? arg[subqueryBrand] : arg[entityQueryBrand];\n return handle instanceof SubqueryHandle ? handle : fail(\"Invalid read query value handle\");\n}\n\nconst SET_OPERATIONS: Record<SetOperation, string> = {\n union: \"UNION\",\n unionAll: \"UNION ALL\",\n intersect: \"INTERSECT\",\n intersectAll: \"INTERSECT ALL\",\n except: \"EXCEPT\",\n exceptAll: \"EXCEPT ALL\",\n};\n\nconst MUTATION_KEYS: readonly MutationKey[] = [\"insert\", \"update\", \"delete\", \"values\", \"set\", \"returning\", \"allowAll\"];\n\nconst READ_KEYS: readonly (keyof Clauses | \"from\" | \"as\")[] = [\n \"from\",\n \"join\",\n \"where\",\n \"groupBy\",\n \"having\",\n \"select\",\n \"orderBy\",\n \"limit\",\n \"offset\",\n \"distinct\",\n \"pruneJoins\",\n \"softDeletes\",\n \"as\",\n];\n\n/**\n * Checks every ordinary or compound root before exposing output metadata or compiling SQL.\n * Validate options before applying defaults so wrong-type values, including null, cannot disappear.\n */\nfunction validateReadQuery(arg: unknown): asserts arg is AnyReadQuery {\n if (typeof arg !== \"object\" || arg === null || Array.isArray(arg)) {\n fail(\"em.query expects a { from, select, ... } object or a query(...) value\");\n }\n if (isSetQuery(arg)) {\n setOperands(arg);\n } else {\n validateQueryKeys(arg, READ_KEYS, \"Read queries\");\n if (!(\"from\" in arg && \"select\" in arg))\n fail(\"em.query expects a { from, select, ... } object or a query(...) value\");\n if (isTable(arg.select)) {\n const meta = getTableMetadata(arg.select);\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(`Inherited table ${meta.type} cannot be selected as entities; select its columns individually`);\n }\n }\n }\n const options = arg as Record<string, unknown>;\n for (const key of [\"limit\", \"offset\"]) {\n const value = options[key];\n if (value !== undefined && (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)) {\n fail(`Read query ${key} must be a nonnegative finite integer`);\n }\n }\n if (options.softDeletes !== undefined && options.softDeletes !== \"include\" && options.softDeletes !== \"exclude\") {\n fail(\"Read query softDeletes must be 'include' or 'exclude'\");\n }\n for (const key of [\"distinct\", \"pruneJoins\"]) {\n if (options[key] !== undefined && typeof options[key] !== \"boolean\") fail(`Read query ${key} must be a boolean`);\n }\n if (options.as !== undefined && typeof options.as !== \"string\") fail(\"Read query as must be a string\");\n}\n\n/** Includes undefined, symbol, non-enumerable, and inherited clauses rather than silently ignoring them. */\nfunction validateQueryKeys(arg: object, allowed: readonly PropertyKey[], description: string): void {\n for (let object: object | null = arg; object && object !== Object.prototype; object = Object.getPrototypeOf(object)) {\n for (const key of Reflect.ownKeys(object)) {\n if (allowed.includes(key)) continue;\n if (MUTATION_KEYS.includes(key as MutationKey)) {\n fail(`Read queries do not support mutation clause '${String(key)}'; use em.execute`);\n }\n fail(`${description} do not support clause '${String(key)}'`);\n }\n }\n}\n\n/** Detect operation keys even when their values are invalid, so mixed roots cannot fall through to SELECT. */\nfunction isSetQuery(value: unknown): value is SetQuery<readonly SetOperand[]> {\n return typeof value === \"object\" && value !== null && Object.keys(SET_OPERATIONS).some((key) => key in value);\n}\n\n/** Validate each root independently; no operand, including the left side of EXCEPT, can be pruned. */\nfunction setOperands(q: SetQuery<readonly SetOperand[]>): [SetOperation, readonly SetOperand[]] {\n const keys = (Object.keys(SET_OPERATIONS) as SetOperation[]).filter((key) => key in q);\n if (keys.length !== 1) fail(\"A set query requires exactly one operation key\");\n validateQueryKeys(q, [keys[0], \"orderBy\", \"limit\", \"offset\", \"as\"], \"Set queries\");\n const operands = q[keys[0]];\n if (!Array.isArray(operands) || operands.length < 2) fail(\"Set operations require at least two operands\");\n return [keys[0], operands];\n}\n\n/**\n * Resolve ordered output columns without rendering SQL. Set compatibility is deliberately conservative:\n * every column needs the same known SQL representation, logical domain, and precise ID target.\n *\n * I.e. Author.id and Book.author share the Author key codec, but Book.id must never decode as Author.id.\n * The first branch supplies names and conversions only after every branch passes these checks.\n * UNION admits NULL from any branch; EXCEPT/INTERSECT retain the left branch's nullable facts.\n * Unknown nullability stays unknown unless another UNION branch is known nullable.\n */\nfunction queryOutput(q: AnyReadQuery): QueryOutput {\n validateReadQuery(q);\n if (isSetQuery(q)) {\n const [operation, operands] = setOperands(q);\n const first = queryOutput(toQuery(operands[0]));\n const columns = [...first.columns];\n for (const operand of operands) {\n const output = operand === operands[0] ? first : queryOutput(toQuery(operand));\n if (output.kind !== \"pojo\") {\n fail(\n output.kind === \"entity\"\n ? \"Set operations do not support entity-mode operands\"\n : \"Set operations require POJO operands; wrap scalar expressions in a named select projection\",\n );\n }\n if (output.columns.length !== first.columns.length) fail(\"Set operands must have the same POJO keys\");\n for (let i = 0; i < columns.length; i++) {\n const [key, expr] = columns[i];\n const other = output.columns.find(([name]) => name === key)?.[1];\n if (!other) fail(`Set operands must have the same POJO keys; missing '${key}'`);\n const left = expr.outputType;\n const right = other.outputType;\n if (!left || !right)\n fail(\n `Set column '${key}' has an unknown or unsupported output codec; sql<R> does not declare a SQL type or codec`,\n );\n if (left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) {\n fail(\n `Set column '${key}' has incompatible output codecs (${left.dbType} and ${right.dbType}); use matching SQL representations and logical domains`,\n );\n }\n if (operation === \"union\" || operation === \"unionAll\") {\n const nullable =\n expr.sqlNullable === true || other.sqlNullable === true\n ? true\n : expr.sqlNullable === undefined || other.sqlNullable === undefined\n ? undefined\n : false;\n if (nullable !== expr.sqlNullable) columns[i] = [key, new OutputExpr(expr, nullable)];\n }\n }\n }\n setOrderBys(q, first);\n return { kind: first.kind, columns };\n }\n const { select } = q;\n if (isTable(select)) return { kind: \"entity\", columns: [] };\n if (isSubqueryValue(select)) return readValueHandle(select).output();\n return joinedOutput(projectionOutput(select), q.join);\n}\n\n/** Validates the projection before compiling SQL or exposing reusable query columns. */\nfunction projectionOutput(select: unknown): QueryOutput {\n if (isExpr(select)) return { kind: \"scalar\", columns: [[\"value\", asExpr(select, \"select\")]] };\n if (isPlainSelect(select)) {\n const columns: [string, BaseExpr][] = [];\n // Enumerate once: a projection proxy must not be revisited just to check for symbol keys.\n for (const key of Reflect.ownKeys(select)) {\n if (typeof key !== \"string\") fail(\"Projection keys must be strings\");\n if (Object.prototype.propertyIsEnumerable.call(select, key))\n columns.push([key, asExpr(select[key], `select.${key}`)]);\n }\n if (columns.length === 0) fail(\"A named expression projection must not be empty\");\n return { kind: \"pojo\", columns };\n }\n return fail(\"Expected a scalar expression or a nonempty named expression projection\");\n}\n\n/**\n * Adds physical NULL from unmatched LEFT joins without mutating shared expressions or their codecs.\n * Only direct columns carry sqlSource; COUNT and COALESCE retain their own SQL nullability.\n * I.e. selecting Book.title from a LEFT-joined Book makes its output nullable, but COUNT(Book.id) stays NOT NULL.\n */\nfunction joinedOutput(output: QueryOutput, joins: QueryJoins | undefined): QueryOutput {\n if (!joins?.some((join) => join?.left)) return output;\n const left = new Set<object>();\n for (const join of joins) if (join?.left) left.add(handleOf(join.left));\n return {\n kind: output.kind,\n columns: output.columns.map((column) => {\n const [key, expr] = column;\n return expr.sqlSource && left.has(expr.sqlSource) && expr.sqlNullable !== true\n ? [key, new OutputExpr(expr, true)]\n : column;\n }),\n };\n}\n\n/** An output-only nullability adjustment that preserves the selected expression's SQL and conversions. */\nclass OutputExpr extends BaseExpr {\n constructor(\n readonly inner: BaseExpr,\n private nullable: boolean | undefined,\n ) {\n super();\n }\n\n get outputType(): TypeInfo | undefined {\n return this.inner.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.nullable;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n return this.inner.toSql(ctx);\n }\n\n decode(value: unknown): unknown {\n return this.inner.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.inner.encode(value);\n }\n}\n\n/**\n * Compile siblings in separate local scopes with the same enclosing context. Projection wrappers align\n * output positions without moving DISTINCT/order/pagination or repeating volatile selected expressions.\n * Parenthesizing each accumulated left side preserves array association and explicit nested grouping.\n */\nfunction parseSetQuery(q: SetQuery<readonly SetOperand[]>, parent: Ctx | undefined, assigner: AliasAssigner): Plan {\n const [operation, operands] = setOperands(q);\n const output = queryOutput(q);\n const plans = operands.map((operand) => parseQuery(toQuery(operand), parent, assigner));\n let sql = \"\";\n for (const plan of plans) {\n let branch = plan.sql;\n if (output.columns.some(([key], i) => plan.output.columns[i][0] !== key)) {\n const alias = safeKq(assigner.getLiteralAlias(\"sq\"));\n branch = `SELECT ${output.columns.map(([key]) => `${alias}.${safeKq(key)} AS ${safeKq(key)}`).join(\", \")} FROM (${branch}) AS ${alias}`;\n }\n sql = sql ? `(${sql}) ${SET_OPERATIONS[operation]} (${branch})` : branch;\n }\n const orderBys = setOrderBys(q, output);\n if (orderBys.length > 0) sql += ` ORDER BY ${orderBys.join(\", \")}`;\n const bindings = plans.flatMap((plan) => plan.bindings);\n if (q.limit !== undefined) {\n sql += \" LIMIT ?\";\n bindings.push(q.limit);\n }\n if (q.offset !== undefined) {\n sql += \" OFFSET ?\";\n bindings.push(q.offset);\n }\n return {\n sql,\n bindings,\n outerRefs: [...new Set(plans.flatMap((plan) => plan.outerRefs))],\n output,\n decodeRows: plans[0].decodeRows,\n };\n}\n\n/** Validate and quote only named set output sorts, including before a reusable value is parsed. */\nfunction setOrderBys(q: SetQuery<readonly SetOperand[]>, output: QueryOutput): string[] {\n const orderBys: string[] = [];\n for (const entry of Array.isArray(q.orderBy) ? q.orderBy : q.orderBy ? [q.orderBy] : []) {\n if (entry === undefined) continue;\n if (!entry || typeof entry !== \"object\" || isExpr(entry))\n fail(\"Set orderBy requires output-key hashes; use an outer query for expressions\");\n for (const [key, direction] of Object.entries(entry)) {\n if (direction === undefined) continue;\n if (!output.columns.some(([name]) => name === key)) fail(`Set orderBy key '${key}' is not a named output column`);\n if (!ORDER_BY_DIRECTIONS.includes(direction as string))\n fail(\"Set orderBy requires output-key directions; use an outer query for expressions\");\n orderBys.push(`${safeKq(key)} ${direction}`);\n }\n }\n return orderBys;\n}\n\n/**\n * What an expression needs from the query it is generating SQL for.\n *\n * Each (sub)query gets its own `Ctx`; a lookup that misses locally walks up to the enclosing query and\n * records the hit in `outerRefs`, which is how a correlated subquery reports the outer aliases it\n * depends on (the way `ExistsCondition.outerAliases` does), so join pruning keeps them.\n */\nexport class Ctx implements ExprContext {\n private aliases = new Map<object, string>();\n readonly outerRefs = new Set<string>();\n\n constructor(\n readonly assigner: AliasAssigner,\n private parent: Ctx | undefined,\n ) {}\n\n register(handle: object, alias: string): void {\n this.aliases.set(handle, alias);\n }\n\n aliasFor(handle: object): string {\n const local = this.aliases.get(handle);\n if (local) return local;\n if (this.parent) {\n const outer = this.parent.aliasFor(handle);\n this.outerRefs.add(outer);\n return outer;\n }\n return fail(`${describeHandle(handle)} is not in this query's from/join`);\n }\n\n conditionToSql(cond: SqlCondition): SqlFragment | undefined {\n // Inside another expression (i.e. a `sql` template), keep `a OR b` grouped\n return conditionToSql(cond, this, false);\n }\n}\n\nfunction describeHandle(handle: object): string {\n if (handle instanceof SubqueryHandle) return `Subquery ${handle.describe()}`;\n if (handle instanceof JoinTableHandle) return `Join table ${handle.joinTableName}`;\n if (\"tableName\" in handle) return `Table for ${(handle as TableMgmt).tableName}`;\n return \"Table\";\n}\n\ninterface ParsedSource {\n handle: TableMgmt | SubqueryHandle | JoinTableHandle;\n alias: string;\n /** `table AS alias` or `(SELECT ...) AS alias`. */\n sql: string;\n bindings: any[];\n /** Outer aliases a derived table references; PG rejects those without LATERAL, but pruning should still see them. */\n refs: string[];\n /** Entity-mode selects, i.e. `a.*` excluding lazy columns. */\n entitySelects: string[];\n meta: EntityMetadata | undefined;\n}\n\ninterface ParsedJoin {\n kind: \"inner\" | \"left\";\n source: ParsedSource;\n /** The user's ON alone; `undefined` means it pruned away entirely, an error if the join is kept. */\n userOn: SqlFragment | undefined;\n /** The ON to emit: the user's ON plus any injected soft-delete conditions. */\n fullOn: SqlFragment | undefined;\n keep: boolean;\n}\n\n/**\n * Parses one `Query` POJO into SQL, recursively for subqueries.\n *\n * 1. Register every source's runtime identity with its SQL alias in this parse's context.\n * 2. Generate SQL for sources, selects, conditions, group-bys, and order-bys against the context; every fragment\n * reports the aliases it references.\n * 3. Prune: drop joins nothing references (see below), then reject a kept join whose ON collapsed.\n * 4. Assemble the SQL from the kept fragments, so pruned bindings disappear with their SQL.\n */\nfunction parseQuery(q: AnyReadQuery, parent: Ctx | undefined, assigner: AliasAssigner): Plan {\n validateReadQuery(q);\n if (isSetQuery(q)) return parseSetQuery(q, parent, assigner);\n const ctx = new Ctx(assigner, parent);\n const joinEntries = [...(q.join ?? [])].filter(isDefined);\n\n // 1. Register every source before generating SQL, so conditions can resolve their aliases.\n const parseFrom = registerSource(q.from, ctx, assigner);\n const pendingJoins = joinEntries.flatMap((j) => {\n const kind = \"inner\" in j && j.inner ? (\"inner\" as const) : (\"left\" as const);\n const alias = kind === \"inner\" ? j.inner : j.left;\n const keep = j.keep ?? false;\n // Only collection sugar joins (o2m/m2m) filter soft-deletes, em.find's relation semantics:\n // references (m2o/o2o/poly) resolve soft-deleted entities, and explicit joins are the user's own\n const softDeletes = (j as any)[collectionJoin] === true;\n const target = { kind, keep, on: j.on, softDeletes, parseSource: registerSource(alias, ctx, assigner) };\n // A sugar m2m join (`a.tags.as(t)`) carries a hidden join-table join; emit it first, with the same kind\n const m2m: M2mJoinTable | undefined = (j as any)[m2mJoinTable];\n if (!m2m) return [target];\n return [\n { kind, keep, on: m2m.on, softDeletes: false, parseSource: registerJoinTable(m2m.handle, ctx, assigner) },\n target,\n ];\n });\n\n // 2. Generate SQL.\n const softDeletes = q.softDeletes ?? \"exclude\";\n const from = parseFrom();\n const joins: ParsedJoin[] = pendingJoins.map((j) => {\n const source = j.parseSource();\n // `userOn` is the user's ON alone, so the collapsed-ON check below is not fooled by injections\n const userOn = conditionToSql(j.on, ctx, true);\n const injected = injectedConditions(source, j.softDeletes ? softDeletes : \"include\");\n const fullOn = userOn && injected.length > 0 ? conditionToSql({ and: [j.on, ...injected] }, ctx, true) : userOn;\n return { kind: j.kind, keep: j.keep, source, userOn, fullOn };\n });\n const { selects, decodeRows, output } = selectsToSql(q, ctx, from);\n const fromInjected = injectedConditions(from, softDeletes);\n const where = conditionToSql(fromInjected.length > 0 ? { and: [q.where, ...fromInjected] } : q.where, ctx, true);\n const having = conditionToSql(q.having, ctx, true);\n const groupBys = (q.groupBy ?? []).map((g) => asExpr(g, \"groupBy\").toSql(ctx));\n const orderBys = orderBysToSql(q, ctx);\n\n // 3. Prune.\n const kept = pruneJoins(q, from, joins, [...selects, ...groupBys, ...orderBys, where, having].filter(isDefined));\n // Joins emit in declaration order, so an ON may only reference sources declared before it; a forward\n // reference would reach PG as invalid SQL (\"missing FROM-clause entry\"). Reordering is not offered:\n // it is not semantics-preserving once INNER and LEFT joins mix, and the caller's fix is trivial.\n const laterAliases = new Set(kept.map((j) => j.source.alias));\n for (const j of kept) {\n if (!j.userOn) {\n fail(\n `Join ${describeHandle(j.source.handle)} has no ON condition left (they all pruned), but the query still references it`,\n );\n }\n laterAliases.delete(j.source.alias);\n const forward = j.fullOn!.refs.find((r) => laterAliases.has(r));\n if (forward) {\n fail(\n `Join ${describeHandle(j.source.handle)} references '${forward}', which is joined later; move that join earlier in the join array`,\n );\n }\n }\n\n // 4. Assemble.\n const out: SqlFragment[] = [];\n out.push({ sql: `SELECT ${q.distinct ? \"DISTINCT \" : \"\"}`, bindings: [], refs: [] });\n out.push(joinFragmentParts(selects, \", \"));\n out.push({ sql: ` FROM ${from.sql}`, bindings: from.bindings, refs: [] });\n for (const j of kept) {\n const keyword = j.kind === \"inner\" ? \"JOIN\" : \"LEFT OUTER JOIN\";\n out.push({\n sql: ` ${keyword} ${j.source.sql} ON ${j.fullOn!.sql}`,\n bindings: [...j.source.bindings, ...j.fullOn!.bindings],\n refs: [],\n });\n }\n if (where) out.push({ sql: ` WHERE ${where.sql}`, bindings: where.bindings, refs: [] });\n if (groupBys.length > 0)\n out.push({ ...joinFragmentParts(groupBys, \", \"), sql: ` GROUP BY ${groupBys.map((g) => g.sql).join(\", \")}` });\n if (having) out.push({ sql: ` HAVING ${having.sql}`, bindings: having.bindings, refs: [] });\n if (orderBys.length > 0)\n out.push({ ...joinFragmentParts(orderBys, \", \"), sql: ` ORDER BY ${orderBys.map((o) => o.sql).join(\", \")}` });\n if (q.limit !== undefined) out.push({ sql: ` LIMIT ?`, bindings: [q.limit], refs: [] });\n if (q.offset !== undefined) out.push({ sql: ` OFFSET ?`, bindings: [q.offset], refs: [] });\n\n return {\n sql: out.map((o) => o.sql).join(\"\"),\n bindings: out.flatMap((o) => o.bindings),\n outerRefs: [...ctx.outerRefs],\n output,\n decodeRows,\n };\n}\n\n/**\n * Assigns a SQL alias to a source and returns a function that parses it after all sources are registered.\n *\n * Conditions resolve source identities through the context when their SQL is generated.\n * Each entity source reads only its physical table, without inheritance joins or class tags.\n */\nfunction registerSource(source: unknown, ctx: Ctx, assigner: AliasAssigner): () => ParsedSource {\n const handle = handleOf(source);\n if (handle instanceof SubqueryHandle) {\n const alias = handle.name ? assigner.getLiteralAlias(handle.name) : assigner.getLiteralAlias(\"sq\");\n ctx.register(handle, alias);\n return () => {\n const inner = parseQuery(handle.q, ctx, assigner);\n return {\n handle,\n alias,\n sql: `(${inner.sql}) AS ${safeKq(alias)}`,\n bindings: inner.bindings,\n refs: inner.outerRefs,\n entitySelects: [],\n meta: undefined,\n };\n };\n } else {\n const meta = getTableMetadata(source as any);\n const alias = assigner.getAlias(meta.tableName);\n ctx.register(handle, alias);\n return () => {\n // Ordinary entity mode selects the table's columns, excluding lazy ones like em.find.\n const entitySelects = meta.hasLazyColumns ? lazyExcludedSelects(meta, alias) : [kqStar(alias)];\n return {\n handle,\n alias,\n sql: `${kq(meta.tableName)} AS ${kq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects,\n meta,\n };\n };\n }\n}\n\n/**\n * Per-source soft-delete injections: `alias.deleted_at IS NULL` for a soft-deletable entity.\n * CTI subtypes are skipped because their deleted-at column belongs to the base table (see\n * `filterSoftDeletes`). STI sources read all physical rows without discriminator predicates.\n *\n * The conditions go into the from's WHERE or the join's ON, and never keep an otherwise unreferenced\n * join alive, which is what `pruneable: true` means on em.find's side.\n */\nexport function injectedConditions(\n source: { meta: EntityMetadata | undefined; alias: string },\n softDeletes: \"include\" | \"exclude\",\n): ColumnCondition[] {\n const { meta } = source;\n if (!meta) return [];\n const conditions: ColumnCondition[] = [];\n if (filterSoftDeletes(meta, softDeletes)) {\n const field = meta.allFields[getBaseMeta(meta).timestampFields!.deletedAt!];\n const column = field.serde!.columns[0];\n conditions.push({\n kind: \"column\",\n alias: `${source.alias}${field.aliasSuffix}`,\n column: column.columnName,\n dbType: column.dbType,\n cond: { kind: \"is-null\" },\n pruneable: true,\n });\n }\n return conditions;\n}\n\n/** Registers a sugar m2m join table, i.e. `authors_to_tags`: a raw table with no entity metadata. */\nfunction registerJoinTable(handle: JoinTableHandle, ctx: Ctx, assigner: AliasAssigner): () => ParsedSource {\n const alias = assigner.getAlias(handle.joinTableName);\n ctx.register(handle, alias);\n return () => ({\n handle,\n alias,\n sql: `${kq(handle.joinTableName)} AS ${kq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects: [],\n meta: undefined,\n });\n}\n\n/** Generates the `select` clause SQL and returns how to decode the resulting rows. */\nfunction selectsToSql(\n q: AnyQuery,\n ctx: Ctx,\n from: ParsedSource,\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const { select } = q;\n if (isTable(select)) {\n // Ordinary entity mode: `a.*`, hydrated through the identity map. Only the from is\n // hydratable: a joined alias would need null-row skipping and left-join nullability (see TODO.md)\n if (from.handle !== getTableMgmt(select)) {\n fail(\"Selecting a joined table is not supported yet; select the from table, or select its columns individually\");\n }\n const alias = ctx.aliasFor(getTableMgmt(select));\n const meta = getTableMetadata(select);\n const selects = from.entitySelects.map((s) => ({ sql: s, bindings: [], refs: [alias] }));\n return {\n selects,\n decodeRows: (em, rows) => em.hydrate(meta.cstr as any, rows),\n output: { kind: \"entity\", columns: [] },\n };\n } else if (isSubqueryValue(select)) {\n // `select: <subquery>` is `select *` for that table; like entity mode, only for the from, since a\n // left-joined subquery's unmatched rows would decode null fields the row type calls non-null\n const handle = readValueHandle(select);\n if (from.handle !== handle) {\n fail(\n \"Selecting a joined subquery is not supported; select the from subquery, or select its columns individually\",\n );\n }\n const alias = ctx.aliasFor(handle);\n const output = handle.output();\n const selects = output.columns.map(([k]) => ({\n sql: `${safeKq(alias)}.${safeKq(k)} AS ${safeKq(k)}`,\n bindings: [],\n refs: [alias],\n }));\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => decodeRow(row, output.columns)),\n output,\n };\n }\n const projection = projectionToSql(select, ctx);\n projection.output = joinedOutput(projection.output, q.join);\n return projection;\n}\n\nfunction decodeRow(row: any, decoders: readonly (readonly [string, BaseExpr])[]): any {\n const result: any = {};\n for (const [key, expr] of decoders) {\n const value = row[key];\n const decoded = value === null || value === undefined ? null : expr.decode(value);\n // A projected __proto__ is data, not a request to replace the result object's prototype.\n if (key === \"__proto__\") {\n Object.defineProperty(result, key, { value: decoded, enumerable: true, configurable: true, writable: true });\n } else {\n result[key] = decoded;\n }\n }\n return result;\n}\n\nconst ORDER_BY_DIRECTIONS: string[] = [\n \"ASC\",\n \"DESC\",\n \"ASC NULLS FIRST\",\n \"ASC NULLS LAST\",\n \"DESC NULLS FIRST\",\n \"DESC NULLS LAST\",\n];\n\n/**\n * Generates ORDER BY SQL in entry order for keyed/expression arrays or a single keyed object.\n *\n * Expression entries retain bindings and alias references for join pruning. Undefined entries and\n * directions are omitted.\n */\nfunction orderBysToSql(q: AnyQuery, ctx: Ctx): SqlFragment[] {\n const { orderBy, select } = q;\n if (!orderBy) return [];\n const result: SqlFragment[] = [];\n for (const entry of Array.isArray(orderBy) ? orderBy : [orderBy]) {\n if (entry === undefined) continue;\n // A select key can also be named asc or desc, so distinguish entries by their values, not their keys.\n if (isExpr(entry.asc) || isExpr(entry.desc)) {\n result.push(orderByToSql(entry, ctx));\n continue;\n }\n for (const [key, dir] of Object.entries(entry)) {\n if (dir === undefined) continue;\n // The direction is interpolated into the SQL, so never trust it, i.e. it might be a request param\n if (!ORDER_BY_DIRECTIONS.includes(dir as string)) return fail(`Invalid orderBy direction '${dir}'`);\n // Entity mode orders by the alias's column; POJO/subquery selects order by the output column name\n if (isTable(select)) {\n const column = (select as any)[key];\n if (!isExpr(column)) return fail(`orderBy key '${key}' is not a sortable column of the table`);\n const fragment = asNode(column).toSql(ctx);\n result.push({ ...fragment, sql: `${fragment.sql} ${dir}` });\n } else {\n if (isExpr(select)) return fail(`the keyed orderBy form needs a POJO or entity select`);\n const keys = isSubqueryValue(select) ? select[subqueryBrand].columnKeys() : Object.keys(select as object);\n if (!keys.includes(key)) return fail(`orderBy key '${key}' is not a key of select`);\n result.push({ sql: `${safeKq(key)} ${dir}`, bindings: [], refs: [] });\n }\n }\n }\n return result;\n}\n\nfunction orderByToSql(o: QueryOrderBy, ctx: Ctx): SqlFragment {\n const [expr, direction] = \"asc\" in o && o.asc ? [o.asc, \"ASC\"] : [o.desc, \"DESC\"];\n const fragment = asExpr(expr, \"orderBy\").toSql(ctx);\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 nulls = o.nulls ? ` NULLS ${o.nulls.toUpperCase()}` : \"\";\n return { ...fragment, sql: `${fragment.sql} ${direction}${nulls}` };\n}\n\n/**\n * Parses a user-facing condition (a single condition or an `{ and }`/`{ or }` filter) with the same\n * `ConditionBuilder` `em.find` uses, so `undefined` members drop out, empty groups drop, and\n * `pruneIfUndefined` applies unchanged. Deferred SQL expression conditions are resolved\n * against the context first.\n */\nexport function conditionToSql(cond: QueryCondition | undefined, ctx: Ctx, topLevel: boolean): SqlFragment | undefined {\n checkCondition(cond);\n if (cond === undefined) return undefined;\n const resolved = resolveDeferredConditions(resolveQueryCondition(cond, ctx), ctx)!;\n const filter: ConditionGroup<ConditionInput> = isFilter(resolved) ? resolved : { and: [resolved] };\n const cb = new ConditionBuilder();\n cb.maybeAddExpression(filter);\n const parsed = cb.toExpressionFilter();\n if (!parsed) return undefined;\n const where = buildWhereClause(parsed, topLevel);\n if (!where) return undefined;\n return { sql: where[0], bindings: where[1], refs: refsOf(parsed) };\n}\n\n/**\n * Rejects malformed predicates throughout a condition tree before pruning can discard a restriction.\n * I.e. an invalid Author-name condition stays invalid even inside a group that would otherwise prune.\n */\nfunction checkCondition(value: unknown): void {\n if (\n isDeferredAliasCondition(value) ||\n (value && typeof value === \"object\" && predicateBrand in value && value[predicateBrand] === \"domain\")\n )\n fail(\n \"Domain alias conditions are only supported by em.find; use table(...) predicates in SQL queries and mutations.\",\n );\n if (value === undefined || value === skipCondition) return;\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value))\n fail(\"Query predicate must be a condition or an and/or group\");\n const condition = value as Record<string, unknown>;\n if (\"and\" in condition || \"or\" in condition) {\n if (\"and\" in condition === \"or\" in condition) fail(\"Query conditions require exactly one and/or group\");\n const key = \"and\" in condition ? \"and\" : \"or\";\n checkConditionKeys(condition, [key, \"pruneIfUndefined\"], \"Query condition group\");\n if (!Array.isArray(condition[key])) fail(\"Query condition groups require an array\");\n if (\n condition.pruneIfUndefined !== undefined &&\n condition.pruneIfUndefined !== \"any\" &&\n condition.pruneIfUndefined !== \"all\"\n )\n fail(\"Invalid query pruneIfUndefined policy\");\n for (const child of condition[key]) checkCondition(child);\n } else if (\"exists\" in condition || \"notExists\" in condition) {\n const key = \"exists\" in condition ? \"exists\" : \"notExists\";\n checkConditionKeys(condition, [key], \"Query existence condition\");\n const query = condition[key];\n if (!(query instanceof SubqueryExpr) && !isReadQueryValue(query)) fail(`Query ${key} requires a query(...) value`);\n toQuery(query);\n } else if (condition.kind === \"raw\") {\n checkConditionKeys(\n condition,\n [\"kind\", \"aliases\", \"condition\", \"bindings\", \"pruneable\", deferredSym, predicateBrand],\n \"Query raw condition\",\n );\n if (\n typeof condition.condition !== \"string\" ||\n !Array.isArray(condition.aliases) ||\n !condition.aliases.every((alias) => typeof alias === \"string\") ||\n !Array.isArray(condition.bindings) ||\n typeof condition.pruneable !== \"boolean\"\n )\n fail(\"Malformed query raw condition\");\n } else if (condition.kind === \"column\") {\n checkConditionKeys(\n condition,\n [\"kind\", \"alias\", \"column\", \"dbType\", \"cond\", \"pruneable\", predicateBrand],\n \"Query column condition\",\n );\n if (\n typeof condition.alias !== \"string\" ||\n typeof condition.column !== \"string\" ||\n typeof condition.dbType !== \"string\" ||\n (condition.pruneable !== undefined && typeof condition.pruneable !== \"boolean\")\n )\n fail(\"Malformed query column condition\");\n const filter = condition.cond as Record<string, unknown> | undefined;\n if (!filter) fail(\"Malformed query column filter\");\n checkConditionKeys(filter, [\"kind\", \"value\"], \"Query column filter\");\n const unary = filter.kind === \"is-null\" || filter.kind === \"not-null\";\n if (\n !unary &&\n (![\n \"eq\",\n \"ne\",\n \"in\",\n \"nin\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"like\",\n \"nlike\",\n \"ilike\",\n \"nilike\",\n \"regex\",\n \"nregex\",\n \"iregex\",\n \"niregex\",\n \"contains\",\n \"ncontains\",\n \"overlaps\",\n \"noverlaps\",\n \"containedBy\",\n \"between\",\n \"jsonPathExists\",\n \"jsonPathPredicate\",\n ].includes(filter.kind as string) ||\n !(\"value\" in filter))\n )\n fail(\"Malformed query column filter\");\n if (unary && \"value\" in filter) fail(\"Unary query filters do not accept values\");\n } else {\n fail(\"Unknown query condition\");\n }\n}\n\n/** Conditions use own enumerable POJO fields, with predicate-brand and SQL-resolver symbols allowed. */\nfunction checkConditionKeys(value: object, allowed: readonly PropertyKey[], description: string): void {\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n fail(`${description} must be a plain POJO`);\n for (const key of Reflect.ownKeys(value)) {\n if (!allowed.includes(key)) fail(`${description} does not support '${String(key)}'`);\n if (typeof key === \"string\" && !Object.prototype.propertyIsEnumerable.call(value, key))\n fail(`${description} requires enumerable fields`);\n }\n}\n\n/**\n * Converts query-valued predicates to SQL conditions for the shared condition builder.\n * Keeps each subquery's projection and reports its outer aliases for join pruning.\n */\nfunction resolveQueryCondition(cond: QueryCondition | undefined, ctx: Ctx): ConditionInput | undefined {\n if (cond === undefined) return undefined;\n if (\"and\" in cond && cond.and) {\n return {\n and: cond.and.map((child) => resolveQueryCondition(child, ctx)),\n pruneIfUndefined: cond.pruneIfUndefined,\n };\n }\n if (\"or\" in cond && cond.or) {\n return { or: cond.or.map((child) => resolveQueryCondition(child, ctx)), pruneIfUndefined: cond.pruneIfUndefined };\n }\n if (\"exists\" in cond || \"notExists\" in cond) {\n const positive = cond.exists !== undefined;\n const plan = parseQuery(toQuery(positive ? cond.exists : cond.notExists), ctx, ctx.assigner);\n return {\n kind: \"raw\",\n condition: `${positive ? \"EXISTS\" : \"NOT EXISTS\"} (${plan.sql})`,\n bindings: plan.bindings,\n aliases: plan.outerRefs,\n pruneable: false,\n };\n }\n return cond as ConditionInput;\n}\n\nfunction isFilter(cond: ConditionInput): cond is ConditionGroup<ConditionInput> {\n return (\"and\" in cond && cond.and !== undefined) || (\"or\" in cond && cond.or !== undefined);\n}\n\n/** The physical source aliases a parsed condition tree references. */\nfunction refsOf(parsed: ParsedExpressionFilter): string[] {\n return deepFindConditions(parsed, false).flatMap((c) =>\n c.kind === \"column\" ? [c.alias] : c.kind === \"raw\" ? c.aliases : c.outerAliases,\n );\n}\n\n/**\n * Pruning: em.find's paradigm, on a flat join list.\n *\n * A condition given `undefined` was already dropped by `ConditionBuilder`. Now a join that nothing\n * references anymore drops with it: a join is required if the source, a select, a surviving condition,\n * a group-by, an order-by, or another required join's ON references it, or if it is pinned with\n * `keep: true`. Marking follows ON dependencies transitively, exactly like `pruneUnusedJoins`'s\n * `DependencyTracker`.\n *\n * em.find's joins almost never filter rows by themselves, so pruning them is semantics-preserving. An\n * explicit `{ inner: b, on }` here does filter rows, so pruning it when unreferenced drops that filter;\n * that matches `{ books: { title: undefined } }` in em.find and is deliberate. `keep: true` pins it, and\n * a pure existence filter is better written as `a.id.in(query({ ... }))`, which is never `undefined`.\n */\nfunction pruneJoins(q: AnyQuery, from: ParsedSource, joins: ParsedJoin[], used: SqlFragment[]): ParsedJoin[] {\n if (q.pruneJoins === false) return joins;\n const deps = new Map<string, string[]>();\n for (const j of joins) {\n const refs = [...(j.userOn?.refs ?? []), ...j.source.refs].filter((r) => r !== j.source.alias);\n deps.set(j.source.alias, refs);\n }\n const required = new Set<string>();\n function markRequired(alias: string): void {\n if (required.has(alias)) return;\n required.add(alias);\n for (const dep of deps.get(alias) ?? []) markRequired(dep);\n }\n markRequired(from.alias);\n for (const r of used.flatMap((u) => u.refs)) markRequired(r);\n for (const j of joins) if (j.keep) markRequired(j.source.alias);\n return joins.filter((j) => required.has(j.source.alias));\n}\n\nfunction asExpr(value: unknown, where: string): BaseExpr {\n if (value instanceof BaseExpr) return value;\n return fail(`${where} must be an expression, i.e. a table column, aggregate, sql\\`...\\`, or scalar query(...)`);\n}\n\nfunction joinFragmentParts(parts: SqlFragment[], sep: string): SqlFragment {\n return { sql: parts.map((p) => p.sql).join(sep), bindings: parts.flatMap((p) => p.bindings), refs: [] };\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n return value !== undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,MAAa,gBAA+B,OAAO,gBAAgB;AACnE,MAAa,mBAAkC,OAAO,mBAAmB;AACzE,MAAa,mBAAkC,OAAO,mBAAmB;AAmlBzE,SAAgB,MAAM,GAA0B;CAC9C,MAAM,SAAS,IAAI,eAAe,QAAQ,CAAC,CAAC;CAC5C,MAAM,SAAS,OAAO,OAAO;CAC7B,IAAI,OAAO,SAAS,UAClB,OAAO,GAAG,mBAAmB,OAAO;MAC/B,IAAI,OAAO,SAAS,UACzB,OAAO,IAAI,aAAa,MAAM;MAE9B,OAAO,iBAAiB,MAAM;AAElC;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,IAAiB,SAA+B,GAAG,QAAmC;CACpG,OAAO,IAAIA,aAAAA,aAAa,SAAS,MAAM;AACzC;;AAGA,IAAI,SAAS;;AAGb,IAAI,eAAe;;AAGnB,IAAI,SAAS;;AAGb,IAAI,eAAe;;AAGnB,IAAI,UAAU;;AAGd,IAAI,gBAAgB;;AAGpB,IAAI,YAAY,SAAS,UAAU,SAA+B,GAAG,QAAiC;CACpG,OAAOC,aAAAA,mBAAmB,QAAQ,IAAID,aAAAA,aAAa,SAAS,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC;AAChF;;AAGA,IAAI,MAAM,SAAS,IAAiB,QAAqB,QAAiC;CACxF,OAAO,IAAIE,aAAAA,QAAQ,SAAS,MAAM,GAAG,MAAM;AAC7C;;;;;;;AAQA,SAAgB,eAAe,KAAoB;CACjD,IAAI,eAAe,cAAc,cAAA,KAAK,iEAAiE;CACvG,OAAO,WAAW,QAAQ,GAAG,GAAG,KAAA,GAAW,I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ition","RefExpr","AliasAssigner","safeKq","fail","BaseExpr","isExpr","isTable","getTableMgmt","getTableMetadata","JoinTableHandle","collectionJoin","m2mJoinTable","lazyExcludedSelects","kqStar","kq","filterSoftDeletes","getBaseMeta","asNode","resolveDeferredConditions","ConditionBuilder","buildWhereClause","isDeferredAliasCondition","predicateBrand","skipCondition","deferredSym","deepFindConditions"],"sources":["../src/query.ts"],"sourcesContent":["import { AliasAssigner } from \"./AliasAssigner.ts\";\nimport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nimport {\n type ConditionGroup,\n type ConditionInput,\n type SqlCondition,\n type SqlPredicate,\n type UnbrandedPredicate,\n predicateBrand,\n} from \"./conditions.ts\";\nimport { isDeferredAliasCondition } from \"./DeferredAlias.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityMetadata, getBaseMeta } from \"./EntityMetadata.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprBrand,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n RefExpr,\n type SqlFragment,\n TemplateExpr,\n asNode,\n deferredCondition,\n deferredSym,\n exprBrand,\n isExpr,\n resolveDeferredConditions,\n} from \"./Expr.ts\";\nimport { kq, kqStar, safeKq } from \"./keywords.ts\";\nimport { deepFindConditions } from \"./QueryParser.pruning.ts\";\nimport {\n type ColumnCondition,\n type ParsedExpressionFilter,\n filterSoftDeletes,\n lazyExcludedSelects,\n} from \"./QueryParser.ts\";\nimport { skipCondition } from \"./skipCondition.ts\";\nimport {\n JoinTableHandle,\n type M2mJoinTable,\n type Table,\n type TableBrand,\n type TableMgmt,\n collectionJoin,\n getTableMetadata,\n getTableMgmt,\n isTable,\n m2mJoinTable,\n tableMgmt,\n} from \"./Tables.ts\";\nimport { type TypeInfo } from \"./TypeInfo.ts\";\nimport { type TypeMapEntry } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\n/**\n * `em.query`: SQL-shaped queries as plain object literals.\n *\n * A query is data, a `Query<S, J>` POJO, `{ from, join, where, groupBy, having, select, orderBy, ... }`\n * in SQL evaluation order:\n *\n * const [a, b] = tables(Author, Book);\n * const bookStats = query({ from: b, groupBy: [b.author_id], select: { authorId: b.author_id, n: b.id.count() } });\n * const rows = await em.query({\n * from: a,\n * join: [{ left: bookStats, on: bookStats.authorId.eq(a.id) }],\n * select: { name: a.first_name, n: bookStats.n },\n * orderBy: { n: \"DESC\" },\n * });\n * // rows: { name: string; n: number | null }[] (null because of the LEFT join)\n *\n * `em.query(pojo)` runs it. `select` decides the row type: a bare table returns entities, a\n * `{ key: expr }` object returns typed POJOs, a bare subquery returns that subquery's rows.\n *\n * `query(pojo)` turns the *same* POJO into a value: a derived table with typed columns, a scalar\n * expression, or an entity list. It is the one non-POJO step, and the subquery analog of `table(Author)`:\n * to reference a query's columns, the outer query needs *values* for them, and no POJO can manufacture\n * values keyed off its own `select` keys.\n *\n * `table()`/`tables()` and `query()` are the only free functions a query needs, plus the `sql` tagged\n * template as the escape hatch for SQL with no modeled shape. Everything else is in-DSL: join kinds and\n * sort directions are keyword keys (`{ left: b, on }`, `{ desc: x }`), SQL functions are methods on\n * expressions (`b.id.count()`, `b.title.max()`, `x.coalesce(0)`), conditions are methods\n * (`a.age.gte(18)`), and pruning is `undefined`: an `undefined` condition drops out, and a join nothing\n * references anymore drops with it (see \"Pruning\" below).\n *\n * User documentation: `docs/src/content/docs/features/queries-raw.md`.\n */\n\n// =====================================================================================================\n// Sources, joins, clauses\n// =====================================================================================================\n\nexport const subqueryBrand: unique symbol = Symbol(\"joist.subquery\");\nexport const entityQueryBrand: unique symbol = Symbol(\"joist.entityQuery\");\nexport const scalarQueryBrand: unique symbol = Symbol(\"joist.scalarQuery\");\n\n/** A query(...) value with any projection, for EXISTS and NOT EXISTS predicates. */\nexport type ExistsQuery = Subquery<unknown, string> | EntityQuery<Entity> | { readonly [scalarQueryBrand]: true };\n\n/**\n * A condition for a query's where, having, or join on clause. Combine conditions with and/or,\n * or use exists/notExists to check whether a query(...) value returns any rows.\n *\n * I.e. `{ and: [a.age.gte(18), { exists: booksForAuthor }] }` selects adult Authors with Books,\n * where `booksForAuthor` is `query({ from: b, where: b.author_id.eq(a.id), select: b.id })`.\n */\nexport type QueryCondition =\n | SqlPredicate\n | UnbrandedPredicate\n | ((\n | { and: Array<QueryCondition | undefined>; or?: never; exists?: never; notExists?: never }\n | { or: Array<QueryCondition | undefined>; and?: never; exists?: never; notExists?: never }\n ) & { pruneIfUndefined?: \"any\" | \"all\" })\n | { exists: ExistsQuery | undefined; notExists?: never; and?: never; or?: never }\n | { notExists: ExistsQuery | undefined; exists?: never; and?: never; or?: never };\n\n/** Phantom type information carried by a table-shaped subquery. */\nexport interface SubqueryBrand<R, Name extends string> {\n readonly __row: R;\n readonly __name: Name;\n}\n\n/** Anything that can be a source or be joined: an entity table or a table-shaped subquery. */\nexport type QuerySource =\n | { readonly [tableMgmt]: TableBrand<any, string> }\n | { readonly [subqueryBrand]: SubqueryBrand<any, string> };\n\n/**\n * A join entry (see `InnerJoin`/`LeftJoin` in `Expr.ts`): the expanded `{ inner: b, on }` form, or the\n * entry a relation join factory returns (`a.books.as(b)`); joins to a subquery are always the expanded\n * form, since a subquery has no FK metadata.\n */\nexport type QueryJoin = InnerJoin<QuerySource, QueryCondition> | LeftJoin<QuerySource, QueryCondition>;\nexport type QueryJoins = readonly (QueryJoin | undefined)[];\n\n/**\n * An expression order-by entry: the direction is the key and the expression is the value, unlike\n * the keyed form's field name and `\"ASC\" | \"DESC\"` value. `never` on the other key keeps an\n * entry to one direction, the same trick `ConditionGroup` uses for `and`/`or`. `nulls` is\n * `NULLS FIRST/LAST`.\n *\n * When select keys are known, exclude them so a keyed sort cannot be silently ignored inside an\n * expression entry. An untyped `Query` has no known keys to exclude.\n */\nexport type QueryOrderBy<S = never> = (\n | { readonly asc: ExprLike<any>; readonly desc?: never }\n | { readonly desc: ExprLike<any>; readonly asc?: never }\n) & { readonly nulls?: \"first\" | \"last\" } & (string extends OrderByKey<S>\n ? unknown\n : { readonly [K in Exclude<OrderByKey<S>, \"asc\" | \"desc\" | \"nulls\">]?: never });\n\nexport type OrderByDirection =\n | \"ASC\"\n | \"DESC\"\n | \"ASC NULLS FIRST\"\n | \"ASC NULLS LAST\"\n | \"DESC NULLS FIRST\"\n | \"DESC NULLS LAST\";\n\n/**\n * A keyed `orderBy` entry, used alone or in an array, like `em.find`'s `orderBy: [{ firstName: \"ASC\" }]`.\n *\n * The keys are the keys of a POJO/subquery `select` (rendered as SQL output-column names, so ordering\n * by an aggregate does not repeat its expression), or the entity's sortable fields in entity mode.\n * An `undefined` direction prunes the entry, like any other condition. For expressions that are not\n * in `select`, mix in `{ asc: expr }` / `{ desc: expr }` entries in the array form.\n */\nexport type OrderByKeys<S> = S extends { readonly [tableMgmt]: { readonly __entity: infer T } }\n ? T extends Entity\n ? { readonly [K in keyof Table<T> as Table<T>[K] extends ExprLike<any> ? K : never]?: OrderByDirection | undefined }\n : never\n : S extends { readonly [exprBrand]: any }\n ? never\n : { readonly [K in keyof S & string]?: OrderByDirection | undefined };\n\n/** All sortable keys across select variants, not just the keys shared by every variant. */\ntype OrderByKey<S> = S extends unknown ? keyof OrderByKeys<S> : never;\n\n/** The three select shapes: entity mode, single-expression mode (scalar/list subqueries), and POJO mode. */\nexport type QuerySelect = QuerySource | ExprLike<any> | Record<string, ExprLike<any>>;\n\n/**\n * Everything but the source, in SQL evaluation order: FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT,\n * ORDER BY, LIMIT.\n *\n * `S` and `J` are generic so callers keep the literal shape of `select` and `join`; the defaults let\n * a standalone object use `satisfies Query` (or `satisfies Clauses` for a source-less fragment).\n */\nexport interface Clauses<S extends QuerySelect = QuerySelect, J extends QueryJoins = QueryJoins> {\n join?: J;\n /** A boolean group, an exists/notExists query, or a bare condition such as `a.age.gte(18)`. */\n where?: QueryCondition;\n groupBy?: readonly ExprLike<any>[];\n having?: QueryCondition;\n select: S & CheckEntitySelect<S>;\n orderBy?: readonly (QueryOrderBy<S> | OrderByKeys<S> | undefined)[] | OrderByKeys<S>;\n limit?: number;\n offset?: number;\n distinct?: boolean;\n /** Defaults to true. `false` keeps every join, em.find's opt-out. */\n pruneJoins?: boolean;\n /**\n * Defaults to `\"exclude\"`, em.find's rule: a soft-deletable entity in `from` gains a\n * `deleted_at IS NULL` condition in WHERE, and a joined one gains it in its join's ON (so a LEFT\n * join nulls its columns out instead of dropping rows). `\"include\"` turns the injection off for\n * this query; subqueries read their own key.\n */\n softDeletes?: \"include\" | \"exclude\";\n}\n\n/** A whole query: `Clauses` plus its source. `query(q)` turns it into a value; `em.query(q)` runs it. */\nexport interface Query<S extends QuerySelect = QuerySelect, J extends QueryJoins = QueryJoins>\n extends Clauses<S, J>, Partial<Record<SetOperation | MutationKey | \"with\" | \"ctes\", never>> {\n from: QuerySource;\n}\n\n/**\n * The six PostgreSQL set operations. Each compound root has exactly one operation.\n *\n * I.e. `union` removes duplicate projected Author names; `unionAll` keeps every copy.\n */\nexport type SetOperation = \"union\" | \"unionAll\" | \"intersect\" | \"intersectAll\" | \"except\" | \"exceptAll\";\n\n/** Mutation clauses are forbidden even on nonliteral read inputs. */\ntype MutationKey = \"insert\" | \"update\" | \"delete\" | \"values\" | \"set\" | \"returning\" | \"allowAll\";\n\n/**\n * For set operations like UNION, this is one read operand with named POJO columns: an ordinary query,\n * a reusable query value, or another compound.\n * Scalar queries, expressions, and entity hydration are excluded.\n *\n * I.e. `{ from: a, select: { id: a.id } }` and its `query(...)` value can contribute Author IDs to a\n * union. `{ from: a, select: a.id }` cannot: even one-column set operands must give that column a name.\n */\nexport type SetOperand =\n | Query<Record<string, ExprLike<unknown>> | Subquery<unknown, string>>\n | Subquery<unknown, string>\n | SetQuery<readonly SetOperand[]>;\n\n/**\n * SQL-shaped compound input; use `satisfies SetQuery` to retain the operands' literal row types.\n *\n * I.e. for Author alias `a` and Book alias `b`:\n * ```ts\n * const names = {\n * union: [\n * { from: a, select: { name: a.first_name } },\n * { from: b, select: { name: b.title } },\n * ],\n * orderBy: { name: \"ASC\" },\n * } satisfies SetQuery;\n * ```\n *\n * The default operand tuple requires at least two reads. `query` and `em.query` also infer dynamically\n * sized arrays; `CheckSetQuery` validates their row types, and runtime validation checks their length.\n * This input shape checks direction values; `CheckSetQuery` checks the inferred output keys in orderBy.\n */\nexport type SetQuery<Operands extends readonly SetOperand[] = readonly [SetOperand, SetOperand, ...SetOperand[]]> = {\n // Each K creates one alternative, i.e. required `union` with the other five operation keys forbidden.\n [K in SetOperation]: { readonly [P in K]: Operands } & { readonly [P in Exclude<SetOperation, K>]?: never };\n}[SetOperation] & {\n // These clauses belong to the combined rows, not to an implicit first SELECT.\n readonly orderBy?:\n | Readonly<Record<string, OrderByDirection | undefined>>\n | readonly (Readonly<Record<string, OrderByDirection | undefined>> | undefined)[];\n readonly limit?: number;\n readonly offset?: number;\n readonly as?: string;\n} & {\n // SELECT clauses and branch policies must stay inside operands or an ordinary outer query.\n readonly [\n K in\n | \"from\"\n | \"select\"\n | \"join\"\n | \"where\"\n | \"groupBy\"\n | \"having\"\n | \"distinct\"\n | \"softDeletes\"\n | \"pruneJoins\"\n | MutationKey\n | \"with\"\n | \"ctes\"\n ]?: never;\n};\n\n/**\n * Extracts the operand collection from each possible compound root, ignoring pagination and ordering.\n *\n * I.e. for `Q = { union: readonly [typeof authorNames, typeof bookNames]; limit: 10 }`, the result is\n * `readonly [typeof authorNames, typeof bookNames]`. Distributing over Q also handles a runtime choice\n * between different operations; Extract discards optional, unused operation keys whose value is undefined.\n */\ntype OperandsOf<Q> = Q extends unknown ? Extract<Q[keyof Q & SetOperation], readonly SetOperand[]> : never;\n\n/**\n * Gets the left operand, which supplies canonical output keys and the retained row type for EXCEPT/INTERSECT.\n *\n * I.e. `FirstOperand<{ except: readonly [typeof authorNames, typeof bookNames] }>` is `typeof authorNames`.\n * For a dynamic array, the exact first element is unknown, so this is the array's element type instead.\n */\ntype FirstOperand<Q> = OperandsOf<Q>[0];\n\n/**\n * Resolves the named rows of an ordinary or compound read operand, including its LEFT join nullability.\n *\n * I.e. a query from Author `a` with a LEFT-joined Book `b` and `select: { title: b.title }` has row type\n * `{ title: string | null }`, even though Book.title is required. A reusable `query(...)` value already\n * stores that row type in its brand; a nested compound combines its own operands recursively.\n */\nexport type ReadQueryRow<Q> = SetOperand extends Q\n ? // Stop at the general, recursive operand type: its projection is unknown, not an empty POJO.\n unknown\n : // Read the brand before inspecting `select`, which could itself be a named column on a query value.\n Q extends { readonly [subqueryBrand]: { readonly __row: infer R } }\n ? R\n : Q extends { select: infer S }\n ? // A declared Query<S, J> has an optional join property that still carries J's LEFT joins.\n QueryRow<S, \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoins> : []>\n : [OperandsOf<Q>] extends [never]\n ? never\n : SetQueryRow<Q>;\n\n/**\n * UNION combines each column's values; INTERSECT and EXCEPT conservatively retain the left row.\n *\n * I.e. Author first names projected as `{ name: string }` unioned with LEFT-joined Book titles projected\n * as `{ name: string | null }` produce `{ name: string | null }`. EXCEPT with those Author names on the\n * left retains `{ name: string }`; it neither adds the right side's NULL nor promises narrower values.\n *\n * The outer conditional distributes over a TypeScript union of alternative queries. I.e. a runtime\n * choice between an Author-name UNION and a Book-order EXCEPT must retain `{ name: string } | { order: number }`.\n */\nexport type SetQueryRow<Q> = Q extends unknown\n ? {\n // The first operand supplies keys; const/readonly input projections do not make result rows readonly.\n -readonly [K in keyof ReadQueryRow<FirstOperand<Q>>]: ColumnValue<\n // UNION can return values from any operand; EXCEPT/INTERSECT return values from the left.\n Q extends { union: readonly SetOperand[] } | { unionAll: readonly SetOperand[] }\n ? ReadQueryRow<OperandsOf<Q>[number]>\n : ReadQueryRow<FirstOperand<Q>>,\n K\n >;\n }\n : never;\n\n/**\n * Collects column K's value from each row alternative in R, rather than requiring K on every alternative.\n *\n * I.e. `ColumnValue<{ name: string } | { name: string | null }, \"name\">` is `string | null`.\n * An alternative without K contributes never; `CompatibleRow` separately rejects mismatched operand keys.\n */\ntype ColumnValue<R, K extends PropertyKey> = R extends unknown ? (K extends keyof R ? R[K] : never) : never;\n\n/**\n * Checks whether either non-null value type is assignable to the other, without requiring equal nullability.\n *\n * I.e. `CompatibleValue<number, number | null>` is true, while `CompatibleValue<AuthorId, BookId>` is false.\n * This is only a TypeScript check: Author.age and Author.age.sum() both pass as numbers, but runtime\n * output-type checks must still reject their different int4/int8 representations.\n */\ntype CompatibleValue<L, R> = [NonNullable<L>] extends [NonNullable<R>]\n ? true\n : [NonNullable<R>] extends [NonNullable<L>]\n ? true\n : false;\n\n/**\n * Requires exactly the same output keys and compatible TypeScript values for every column.\n *\n * I.e. `L = { name: string; age: number }` and `R = { age: number | null; name: string }` are compatible despite\n * key order and nullability. `{ name: string }` and `{ title: string }` are not. SQL representations and\n * codec domains still need runtime validation; this boolean does not establish decoder compatibility.\n */\ntype CompatibleRow<L, R> = [keyof L] extends [keyof R]\n ? // Checking both directions rejects missing and extra right-side keys, not just a shared subset.\n [keyof R] extends [keyof L]\n ? // Reduce the per-column flags to a union: any false rejects the complete row.\n false extends { [K in keyof L]: CompatibleValue<L[K], ColumnValue<R, K>> }[keyof L]\n ? false\n : true\n : false\n : false;\n\n/**\n * Produces a constraint for Q: unknown leaves a valid operand unchanged, while a message rejects it.\n *\n * I.e. First can select Author.firstName as `name` and Q can select Book.title as `name`. Both pass.\n * Changing Q's key to `title` produces the key/value diagnostic. A nested compound must also pass its own\n * arity and ordering checks, not merely expose a compatible result row.\n */\ntype CheckOperand<First, Q> =\n CompatibleRow<ReadQueryRow<First>, ReadQueryRow<Q>> extends true\n ? // Validate nested roots too, so an otherwise compatible one-operand UNION cannot hide inside Q.\n Q extends SetQuery<readonly SetOperand[]>\n ? CheckSetQuery<Q>\n : CheckReadQuery<Q>\n : \"set operands must have the same keys and compatible column values\";\n\n/**\n * Checks every operand against O[0] while preserving the collection's tuple shape and readonly modifier.\n *\n * I.e. compatible operands `O = readonly [typeof authorNames, typeof bookNames]` produce\n * `readonly [unknown, unknown]` constraints. Mapping O directly preserves length instead of validating\n * array methods and the length property as though they were additional query operands.\n */\ntype CheckOperands<O extends readonly SetOperand[]> = { readonly [I in keyof O]: CheckOperand<O[0], O[I]> };\n\n/**\n * Restricts each ordering hash to Keys, including hashes supplied through variables or readonly arrays.\n *\n * I.e. with `Keys = \"name\"`, `{ name: \"ASC\" }` and `[undefined, { name: \"DESC\" }]` pass, but a `title`\n * key receives a diagnostic. SetQuery already restricts direction values; this check does not replace them.\n */\ntype CheckSetOrder<O, Keys> = O extends readonly unknown[]\n ? // Preserve each array entry so an invalid hash is reported at its own position.\n { readonly [I in keyof O]: CheckSetOrder<O[I], Keys> }\n : { readonly [K in keyof O]: K extends Keys ? unknown : \"orderBy must name a set output column\" };\n\n/**\n * Validate known tuples and output ordering without widening the inferred operand projections.\n * Preserve optional keys when TypeScript infers a runtime choice between different operations.\n *\n * I.e. `{ union: [authorNames] as const }` fails minimum arity; a `typeof authorNames[]` can pass the\n * static checks but still needs a runtime length check. If authorNames and bookNames both expose only\n * `name`, combining them with `orderBy: { title: \"ASC\" }` fails the output-key check.\n *\n * The result is intersected with the inferred input Q. Unknown constraints leave its literal types\n * intact; error messages make the offending operands or ordering keys incompatible with that input.\n */\nexport type CheckSetQuery<Q extends SetQuery<readonly SetOperand[]>> = Q extends unknown\n ? // A widened first operand has lost the output keys and values needed to validate the remaining reads.\n SetOperand extends FirstOperand<Q>\n ? \"set operands were typed too generically; use `satisfies SetQuery` instead\"\n : {\n // Map Q itself so unused optional operation keys stay optional for UNION-or-EXCEPT input types.\n readonly [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly SetOperand[]\n ? // Dynamic arrays retain their row types but defer minimum arity to runtime.\n number extends Q[K][\"length\"]\n ? CheckOperands<Q[K]>\n : // A known tuple must guarantee two operands before any row comparisons can pass.\n Q[K] extends readonly [SetOperand, SetOperand, ...SetOperand[]]\n ? CheckOperands<Q[K]>\n : \"set operations require at least two operands\"\n : never\n : // Non-operation clauses retain their inferred types; SetQuery already constrains their shapes.\n unknown;\n } & CheckReadQuery<Q> & {\n // Only the inferred output keys are legal here; expression ordering needs an outer SELECT.\n readonly orderBy?: CheckSetOrder<Q[\"orderBy\"], keyof ReadQueryRow<FirstOperand<Q>>>;\n }\n : never;\n\n/**\n * Rejects unknown clauses on concrete read inputs, recursively through compound operands.\n * Intersect this with an inferred Q; a widened annotation cannot reveal keys already erased from its type.\n * I.e. an INSERT source with `select: { title: b.title }` and `ctes: [...]` must not silently discard the CTEs.\n */\nexport type CheckReadQuery<Q> = SetOperand extends Q\n ? unknown\n : Q extends readonly unknown[]\n ? { readonly [I in keyof Q]: CheckReadQuery<Q[I]> }\n : Q extends { readonly [subqueryBrand]: SubqueryBrand<infer R, string> }\n ? { readonly [K in keyof Q]: K extends keyof R | typeof subqueryBrand ? unknown : never }\n : Q extends { readonly [entityQueryBrand]: unknown }\n ? { readonly [K in keyof Q]: K extends typeof entityQueryBrand ? unknown : never }\n : Q extends { readonly from: unknown; readonly select: unknown }\n ? { readonly [K in keyof Q]: K extends keyof Clauses | \"from\" | \"as\" ? unknown : never }\n : {\n readonly [K in keyof Q]: K extends SetOperation\n ? Q[K] extends readonly unknown[]\n ? CheckReadQuery<Q[K]>\n : unknown\n : K extends \"orderBy\" | \"limit\" | \"offset\" | \"as\"\n ? unknown\n : never;\n };\n\n// =====================================================================================================\n// Result-row types\n// =====================================================================================================\n\n/** The type-level name of a table or subquery, i.e. `\"Author\"` or `\"book_stats\"`. */\nexport type NameOf<A> = A extends { readonly [tableMgmt]: { readonly __name: infer N } }\n ? N\n : A extends { readonly [subqueryBrand]: { readonly __name: infer N } }\n ? N\n : never;\n\n/** The names of every alias that was LEFT JOINed; `X` is a naked type parameter so this distributes. */\ntype LeftJoined<X> = X extends LeftJoin<infer A> ? NameOf<A> : never;\n\n/**\n * Asks: is this expression's source key among the LEFT-joined sources in this query's join list? If\n * yes, the value can be `null`, so `R` becomes `R | null`; if no, `R` is unchanged.\n *\n * I.e. `MaybeNull<number, \"book_stats\", [LeftJoin<typeof bookStats>]>` is `number | null`,\n * because `book_stats` is in `LeftJoined<J[number]>`; with an inner join it stays `number`.\n *\n * Source-less expressions (`Src` is `never`, i.e. `b.id.count()`) are never nullified. Untracked ones\n * (`Src` is `string`, i.e. a `sql.ref` on an unknown table) might come from any left-joined table,\n * so they are conservatively nullified whenever the query has a left join at all.\n *\n * `string` must never be a *table's* name: `Extract<\"Author\", string>` matches, so one left-joined\n * table named `string` would nullify every column in the query. That is why anonymous subqueries\n * share the literal sentinel `\"?\"` instead.\n */\nexport type MaybeNull<R, Src extends string, J extends QueryJoins> = string extends Src\n ? [LeftJoined<J[number]>] extends [never]\n ? R\n : R | null\n : [Extract<Src, LeftJoined<J[number]>>] extends [never]\n ? R\n : R | null;\n\n/**\n * The result row for a query with select `S` and joins `J`.\n *\n * - entity mode (`select: a`) is the entity\n * - subquery mode (`select: bookStats`) is the subquery's row, i.e. `select *`\n * - single expression (`select: b.id.count()`) is that expression's value, used by scalar subqueries\n * - POJO mode is a mapped type over the select keys, with left-join nullability applied\n */\nexport type QueryRow<S, J extends QueryJoins = []> = S extends { readonly [tableMgmt]: { readonly __entity: infer T } }\n ? T\n : S extends { readonly [subqueryBrand]: { readonly __row: infer R } }\n ? R\n : S extends { readonly [exprBrand]: ExprBrand<infer R, infer Src> }\n ? MaybeNull<R, Src, J>\n : {\n [K in keyof S]: S[K] extends { readonly [exprBrand]: ExprBrand<infer R, infer Src> }\n ? MaybeNull<R, Src, J>\n : never;\n };\n\n// =====================================================================================================\n// `query()`: a query POJO becomes a typed table, scalar, or entity list\n// =====================================================================================================\n\n/**\n * A table-shaped query: one `Expr` per select key, each tagged with the table's name as its `Src`,\n * plus a brand carrying the row type. This is the direct analog of `Table<T>`: `Table<T>` maps physical\n * columns to expressions, `Subquery<Row, Name>` maps the inner query's select keys to expressions.\n */\nexport type Subquery<R, Name extends string> = {\n readonly [subqueryBrand]: SubqueryBrand<R, Name>;\n} & { readonly [K in keyof R]: Expr<R[K], Name> };\n\n/** An entity-mode query (`select: a`): runnable, but it has no columns to reference. */\nexport type EntityQuery<T extends Entity> = { readonly [entityQueryBrand]: { readonly __row: T } } & Partial<\n Record<MutationKey | \"with\" | \"ctes\", never>\n>;\n\n/** A scalar/list query that remains distinguishable from ordinary expressions for EXISTS. */\nexport type ScalarQuery<R> = Expr<R | null, never> & { readonly [scalarQueryBrand]: true };\n\n/** Physical inheritance tables cannot supply complete entities; select their columns instead. */\ntype CheckEntitySelect<S> = [\n Extract<\n TypeMapEntry<S extends { readonly [tableMgmt]: { readonly __entity: infer T } } ? T : never, \"inheritanceType\">,\n \"cti\" | \"sti\"\n >,\n] extends [never]\n ? unknown\n : \"Inherited tables cannot be selected as entities; select their columns individually\";\n\n/**\n * Rejects a `select` that a `: Query` annotation widened to the whole `QuerySelect` union.\n *\n * `satisfies Query` checks the shape but keeps the literal type of `select`, so `S` infers as\n * `{ name: Expr<string, \"Author\"> }`. A `: Query` annotation replaces that type with the annotation, so\n * `S` infers as `QuerySelect` itself, and without this guard `query(q)` returned a useless union with no\n * error at all.\n *\n * A widened `S` is the only kind of `S` the whole `QuerySelect` union is assignable to (a POJO, an\n * `Expr`, or a `Table` never is), so `QuerySelect extends S` detects it, and intersecting the parameter\n * with `{ select: \"<message>\" }` fails the call on `select` with that message, for `query()` and\n * `em.query()` alike:\n *\n * const narrow = { from: a, select: { name: a.first_name } } satisfies Query;\n * query(narrow); // Subquery<{ name: string }, \"?\">\n *\n * const widened: Query = { from: a, select: { name: a.first_name } };\n * query(widened);\n * // error: Type 'QuerySelect' is not assignable to type\n * // '\"select was typed too generically; use `satisfies Query` instead of `: Query`\"'\n *\n * `S` also defaults to `never`, so a *missing* `select` is reported as \"Property 'select' is missing\"\n * against `Query<never, []>` instead of tripping this guard.\n */\nexport type NotWidened<S> = QuerySelect extends S\n ? { select: \"select was typed too generically; use `satisfies Query` instead of `: Query`\" }\n : unknown;\n\n/** What `query()` returns, by select shape: an entity list, a scalar/list subquery, or a derived table. */\nexport type QueryValue<S, J extends QueryJoins, Name extends string> = S extends {\n readonly [tableMgmt]: { readonly __entity: infer T extends Entity };\n}\n ? EntityQuery<T>\n : S extends { readonly [exprBrand]: ExprBrand<unknown, any> }\n ? ScalarQuery<QueryRow<S, J>>\n : Subquery<QueryRow<S, J>, Name>;\n\n/** The names of every alias in scope for a query: the source alias plus every joined alias. */\ntype JoinedName<X> = X extends { readonly inner: infer A }\n ? NameOf<A>\n : X extends { readonly left: infer A }\n ? NameOf<A>\n : never;\ntype InScope<F, J extends QueryJoins> = NameOf<F> | JoinedName<J[number]>;\n\n/**\n * Asks, for every column of a POJO select: is its source key among `from` + `join` at all? If no, the\n * query reads from a table it never joined, and that select key's type becomes an error message.\n *\n * Because `Expr` already carries `Src`, this is nearly free: for each select key, if `Src` is tracked\n * and any of its names is outside `InScope`, intersect that key's type with an error string, so the\n * caller sees `Type 'Expr<number, \"book_stats\">' is not assignable to type '... is not in from/join'`.\n * Untracked (`string`) and source-less (`never`) expressions always pass. Tables with the same\n * type-level name (two bare `table(Author)`, or two anonymous tables) cannot be told apart, so a miss\n * there goes unreported; the check never gives a false positive, only false negatives on collisions.\n *\n * `[S] extends [...]` keeps this non-distributive, and `never` is skipped outright: `query()` defaults\n * `S` to `never` when `select` is missing, and a distributive conditional over `never` would swallow the\n * whole parameter type.\n */\nexport type CheckScope<S, F, J extends QueryJoins> = [S] extends [never]\n ? unknown\n : // A source-shaped select (`select: a`, `select: bookStats`) must be the `from`: a joined source's\n // rows would need left-join nullability (and entity hydration) that source-shaped selects don't\n // model. Two same-named sources (unnamed aliases of one entity, anonymous subqueries) pass this\n // check and are caught at runtime instead.\n [S] extends [QuerySource]\n ? NameOf<S> extends NameOf<F>\n ? unknown\n : { select: `'${NameOf<S> & string}' is a joined source, not the from; select its columns individually` }\n : [S] extends [Record<string, ExprLike<any>>]\n ? {\n select: {\n [K in keyof S]: S[K] extends { readonly [exprBrand]: ExprBrand<any, infer Src> }\n ? string extends Src\n ? unknown\n : [Exclude<Src, InScope<F, J>>] extends [never]\n ? unknown\n : `table '${Exclude<Src, InScope<F, J>> & string}' is not in from/join`\n : unknown;\n };\n }\n : unknown;\n\n/** The one argument type `query()` and `em.query()` share: a `Query` POJO plus its source, name, and checks. */\nexport type QueryArg<F extends QuerySource, S extends QuerySelect, J extends QueryJoins, Name extends string> = Query<\n S,\n J\n> & {\n from: F;\n as?: Name;\n} & CheckScope<S, F, J> &\n NotWidened<S>;\n\n/**\n * Turns a `Query` POJO into a value. The select shape decides which (`QueryValue`):\n *\n * - a single expression is a scalar subquery or an IN list (`Expr<R | null>`; a scalar subquery can\n * return no row, so use `.coalesce(0)` when the SQL guarantees a value, i.e. an ungrouped `count`)\n * - an entity table is an entity list, runnable via `em.query`\n * - a POJO is a derived table whose columns are `Expr`s; it can be a source, be joined, or be run\n *\n * `as` is the SQL alias and the type-level identity, the same role the second argument of\n * `table(Author, \"m\")` plays. Without it the SQL alias is generated, like `table(Author)`, and all\n * anonymous tables share the type-level identity `\"?\"`: precise against every named alias, and\n * conservative (a left-joined anonymous table nullifies every anonymous table's columns) only among\n * themselves. This is the same collision two bare `table(Author)` have.\n *\n * Ordinary SELECT shapes share one signature: separate scalar/entity/POJO overloads hid `as` from\n * completions and cost 15-28% check time. The separate compound root has one additional signature;\n * `NotWidened` still rejects a SELECT widened by a `: Query` annotation.\n */\nexport function query<const Q extends SetQuery<readonly SetOperand[]>, Name extends string = \"?\">(\n q: Q & CheckSetQuery<Q> & { as?: Name },\n): Subquery<SetQueryRow<Q>, Name>;\nexport function query<\n F extends QuerySource,\n S extends QuerySelect = never,\n J extends QueryJoins = [],\n Name extends string = \"?\",\n>(q: QueryArg<F, S, J, Name>): QueryValue<S, J, Name>;\nexport function query(q: AnyReadQuery): unknown {\n const handle = new SubqueryHandle(toQuery(q));\n const output = handle.output();\n if (output.kind === \"entity\") {\n return { [entityQueryBrand]: handle } as any;\n } else if (output.kind === \"scalar\") {\n return new SubqueryExpr(handle) as any;\n } else {\n return newSubqueryProxy(handle) as any;\n }\n}\n\n/**\n * Builds a SQL expression from a tagged template.\n *\n * For an Author alias `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 * // Selecting this expression keeps the join to Book b.\n * sql.number`${b.order} * ${2}`\n *\n * // Reference an unmodeled column; it is untracked at the type level.\n * sql.ref<string>(a, \"ts_search\")\n * sql.condition`${sql.ref(a, \"ts_search\")} @@ plainto_tsquery(${term})`\n * ```\n */\nexport function sql<R = unknown>(strings: TemplateStringsArray, ...values: unknown[]): Expr<R, never> {\n return new TemplateExpr(strings, values) as any;\n}\n\n/** Shorthand for `sql<number>`; does not cast or convert the SQL result. */\nsql.number = sql<number>;\n\n/** Shorthand for `sql<number | null>`; does not cast or convert the SQL result. */\nsql.numberOrNull = sql<number | null>;\n\n/** Shorthand for `sql<string>`; does not cast or convert the SQL result. */\nsql.string = sql<string>;\n\n/** Shorthand for `sql<string | null>`; does not cast or convert the SQL result. */\nsql.stringOrNull = sql<string | null>;\n\n/** Shorthand for `sql<boolean>`; does not cast or convert the SQL result. */\nsql.boolean = sql<boolean>;\n\n/** Shorthand for `sql<boolean | null>`; does not cast or convert the SQL result. */\nsql.booleanOrNull = sql<boolean | null>;\n\n/** A raw condition for `where`, `having`, or `on`. */\nsql.condition = function condition(strings: TemplateStringsArray, ...values: unknown[]): SqlCondition {\n return deferredCondition((ctx) => new TemplateExpr(strings, values).toSql(ctx));\n};\n\n/** A column Joist does not model, on a source that is in the query. */\nsql.ref = function ref<R = unknown>(source: QuerySource, column: string): Expr<R, string> {\n return new RefExpr(handleOf(source), column) as any;\n};\n\n/**\n * Parses `arg` (a `Query` POJO or `query(...)` value) into a runnable `Plan`.\n *\n * `EntityManager.query` runs the plan; this module deliberately does not import `EntityManager` (see\n * `EntityHydrator`), so it parses and hands back `{ sql, bindings, decodeRows }` instead of executing.\n */\nexport function parseUserQuery(arg: unknown): Plan {\n if (arg instanceof SubqueryExpr) fail(\"Scalar query values are expressions, not executable read inputs\");\n return parseQuery(toQuery(arg), undefined, new AliasAssigner());\n}\n\n/** Recognizes read brands, including malformed hybrids that must reach read validation rather than mutation execution. */\nexport function isReadQueryValue(arg: unknown): boolean {\n return isSubqueryValue(arg) || isEntityQueryValue(arg);\n}\n\n/**\n * Compiles scalar or nonempty named expression projections, shared by SELECT and mutation RETURNING.\n * Source-shaped values need read hydration/source rules and are deliberately excluded here.\n */\nexport function projectionToSql(\n select: unknown,\n ctx: Ctx,\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const output = projectionOutput(select);\n if (output.kind === \"scalar\") {\n // Scalar mode: one value per row, used by scalar/IN-list subqueries\n const expr = output.columns[0][1];\n const fragment = expr.toSql(ctx);\n const selects = [{ ...fragment, sql: `${fragment.sql} AS value` }];\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => expr.decode(row.value)),\n output,\n };\n }\n // POJO mode\n const entries = output.columns;\n const selects = entries.map((entry) => {\n const [key, expr] = entry;\n const fragment = expr.toSql(ctx);\n return { ...fragment, sql: `${fragment.sql} AS ${safeKq(key)}` };\n });\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => decodeRow(row, entries)),\n output,\n };\n}\n\n/**\n * The one `EntityManager` capability that row decoding needs, typed structurally.\n *\n * Importing `EntityManager.ts` here would complete an `EntityManager.ts` <-> `query.ts` declaration\n * cycle (`EntityManager.query` imports this module's types), which correlated with a tsc 7.0.2\n * incremental-build bug: after tsdown rewrites `build/`, `tsc --build` sporadically reports thousands\n * of phantom \"Module 'joist-orm' has no exported member ...\" errors and caches them in `.tsbuildinfo`.\n */\nexport interface EntityHydrator {\n hydrate(cstr: any, rows: readonly any[]): any[];\n}\n\nexport interface Plan {\n sql: string;\n bindings: any[];\n /** Aliases of enclosing queries this (sub)query referenced. */\n outerRefs: string[];\n /** Ordered SQL output columns and their existing expression codecs, before JS row decoding. */\n output: QueryOutput;\n decodeRows(em: EntityHydrator, rows: any[]): any[];\n}\n\n// =====================================================================================================\n// Runtime: handles, subquery expressions, the proxy\n// =====================================================================================================\n\ntype AnyQuery = Query<any, any> & { as?: string };\ntype AnyReadQuery = AnyQuery | SetQuery<readonly SetOperand[]>;\n\n/** Only POJO outputs can be set operands; ordinary scalar reads also expose an ordered output column. */\nexport interface QueryOutput {\n kind: \"entity\" | \"scalar\" | \"pojo\";\n /** Expressions retain codecs and physical nullability after LEFT joins and set operations. */\n columns: readonly (readonly [string, BaseExpr])[];\n}\n\n/** The runtime identity of a `query(...)` value; `Ctx.aliasFor` keys on it, like a table's `TableMgmt`. */\nexport class SubqueryHandle {\n constructor(readonly q: AnyReadQuery) {}\n\n get name(): string | undefined {\n return this.q.as;\n }\n\n /** The select keys, for `select: <subquery>` and for reporting unknown columns. */\n columnKeys(): string[] {\n const output = this.output();\n if (output.kind === \"pojo\") return output.columns.map(([key]) => key);\n return fail(`A subquery with an entity or scalar select has no columns`);\n }\n\n /** The inner expression behind `key`, for its decoder/encoder. */\n columnExpr(key: string): BaseExpr {\n return (\n this.output().columns.find(([name]) => name === key)?.[1] ??\n fail(`Subquery ${this.describe()} has no column ${key}`)\n );\n }\n\n /** Resolve output metadata without parsing SQL or caching aliases from an enclosing query. */\n output(): QueryOutput {\n return queryOutput(this.q);\n }\n\n column(key: string): SubqueryColumnExpr {\n return new SubqueryColumnExpr(this, key, this.columnExpr(key));\n }\n\n describe(): string {\n return this.q.as ? `'${this.q.as}'` : \"(anonymous)\";\n }\n}\n\n/** A column of a joined/from'd subquery, i.e. `bookStats.bookCount`, which becomes `book_stats.\"bookCount\"`. */\nclass SubqueryColumnExpr extends BaseExpr {\n constructor(\n private handle: SubqueryHandle,\n private key: string,\n private inner: BaseExpr,\n ) {\n super();\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const alias = ctx.aliasFor(this.handle);\n // safeKq for the alias too: a subquery's canonical alias is its user-provided `as` name\n return { sql: `${safeKq(alias)}.${safeKq(this.key)}`, bindings: [], refs: [alias] };\n }\n\n decode(value: unknown): unknown {\n return this.inner.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.inner.encode(value);\n }\n\n get outputType(): TypeInfo | undefined {\n return this.inner.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.inner.sqlNullable;\n }\n\n get sqlSource(): object {\n return this.handle;\n }\n}\n\n/**\n * A scalar (or IN-list) subquery, i.e. `query({ from: b, where: [...], select: b.id.count() })`.\n *\n * It closes over the outer aliases it references, so correlation is free; those references are the\n * subquery's \"free\" aliases and count toward the outer query's join pruning.\n */\nclass SubqueryExpr extends BaseExpr {\n readonly [scalarQueryBrand] = true;\n\n constructor(readonly handle: SubqueryHandle) {\n super();\n }\n\n get subquerySelect(): BaseExpr {\n const expr = this.handle.output().columns[0][1];\n // Polymorphic IN uses the original alias's ID metadata when its key codec is unknown.\n return expr instanceof OutputExpr ? expr.inner : expr;\n }\n\n get outputType(): TypeInfo | undefined {\n return this.subquerySelect.outputType;\n }\n\n get sqlNullable(): boolean {\n // Even a NOT NULL projection becomes NULL when a scalar subquery returns no rows.\n return true;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n const bare = this.toSqlBare(ctx);\n return { ...bare, sql: `(${bare.sql})` };\n }\n\n toSqlBare(ctx: ExprContext): SqlFragment {\n const parent = ctx instanceof Ctx ? ctx : fail(\"Subqueries need the query parser's context\");\n const plan = parseQuery(this.handle.q, parent, parent.assigner);\n return { sql: plan.sql, bindings: plan.bindings, refs: plan.outerRefs };\n }\n\n decode(value: unknown): unknown {\n return this.subquerySelect.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.subquerySelect.encode(value);\n }\n}\n\nfunction newSubqueryProxy(handle: SubqueryHandle): object {\n return new Proxy(\n {},\n {\n get(_, key) {\n if (key === subqueryBrand) return handle;\n if (typeof key === \"string\") return handle.column(key);\n return undefined;\n },\n has(_, key) {\n return key === subqueryBrand || (typeof key === \"string\" && handle.columnKeys().includes(key));\n },\n },\n );\n}\n\nfunction isSubqueryValue(value: unknown): value is { [subqueryBrand]: SubqueryHandle } {\n return typeof value === \"object\" && value !== null && subqueryBrand in value;\n}\n\nfunction isEntityQueryValue(value: unknown): value is { [entityQueryBrand]: SubqueryHandle } {\n return typeof value === \"object\" && value !== null && entityQueryBrand in value;\n}\n\nfunction isPlainSelect(select: unknown): select is Record<string, ExprLike<any>> {\n return (\n typeof select === \"object\" &&\n select !== null &&\n !isExpr(select) &&\n !isSubqueryValue(select) &&\n !isEntityQueryValue(select) &&\n (Object.getPrototypeOf(select) === Object.prototype || Object.getPrototypeOf(select) === null)\n );\n}\n\n/** Returns the runtime identity of a source: a table's `TableMgmt` or a subquery's handle. */\nfunction handleOf(source: unknown): TableMgmt | SubqueryHandle {\n if (isTable(source)) return getTableMgmt(source);\n if (isSubqueryValue(source)) return readValueHandle(source);\n return fail(`Expected a table or a query(...) value, got ${source}`);\n}\n\n// =====================================================================================================\n// Runtime: parse -> prune -> SQL -> decode\n// =====================================================================================================\n\nfunction toQuery(arg: unknown): AnyReadQuery {\n if (isReadQueryValue(arg)) return toQuery(readValueHandle(arg).q);\n if (arg instanceof SubqueryExpr) return toQuery(arg.handle.q);\n validateReadQuery(arg);\n return arg;\n}\n\n/** Virtual subquery columns are not own clauses; attached properties on the value are always rejected. */\nfunction readValueHandle(arg: unknown): SubqueryHandle {\n if (!isSubqueryValue(arg) && !isEntityQueryValue(arg)) return fail(\"Expected a branded read query value\");\n const brand = isSubqueryValue(arg) ? subqueryBrand : entityQueryBrand;\n validateQueryKeys(arg, [brand], \"Read query values\");\n const handle = isSubqueryValue(arg) ? arg[subqueryBrand] : arg[entityQueryBrand];\n return handle instanceof SubqueryHandle ? handle : fail(\"Invalid read query value handle\");\n}\n\nconst SET_OPERATIONS: Record<SetOperation, string> = {\n union: \"UNION\",\n unionAll: \"UNION ALL\",\n intersect: \"INTERSECT\",\n intersectAll: \"INTERSECT ALL\",\n except: \"EXCEPT\",\n exceptAll: \"EXCEPT ALL\",\n};\n\nconst MUTATION_KEYS: readonly MutationKey[] = [\"insert\", \"update\", \"delete\", \"values\", \"set\", \"returning\", \"allowAll\"];\n\nconst READ_KEYS: readonly (keyof Clauses | \"from\" | \"as\")[] = [\n \"from\",\n \"join\",\n \"where\",\n \"groupBy\",\n \"having\",\n \"select\",\n \"orderBy\",\n \"limit\",\n \"offset\",\n \"distinct\",\n \"pruneJoins\",\n \"softDeletes\",\n \"as\",\n];\n\n/**\n * Checks every ordinary or compound root before exposing output metadata or compiling SQL.\n * Validate options before applying defaults so wrong-type values, including null, cannot disappear.\n */\nfunction validateReadQuery(arg: unknown): asserts arg is AnyReadQuery {\n if (typeof arg !== \"object\" || arg === null || Array.isArray(arg)) {\n fail(\"em.query expects a { from, select, ... } object or a query(...) value\");\n }\n if (isSetQuery(arg)) {\n setOperands(arg);\n } else {\n validateQueryKeys(arg, READ_KEYS, \"Read queries\");\n if (!(\"from\" in arg && \"select\" in arg))\n fail(\"em.query expects a { from, select, ... } object or a query(...) value\");\n if (isTable(arg.select)) {\n const meta = getTableMetadata(arg.select);\n if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) {\n fail(`Inherited table ${meta.type} cannot be selected as entities; select its columns individually`);\n }\n }\n }\n const options = arg as Record<string, unknown>;\n for (const key of [\"limit\", \"offset\"]) {\n const value = options[key];\n if (value !== undefined && (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)) {\n fail(`Read query ${key} must be a nonnegative finite integer`);\n }\n }\n if (options.softDeletes !== undefined && options.softDeletes !== \"include\" && options.softDeletes !== \"exclude\") {\n fail(\"Read query softDeletes must be 'include' or 'exclude'\");\n }\n for (const key of [\"distinct\", \"pruneJoins\"]) {\n if (options[key] !== undefined && typeof options[key] !== \"boolean\") fail(`Read query ${key} must be a boolean`);\n }\n if (options.as !== undefined && typeof options.as !== \"string\") fail(\"Read query as must be a string\");\n}\n\n/** Includes undefined, symbol, non-enumerable, and inherited clauses rather than silently ignoring them. */\nfunction validateQueryKeys(arg: object, allowed: readonly PropertyKey[], description: string): void {\n for (let object: object | null = arg; object && object !== Object.prototype; object = Object.getPrototypeOf(object)) {\n for (const key of Reflect.ownKeys(object)) {\n if (allowed.includes(key)) continue;\n if (MUTATION_KEYS.includes(key as MutationKey)) {\n fail(`Read queries do not support mutation clause '${String(key)}'; use em.execute`);\n }\n fail(`${description} do not support clause '${String(key)}'`);\n }\n }\n}\n\n/** Detect operation keys even when their values are invalid, so mixed roots cannot fall through to SELECT. */\nfunction isSetQuery(value: unknown): value is SetQuery<readonly SetOperand[]> {\n return typeof value === \"object\" && value !== null && Object.keys(SET_OPERATIONS).some((key) => key in value);\n}\n\n/** Validate each root independently; no operand, including the left side of EXCEPT, can be pruned. */\nfunction setOperands(q: SetQuery<readonly SetOperand[]>): [SetOperation, readonly SetOperand[]] {\n const keys = (Object.keys(SET_OPERATIONS) as SetOperation[]).filter((key) => key in q);\n if (keys.length !== 1) fail(\"A set query requires exactly one operation key\");\n validateQueryKeys(q, [keys[0], \"orderBy\", \"limit\", \"offset\", \"as\"], \"Set queries\");\n const operands = q[keys[0]];\n if (!Array.isArray(operands) || operands.length < 2) fail(\"Set operations require at least two operands\");\n return [keys[0], operands];\n}\n\n/**\n * Resolve ordered output columns without rendering SQL. Set compatibility is deliberately conservative:\n * every column needs the same known SQL representation, logical domain, and precise ID target.\n *\n * I.e. Author.id and Book.author share the Author key codec, but Book.id must never decode as Author.id.\n * The first branch supplies names and conversions only after every branch passes these checks.\n * UNION admits NULL from any branch; EXCEPT/INTERSECT retain the left branch's nullable facts.\n * Unknown nullability stays unknown unless another UNION branch is known nullable.\n */\nfunction queryOutput(q: AnyReadQuery): QueryOutput {\n validateReadQuery(q);\n if (isSetQuery(q)) {\n const [operation, operands] = setOperands(q);\n const first = queryOutput(toQuery(operands[0]));\n const columns = [...first.columns];\n for (const operand of operands) {\n const output = operand === operands[0] ? first : queryOutput(toQuery(operand));\n if (output.kind !== \"pojo\") {\n fail(\n output.kind === \"entity\"\n ? \"Set operations do not support entity-mode operands\"\n : \"Set operations require POJO operands; wrap scalar expressions in a named select projection\",\n );\n }\n if (output.columns.length !== first.columns.length) fail(\"Set operands must have the same POJO keys\");\n for (let i = 0; i < columns.length; i++) {\n const [key, expr] = columns[i];\n const other = output.columns.find(([name]) => name === key)?.[1];\n if (!other) fail(`Set operands must have the same POJO keys; missing '${key}'`);\n const left = expr.outputType;\n const right = other.outputType;\n if (!left || !right)\n fail(\n `Set column '${key}' has an unknown or unsupported output codec; sql<R> does not declare a SQL type or codec`,\n );\n if (left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) {\n fail(\n `Set column '${key}' has incompatible output codecs (${left.dbType} and ${right.dbType}); use matching SQL representations and logical domains`,\n );\n }\n if (operation === \"union\" || operation === \"unionAll\") {\n const nullable =\n expr.sqlNullable === true || other.sqlNullable === true\n ? true\n : expr.sqlNullable === undefined || other.sqlNullable === undefined\n ? undefined\n : false;\n if (nullable !== expr.sqlNullable) columns[i] = [key, new OutputExpr(expr, nullable)];\n }\n }\n }\n setOrderBys(q, first);\n return { kind: first.kind, columns };\n }\n const { select } = q;\n if (isTable(select)) return { kind: \"entity\", columns: [] };\n if (isSubqueryValue(select)) return readValueHandle(select).output();\n return joinedOutput(projectionOutput(select), q.join);\n}\n\n/** Validates the projection before compiling SQL or exposing reusable query columns. */\nfunction projectionOutput(select: unknown): QueryOutput {\n if (isExpr(select)) return { kind: \"scalar\", columns: [[\"value\", asExpr(select, \"select\")]] };\n if (isPlainSelect(select)) {\n const columns: [string, BaseExpr][] = [];\n // Enumerate once: a projection proxy must not be revisited just to check for symbol keys.\n for (const key of Reflect.ownKeys(select)) {\n if (typeof key !== \"string\") fail(\"Projection keys must be strings\");\n if (Object.prototype.propertyIsEnumerable.call(select, key))\n columns.push([key, asExpr(select[key], `select.${key}`)]);\n }\n if (columns.length === 0) fail(\"A named expression projection must not be empty\");\n return { kind: \"pojo\", columns };\n }\n return fail(\"Expected a scalar expression or a nonempty named expression projection\");\n}\n\n/**\n * Adds physical NULL from unmatched LEFT joins without mutating shared expressions or their codecs.\n * Only direct columns carry sqlSource; COUNT and COALESCE retain their own SQL nullability.\n * I.e. selecting Book.title from a LEFT-joined Book makes its output nullable, but COUNT(Book.id) stays NOT NULL.\n */\nfunction joinedOutput(output: QueryOutput, joins: QueryJoins | undefined): QueryOutput {\n if (!joins?.some((join) => join?.left)) return output;\n const left = new Set<object>();\n for (const join of joins) if (join?.left) left.add(handleOf(join.left));\n return {\n kind: output.kind,\n columns: output.columns.map((column) => {\n const [key, expr] = column;\n return expr.sqlSource && left.has(expr.sqlSource) && expr.sqlNullable !== true\n ? [key, new OutputExpr(expr, true)]\n : column;\n }),\n };\n}\n\n/** An output-only nullability adjustment that preserves the selected expression's SQL and conversions. */\nclass OutputExpr extends BaseExpr {\n constructor(\n readonly inner: BaseExpr,\n private nullable: boolean | undefined,\n ) {\n super();\n }\n\n get outputType(): TypeInfo | undefined {\n return this.inner.outputType;\n }\n\n get sqlNullable(): boolean | undefined {\n return this.nullable;\n }\n\n toSql(ctx: ExprContext): SqlFragment {\n return this.inner.toSql(ctx);\n }\n\n decode(value: unknown): unknown {\n return this.inner.decode(value);\n }\n\n encode(value: unknown): unknown {\n return this.inner.encode(value);\n }\n}\n\n/**\n * Compile siblings in separate local scopes with the same enclosing context. Projection wrappers align\n * output positions without moving DISTINCT/order/pagination or repeating volatile selected expressions.\n * Parenthesizing each accumulated left side preserves array association and explicit nested grouping.\n */\nfunction parseSetQuery(q: SetQuery<readonly SetOperand[]>, parent: Ctx | undefined, assigner: AliasAssigner): Plan {\n const [operation, operands] = setOperands(q);\n const output = queryOutput(q);\n const plans = operands.map((operand) => parseQuery(toQuery(operand), parent, assigner));\n let sql = \"\";\n for (const plan of plans) {\n let branch = plan.sql;\n if (output.columns.some(([key], i) => plan.output.columns[i][0] !== key)) {\n const alias = safeKq(assigner.getLiteralAlias(\"sq\"));\n branch = `SELECT ${output.columns.map(([key]) => `${alias}.${safeKq(key)} AS ${safeKq(key)}`).join(\", \")} FROM (${branch}) AS ${alias}`;\n }\n sql = sql ? `(${sql}) ${SET_OPERATIONS[operation]} (${branch})` : branch;\n }\n const orderBys = setOrderBys(q, output);\n if (orderBys.length > 0) sql += ` ORDER BY ${orderBys.join(\", \")}`;\n const bindings = plans.flatMap((plan) => plan.bindings);\n if (q.limit !== undefined) {\n sql += \" LIMIT ?\";\n bindings.push(q.limit);\n }\n if (q.offset !== undefined) {\n sql += \" OFFSET ?\";\n bindings.push(q.offset);\n }\n return {\n sql,\n bindings,\n outerRefs: [...new Set(plans.flatMap((plan) => plan.outerRefs))],\n output,\n decodeRows: plans[0].decodeRows,\n };\n}\n\n/** Validate and quote only named set output sorts, including before a reusable value is parsed. */\nfunction setOrderBys(q: SetQuery<readonly SetOperand[]>, output: QueryOutput): string[] {\n const orderBys: string[] = [];\n for (const entry of Array.isArray(q.orderBy) ? q.orderBy : q.orderBy ? [q.orderBy] : []) {\n if (entry === undefined) continue;\n if (!entry || typeof entry !== \"object\" || isExpr(entry))\n fail(\"Set orderBy requires output-key hashes; use an outer query for expressions\");\n for (const [key, direction] of Object.entries(entry)) {\n if (direction === undefined) continue;\n if (!output.columns.some(([name]) => name === key)) fail(`Set orderBy key '${key}' is not a named output column`);\n if (!ORDER_BY_DIRECTIONS.includes(direction as string))\n fail(\"Set orderBy requires output-key directions; use an outer query for expressions\");\n orderBys.push(`${safeKq(key)} ${direction}`);\n }\n }\n return orderBys;\n}\n\n/**\n * What an expression needs from the query it is generating SQL for.\n *\n * Each (sub)query gets its own `Ctx`; a lookup that misses locally walks up to the enclosing query and\n * records the hit in `outerRefs`, which is how a correlated subquery reports the outer aliases it\n * depends on (the way `ExistsCondition.outerAliases` does), so join pruning keeps them.\n */\nexport class Ctx implements ExprContext {\n private aliases = new Map<object, string>();\n readonly outerRefs = new Set<string>();\n\n constructor(\n readonly assigner: AliasAssigner,\n private parent: Ctx | undefined,\n ) {}\n\n register(handle: object, alias: string): void {\n this.aliases.set(handle, alias);\n }\n\n aliasFor(handle: object): string {\n const local = this.aliases.get(handle);\n if (local) return local;\n if (this.parent) {\n const outer = this.parent.aliasFor(handle);\n this.outerRefs.add(outer);\n return outer;\n }\n return fail(`${describeHandle(handle)} is not in this query's from/join`);\n }\n\n conditionToSql(cond: SqlCondition): SqlFragment | undefined {\n // Inside another expression (i.e. a `sql` template), keep `a OR b` grouped\n return conditionToSql(cond, this, false);\n }\n}\n\nfunction describeHandle(handle: object): string {\n if (handle instanceof SubqueryHandle) return `Subquery ${handle.describe()}`;\n if (handle instanceof JoinTableHandle) return `Join table ${handle.joinTableName}`;\n if (\"tableName\" in handle) return `Table for ${(handle as TableMgmt).tableName}`;\n return \"Table\";\n}\n\ninterface ParsedSource {\n handle: TableMgmt | SubqueryHandle | JoinTableHandle;\n alias: string;\n /** `table AS alias` or `(SELECT ...) AS alias`. */\n sql: string;\n bindings: any[];\n /** Outer aliases a derived table references; PG rejects those without LATERAL, but pruning should still see them. */\n refs: string[];\n /** Entity-mode selects, i.e. `a.*` excluding lazy columns. */\n entitySelects: string[];\n meta: EntityMetadata | undefined;\n}\n\ninterface ParsedJoin {\n kind: \"inner\" | \"left\";\n source: ParsedSource;\n /** The user's ON alone; `undefined` means it pruned away entirely, an error if the join is kept. */\n userOn: SqlFragment | undefined;\n /** The ON to emit: the user's ON plus any injected soft-delete conditions. */\n fullOn: SqlFragment | undefined;\n keep: boolean;\n}\n\n/**\n * Parses one `Query` POJO into SQL, recursively for subqueries.\n *\n * 1. Register every source's runtime identity with its SQL alias in this parse's context.\n * 2. Generate SQL for sources, selects, conditions, group-bys, and order-bys against the context; every fragment\n * reports the aliases it references.\n * 3. Prune: drop joins nothing references (see below), then reject a kept join whose ON collapsed.\n * 4. Assemble the SQL from the kept fragments, so pruned bindings disappear with their SQL.\n */\nfunction parseQuery(q: AnyReadQuery, parent: Ctx | undefined, assigner: AliasAssigner): Plan {\n validateReadQuery(q);\n if (isSetQuery(q)) return parseSetQuery(q, parent, assigner);\n const ctx = new Ctx(assigner, parent);\n const joinEntries = [...(q.join ?? [])].filter(isDefined);\n\n // 1. Register every source before generating SQL, so conditions can resolve their aliases.\n const parseFrom = registerSource(q.from, ctx, assigner);\n const pendingJoins = joinEntries.flatMap((j) => {\n const kind = \"inner\" in j && j.inner ? (\"inner\" as const) : (\"left\" as const);\n const alias = kind === \"inner\" ? j.inner : j.left;\n const keep = j.keep ?? false;\n // Only collection sugar joins (o2m/m2m) filter soft-deletes, em.find's relation semantics:\n // references (m2o/o2o/poly) resolve soft-deleted entities, and explicit joins are the user's own\n const softDeletes = (j as any)[collectionJoin] === true;\n const target = { kind, keep, on: j.on, softDeletes, parseSource: registerSource(alias, ctx, assigner) };\n // A sugar m2m join (`a.tags.as(t)`) carries a hidden join-table join; emit it first, with the same kind\n const m2m: M2mJoinTable | undefined = (j as any)[m2mJoinTable];\n if (!m2m) return [target];\n return [\n { kind, keep, on: m2m.on, softDeletes: false, parseSource: registerJoinTable(m2m.handle, ctx, assigner) },\n target,\n ];\n });\n\n // 2. Generate SQL.\n const softDeletes = q.softDeletes ?? \"exclude\";\n const from = parseFrom();\n const joins: ParsedJoin[] = pendingJoins.map((j) => {\n const source = j.parseSource();\n // `userOn` is the user's ON alone, so the collapsed-ON check below is not fooled by injections\n const userOn = conditionToSql(j.on, ctx, true);\n const injected = injectedConditions(source, j.softDeletes ? softDeletes : \"include\");\n const fullOn = userOn && injected.length > 0 ? conditionToSql({ and: [j.on, ...injected] }, ctx, true) : userOn;\n return { kind: j.kind, keep: j.keep, source, userOn, fullOn };\n });\n const { selects, decodeRows, output } = selectsToSql(q, ctx, from);\n const fromInjected = injectedConditions(from, softDeletes);\n const where = conditionToSql(fromInjected.length > 0 ? { and: [q.where, ...fromInjected] } : q.where, ctx, true);\n const having = conditionToSql(q.having, ctx, true);\n const groupBys = (q.groupBy ?? []).map((g) => asExpr(g, \"groupBy\").toSql(ctx));\n const orderBys = orderBysToSql(q, ctx);\n\n // 3. Prune.\n const kept = pruneJoins(q, from, joins, [...selects, ...groupBys, ...orderBys, where, having].filter(isDefined));\n // Joins emit in declaration order, so an ON may only reference sources declared before it; a forward\n // reference would reach PG as invalid SQL (\"missing FROM-clause entry\"). Reordering is not offered:\n // it is not semantics-preserving once INNER and LEFT joins mix, and the caller's fix is trivial.\n const laterAliases = new Set(kept.map((j) => j.source.alias));\n for (const j of kept) {\n if (!j.userOn) {\n fail(\n `Join ${describeHandle(j.source.handle)} has no ON condition left (they all pruned), but the query still references it`,\n );\n }\n laterAliases.delete(j.source.alias);\n const forward = j.fullOn!.refs.find((r) => laterAliases.has(r));\n if (forward) {\n fail(\n `Join ${describeHandle(j.source.handle)} references '${forward}', which is joined later; move that join earlier in the join array`,\n );\n }\n }\n\n // 4. Assemble.\n const out: SqlFragment[] = [];\n out.push({ sql: `SELECT ${q.distinct ? \"DISTINCT \" : \"\"}`, bindings: [], refs: [] });\n out.push(joinFragmentParts(selects, \", \"));\n out.push({ sql: ` FROM ${from.sql}`, bindings: from.bindings, refs: [] });\n for (const j of kept) {\n const keyword = j.kind === \"inner\" ? \"JOIN\" : \"LEFT OUTER JOIN\";\n out.push({\n sql: ` ${keyword} ${j.source.sql} ON ${j.fullOn!.sql}`,\n bindings: [...j.source.bindings, ...j.fullOn!.bindings],\n refs: [],\n });\n }\n if (where) out.push({ sql: ` WHERE ${where.sql}`, bindings: where.bindings, refs: [] });\n if (groupBys.length > 0)\n out.push({ ...joinFragmentParts(groupBys, \", \"), sql: ` GROUP BY ${groupBys.map((g) => g.sql).join(\", \")}` });\n if (having) out.push({ sql: ` HAVING ${having.sql}`, bindings: having.bindings, refs: [] });\n if (orderBys.length > 0)\n out.push({ ...joinFragmentParts(orderBys, \", \"), sql: ` ORDER BY ${orderBys.map((o) => o.sql).join(\", \")}` });\n if (q.limit !== undefined) out.push({ sql: ` LIMIT ?`, bindings: [q.limit], refs: [] });\n if (q.offset !== undefined) out.push({ sql: ` OFFSET ?`, bindings: [q.offset], refs: [] });\n\n return {\n sql: out.map((o) => o.sql).join(\"\"),\n bindings: out.flatMap((o) => o.bindings),\n outerRefs: [...ctx.outerRefs],\n output,\n decodeRows,\n };\n}\n\n/**\n * Assigns a SQL alias to a source and returns a function that parses it after all sources are registered.\n *\n * Conditions resolve source identities through the context when their SQL is generated.\n * Each entity source reads only its physical table, without inheritance joins or class tags.\n */\nfunction registerSource(source: unknown, ctx: Ctx, assigner: AliasAssigner): () => ParsedSource {\n const handle = handleOf(source);\n if (handle instanceof SubqueryHandle) {\n const alias = handle.name ? assigner.getLiteralAlias(handle.name) : assigner.getLiteralAlias(\"sq\");\n ctx.register(handle, alias);\n return () => {\n const inner = parseQuery(handle.q, ctx, assigner);\n return {\n handle,\n alias,\n sql: `(${inner.sql}) AS ${safeKq(alias)}`,\n bindings: inner.bindings,\n refs: inner.outerRefs,\n entitySelects: [],\n meta: undefined,\n };\n };\n } else {\n const meta = getTableMetadata(source as any);\n const alias = assigner.getAlias(meta.tableName);\n ctx.register(handle, alias);\n return () => {\n // Ordinary entity mode selects the table's columns, excluding lazy ones like em.find.\n const entitySelects = meta.hasLazyColumns ? lazyExcludedSelects(meta, alias) : [kqStar(alias)];\n return {\n handle,\n alias,\n sql: `${kq(meta.tableName)} AS ${kq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects,\n meta,\n };\n };\n }\n}\n\n/**\n * Per-source soft-delete injections: `alias.deleted_at IS NULL` for a soft-deletable entity.\n * CTI subtypes are skipped because their deleted-at column belongs to the base table (see\n * `filterSoftDeletes`). STI sources read all physical rows without discriminator predicates.\n *\n * The conditions go into the from's WHERE or the join's ON, and never keep an otherwise unreferenced\n * join alive, which is what `pruneable: true` means on em.find's side.\n */\nexport function injectedConditions(\n source: { meta: EntityMetadata | undefined; alias: string },\n softDeletes: \"include\" | \"exclude\",\n): ColumnCondition[] {\n const { meta } = source;\n if (!meta) return [];\n const conditions: ColumnCondition[] = [];\n if (filterSoftDeletes(meta, softDeletes)) {\n const field = meta.allFields[getBaseMeta(meta).timestampFields!.deletedAt!];\n const column = field.serde!.columns[0];\n conditions.push({\n kind: \"column\",\n alias: `${source.alias}${field.aliasSuffix}`,\n column: column.columnName,\n dbType: column.dbType,\n cond: { kind: \"is-null\" },\n pruneable: true,\n });\n }\n return conditions;\n}\n\n/** Registers a sugar m2m join table, i.e. `authors_to_tags`: a raw table with no entity metadata. */\nfunction registerJoinTable(handle: JoinTableHandle, ctx: Ctx, assigner: AliasAssigner): () => ParsedSource {\n const alias = assigner.getAlias(handle.joinTableName);\n ctx.register(handle, alias);\n return () => ({\n handle,\n alias,\n sql: `${kq(handle.joinTableName)} AS ${kq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects: [],\n meta: undefined,\n });\n}\n\n/** Generates the `select` clause SQL and returns how to decode the resulting rows. */\nfunction selectsToSql(\n q: AnyQuery,\n ctx: Ctx,\n from: ParsedSource,\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const { select } = q;\n if (isTable(select)) {\n // Ordinary entity mode: `a.*`, hydrated through the identity map. Only the from is\n // hydratable: a joined alias would need null-row skipping and left-join nullability (see TODO.md)\n if (from.handle !== getTableMgmt(select)) {\n fail(\"Selecting a joined table is not supported yet; select the from table, or select its columns individually\");\n }\n const alias = ctx.aliasFor(getTableMgmt(select));\n const meta = getTableMetadata(select);\n const selects = from.entitySelects.map((s) => ({ sql: s, bindings: [], refs: [alias] }));\n return {\n selects,\n decodeRows: (em, rows) => em.hydrate(meta.cstr as any, rows),\n output: { kind: \"entity\", columns: [] },\n };\n } else if (isSubqueryValue(select)) {\n // `select: <subquery>` is `select *` for that table; like entity mode, only for the from, since a\n // left-joined subquery's unmatched rows would decode null fields the row type calls non-null\n const handle = readValueHandle(select);\n if (from.handle !== handle) {\n fail(\n \"Selecting a joined subquery is not supported; select the from subquery, or select its columns individually\",\n );\n }\n const alias = ctx.aliasFor(handle);\n const output = handle.output();\n const selects = output.columns.map(([k]) => ({\n sql: `${safeKq(alias)}.${safeKq(k)} AS ${safeKq(k)}`,\n bindings: [],\n refs: [alias],\n }));\n return {\n selects,\n decodeRows: (_, rows) => rows.map((row) => decodeRow(row, output.columns)),\n output,\n };\n }\n const projection = projectionToSql(select, ctx);\n projection.output = joinedOutput(projection.output, q.join);\n return projection;\n}\n\nfunction decodeRow(row: any, decoders: readonly (readonly [string, BaseExpr])[]): any {\n const result: any = {};\n for (const [key, expr] of decoders) {\n const value = row[key];\n const decoded = value === null || value === undefined ? null : expr.decode(value);\n // A projected __proto__ is data, not a request to replace the result object's prototype.\n if (key === \"__proto__\") {\n Object.defineProperty(result, key, { value: decoded, enumerable: true, configurable: true, writable: true });\n } else {\n result[key] = decoded;\n }\n }\n return result;\n}\n\nconst ORDER_BY_DIRECTIONS: string[] = [\n \"ASC\",\n \"DESC\",\n \"ASC NULLS FIRST\",\n \"ASC NULLS LAST\",\n \"DESC NULLS FIRST\",\n \"DESC NULLS LAST\",\n];\n\n/**\n * Generates ORDER BY SQL in entry order for keyed/expression arrays or a single keyed object.\n *\n * Expression entries retain bindings and alias references for join pruning. Undefined entries and\n * directions are omitted.\n */\nfunction orderBysToSql(q: AnyQuery, ctx: Ctx): SqlFragment[] {\n const { orderBy, select } = q;\n if (!orderBy) return [];\n const result: SqlFragment[] = [];\n for (const entry of Array.isArray(orderBy) ? orderBy : [orderBy]) {\n if (entry === undefined) continue;\n // A select key can also be named asc or desc, so distinguish entries by their values, not their keys.\n if (isExpr(entry.asc) || isExpr(entry.desc)) {\n result.push(orderByToSql(entry, ctx));\n continue;\n }\n for (const [key, dir] of Object.entries(entry)) {\n if (dir === undefined) continue;\n // The direction is interpolated into the SQL, so never trust it, i.e. it might be a request param\n if (!ORDER_BY_DIRECTIONS.includes(dir as string)) return fail(`Invalid orderBy direction '${dir}'`);\n // Entity mode orders by the alias's column; POJO/subquery selects order by the output column name\n if (isTable(select)) {\n const column = (select as any)[key];\n if (!isExpr(column)) return fail(`orderBy key '${key}' is not a sortable column of the table`);\n const fragment = asNode(column).toSql(ctx);\n result.push({ ...fragment, sql: `${fragment.sql} ${dir}` });\n } else {\n if (isExpr(select)) return fail(`the keyed orderBy form needs a POJO or entity select`);\n const keys = isSubqueryValue(select) ? select[subqueryBrand].columnKeys() : Object.keys(select as object);\n if (!keys.includes(key)) return fail(`orderBy key '${key}' is not a key of select`);\n result.push({ sql: `${safeKq(key)} ${dir}`, bindings: [], refs: [] });\n }\n }\n }\n return result;\n}\n\nfunction orderByToSql(o: QueryOrderBy, ctx: Ctx): SqlFragment {\n const [expr, direction] = \"asc\" in o && o.asc ? [o.asc, \"ASC\"] : [o.desc, \"DESC\"];\n const fragment = asExpr(expr, \"orderBy\").toSql(ctx);\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 nulls = o.nulls ? ` NULLS ${o.nulls.toUpperCase()}` : \"\";\n return { ...fragment, sql: `${fragment.sql} ${direction}${nulls}` };\n}\n\n/**\n * Parses a user-facing condition (a single condition or an `{ and }`/`{ or }` filter) with the same\n * `ConditionBuilder` `em.find` uses, so `undefined` members drop out, empty groups drop, and\n * `pruneIfUndefined` applies unchanged. Deferred SQL expression conditions are resolved\n * against the context first.\n */\nexport function conditionToSql(cond: QueryCondition | undefined, ctx: Ctx, topLevel: boolean): SqlFragment | undefined {\n checkCondition(cond);\n if (cond === undefined) return undefined;\n const resolved = resolveDeferredConditions(resolveQueryCondition(cond, ctx), ctx);\n if (resolved === undefined) return undefined;\n const filter: ConditionGroup<ConditionInput> = isFilter(resolved) ? resolved : { and: [resolved] };\n const cb = new ConditionBuilder();\n cb.maybeAddExpression(filter);\n const parsed = cb.toExpressionFilter();\n if (!parsed) return undefined;\n const where = buildWhereClause(parsed, topLevel);\n if (!where) return undefined;\n return { sql: where[0], bindings: where[1], refs: refsOf(parsed) };\n}\n\n/**\n * Rejects malformed predicates throughout a condition tree before pruning can discard a restriction.\n * I.e. an invalid Author-name condition stays invalid even inside a group that would otherwise prune,\n * while an explicitly omitted query-valued condition is allowed to prune.\n */\nfunction checkCondition(value: unknown): void {\n if (\n isDeferredAliasCondition(value) ||\n (value && typeof value === \"object\" && predicateBrand in value && value[predicateBrand] === \"domain\")\n )\n fail(\n \"Domain alias conditions are only supported by em.find; use table(...) predicates in SQL queries and mutations.\",\n );\n if (value === undefined || value === skipCondition) return;\n if (!value || typeof value !== \"object\" || Array.isArray(value) || isExpr(value))\n fail(\"Query predicate must be a condition or an and/or group\");\n const condition = value as Record<string, unknown>;\n if (\"and\" in condition || \"or\" in condition) {\n if (\"and\" in condition === \"or\" in condition) fail(\"Query conditions require exactly one and/or group\");\n const key = \"and\" in condition ? \"and\" : \"or\";\n checkConditionKeys(condition, [key, \"pruneIfUndefined\"], \"Query condition group\");\n if (!Array.isArray(condition[key])) fail(\"Query condition groups require an array\");\n if (\n condition.pruneIfUndefined !== undefined &&\n condition.pruneIfUndefined !== \"any\" &&\n condition.pruneIfUndefined !== \"all\"\n )\n fail(\"Invalid query pruneIfUndefined policy\");\n for (const child of condition[key]) checkCondition(child);\n } else if (\"exists\" in condition || \"notExists\" in condition) {\n const key = \"exists\" in condition ? \"exists\" : \"notExists\";\n checkConditionKeys(condition, [key], \"Query existence condition\");\n const query = condition[key];\n if (query === undefined) return;\n if (!(query instanceof SubqueryExpr) && !isReadQueryValue(query)) fail(`Query ${key} requires a query(...) value`);\n toQuery(query);\n } else if (condition.kind === \"raw\") {\n checkConditionKeys(\n condition,\n [\"kind\", \"aliases\", \"condition\", \"bindings\", \"pruneable\", deferredSym, predicateBrand],\n \"Query raw condition\",\n );\n if (\n typeof condition.condition !== \"string\" ||\n !Array.isArray(condition.aliases) ||\n !condition.aliases.every((alias) => typeof alias === \"string\") ||\n !Array.isArray(condition.bindings) ||\n typeof condition.pruneable !== \"boolean\"\n )\n fail(\"Malformed query raw condition\");\n } else if (condition.kind === \"column\") {\n checkConditionKeys(\n condition,\n [\"kind\", \"alias\", \"column\", \"dbType\", \"cond\", \"pruneable\", predicateBrand],\n \"Query column condition\",\n );\n if (\n typeof condition.alias !== \"string\" ||\n typeof condition.column !== \"string\" ||\n typeof condition.dbType !== \"string\" ||\n (condition.pruneable !== undefined && typeof condition.pruneable !== \"boolean\")\n )\n fail(\"Malformed query column condition\");\n const filter = condition.cond as Record<string, unknown> | undefined;\n if (!filter) fail(\"Malformed query column filter\");\n checkConditionKeys(filter, [\"kind\", \"value\"], \"Query column filter\");\n const unary = filter.kind === \"is-null\" || filter.kind === \"not-null\";\n if (\n !unary &&\n (![\n \"eq\",\n \"ne\",\n \"in\",\n \"nin\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"like\",\n \"nlike\",\n \"ilike\",\n \"nilike\",\n \"regex\",\n \"nregex\",\n \"iregex\",\n \"niregex\",\n \"contains\",\n \"ncontains\",\n \"overlaps\",\n \"noverlaps\",\n \"containedBy\",\n \"between\",\n \"jsonPathExists\",\n \"jsonPathPredicate\",\n ].includes(filter.kind as string) ||\n !(\"value\" in filter))\n )\n fail(\"Malformed query column filter\");\n if (unary && \"value\" in filter) fail(\"Unary query filters do not accept values\");\n } else {\n fail(\"Unknown query condition\");\n }\n}\n\n/** Conditions use own enumerable POJO fields, with predicate-brand and SQL-resolver symbols allowed. */\nfunction checkConditionKeys(value: object, allowed: readonly PropertyKey[], description: string): void {\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n fail(`${description} must be a plain POJO`);\n for (const key of Reflect.ownKeys(value)) {\n if (!allowed.includes(key)) fail(`${description} does not support '${String(key)}'`);\n if (typeof key === \"string\" && !Object.prototype.propertyIsEnumerable.call(value, key))\n fail(`${description} requires enumerable fields`);\n }\n}\n\n/**\n * Converts query-valued predicates to SQL conditions for the shared condition builder.\n * Keeps each subquery's projection and reports its outer aliases for join pruning.\n */\nfunction resolveQueryCondition(cond: QueryCondition | undefined, ctx: Ctx): ConditionInput | undefined {\n if (cond === undefined) return undefined;\n if (\"and\" in cond && cond.and) {\n return {\n and: cond.and.map((child) => resolveQueryCondition(child, ctx)),\n pruneIfUndefined: cond.pruneIfUndefined,\n };\n }\n if (\"or\" in cond && cond.or) {\n return { or: cond.or.map((child) => resolveQueryCondition(child, ctx)), pruneIfUndefined: cond.pruneIfUndefined };\n }\n if (\"exists\" in cond || \"notExists\" in cond) {\n const positive = \"exists\" in cond;\n const subquery = positive ? cond.exists : cond.notExists;\n if (subquery === undefined) return undefined;\n const plan = parseQuery(toQuery(subquery), ctx, ctx.assigner);\n return {\n kind: \"raw\",\n condition: `${positive ? \"EXISTS\" : \"NOT EXISTS\"} (${plan.sql})`,\n bindings: plan.bindings,\n aliases: plan.outerRefs,\n pruneable: false,\n };\n }\n return cond as ConditionInput;\n}\n\nfunction isFilter(cond: ConditionInput): cond is ConditionGroup<ConditionInput> {\n return (\"and\" in cond && cond.and !== undefined) || (\"or\" in cond && cond.or !== undefined);\n}\n\n/** The physical source aliases a parsed condition tree references. */\nfunction refsOf(parsed: ParsedExpressionFilter): string[] {\n return deepFindConditions(parsed, false).flatMap((c) =>\n c.kind === \"column\" ? [c.alias] : c.kind === \"raw\" ? c.aliases : c.outerAliases,\n );\n}\n\n/**\n * Pruning: em.find's paradigm, on a flat join list.\n *\n * A condition given `undefined` was already dropped by `ConditionBuilder`. Now a join that nothing\n * references anymore drops with it: a join is required if the source, a select, a surviving condition,\n * a group-by, an order-by, or another required join's ON references it, or if it is pinned with\n * `keep: true`. Marking follows ON dependencies transitively, exactly like `pruneUnusedJoins`'s\n * `DependencyTracker`.\n *\n * em.find's joins almost never filter rows by themselves, so pruning them is semantics-preserving. An\n * explicit `{ inner: b, on }` here does filter rows, so pruning it when unreferenced drops that filter;\n * that matches `{ books: { title: undefined } }` in em.find and is deliberate. `keep: true` pins it, and\n * a pure existence filter is better written as `a.id.in(query({ ... }))`, which is never `undefined`.\n */\nfunction pruneJoins(q: AnyQuery, from: ParsedSource, joins: ParsedJoin[], used: SqlFragment[]): ParsedJoin[] {\n if (q.pruneJoins === false) return joins;\n const deps = new Map<string, string[]>();\n for (const j of joins) {\n const refs = [...(j.userOn?.refs ?? []), ...j.source.refs].filter((r) => r !== j.source.alias);\n deps.set(j.source.alias, refs);\n }\n const required = new Set<string>();\n function markRequired(alias: string): void {\n if (required.has(alias)) return;\n required.add(alias);\n for (const dep of deps.get(alias) ?? []) markRequired(dep);\n }\n markRequired(from.alias);\n for (const r of used.flatMap((u) => u.refs)) markRequired(r);\n for (const j of joins) if (j.keep) markRequired(j.source.alias);\n return joins.filter((j) => required.has(j.source.alias));\n}\n\nfunction asExpr(value: unknown, where: string): BaseExpr {\n if (value instanceof BaseExpr) return value;\n return fail(`${where} must be an expression, i.e. a table column, aggregate, sql\\`...\\`, or scalar query(...)`);\n}\n\nfunction joinFragmentParts(parts: SqlFragment[], sep: string): SqlFragment {\n return { sql: parts.map((p) => p.sql).join(sep), bindings: parts.flatMap((p) => p.bindings), refs: [] };\n}\n\nfunction isDefined<T>(value: T | undefined): value is T {\n return value !== undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,MAAa,gBAA+B,OAAO,gBAAgB;AACnE,MAAa,mBAAkC,OAAO,mBAAmB;AACzE,MAAa,mBAAkC,OAAO,mBAAmB;AAmlBzE,SAAgB,MAAM,GAA0B;CAC9C,MAAM,SAAS,IAAI,eAAe,QAAQ,CAAC,CAAC;CAC5C,MAAM,SAAS,OAAO,OAAO;CAC7B,IAAI,OAAO,SAAS,UAClB,OAAO,GAAG,mBAAmB,OAAO;MAC/B,IAAI,OAAO,SAAS,UACzB,OAAO,IAAI,aAAa,MAAM;MAE9B,OAAO,iBAAiB,MAAM;AAElC;;;;;;;;;;;;;;;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,KAAK,MAAM,OAAO,KAAK,IAAI,KAAK,KAAK,CAAC,GAAG,aAAa,GAAG;CAC3D;CACA,aAAa,KAAK,KAAK;CACvB,KAAK,MAAM,KAAK,KAAK,SAAS,MAAM,EAAE,IAAI,GAAG,aAAa,CAAC;CAC3D,KAAK,MAAM,KAAK,OAAO,IAAI,EAAE,MAAM,aAAa,EAAE,OAAO,KAAK;CAC9D,OAAO,MAAM,QAAQ,MAAM,SAAS,IAAI,EAAE,OAAO,KAAK,CAAC;AACzD;AAEA,SAAS,OAAO,OAAgB,OAAyB;CACvD,IAAI,iBAAiBrB,aAAAA,UAAU,OAAO;CACtC,OAAOD,cAAAA,KAAK,GAAG,MAAM,yFAAyF;AAChH;AAEA,SAAS,kBAAkB,OAAsB,KAA0B;CACzE,OAAO;EAAE,KAAK,MAAM,KAAK,MAAM,EAAE,GAAG,CAAC,CAAC,KAAK,GAAG;EAAG,UAAU,MAAM,SAAS,MAAM,EAAE,QAAQ;EAAG,MAAM,CAAC;CAAE;AACxG;AAEA,SAAS,UAAa,OAAkC;CACtD,OAAO,UAAU,KAAA;AACnB"}
|
package/build/query.d.cts
CHANGED
|
@@ -68,12 +68,12 @@ type QueryCondition = SqlPredicate | UnbrandedPredicate | (({
|
|
|
68
68
|
}) & {
|
|
69
69
|
pruneIfUndefined?: "any" | "all";
|
|
70
70
|
}) | {
|
|
71
|
-
exists: ExistsQuery;
|
|
71
|
+
exists: ExistsQuery | undefined;
|
|
72
72
|
notExists?: never;
|
|
73
73
|
and?: never;
|
|
74
74
|
or?: never;
|
|
75
75
|
} | {
|
|
76
|
-
notExists: ExistsQuery;
|
|
76
|
+
notExists: ExistsQuery | undefined;
|
|
77
77
|
exists?: never;
|
|
78
78
|
and?: never;
|
|
79
79
|
or?: never;
|