joist-core 2.3.0-next.99 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/build/EntityManager.cjs +1 -1
  2. package/build/EntityManager.cjs.map +1 -1
  3. package/build/EntityManager.d.cts +9 -8
  4. package/build/EntityManager.d.cts.map +1 -1
  5. package/build/EntityManager.d.mts +9 -8
  6. package/build/EntityManager.d.mts.map +1 -1
  7. package/build/EntityManager.js +1 -1
  8. package/build/EntityManager.js.map +1 -1
  9. package/build/dataloaders/findCountDataLoader.cjs +2 -0
  10. package/build/dataloaders/findCountDataLoader.cjs.map +1 -1
  11. package/build/dataloaders/findCountDataLoader.d.cts.map +1 -1
  12. package/build/dataloaders/findCountDataLoader.d.mts.map +1 -1
  13. package/build/dataloaders/findCountDataLoader.js +2 -0
  14. package/build/dataloaders/findCountDataLoader.js.map +1 -1
  15. package/build/dataloaders/findDataLoader.cjs +1 -0
  16. package/build/dataloaders/findDataLoader.cjs.map +1 -1
  17. package/build/dataloaders/findDataLoader.d.cts.map +1 -1
  18. package/build/dataloaders/findDataLoader.d.mts.map +1 -1
  19. package/build/dataloaders/findDataLoader.js +2 -1
  20. package/build/dataloaders/findDataLoader.js.map +1 -1
  21. package/build/dataloaders/findIdsDataLoader.cjs +2 -0
  22. package/build/dataloaders/findIdsDataLoader.cjs.map +1 -1
  23. package/build/dataloaders/findIdsDataLoader.d.cts.map +1 -1
  24. package/build/dataloaders/findIdsDataLoader.d.mts.map +1 -1
  25. package/build/dataloaders/findIdsDataLoader.js +2 -0
  26. package/build/dataloaders/findIdsDataLoader.js.map +1 -1
  27. package/build/dataloaders/findPaginatedDataLoader.cjs +2 -0
  28. package/build/dataloaders/findPaginatedDataLoader.cjs.map +1 -1
  29. package/build/dataloaders/findPaginatedDataLoader.d.cts.map +1 -1
  30. package/build/dataloaders/findPaginatedDataLoader.d.mts.map +1 -1
  31. package/build/dataloaders/findPaginatedDataLoader.js +2 -0
  32. package/build/dataloaders/findPaginatedDataLoader.js.map +1 -1
  33. package/build/index.cjs +6 -3
  34. package/build/index.cjs.map +1 -1
  35. package/build/index.d.cts +6 -4
  36. package/build/index.d.cts.map +1 -1
  37. package/build/index.d.mts +6 -4
  38. package/build/index.d.mts.map +1 -1
  39. package/build/index.js +6 -5
  40. package/build/index.js.map +1 -1
  41. package/build/keys.cjs +6 -1
  42. package/build/keys.cjs.map +1 -1
  43. package/build/keys.d.cts +3 -1
  44. package/build/keys.d.cts.map +1 -1
  45. package/build/keys.d.mts +3 -1
  46. package/build/keys.d.mts.map +1 -1
  47. package/build/keys.js +6 -2
  48. package/build/keys.js.map +1 -1
  49. package/build/queries/find/QueryParser.cjs +1 -2
  50. package/build/queries/find/QueryParser.cjs.map +1 -1
  51. package/build/queries/find/QueryParser.d.cts.map +1 -1
  52. package/build/queries/find/QueryParser.d.mts.map +1 -1
  53. package/build/queries/find/QueryParser.js +2 -3
  54. package/build/queries/find/QueryParser.js.map +1 -1
  55. package/build/queries/find/QueryVisitor.cjs +17 -0
  56. package/build/queries/find/QueryVisitor.cjs.map +1 -1
  57. package/build/queries/find/QueryVisitor.d.cts +3 -1
  58. package/build/queries/find/QueryVisitor.d.cts.map +1 -1
  59. package/build/queries/find/QueryVisitor.d.mts +3 -1
  60. package/build/queries/find/QueryVisitor.d.mts.map +1 -1
  61. package/build/queries/find/QueryVisitor.js +17 -1
  62. package/build/queries/find/QueryVisitor.js.map +1 -1
  63. package/build/queries/sql/Expr.cjs +18 -1
  64. package/build/queries/sql/Expr.cjs.map +1 -1
  65. package/build/queries/sql/Expr.d.cts +13 -3
  66. package/build/queries/sql/Expr.d.cts.map +1 -1
  67. package/build/queries/sql/Expr.d.mts +13 -3
  68. package/build/queries/sql/Expr.d.mts.map +1 -1
  69. package/build/queries/sql/Expr.js +18 -2
  70. package/build/queries/sql/Expr.js.map +1 -1
  71. package/build/queries/sql/JoinTree.cjs +72 -0
  72. package/build/queries/sql/JoinTree.cjs.map +1 -0
  73. package/build/queries/sql/JoinTree.d.cts +107 -0
  74. package/build/queries/sql/JoinTree.d.cts.map +1 -0
  75. package/build/queries/sql/JoinTree.d.mts +107 -0
  76. package/build/queries/sql/JoinTree.d.mts.map +1 -0
  77. package/build/queries/sql/JoinTree.js +71 -0
  78. package/build/queries/sql/JoinTree.js.map +1 -0
  79. package/build/queries/sql/Tables.cjs +103 -6
  80. package/build/queries/sql/Tables.cjs.map +1 -1
  81. package/build/queries/sql/Tables.d.cts +72 -13
  82. package/build/queries/sql/Tables.d.cts.map +1 -1
  83. package/build/queries/sql/Tables.d.mts +72 -13
  84. package/build/queries/sql/Tables.d.mts.map +1 -1
  85. package/build/queries/sql/Tables.js +101 -10
  86. package/build/queries/sql/Tables.js.map +1 -1
  87. package/build/queries/sql/custom.cjs +52 -0
  88. package/build/queries/sql/custom.cjs.map +1 -0
  89. package/build/queries/sql/custom.d.cts +85 -0
  90. package/build/queries/sql/custom.d.cts.map +1 -0
  91. package/build/queries/sql/custom.d.mts +85 -0
  92. package/build/queries/sql/custom.d.mts.map +1 -0
  93. package/build/queries/sql/custom.js +49 -0
  94. package/build/queries/sql/custom.js.map +1 -0
  95. package/build/queries/sql/execute.cjs +68 -28
  96. package/build/queries/sql/execute.cjs.map +1 -1
  97. package/build/queries/sql/execute.d.cts +110 -11
  98. package/build/queries/sql/execute.d.cts.map +1 -1
  99. package/build/queries/sql/execute.d.mts +110 -11
  100. package/build/queries/sql/execute.d.mts.map +1 -1
  101. package/build/queries/sql/execute.js +69 -29
  102. package/build/queries/sql/execute.js.map +1 -1
  103. package/build/queries/sql/expressions/types.d.cts +5 -5
  104. package/build/queries/sql/expressions/types.d.cts.map +1 -1
  105. package/build/queries/sql/expressions/types.d.mts +5 -5
  106. package/build/queries/sql/expressions/types.d.mts.map +1 -1
  107. package/build/queries/sql/keywords.cjs +1 -1
  108. package/build/queries/sql/keywords.cjs.map +1 -1
  109. package/build/queries/sql/keywords.d.cts +1 -1
  110. package/build/queries/sql/keywords.d.mts +1 -1
  111. package/build/queries/sql/keywords.js +1 -1
  112. package/build/queries/sql/keywords.js.map +1 -1
  113. package/build/queries/sql/query.cjs +100 -38
  114. package/build/queries/sql/query.cjs.map +1 -1
  115. package/build/queries/sql/query.d.cts +96 -46
  116. package/build/queries/sql/query.d.cts.map +1 -1
  117. package/build/queries/sql/query.d.mts +96 -46
  118. package/build/queries/sql/query.d.mts.map +1 -1
  119. package/build/queries/sql/query.js +102 -40
  120. package/build/queries/sql/query.js.map +1 -1
  121. package/build/queries/valueFilters.cjs +28 -36
  122. package/build/queries/valueFilters.cjs.map +1 -1
  123. package/build/queries/valueFilters.d.cts +2 -4
  124. package/build/queries/valueFilters.d.cts.map +1 -1
  125. package/build/queries/valueFilters.d.mts +2 -4
  126. package/build/queries/valueFilters.d.mts.map +1 -1
  127. package/build/queries/valueFilters.js +29 -36
  128. package/build/queries/valueFilters.js.map +1 -1
  129. package/build/serde/serde.cjs.map +1 -1
  130. package/build/serde/serde.js.map +1 -1
  131. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"query.js","names":["#q"],"sources":["../../../src/queries/sql/query.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { type EntityMetadata, getBaseMeta } from \"src/EntityMetadata.ts\";\nimport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nimport {\n type ConditionGroup,\n type ConditionInput,\n type SqlCondition,\n type SqlPredicate,\n type UnbrandedPredicate,\n predicateBrand,\n} from \"src/queries/conditions.ts\";\nimport { filterSoftDeletes, lazyExcludedSelects, stiSubtypeFilter } from \"src/queries/entityQueryUtils.ts\";\nimport { isDeferredAliasCondition } from \"src/queries/find/DeferredAlias.ts\";\nimport { type ColumnCondition, type ParsedExpressionFilter, deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { buildWhereClause } from \"src/queries/renderConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n RefExpr,\n type SqlFragment,\n TemplateExpr,\n asNode,\n deferredCondition,\n deferredSym,\n exprBrand,\n isExpr,\n orderByToSql,\n resolveDeferredConditions,\n} from \"src/queries/sql/Expr.ts\";\nimport {\n type CheckInput,\n type ExprFromInput,\n type ExprInput,\n type ExpressionSources,\n type ExpressionValue,\n buildExpr,\n} from \"src/queries/sql/expressions/expression.ts\";\nimport { kq, kqStar, safeKq } from \"src/queries/sql/keywords.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 referenceJoinSource,\n tableMgmt,\n} from \"src/queries/sql/Tables.ts\";\nimport type { TypeInfo } from \"src/serde/TypeInfo.ts\";\nimport { fail } from \"src/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 are\n * keyword keys (`{ left: b, on }`), 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: readonly (QueryCondition | undefined)[]; or?: never; exists?: never; notExists?: never }\n | { or: readonly (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 * A CTE declaration: a `query(...)` value with named columns, i.e. a POJO or set-operation select.\n *\n * Entity-mode and scalar `query(...)` shapes are excluded: a CTE must be a table shape, so it needs\n * columns.\n */\nexport type WithSource = Subquery<unknown, string>;\n\n/** One CTE or an array of them; an `undefined` entry prunes, like any other clause. */\nexport type WithInput = WithSource | readonly (WithSource | undefined)[];\n\n/** How a recursive CTE combines its two terms: `UNION ALL` keeps every row, `UNION` drops duplicates. */\nexport interface RecursiveOptions {\n /** Defaults to `\"all\"`. `\"distinct\"` emits UNION, which stops a cyclic graph from looping forever. */\n union?: \"all\" | \"distinct\";\n}\n\n/** An expression order-by entry. An undefined order prunes the complete entry. */\nexport type ExpressionOrderBy = {\n readonly sort: ExprLike<unknown>;\n readonly order: \"ASC\" | \"DESC\" | undefined;\n readonly nulls?: \"first\" | \"last\";\n};\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 `{ sort, order }` 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 ExprLike<unknown>\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/** Prevents a selected keyed sort from being silently mixed into an expression entry. */\ntype CheckedExpressionOrderBy<S> = ExpressionOrderBy &\n (string extends OrderByKey<S>\n ? unknown\n : [S] extends [{ readonly [tableMgmt]: unknown }]\n ? unknown\n : { readonly [K in Exclude<OrderByKey<S>, keyof ExpressionOrderBy>]?: never });\n\n/** The three select shapes: a source, an existing scalar expression, or a POJO naming result columns. */\nexport type QuerySelect = QuerySource | ExprLike<unknown> | Record<string, SelectExpression>;\n\n/** A named projection value may be an existing expression or an inline expression literal. */\nexport type SelectExpression = ExprLike<unknown> | ExprInput;\n\n/** Checks expression literals only inside named projections. */\ntype CheckSelect<S> = S extends QuerySource | ExprLike<unknown>\n ? unknown\n : { readonly [K in keyof S]: S[K] extends ExprInput ? CheckInput<S[K]> : unknown };\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 /**\n * CTEs to include in a `WITH` clause, declared as `query(...)` values; either a single value or an array.\n *\n * I.e. `{ with: bookStats, from: a, join: [{ left: bookStats, on: ... }], select: { n: bookStats.n } }`.\n *\n * An `undefined` entry is ignored, and a CTE that nothing else in the query references will be pruned,\n * the same pruning `join` gets (see \"Pruning\"); `pruneJoins: false` keeps every CTE.\n */\n with?: WithInput;\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;\n orderBy?: readonly (CheckedExpressionOrderBy<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 | \"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, SelectExpression> | 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 /** CTEs for the combined query, declared once and in scope for every operand; see `Clauses.with`. */\n readonly with?: WithInput;\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 | \"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 */\nexport type 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 ? {\n readonly [K in keyof Q]: K extends \"select\"\n ? CheckSelect<Q[K]>\n : K extends keyof Clauses | \"from\" | \"as\"\n ? unknown\n : never;\n }\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 \"with\" | \"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/** Adds default reference targets whose source is already nullable; explicit INNER joins do not inherit. */\ntype InheritedLeft<X, Left> = X extends { readonly [referenceJoinSource]: infer Src; readonly inner: infer A }\n ? // Extract finds this reference's source among nullable aliases. No overlap means its target stays INNER.\n // I.e. Src = \"Book\" and Left = \"Book\" adds NameOf<A> = \"Author\"; Left = \"Publisher\" adds nothing.\n [Extract<Src, Left>] extends [never]\n ? never\n : NameOf<A>\n : never;\n\n/**\n * Finds all aliases that can be NULL through LEFT joins and subsequent reference joins.\n * I.e. LEFT Book adds Author via Book.author.as(a), then further required references inherit Author's NULL.\n * Alias-name collisions are conservative, as they are for explicit LEFT joins; runtime uses exact handles.\n */\ntype NullableSources<X, Left = LeftJoined<X>> =\n // X is J[number], the union of entries in em.query's `join: [...]` array. A variable like\n // `const joins = [j1, j2]` normally infers an array, not a tuple, so this recursive conditional type\n // works over that union instead of walking tuple positions. LeftJoined<X> seeds Left with the aliases\n // from `left: ...` entries. InheritedLeft<X, Left> discovers reference targets whose sources are in Left.\n // Exclude removes names already in Left. If all were already known, stop recursing and use Left as the value;\n // otherwise, add the newly discovered LEFT-joined aliases to our set and recurse.\n [Exclude<InheritedLeft<X, Left>, Left>] extends [never] ? Left : NullableSources<X, Left | InheritedLeft<X, Left>>;\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 `NullableSources<J[number]>`; with an inner join it stays `number`.\n * Default references from nullable sources are included transitively.\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 ? [NullableSources<J[number]>] extends [never]\n ? R\n : R | null\n : [Extract<Src, NullableSources<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 ExprLike<unknown>\n ? ExpressionValue<S, J>\n : {\n // Inline inputs retain readonly tuples for inference; result rows are still mutable.\n -readonly [K in keyof S]: S[K] extends SelectExpression\n ? ExpressionValue<S[K] extends ExprInput ? ExprFromInput<S[K]> : S[K], 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/**\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 ExprLike<unknown>\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, SelectExpression>]\n ? {\n select: {\n [K in keyof S]: CheckExpressionScope<S[K], InScope<F, J>>;\n };\n }\n : unknown;\n\n/** Includes columns nested in inline CASE values and fallbacks in the existing scope check. */\ntype CheckExpressionScope<V, Scope> =\n string extends ExpressionSources<V>\n ? unknown\n : [Exclude<ExpressionSources<V>, Scope>] extends [never]\n ? unknown\n : `table '${Exclude<ExpressionSources<V>, Scope> & string}' is not in from/join`;\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> & { select: CheckSelect<NoInfer<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 const 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 query value only when its user-supplied `where` survives pruning.\n *\n * Missing or empty conditions prune the value, including nested groups and `pruneIfUndefined`.\n * Joins, HAVING, and implicit soft-delete/STI conditions do not keep the value alive.\n *\n * I.e. `queryMaybe({ from: b, where: b.authorId.eq(enabled ? a.id : undefined), select: b.id })`\n * returns `undefined` when `enabled` is false, so an enclosing `notExists` also prunes.\n */\nexport function queryMaybe<\n F extends QuerySource,\n const S extends QuerySelect = never,\n J extends QueryJoins = [],\n Name extends string = \"?\",\n>(q: QueryArg<F, S, J, Name>): QueryValue<S, J, Name> | undefined {\n checkCondition(q.where);\n return isPrunedQueryCondition(q.where) ? undefined : query(q);\n}\n\n/**\n * Declares a `WITH RECURSIVE` CTE from its two terms, and returns the CTE as a readable value.\n *\n * `base` is the non-recursive term, which seeds the rows and, as in PostgreSQL, supplies the CTE's\n * columns. `step` is the recursive term: it receives the CTE itself, so it can join back to the rows\n * found so far. The two terms are combined with UNION ALL, or UNION when `union: \"distinct\"` drops\n * duplicates, which is how a cyclic graph is kept from looping forever.\n *\n * ```ts\n * const [a] = tables(Author);\n * const tree = recursiveQuery(\n * \"tree\",\n * { from: a, where: a.mentor_id.isNull(), select: { id: a.id, mentorId: a.mentor_id } },\n * (self) => ({\n * from: a,\n * join: [{ inner: self, on: a.mentor_id.eq(self.id) }],\n * select: { id: a.id, mentorId: a.mentor_id },\n * }),\n * );\n * const rows = await em.query({ with: tree, from: tree, select: tree });\n * ```\n *\n * Unlike `query()`, the name is required, because the step term must name it.\n */\nexport function recursiveQuery<\n Name extends string,\n F extends QuerySource,\n const S extends QuerySelect,\n J extends QueryJoins,\n>(\n name: Name,\n base: QueryArg<F, S, J, Name>,\n step: (self: Subquery<QueryRow<S, J>, Name>) => SetOperand,\n opts: RecursiveOptions = {},\n): Subquery<QueryRow<S, J>, Name> {\n if (typeof name !== \"string\" || name === \"\") fail(\"A recursive CTE needs a name\");\n if (opts.union !== undefined && opts.union !== \"all\" && opts.union !== \"distinct\") {\n fail(\"A recursive CTE's union must be 'all' or 'distinct'\");\n }\n // Start on the base term so `self`'s columns resolve while the step term is still being built.\n const handle = new SubqueryHandle(toQuery(base), true);\n if (handle.output().kind !== \"pojo\") fail(\"A recursive CTE's base term needs a named projection\");\n const self = newSubqueryProxy(handle) as Subquery<QueryRow<S, J>, Name>;\n const operands = [base, step(self)] as unknown as readonly SetOperand[];\n handle.setBody(opts.union === \"distinct\" ? { union: operands, as: name } : { unionAll: operands, as: name });\n return self;\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 typedSql<R>(strings, ...values);\n}\n\n/** Shorthand for `sql<number>`; does not cast or convert the SQL result. */\nsql.number = typedSql<number>;\n\n/** Shorthand for `sql<number | null>`; does not cast or convert the SQL result. */\nsql.numberOrNull = typedSql<number | null>;\n\n/** Shorthand for `sql<number[]>`; does not cast or convert the SQL result. */\nsql.numberArray = typedSql<number[]>;\n\n/** Shorthand for `sql<number[] | null>`; does not cast or convert the SQL result. */\nsql.numberArrayOrNull = typedSql<number[] | null>;\n\n/** Shorthand for `sql<string>`; does not cast or convert the SQL result. */\nsql.string = typedSql<string>;\n\n/** Shorthand for `sql<string | null>`; does not cast or convert the SQL result. */\nsql.stringOrNull = typedSql<string | null>;\n\n/** Shorthand for `sql<string[]>`; does not cast or convert the SQL result. */\nsql.stringArray = typedSql<string[]>;\n\n/** Shorthand for `sql<string[] | null>`; does not cast or convert the SQL result. */\nsql.stringArrayOrNull = typedSql<string[] | null>;\n\n/** Shorthand for `sql<boolean>`; does not cast or convert the SQL result. */\nsql.boolean = typedSql<boolean>;\n\n/** Shorthand for `sql<boolean | null>`; does not cast or convert the SQL result. */\nsql.booleanOrNull = typedSql<boolean | null>;\n\n/** Shorthand for `sql<boolean[]>`; does not cast or convert the SQL result. */\nsql.booleanArray = typedSql<boolean[]>;\n\n/** Shorthand for `sql<boolean[] | null>`; does not cast or convert the SQL result. */\nsql.booleanArrayOrNull = typedSql<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/**\n * Parses a read that sits inside another statement, i.e. an INSERT's SELECT source, so it resolves that\n * statement's CTEs and shares its alias space instead of generating names that could collide with them.\n */\nexport function parseNestedQuery(arg: unknown, parent: Ctx, assigner: AliasAssigner): Plan {\n if (arg instanceof SubqueryExpr) fail(\"Scalar query values are expressions, not executable read inputs\");\n return parseQuery(toQuery(arg), parent, assigner);\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 #q: AnyReadQuery;\n\n constructor(\n q: AnyReadQuery,\n readonly recursive = false,\n ) {\n this.#q = q;\n }\n\n get q(): AnyReadQuery {\n return this.#q;\n }\n\n /**\n * Gives a recursive CTE its finished body. `recursiveQuery` starts the handle on its base term, so\n * the step term can read the CTE's columns while the body that will hold that step is still being\n * built. The base term supplies the CTE's columns either way, PostgreSQL's rule for a recursive WITH.\n */\n setBody(q: AnyReadQuery): void {\n if (!this.recursive) fail(\"Only a recursive CTE replaces its body\");\n this.#q = q;\n }\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, SelectExpression> {\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 \"with\",\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 }\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], \"with\", \"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, asSelectExpr(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 resolveReferenceJoins(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/**\n * Resolves reference joins in declaration order without changing reusable join entries.\n * Only .as() carries a source handle; explicit INNER joins retain their filtering semantics.\n * I.e. LEFT Book followed by Book.author.as(a) adds Author to the set of nullable handles.\n */\nfunction resolveReferenceJoins(joins: QueryJoins | undefined): QueryJoin[] {\n const left = new Set<object>();\n return (joins ?? []).filter(isDefined).map((join) => {\n const source = (join as QueryJoin & { [referenceJoinSource]?: object })[referenceJoinSource];\n if (join.inner && source && left.has(source)) {\n const { inner, ...rest } = join;\n const resolved = { ...rest, left: inner };\n left.add(handleOf(inner));\n return resolved;\n }\n if (join.left) left.add(handleOf(join.left));\n return join;\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(\n q: SetQuery<readonly SetOperand[]>,\n parent: Ctx | undefined,\n assigner: AliasAssigner,\n recursiveSelf?: SubqueryHandle,\n): Plan {\n const [operation, operands] = setOperands(q);\n const output = queryOutput(q);\n // A set query's CTEs need a scope of their own, between the enclosing query and the operands.\n const ctx = new Ctx(assigner, parent);\n if (recursiveSelf) ctx.setRecursiveSelf(recursiveSelf);\n const ctes = registerCtes(q, ctx, assigner);\n const plans = operands.map((operand) => parseQuery(toQuery(operand), ctx, 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 const keptCtes = pruneCtes(ctes, new Set(plans.flatMap((plan) => plan.outerRefs)));\n if (keptCtes.length > 0) {\n const clause = withFragment(keptCtes);\n sql = clause.sql + sql;\n bindings.unshift(...clause.bindings);\n }\n // An operand that reads one of our CTEs resolved that name here, not in the enclosing query, so the\n // name must not go out in `outerRefs`. That list is how this query tells the enclosing one which of\n // *its* aliases we depend on, and the enclosing query keeps those joins alive rather than pruning\n // them; a CTE name in there would pin a join that has nothing to do with it.\n const cteAliases = new Set(ctes.map((cte) => cte.alias));\n const outerRefs = [...ctx.outerRefs, ...plans.flatMap((plan) => plan.outerRefs)];\n return {\n sql,\n bindings,\n outerRefs: [...new Set(outerRefs.filter((ref) => !cteAliases.has(ref)))],\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 /**\n * The subset of `aliases` that are CTE names. A `from`/`join` on one of these emits just the name,\n * i.e. `FROM book_stats`, where an ordinary `query(...)` value emits its whole body inline, i.e.\n * `FROM (SELECT ...) AS sq`.\n */\n private ctes = new Map<object, string>();\n /**\n * `with` entries named but not yet turned into SQL. `registerCtes` names every entry first, then\n * generates the bodies one at a time, so while one body is being generated the entries after it sit\n * here. Reading one of those is a forward reference.\n */\n private pendingCtes = new Map<object, string>();\n /** CTEs already read by this query's `from`/`join`, so a second read fails instead of colliding. */\n private usedCtes = new Set<object>();\n /** The recursive CTE whose body this query is part of, if any; see `recursiveSelf`. */\n private ownRecursiveSelf: SubqueryHandle | undefined;\n readonly outerRefs = new Set<string>();\n\n constructor(\n readonly assigner: AliasAssigner,\n private parent: Ctx | undefined,\n ) {}\n\n /**\n * One handle can hold only one alias per query, so a value used twice must be told apart, not\n * silently collapsed into the second registration's alias.\n */\n register(handle: object, alias: string): void {\n if (this.aliases.has(handle)) {\n fail(\n `${describeHandle(handle)} is already in this query's \\`with\\`/\\`from\\`/\\`join\\`; use a separate table(...)/query(...) value for each use`,\n );\n }\n this.aliases.set(handle, alias);\n }\n\n /** Names every `with` entry up front, so a CTE reading a later sibling is reported, not inlined. */\n declareCte(handle: object, alias: string): void {\n this.pendingCtes.set(handle, alias);\n }\n\n /** Brings a pending CTE into scope, for the sources and columns that may now read it. */\n promoteCte(handle: object): void {\n const alias = this.pendingCtes.get(handle) ?? fail(\"CTE was not declared\");\n this.pendingCtes.delete(handle);\n this.ctes.set(handle, alias);\n this.register(handle, alias);\n }\n\n /**\n * The CTE name for `handle`, looking in the enclosing queries too, because a CTE is in scope for the\n * whole statement.\n *\n * Unlike `aliasFor`, a hit in an enclosing query is not added to `outerRefs`: reading a CTE by name\n * is not a correlated reference, so it must not keep an enclosing join alive.\n */\n cteAliasFor(handle: object): string | undefined {\n return this.ctes.get(handle) ?? this.parent?.cteAliasFor(handle);\n }\n\n /**\n * The recursive CTE this query's terms belong to, inherited from the enclosing query.\n *\n * PostgreSQL requires a recursive term to reference its own CTE, so that reference is not optional\n * and must survive pruning, unlike an ordinary explicit join that nothing else reads.\n */\n get recursiveSelf(): SubqueryHandle | undefined {\n return this.ownRecursiveSelf ?? this.parent?.recursiveSelf;\n }\n\n setRecursiveSelf(handle: SubqueryHandle): void {\n this.ownRecursiveSelf = handle;\n }\n\n /** Whether `handle` is a CTE with no SQL yet, i.e. itself or a later `with` entry. */\n isPendingCte(handle: object): boolean {\n return this.pendingCtes.has(handle) || (this.parent?.isPendingCte(handle) ?? false);\n }\n\n /**\n * Fails if this query already reads `handle`. A `Ctx` maps each handle to a single alias, so two\n * reads of one CTE value would render as the same name, i.e. `FROM tree JOIN tree`, and neither the\n * SQL nor a column expression could say which one it meant. Each read needs its own `query(...)`.\n *\n * Only this query is checked, not the enclosing ones: a nested subquery has its own FROM, so reading\n * the same CTE in there is fine.\n */\n useCte(handle: object): void {\n if (this.usedCtes.has(handle)) {\n fail(\n `${describeHandle(handle)} is already in this query's \\`from\\`/\\`join\\`; use a separate query(...) value for each use`,\n );\n }\n this.usedCtes.add(handle);\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: QueryCondition): 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\n/** A parsed `with` entry: the CTE's name and its body, ready to render into the WITH clause. */\nexport interface ParsedCte {\n alias: string;\n plan: Plan;\n /** A recursive CTE reads itself, and makes the whole clause `WITH RECURSIVE`. */\n recursive: boolean;\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(\n q: AnyReadQuery,\n parent: Ctx | undefined,\n assigner: AliasAssigner,\n recursiveSelf?: SubqueryHandle,\n): Plan {\n validateReadQuery(q);\n if (isSetQuery(q)) return parseSetQuery(q, parent, assigner, recursiveSelf);\n const ctx = new Ctx(assigner, parent);\n if (recursiveSelf) ctx.setRecursiveSelf(recursiveSelf);\n const joinEntries = resolveReferenceJoins(q.join);\n\n // 0. Compile CTEs first: they are in scope for every source below, and cannot read those sources.\n const ctes = registerCtes(q, ctx, assigner);\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 userJoins: 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 cti = ctiEntityPlan(q, from, assigner);\n const joins = [...cti.joins, ...userJoins];\n const sti = stiEntityPlan(q, from);\n const { selects, decodeRows, output } = selectsToSql(q, ctx, from, cti.selects ?? sti.selects);\n const fromInjected = [...injectedConditions(from, softDeletes), ...sti.conditions];\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 { joins: kept, ctes: keptCtes } = pruneJoins(\n q,\n ctx,\n from,\n joins,\n ctes,\n [...selects, ...groupBys, ...orderBys, where, having].filter(isDefined),\n );\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 // WITH leads the statement, so its bindings must be pushed before the SELECT's.\n if (keptCtes.length > 0) out.push(withFragment(keptCtes));\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 const cteAlias = ctx.cteAliasFor(handle);\n if (cteAlias) {\n ctx.useCte(handle);\n // A declared CTE is read by its name; the `with` that declared it already parsed its body.\n return () => ({\n handle,\n alias: cteAlias,\n sql: safeKq(cteAlias),\n bindings: [],\n refs: [],\n entitySelects: [],\n meta: undefined,\n });\n }\n if (ctx.isPendingCte(handle)) {\n fail(\n `${describeHandle(handle)} is declared later in this query's \\`with\\`; a CTE can only read earlier ones, and cannot read itself`,\n );\n }\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 entitySelects?: SqlFragment[],\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 = entitySelects ?? 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\n/**\n * Builds the mandatory CTI joins and flat row projection needed by entity hydration.\n *\n * The joins use the same ParsedJoin path as user joins, but `keep: true` makes them survive pruning.\n * They are generated only for an entity selection of the from source; POJO and scalar reads keep their\n * physical-table behavior. User source aliases have already been allocated, so the preferred `_bN` and\n * `_sN` aliases can be made unique before their projection fragments are built.\n */\nfunction ctiEntityPlan(\n q: AnyQuery,\n from: ParsedSource,\n assigner: AliasAssigner,\n): { joins: ParsedJoin[]; selects: SqlFragment[] | undefined } {\n // CTI expansion belongs only to entity mode. Column projections keep their explicit physical-table shape.\n if (!isTable(q.select) || from.handle !== getTableMgmt(q.select)) return { joins: [], selects: undefined };\n const meta = getTableMetadata(q.select);\n if (meta.inheritanceType !== \"cti\") return { joins: [], selects: undefined };\n\n // Start with the selected table. Hydration expects one flat row containing every CTI table's columns.\n const joins: ParsedJoin[] = [];\n const selects: SqlFragment[] = from.entitySelects.map((sql) => ({ sql, bindings: [], refs: [from.alias] }));\n\n // A subtype starts from its own table, so join each base table to recover inherited fields.\n for (const [i, baseMeta] of meta.baseTypes.entries()) {\n const alias = assigner.getLiteralAlias(`${from.alias}_b${i}`);\n joins.push(ctiJoin(from, baseMeta, alias));\n selects.push(...entitySelectFragments(baseMeta, alias));\n }\n\n // A base type needs every subtype table both for subtype fields and for detecting the concrete class.\n // Record each subtype column's aliases while visiting them because sibling tables can reuse a column name.\n const subtypeColumns = new Map<string, string[]>();\n for (const [i, subtypeMeta] of meta.subTypes.entries()) {\n const alias = assigner.getLiteralAlias(`${from.alias}_s${i}`);\n joins.push(ctiJoin(from, subtypeMeta, alias));\n selects.push(...entitySelectFragments(subtypeMeta, alias));\n for (const field of Object.values(subtypeMeta.fields)) {\n if (field.fieldName === \"id\" || !field.serde || (field.kind === \"primitive\" && field.lazy)) continue;\n for (const column of field.serde.columns) {\n const aliases = subtypeColumns.get(column.columnName);\n if (aliases) aliases.push(alias);\n else subtypeColumns.set(column.columnName, [alias]);\n }\n }\n }\n\n // Joined `table.*` projections can overwrite id, so finish with the selected table's canonical entity id.\n selects.push({\n sql: `${safeKq(from.alias)}.${kq(\"id\")} AS ${kq(\"id\")}`,\n bindings: [],\n refs: [from.alias],\n });\n // Collapse same-named sibling fields into the one column name that entity hydration reads.\n for (const [column, aliases] of subtypeColumns) {\n if (aliases.length < 2) continue;\n selects.push({\n sql: `COALESCE(${aliases.map((alias) => `${safeKq(alias)}.${kq(column)}`).join(\", \")}) AS ${kq(column)}`,\n bindings: [],\n refs: aliases,\n });\n }\n // The first present subtype row identifies the concrete constructor; `_` means the base table itself.\n if (meta.subTypes.length > 0) {\n const subtypeAliases = joins.slice(meta.baseTypes.length).map((join) => join.source.alias);\n selects.push({\n sql: `CASE ${subtypeAliases.map((alias) => `WHEN ${safeKq(alias)}.${kq(\"id\")} IS NOT NULL THEN ?`).join(\" \")} ELSE '_' END AS ${kq(\"__class\")}`,\n bindings: meta.subTypes.map((subtype) => subtype.type),\n refs: subtypeAliases,\n });\n }\n return { joins, selects };\n}\n\n/** Adds the discriminator projection and subtype filter required by STI entity hydration. */\nfunction stiEntityPlan(\n q: AnyQuery,\n from: ParsedSource,\n): { selects: SqlFragment[] | undefined; conditions: ColumnCondition[] } {\n // As with CTI, only a table selected from itself requests entity hydration and inheritance behavior.\n if (!isTable(q.select) || from.handle !== getTableMgmt(q.select)) return { selects: undefined, conditions: [] };\n const meta = getTableMetadata(q.select);\n if (meta.inheritanceType !== \"sti\") return { selects: undefined, conditions: [] };\n\n // STI stores the complete family in one row, so the ordinary physical projection already supplies its fields.\n const selects: SqlFragment[] = from.entitySelects.map((sql) => ({ sql, bindings: [], refs: [from.alias] }));\n // `table.*` includes the discriminator. An explicit lazy-safe projection might not, so append it for hydration.\n if (!(from.entitySelects.length === 1 && from.entitySelects[0] === kqStar(from.alias))) {\n const discriminator = getBaseMeta(meta).stiDiscriminatorColumnName!;\n selects.push({\n sql: `${safeKq(from.alias)}.${kq(discriminator)} AS ${kq(discriminator)}`,\n bindings: [],\n refs: [from.alias],\n });\n }\n // Root reads may hydrate any concrete class. Subtype reads must exclude sibling rows to preserve their result type.\n const condition = stiSubtypeFilter(meta, from.alias);\n return { selects, conditions: condition ? [condition] : [] };\n}\n\n/** Creates one mandatory CTI join through the selected source's primary key. */\nfunction ctiJoin(from: ParsedSource, meta: EntityMetadata, alias: string): ParsedJoin {\n const on = {\n sql: `${safeKq(from.alias)}.${kq(\"id\")} = ${safeKq(alias)}.${kq(\"id\")}`,\n bindings: [],\n refs: [from.alias, alias],\n };\n return {\n kind: \"left\",\n source: {\n handle: { tableName: meta.tableName, meta },\n alias,\n sql: `${kq(meta.tableName)} AS ${safeKq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects: [],\n meta,\n },\n userOn: on,\n fullOn: on,\n keep: true,\n };\n}\n\n/** Selects one physical CTI table while preserving lazy-field exclusions. */\nfunction entitySelectFragments(meta: EntityMetadata, alias: string): SqlFragment[] {\n const selects = meta.hasLazyColumns ? lazyExcludedSelects(meta, alias) : [kqStar(alias)];\n return selects.map((sql) => ({ sql, bindings: [], refs: [alias] }));\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 before expression references are collected.\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 sort, order, or nulls, so distinguish by the sort value.\n if (isExpr(entry.sort)) {\n const fragment = orderByToSql(entry, ctx);\n if (fragment) result.push(fragment);\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\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/**\n * Checks structural pruning without resolving SQL or correlated aliases.\n *\n * Keeps individual predicates and applies ConditionBuilder's pruning policy (i.e. pruneIfUndefined) to groups.\n * I.e. an Author condition AND an omitted Book condition survives unless the group uses `any`.\n */\nfunction isPrunedQueryCondition(cond: QueryCondition | undefined): boolean {\n if (cond === undefined || cond === skipCondition) return true;\n if (\"and\" in cond || \"or\" in cond) {\n const children = (cond.and ?? cond.or ?? []).map(isPrunedQueryCondition);\n return (\n children.every((pruned) => pruned) ||\n (\"pruneIfUndefined\" in cond && cond.pruneIfUndefined === \"any\" && children.some((pruned) => pruned))\n );\n }\n if (\"exists\" in cond) return cond.exists === undefined;\n if (\"notExists\" in cond) return cond.notExists === undefined;\n return false;\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 *\n * CTEs prune on the same rule and through the same dependency map: a `with` entry nothing reads\n * anymore drops with the join that read it, and a CTE read only by another CTE survives with it.\n * A CTE joined into the query shares its alias with that join, so their dependencies are merged.\n *\n * The one join that never prunes is a recursive term's reference to its own CTE: PostgreSQL requires\n * it, so it is not the caller's optional filter (see `Ctx.recursiveSelf`).\n */\nfunction pruneJoins(\n q: AnyQuery,\n ctx: Ctx,\n from: ParsedSource,\n joins: ParsedJoin[],\n ctes: ParsedCte[],\n used: SqlFragment[],\n): { joins: ParsedJoin[]; ctes: ParsedCte[] } {\n if (q.pruneJoins === false) return { joins, ctes };\n const deps = new Map<string, string[]>();\n function addDeps(alias: string, refs: readonly string[]): void {\n const own = refs.filter((r) => r !== alias);\n const existing = deps.get(alias);\n if (existing) existing.push(...own);\n else deps.set(alias, own);\n }\n for (const j of joins) addDeps(j.source.alias, [...(j.userOn?.refs ?? []), ...j.source.refs]);\n for (const c of ctes) addDeps(c.alias, c.plan.outerRefs);\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 // A recursive term must keep its reference to its own CTE; PostgreSQL rejects a term without one,\n // and pruning it would quietly turn the recursion into a plain select over the base term's table.\n for (const j of joins) if (j.source.handle === ctx.recursiveSelf) markRequired(j.source.alias);\n return {\n joins: joins.filter((j) => required.has(j.source.alias)),\n ctes: ctes.filter((c) => required.has(c.alias)),\n };\n}\n\n/**\n * Names and parses each `with` entry, in declaration order.\n *\n * Each entry is in scope before the next is parsed, so a CTE can read an *earlier* sibling by name,\n * PostgreSQL's rule for a non-recursive WITH. A forward reference, or a CTE reading the query's own\n * `from`, fails as \"not in this query's from/join\", the same error any out-of-scope source gets.\n *\n * I.e. `with: [totals, ranked]` parses `totals` first, so `ranked` can join it, but not the reverse.\n */\nexport function registerCtes(q: { with?: WithInput }, ctx: Ctx, assigner: AliasAssigner): ParsedCte[] {\n const entries = q.with === undefined ? [] : Array.isArray(q.with) ? q.with : [q.with as WithSource];\n // Each entry is a `query(...)` proxy; unwrap it to its `SubqueryHandle`, the identity `ctx` keys on.\n const handles = entries.filter(isDefined).map(withEntryHandle);\n // Name every entry before parsing any body, so reading a later one is an error, not a silent inline.\n const aliases = handles.map((handle) => assigner.getLiteralAlias(handle.name ?? \"cte\"));\n handles.forEach((handle, i) => ctx.declareCte(handle, aliases[i]));\n return handles.map((handle, i) => {\n // A recursive CTE's step term reads the CTE itself, so promote it before parsing, not after.\n if (handle.recursive) ctx.promoteCte(handle);\n // Otherwise parse first, then promote: the body sees earlier siblings, but not itself or later ones.\n const plan = parseQuery(handle.q, ctx, assigner, handle.recursive ? handle : undefined);\n if (!handle.recursive) ctx.promoteCte(handle);\n return { alias: aliases[i], plan, recursive: handle.recursive };\n });\n}\n\n/** A CTE must be a table shape, so entity-mode and scalar values, which have no columns, are out. */\nfunction withEntryHandle(entry: unknown): SubqueryHandle {\n if (!isSubqueryValue(entry)) {\n fail(\n entry instanceof SubqueryExpr || isEntityQueryValue(entry)\n ? \"A `with` entry needs named columns; entity and scalar query(...) values have none\"\n : \"A `with` entry must be a query(...) value\",\n );\n }\n return readValueHandle(entry);\n}\n\n/**\n * Drops the CTEs that nothing reads, given the aliases the rest of the statement referenced.\n *\n * A CTE can only read earlier siblings, so going last to first means every CTE that could read this one\n * was already visited, and its own reads are already in `referenced`. That makes one pass enough; first\n * to last would have to repeat until the set stopped growing. `unshift` restores WITH order.\n */\nexport function pruneCtes(ctes: ParsedCte[], referenced: Set<string>): ParsedCte[] {\n const kept: ParsedCte[] = [];\n for (let i = ctes.length - 1; i >= 0; i--) {\n const cte = ctes[i];\n if (!referenced.has(cte.alias)) continue;\n for (const ref of cte.plan.outerRefs) referenced.add(ref);\n kept.unshift(cte);\n }\n return kept;\n}\n\n/**\n * Renders `WITH a AS (...), b AS (...) `, whose bindings lead the statement, as their SQL does.\n *\n * One recursive CTE makes the whole clause `WITH RECURSIVE`, PostgreSQL's rule: the keyword is on the\n * clause, not on the entry that needs it, and it does not force the other entries to be recursive.\n */\nexport function withFragment(ctes: ParsedCte[]): SqlFragment {\n const recursive = ctes.some((c) => c.recursive) ? \" RECURSIVE\" : \"\";\n const sql = ctes.map((c) => `${safeKq(c.alias)} AS (${c.plan.sql})`).join(\", \");\n return { sql: `WITH${recursive} ${sql} `, bindings: ctes.flatMap((c) => c.plan.bindings), refs: [] };\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\n/** Builds inline select expressions while leaving existing expression instances intact. */\nfunction asSelectExpr(value: unknown, where: string): BaseExpr {\n if (value instanceof BaseExpr) return value;\n if (isPlainSelect(value)) return buildExpr(value);\n return fail(`${where} must be a column, an expression, or an expression literal`);\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\n/** Keeps shorthand declarations callable-only, without recursively copying sql's own shorthand properties. */\nfunction typedSql<R>(strings: TemplateStringsArray, ...values: unknown[]): Expr<R, never> {\n return new TemplateExpr(strings, values) as unknown as Expr<R, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,SAAS,OAAO,OAAgB,OAAyB;CACvD,IAAI,iBAAiB,UAAU,OAAO;CACtC,OAAO,KAAK,GAAG,MAAM,yFAAyF;AAChH;;AAGA,SAAS,aAAa,OAAgB,OAAyB;CAC7D,IAAI,iBAAiB,UAAU,OAAO;CACtC,IAAI,cAAc,KAAK,GAAG,OAAO,UAAU,KAAK;CAChD,OAAO,KAAK,GAAG,MAAM,2DAA2D;AAClF;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;;AAGA,SAAS,SAAY,SAA+B,GAAG,QAAmC;CACxF,OAAO,IAAI,aAAa,SAAS,MAAM;AACzC"}
1
+ {"version":3,"file":"query.js","names":["#q"],"sources":["../../../src/queries/sql/query.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { type EntityMetadata, getBaseMeta } from \"src/EntityMetadata.ts\";\nimport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nimport {\n type ConditionGroup,\n type ConditionInput,\n type SqlCondition,\n type SqlPredicate,\n type UnbrandedPredicate,\n predicateBrand,\n} from \"src/queries/conditions.ts\";\nimport { filterSoftDeletes, lazyExcludedSelects, stiSubtypeFilter } from \"src/queries/entityQueryUtils.ts\";\nimport { isDeferredAliasCondition } from \"src/queries/find/DeferredAlias.ts\";\nimport { type ColumnCondition, type ParsedExpressionFilter, deepFindConditions } from \"src/queries/parsedConditions.ts\";\nimport { buildWhereClause } from \"src/queries/renderConditions.ts\";\nimport { skipCondition } from \"src/queries/skipCondition.ts\";\nimport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nimport {\n BaseExpr,\n type Expr,\n type ExprContext,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n type SqlFragment,\n TemplateExpr,\n asNode,\n deferredCondition,\n deferredSym,\n exprBrand,\n isExpr,\n orderByToSql,\n resolveDeferredConditions,\n selectKeyBrand,\n} from \"src/queries/sql/Expr.ts\";\nimport {\n type CheckInput,\n type ExprFromInput,\n type ExprInput,\n type ExpressionSources,\n type ExpressionValue,\n buildExpr,\n} from \"src/queries/sql/expressions/expression.ts\";\nimport { type CheckJoinInput, type TreeEntries, compileJoinTree } from \"src/queries/sql/JoinTree.ts\";\nimport { kq, kqStar, safeKq } from \"src/queries/sql/keywords.ts\";\nimport {\n type InQueryCondition,\n JoinTableHandle,\n type M2mJoinTable,\n type Table,\n type TableBrand,\n type TableFor,\n type TableMgmt,\n type TableSourceBrand,\n type TableSourceMgmt,\n collectionJoin,\n getTableMetadata,\n getTableMgmt,\n inQueryCondition,\n isEntityTable,\n isTable,\n m2mJoinTable,\n referenceJoinSource,\n tableMgmt,\n tableSqlName,\n} from \"src/queries/sql/Tables.ts\";\nimport type { TypeInfo } from \"src/serde/TypeInfo.ts\";\nimport { fail } from \"src/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 | undefined }[] (undefined because of the LEFT join)\n *\n * `em.query(pojo)` runs it. `select` decides the row type: a bare table returns entities, an array of\n * columns or a `{ key: expr }` object returns typed POJOs, and a bare subquery returns its 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 are\n * keyword keys (`{ left: b, on }`), 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: readonly (QueryCondition | undefined)[]; or?: never; exists?: never; notExists?: never }\n | { or: readonly (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]: TableSourceBrand<string> }\n | { readonly [subqueryBrand]: SubqueryBrand<any, string> };\n\n/** A generated entity table or table-shaped subquery that supports `select: source`. */\ntype SelectableQuerySource =\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 QueryJoinList = readonly (QueryJoin | undefined)[];\n\n/** A flat SQL join list or a domain relationship tree rooted at from. */\nexport type QueryJoinInput = QueryJoinList | Readonly<Record<string, unknown>>;\n\n/**\n * Resolves tree bindings to join types for scope and result nullability.\n * Deferring the extracted entry union avoids expanding recursive constraints in generic query signatures.\n */\nexport type ResolvedJoins<F, J> = J extends QueryJoinList\n ? J\n : F extends TableFor<infer T extends Entity>\n ? TreeEntries<T, J> extends infer E\n ? readonly Extract<E, QueryJoin>[]\n : never\n : [];\n\n/**\n * A CTE declaration: a `query(...)` value with named columns, i.e. a POJO or set-operation select.\n *\n * Entity-mode and scalar `query(...)` shapes are excluded: a CTE must be a table shape, so it needs\n * columns.\n */\nexport type WithSource = Subquery<unknown, string>;\n\n/** One CTE or an array of them; an `undefined` entry prunes, like any other clause. */\nexport type WithInput = WithSource | readonly (WithSource | undefined)[];\n\n/** How a recursive CTE combines its two terms: `UNION ALL` keeps every row, `UNION` drops duplicates. */\nexport interface RecursiveOptions {\n /** Defaults to `\"all\"`. `\"distinct\"` emits UNION, which stops a cyclic graph from looping forever. */\n union?: \"all\" | \"distinct\";\n}\n\n/** An expression order-by entry, also returned by `expr.asc()` and `expr.desc()`. An undefined order prunes it. */\nexport type ExpressionOrderBy = {\n readonly sort: ExprLike<unknown>;\n readonly order: \"ASC\" | \"DESC\" | undefined;\n readonly nulls?: \"first\" | \"last\";\n};\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 `expr.asc()`/`expr.desc()` or `{ sort, order }` entries in the array form.\n */\nexport type OrderByKeys<S> =\n // If S is an array select, allow ordering by each selected column's field name.\n S extends readonly NamedSelectExpression[]\n ? { readonly [K in SelectKey<S[number]>]?: OrderByDirection | undefined }\n : // Otherwise, if this is `select: a` entity mode, allow ordering by the entity's expression fields.\n S extends { readonly [tableMgmt]: { readonly __entity: infer T } }\n ? T extends Entity\n ? {\n readonly [K in keyof Table<T> as Table<T>[K] extends ExprLike<any> ? K : never]?:\n | OrderByDirection\n | undefined;\n }\n : never\n : // Otherwise, a scalar expression select has no named result fields to order by.\n S extends ExprLike<unknown>\n ? never\n : // Otherwise, this is POJO mode, so allow ordering by its select keys.\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/** Prevents a selected keyed sort from being silently mixed into an expression entry. */\ntype CheckedExpressionOrderBy<S> = ExpressionOrderBy &\n (string extends OrderByKey<S>\n ? unknown\n : [S] extends [{ readonly [tableMgmt]: unknown }]\n ? unknown\n : { readonly [K in Exclude<OrderByKey<S>, keyof ExpressionOrderBy>]?: never });\n\n/** The select shapes: a source, scalar expression, named column array, or POJO naming result columns. */\nexport type QuerySelect =\n | SelectableQuerySource\n | ExprLike<unknown>\n | readonly NamedSelectExpression[]\n | Record<string, SelectExpression>;\n\n/** A named projection value may be an existing expression or an inline expression literal. */\nexport type SelectExpression = ExprLike<unknown> | ExprInput;\n\n/** A physical or subquery column that retains the field name used for array-select result rows. */\nexport type NamedSelectExpression = ExprLike<unknown> & { readonly [selectKeyBrand]: string };\n\n/** Extracts the table property name carried by a column expression for array selects. */\ntype SelectKey<S> = S extends { readonly [selectKeyBrand]: infer K extends string } ? K : never;\n\n/** Checks expression literals only inside named projections. */\ntype CheckSelect<S> = S extends QuerySource | ExprLike<unknown> | readonly NamedSelectExpression[]\n ? unknown\n : { readonly [K in keyof S]: S[K] extends ExprInput ? CheckInput<S[K]> : unknown };\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 QueryJoinInput = QueryJoinInput> {\n /**\n * CTEs to include in a `WITH` clause, declared as `query(...)` values; either a single value or an array.\n *\n * I.e. `{ with: bookStats, from: a, join: [{ left: bookStats, on: ... }], select: { n: bookStats.n } }`.\n *\n * An `undefined` entry is ignored, and a CTE that nothing else in the query references will be pruned,\n * the same pruning `join` gets (see \"Pruning\"); `pruneJoins: false` keeps every CTE.\n */\n with?: WithInput;\n /** A flat join list, or a domain relationship tree rooted at the entity table in from. */\n join?: J;\n /**\n * An `{ and: [...] }` or `{ or: [...] }` group, an exists/notExists query, or a bare condition such as `a.age.gte(18)`.\n *\n * Arrays are shorthand for `{ and: [...] }`; undefined conditions are pruned.\n */\n where?: QueryCondition | readonly (QueryCondition | undefined)[];\n groupBy?: readonly ExprLike<any>[];\n having?: QueryCondition;\n select: S;\n orderBy?:\n | readonly (CheckedExpressionOrderBy<S> | OrderByKeys<S> | undefined)[]\n | CheckedExpressionOrderBy<S>\n | 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 QueryJoinInput = QueryJoinInput>\n extends Clauses<S, J>, Partial<Record<SetOperation | MutationKey | \"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, SelectExpression> | 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 /** CTEs for the combined query, declared once and in scope for every operand; see `Clauses.with`. */\n readonly with?: WithInput;\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 | \"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 | undefined }`, 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<\n S,\n ResolvedJoins<Q[keyof Q & \"from\"], \"join\" extends keyof Q ? Extract<Q[keyof Q & \"join\"], QueryJoinInput> : []>\n >\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 | undefined }` produce `{ name: string | undefined }`. EXCEPT with those Author names on\n * the left retains `{ name: string }`; it neither adds the right side's absence 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 */\nexport type 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 ? CheckJoinInput<Q[\"from\"], \"join\" extends keyof Q ? Exclude<Q[keyof Q & \"join\"], undefined> : []> & {\n readonly [K in keyof Q]: K extends \"select\"\n ? CheckSelect<Q[K]>\n : K extends keyof Clauses | \"from\" | \"as\"\n ? unknown\n : never;\n }\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 \"with\" | \"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/** Adds default reference targets whose source is already nullable; explicit INNER joins do not inherit. */\ntype InheritedLeft<X, Left> = X extends { readonly [referenceJoinSource]: infer Src; readonly inner: infer A }\n ? // Extract finds this reference's source among nullable aliases. No overlap means its target stays INNER.\n // I.e. Src = \"Book\" and Left = \"Book\" adds NameOf<A> = \"Author\"; Left = \"Publisher\" adds nothing.\n [Extract<Src, Left>] extends [never]\n ? never\n : NameOf<A>\n : never;\n\n/**\n * Finds all aliases that can be NULL through LEFT joins and subsequent reference joins.\n * I.e. LEFT Book adds Author via Book.author.as(a), then further required references inherit Author's NULL.\n * Alias-name collisions are conservative, as they are for explicit LEFT joins; runtime uses exact handles.\n */\ntype NullableSources<X, Left = LeftJoined<X>> =\n // X is J[number], the union of entries in em.query's `join: [...]` array. A variable like\n // `const joins = [j1, j2]` normally infers an array, not a tuple, so this recursive conditional type\n // works over that union instead of walking tuple positions. LeftJoined<X> seeds Left with the aliases\n // from `left: ...` entries. InheritedLeft<X, Left> discovers reference targets whose sources are in Left.\n // Exclude removes names already in Left. If all were already known, stop recursing and use Left as the value;\n // otherwise, add the newly discovered LEFT-joined aliases to our set and recurse.\n [Exclude<InheritedLeft<X, Left>, Left>] extends [never] ? Left : NullableSources<X, Left | InheritedLeft<X, Left>>;\n\n/**\n * Asks: is this expression's source key among the LEFT-joined sources in this query's join list? If\n * yes, SQL can return 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 `NullableSources<J[number]>`; with an inner join it stays `number`.\n * Default references from nullable sources are included transitively.\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 table whose entity type is not statically known) 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 QueryJoinList> = string extends Src\n ? [NullableSources<J[number]>] extends [never]\n ? R\n : R | null\n : [Extract<Src, NullableSources<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 * - column array mode uses each column's field name as the result key\n * - POJO mode is a mapped type over the select keys, with left-join nullability applied\n */\nexport type QueryRow<S, J extends QueryJoinList = []> = S extends {\n readonly [tableMgmt]: { readonly __entity: infer T };\n}\n ? T\n : S extends { readonly [subqueryBrand]: { readonly __row: infer R } }\n ? R\n : S extends ExprLike<unknown>\n ? QueryResultValue<ExpressionValue<S, J>>\n : // If S is an array select, use each column's field name as its result key.\n S extends readonly NamedSelectExpression[]\n ? {\n // Map each selected column to its field name and decoded value type. Remove readonly because\n // const-tuple inference is an input detail and must not make returned row properties readonly.\n -readonly [E in S[number] as SelectKey<E>]: QueryResultValue<ExpressionValue<E, J>>;\n }\n : {\n // Inline inputs retain readonly tuples for inference; result rows are still mutable.\n -readonly [K in keyof S]: S[K] extends SelectExpression\n ? QueryResultValue<ExpressionValue<S[K] extends ExprInput ? ExprFromInput<S[K]> : S[K], J>>\n : never;\n };\n\n/**\n * Converts top-level SQL NULL to Joist's public undefined convention.\n *\n * Column metadata and expressions retain `T | null` because null is an explicit SQL value used by\n * predicates, assignments, and functions such as COALESCE. Undefined instead means an omitted input.\n * Keeping that distinction also lets reusable queries become SQL expressions without changing domains.\n * The conversion therefore happens only at the executed-row boundary; nested array and JSON nulls remain null.\n */\ntype QueryResultValue<V> = Exclude<V, null> | (null extends V ? undefined : never);\n\n/**\n * Restores SQL NULL when a public query result is reused as an expression or mutation source.\n *\n * A future alternative is to retain both domains on every expression, i.e.\n * `Expr<Sql, Src extends string = string, Result = QueryResultValue<Sql>>`. QueryRow could then use Result\n * while predicates and reusable queries use Sql, avoiding this reverse conversion without making the\n * common expression declaration verbose.\n */\nexport type SqlExpressionValue<V> = Exclude<V, undefined> | (undefined extends V ? null : never);\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} & {\n // For each field in row shape R, i.e. `firstName` in `{ firstName: string }`, expose an expression\n // that retains the field name for array selects.\n readonly [K in keyof R]: Expr<SqlExpressionValue<R[K]>, Name> & { readonly [selectKeyBrand]: Extract<K, string> };\n};\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<SqlExpressionValue<R> | null, never> & { readonly [scalarQueryBrand]: true };\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 QueryJoinList, Name extends string> = S extends {\n readonly [tableMgmt]: { readonly __entity: infer T extends Entity };\n}\n ? EntityQuery<T>\n : S extends ExprLike<unknown>\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 QueryJoinList> = 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 QueryJoinInput> = [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 [readonly NamedSelectExpression[]]\n ? // For an array select, verify that every selected column belongs to a source in from/join.\n {\n select: { [K in keyof S]: CheckExpressionScope<S[K], InScope<F, ResolvedJoins<F, J>>> };\n }\n : [S] extends [Record<string, SelectExpression>]\n ? // For a POJO select, verify that every named expression uses only sources in from/join.\n {\n select: {\n [K in keyof S]: CheckExpressionScope<S[K], InScope<F, ResolvedJoins<F, J>>>;\n };\n }\n : unknown;\n\n/** Includes columns nested in inline CASE values and fallbacks in the existing scope check. */\ntype CheckExpressionScope<V, Scope> =\n string extends ExpressionSources<V>\n ? unknown\n : [Exclude<ExpressionSources<V>, Scope>] extends [never]\n ? unknown\n : `table '${Exclude<ExpressionSources<V>, Scope> & string}' is not in from/join`;\n\n/** The one argument type `query()` and `em.query()` share: a `Query` POJO plus its source, name, and checks. */\nexport type QueryArg<\n F extends QuerySource,\n S extends QuerySelect,\n J extends QueryJoinInput,\n Name extends string,\n> = Query<S, J> & {\n from: F;\n as?: Name;\n} & CheckScope<S, F, J> &\n NoInfer<CheckJoinInput<F, J>> &\n NotWidened<S> & { select: CheckSelect<NoInfer<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 const S extends QuerySelect = never,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n>(q: QueryArg<F, S, J, Name>): QueryValue<S, ResolvedJoins<F, J>, Name>;\nexport function query(q: AnyReadQuery): unknown {\n return createQueryValue(q);\n}\n\n/**\n * Builds a query value only when its user-supplied `where` or join-tree filters survive pruning.\n *\n * Missing or empty conditions prune the value, including nested groups and `pruneIfUndefined`.\n * Alias-only joins, HAVING, and implicit soft-delete/STI conditions do not keep the value alive.\n *\n * I.e. `queryMaybe({ from: b, where: b.authorId.eq(enabled ? a.id : undefined), select: b.id })`\n * returns `undefined` when `enabled` is false, so an enclosing `notExists` also prunes.\n */\nexport function queryMaybe<\n F extends QuerySource,\n const S extends QuerySelect = never,\n J extends QueryJoinInput = [],\n Name extends string = \"?\",\n>(q: QueryArg<F, S, J, Name>): QueryValue<S, ResolvedJoins<F, J>, Name> | undefined {\n return createMaybeQueryValue(q) as QueryValue<S, ResolvedJoins<F, J>, Name> | undefined;\n}\n\n/** Applies queryMaybe's structural pruning before creating any kind of read-query value. */\nfunction createMaybeQueryValue(q: AnyQuery): unknown | undefined {\n const normalized = normalizeQueryJoins(q);\n const where = normalizeWhere(normalized.where);\n checkCondition(where);\n return isPrunedQueryCondition(where) ? undefined : createQueryValue(normalized);\n}\n\n/**\n * Declares a `WITH RECURSIVE` CTE from its two terms, and returns the CTE as a readable value.\n *\n * `base` is the non-recursive term, which seeds the rows and, as in PostgreSQL, supplies the CTE's\n * columns. `step` is the recursive term: it receives the CTE itself, so it can join back to the rows\n * found so far. The two terms are combined with UNION ALL, or UNION when `union: \"distinct\"` drops\n * duplicates, which is how a cyclic graph is kept from looping forever.\n *\n * ```ts\n * const [a] = tables(Author);\n * const tree = recursiveQuery(\n * \"tree\",\n * { from: a, where: a.mentor_id.isNull(), select: { id: a.id, mentorId: a.mentor_id } },\n * (self) => ({\n * from: a,\n * join: [{ inner: self, on: a.mentor_id.eq(self.id) }],\n * select: { id: a.id, mentorId: a.mentor_id },\n * }),\n * );\n * const rows = await em.query({ with: tree, from: tree, select: tree });\n * ```\n *\n * Unlike `query()`, the name is required, because the step term must name it.\n */\nexport function recursiveQuery<\n Name extends string,\n F extends QuerySource,\n const S extends QuerySelect,\n J extends QueryJoinInput,\n>(\n name: Name,\n base: QueryArg<F, S, J, Name>,\n step: (self: Subquery<QueryRow<S, ResolvedJoins<F, J>>, Name>) => SetOperand,\n opts: RecursiveOptions = {},\n): Subquery<QueryRow<S, ResolvedJoins<F, J>>, Name> {\n if (typeof name !== \"string\" || name === \"\") fail(\"A recursive CTE needs a name\");\n if (opts.union !== undefined && opts.union !== \"all\" && opts.union !== \"distinct\") {\n fail(\"A recursive CTE's union must be 'all' or 'distinct'\");\n }\n // Start on the base term so `self`'s columns resolve while the step term is still being built.\n const handle = new SubqueryHandle(toQuery(base), true);\n if (handle.output().kind !== \"pojo\") fail(\"A recursive CTE's base term needs a named projection\");\n const self = newSubqueryProxy(handle) as Subquery<QueryRow<S, ResolvedJoins<F, J>>, Name>;\n const operands = [base, step(self)] as unknown as readonly SetOperand[];\n handle.setBody(opts.union === \"distinct\" ? { union: operands, as: name } : { unionAll: operands, as: name });\n return self;\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; prefer the table's own `column`, which keeps its source key.\n * a.column<string>(\"ts_search\")\n * sql.condition`${a.column(\"ts_search\")} @@ plainto_tsquery(${term})`\n * ```\n */\nexport function sql<R = unknown>(strings: TemplateStringsArray, ...values: unknown[]): Expr<R, never> {\n return typedSql<R>(strings, ...values);\n}\n\n/** Shorthand for `sql<number>`; does not cast or convert the SQL result. */\nsql.number = typedSql<number>;\n\n/** Shorthand for `sql<number | null>`; does not cast or convert the SQL result. */\nsql.numberOrNull = typedSql<number | null>;\n\n/** Shorthand for `sql<number[]>`; does not cast or convert the SQL result. */\nsql.numberArray = typedSql<number[]>;\n\n/** Shorthand for `sql<number[] | null>`; does not cast or convert the SQL result. */\nsql.numberArrayOrNull = typedSql<number[] | null>;\n\n/** Shorthand for `sql<string>`; does not cast or convert the SQL result. */\nsql.string = typedSql<string>;\n\n/** Shorthand for `sql<string | null>`; does not cast or convert the SQL result. */\nsql.stringOrNull = typedSql<string | null>;\n\n/** Shorthand for `sql<string[]>`; does not cast or convert the SQL result. */\nsql.stringArray = typedSql<string[]>;\n\n/** Shorthand for `sql<string[] | null>`; does not cast or convert the SQL result. */\nsql.stringArrayOrNull = typedSql<string[] | null>;\n\n/** Shorthand for `sql<boolean>`; does not cast or convert the SQL result. */\nsql.boolean = typedSql<boolean>;\n\n/** Shorthand for `sql<boolean | null>`; does not cast or convert the SQL result. */\nsql.booleanOrNull = typedSql<boolean | null>;\n\n/** Shorthand for `sql<boolean[]>`; does not cast or convert the SQL result. */\nsql.booleanArray = typedSql<boolean[]>;\n\n/** Shorthand for `sql<boolean[] | null>`; does not cast or convert the SQL result. */\nsql.booleanArrayOrNull = typedSql<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/**\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/**\n * Parses a read that sits inside another statement, i.e. an INSERT's SELECT source, so it resolves that\n * statement's CTEs and shares its alias space instead of generating names that could collide with them.\n */\nexport function parseNestedQuery(arg: unknown, parent: Ctx, assigner: AliasAssigner): Plan {\n if (arg instanceof SubqueryExpr) fail(\"Scalar query values are expressions, not executable read inputs\");\n return parseQuery(toQuery(arg), parent, assigner);\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 joins?: QueryJoinList,\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const output = joinedOutput(projectionOutput(select), joins);\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) => decodeValue(expr, 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 #q: AnyReadQuery;\n\n constructor(\n q: AnyReadQuery,\n readonly recursive = false,\n ) {\n this.#q = q;\n }\n\n get q(): AnyReadQuery {\n return this.#q;\n }\n\n /**\n * Gives a recursive CTE its finished body. `recursiveQuery` starts the handle on its base term, so\n * the step term can read the CTE's columns while the body that will hold that step is still being\n * built. The base term supplies the CTE's columns either way, PostgreSQL's rule for a recursive WITH.\n */\n setBody(q: AnyReadQuery): void {\n if (!this.recursive) fail(\"Only a recursive CTE replaces its body\");\n this.#q = q;\n }\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 get [selectKeyBrand](): string {\n return this.key;\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, SelectExpression> {\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): TableSourceMgmt | 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 \"with\",\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 }\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], \"with\", \"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 q = normalizeQueryJoins(q);\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 (Array.isArray(select)) {\n if (select.length === 0) fail(\"A column array projection must not be empty\");\n const columns: [string, BaseExpr][] = select.map((value, index) => {\n const expr = asExpr(value, `select[${index}]`);\n const key = (expr as BaseExpr & { readonly [selectKeyBrand]?: unknown })[selectKeyBrand];\n if (typeof key !== \"string\") fail(`select[${index}] must be a physical or subquery column`);\n return [key, expr];\n });\n const keys = new Set(columns.map(([key]) => key));\n if (keys.size !== columns.length) fail(\"A column array projection must not contain duplicate field names\");\n return { kind: \"pojo\", columns };\n }\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, asSelectExpr(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 SQL nullability 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: QueryJoinList | undefined): QueryOutput {\n if (!joins?.some((join) => join?.left)) return output;\n const left = new Set<object>();\n for (const join of resolveReferenceJoins(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/**\n * Resolves reference joins in declaration order without changing reusable join entries.\n * Only .as() carries a source handle; explicit INNER joins retain their filtering semantics.\n * I.e. LEFT Book followed by Book.author.as(a) adds Author to the set of nullable handles.\n */\nfunction resolveReferenceJoins(joins: QueryJoinList | undefined): QueryJoin[] {\n const left = new Set<object>();\n return (joins ?? []).filter(isDefined).map((join) => {\n const source = (join as QueryJoin & { [referenceJoinSource]?: object })[referenceJoinSource];\n if (join.inner && source && left.has(source)) {\n const { inner, ...rest } = join;\n const resolved = { ...rest, left: inner };\n left.add(handleOf(inner));\n return resolved;\n }\n if (join.left) left.add(handleOf(join.left));\n return join;\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(\n q: SetQuery<readonly SetOperand[]>,\n parent: Ctx | undefined,\n assigner: AliasAssigner,\n recursiveSelf?: SubqueryHandle,\n): Plan {\n const [operation, operands] = setOperands(q);\n const output = queryOutput(q);\n // A set query's CTEs need a scope of their own, between the enclosing query and the operands.\n const ctx = new Ctx(assigner, parent);\n if (recursiveSelf) ctx.setRecursiveSelf(recursiveSelf);\n const ctes = registerCtes(q, ctx, assigner);\n const plans = operands.map((operand) => parseQuery(toQuery(operand), ctx, 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 const keptCtes = pruneCtes(ctes, new Set(plans.flatMap((plan) => plan.outerRefs)));\n if (keptCtes.length > 0) {\n const clause = withFragment(keptCtes);\n sql = clause.sql + sql;\n bindings.unshift(...clause.bindings);\n }\n // An operand that reads one of our CTEs resolved that name here, not in the enclosing query, so the\n // name must not go out in `outerRefs`. That list is how this query tells the enclosing one which of\n // *its* aliases we depend on, and the enclosing query keeps those joins alive rather than pruning\n // them; a CTE name in there would pin a join that has nothing to do with it.\n const cteAliases = new Set(ctes.map((cte) => cte.alias));\n const outerRefs = [...ctx.outerRefs, ...plans.flatMap((plan) => plan.outerRefs)];\n return {\n sql,\n bindings,\n outerRefs: [...new Set(outerRefs.filter((ref) => !cteAliases.has(ref)))],\n output,\n decodeRows: (_, rows) => rows.map((row) => decodeRow(row, output.columns)),\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 /**\n * The subset of `aliases` that are CTE names. A `from`/`join` on one of these emits just the name,\n * i.e. `FROM book_stats`, where an ordinary `query(...)` value emits its whole body inline, i.e.\n * `FROM (SELECT ...) AS sq`.\n */\n private ctes = new Map<object, string>();\n /**\n * `with` entries named but not yet turned into SQL. `registerCtes` names every entry first, then\n * generates the bodies one at a time, so while one body is being generated the entries after it sit\n * here. Reading one of those is a forward reference.\n */\n private pendingCtes = new Map<object, string>();\n /** CTEs already read by this query's `from`/`join`, so a second read fails instead of colliding. */\n private usedCtes = new Set<object>();\n /** The recursive CTE whose body this query is part of, if any; see `recursiveSelf`. */\n private ownRecursiveSelf: SubqueryHandle | undefined;\n readonly outerRefs = new Set<string>();\n\n constructor(\n readonly assigner: AliasAssigner,\n private parent: Ctx | undefined,\n ) {}\n\n /**\n * One handle can hold only one alias per query, so a value used twice must be told apart, not\n * silently collapsed into the second registration's alias.\n */\n register(handle: object, alias: string): void {\n if (this.aliases.has(handle)) {\n fail(\n `${describeHandle(handle)} is already in this query's \\`with\\`/\\`from\\`/\\`join\\`; use a separate table(...)/query(...) value for each use`,\n );\n }\n this.aliases.set(handle, alias);\n }\n\n /** Names every `with` entry up front, so a CTE reading a later sibling is reported, not inlined. */\n declareCte(handle: object, alias: string): void {\n this.pendingCtes.set(handle, alias);\n }\n\n /** Brings a pending CTE into scope, for the sources and columns that may now read it. */\n promoteCte(handle: object): void {\n const alias = this.pendingCtes.get(handle) ?? fail(\"CTE was not declared\");\n this.pendingCtes.delete(handle);\n this.ctes.set(handle, alias);\n this.register(handle, alias);\n }\n\n /**\n * The CTE name for `handle`, looking in the enclosing queries too, because a CTE is in scope for the\n * whole statement.\n *\n * Unlike `aliasFor`, a hit in an enclosing query is not added to `outerRefs`: reading a CTE by name\n * is not a correlated reference, so it must not keep an enclosing join alive.\n */\n cteAliasFor(handle: object): string | undefined {\n return this.ctes.get(handle) ?? this.parent?.cteAliasFor(handle);\n }\n\n /**\n * The recursive CTE this query's terms belong to, inherited from the enclosing query.\n *\n * PostgreSQL requires a recursive term to reference its own CTE, so that reference is not optional\n * and must survive pruning, unlike an ordinary explicit join that nothing else reads.\n */\n get recursiveSelf(): SubqueryHandle | undefined {\n return this.ownRecursiveSelf ?? this.parent?.recursiveSelf;\n }\n\n setRecursiveSelf(handle: SubqueryHandle): void {\n this.ownRecursiveSelf = handle;\n }\n\n /** Whether `handle` is a CTE with no SQL yet, i.e. itself or a later `with` entry. */\n isPendingCte(handle: object): boolean {\n return this.pendingCtes.has(handle) || (this.parent?.isPendingCte(handle) ?? false);\n }\n\n /**\n * Fails if this query already reads `handle`. A `Ctx` maps each handle to a single alias, so two\n * reads of one CTE value would render as the same name, i.e. `FROM tree JOIN tree`, and neither the\n * SQL nor a column expression could say which one it meant. Each read needs its own `query(...)`.\n *\n * Only this query is checked, not the enclosing ones: a nested subquery has its own FROM, so reading\n * the same CTE in there is fine.\n */\n useCte(handle: object): void {\n if (this.usedCtes.has(handle)) {\n fail(\n `${describeHandle(handle)} is already in this query's \\`from\\`/\\`join\\`; use a separate query(...) value for each use`,\n );\n }\n this.usedCtes.add(handle);\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: QueryCondition): 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 TableSourceMgmt).tableName}`;\n return \"Table\";\n}\n\ninterface ParsedSource {\n handle: TableSourceMgmt | 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\n/** A parsed `with` entry: the CTE's name and its body, ready to render into the WITH clause. */\nexport interface ParsedCte {\n alias: string;\n plan: Plan;\n /** A recursive CTE reads itself, and makes the whole clause `WITH RECURSIVE`. */\n recursive: boolean;\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(\n q: AnyReadQuery,\n parent: Ctx | undefined,\n assigner: AliasAssigner,\n recursiveSelf?: SubqueryHandle,\n): Plan {\n validateReadQuery(q);\n if (isSetQuery(q)) return parseSetQuery(q, parent, assigner, recursiveSelf);\n q = normalizeQueryJoins(q);\n const ctx = new Ctx(assigner, parent);\n if (recursiveSelf) ctx.setRecursiveSelf(recursiveSelf);\n const joinEntries = resolveReferenceJoins(q.join);\n\n // 0. Compile CTEs first: they are in scope for every source below, and cannot read those sources.\n const ctes = registerCtes(q, ctx, assigner);\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 userJoins: 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 cti = ctiEntityPlan(q, from, assigner);\n const joins = [...cti.joins, ...userJoins];\n const sti = stiEntityPlan(q, from);\n const { selects, decodeRows, output } = selectsToSql(q, ctx, from, cti.selects ?? sti.selects);\n const fromInjected = [...injectedConditions(from, softDeletes), ...sti.conditions];\n const predicate = normalizeWhere(q.where);\n const where = conditionToSql(fromInjected.length > 0 ? { and: [predicate, ...fromInjected] } : predicate, 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 { joins: kept, ctes: keptCtes } = pruneJoins(\n q,\n ctx,\n from,\n joins,\n ctes,\n [...selects, ...groupBys, ...orderBys, where, having].filter(isDefined),\n );\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 // WITH leads the statement, so its bindings must be pushed before the SELECT's.\n if (keptCtes.length > 0) out.push(withFragment(keptCtes));\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 const cteAlias = ctx.cteAliasFor(handle);\n if (cteAlias) {\n ctx.useCte(handle);\n // A declared CTE is read by its name; the `with` that declared it already parsed its body.\n return () => ({\n handle,\n alias: cteAlias,\n sql: safeKq(cteAlias),\n bindings: [],\n refs: [],\n entitySelects: [],\n meta: undefined,\n });\n }\n if (ctx.isPendingCte(handle)) {\n fail(\n `${describeHandle(handle)} is declared later in this query's \\`with\\`; a CTE can only read earlier ones, and cannot read itself`,\n );\n }\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 mgmt = getTableMgmt(source as any);\n const { tableName } = mgmt;\n const meta = \"meta\" in mgmt ? mgmt.meta : undefined;\n const alias = assigner.getAlias(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 ? [] : meta.hasLazyColumns ? lazyExcludedSelects(meta, alias) : [kqStar(alias)];\n return {\n handle,\n alias,\n sql: `${tableSqlName(mgmt)} 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 entitySelects?: SqlFragment[],\n): { selects: SqlFragment[]; decodeRows: Plan[\"decodeRows\"]; output: QueryOutput } {\n const { select } = q;\n if (isTable(select) && !isEntityTable(select)) {\n fail(\"A custom table cannot be selected as an entity; select its columns individually\");\n }\n if (isEntityTable(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 = entitySelects ?? 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 return projectionToSql(select, ctx, q.join);\n}\n\n/**\n * Builds the mandatory CTI joins and flat row projection needed by entity hydration.\n *\n * The joins use the same ParsedJoin path as user joins, but `keep: true` makes them survive pruning.\n * They are generated only for an entity selection of the from source; POJO and scalar reads keep their\n * physical-table behavior. User source aliases have already been allocated, so the preferred `_bN` and\n * `_sN` aliases can be made unique before their projection fragments are built.\n */\nfunction ctiEntityPlan(\n q: AnyQuery,\n from: ParsedSource,\n assigner: AliasAssigner,\n): { joins: ParsedJoin[]; selects: SqlFragment[] | undefined } {\n // CTI expansion belongs only to entity mode. Column projections keep their explicit physical-table shape.\n if (!isEntityTable(q.select) || from.handle !== getTableMgmt(q.select)) return { joins: [], selects: undefined };\n const meta = getTableMetadata(q.select);\n if (meta.inheritanceType !== \"cti\") return { joins: [], selects: undefined };\n\n // Start with the selected table. Hydration expects one flat row containing every CTI table's columns.\n const joins: ParsedJoin[] = [];\n const selects: SqlFragment[] = from.entitySelects.map((sql) => ({ sql, bindings: [], refs: [from.alias] }));\n\n // A subtype starts from its own table, so join each base table to recover inherited fields.\n for (const [i, baseMeta] of meta.baseTypes.entries()) {\n const alias = assigner.getLiteralAlias(`${from.alias}_b${i}`);\n joins.push(ctiJoin(from, baseMeta, alias));\n selects.push(...entitySelectFragments(baseMeta, alias));\n }\n\n // A base type needs every subtype table both for subtype fields and for detecting the concrete class.\n // Record each subtype column's aliases while visiting them because sibling tables can reuse a column name.\n const subtypeColumns = new Map<string, string[]>();\n for (const [i, subtypeMeta] of meta.subTypes.entries()) {\n const alias = assigner.getLiteralAlias(`${from.alias}_s${i}`);\n joins.push(ctiJoin(from, subtypeMeta, alias));\n selects.push(...entitySelectFragments(subtypeMeta, alias));\n for (const field of Object.values(subtypeMeta.fields)) {\n if (field.fieldName === \"id\" || !field.serde || (field.kind === \"primitive\" && field.lazy)) continue;\n for (const column of field.serde.columns) {\n const aliases = subtypeColumns.get(column.columnName);\n if (aliases) aliases.push(alias);\n else subtypeColumns.set(column.columnName, [alias]);\n }\n }\n }\n\n // Joined `table.*` projections can overwrite id, so finish with the selected table's canonical entity id.\n selects.push({\n sql: `${safeKq(from.alias)}.${kq(\"id\")} AS ${kq(\"id\")}`,\n bindings: [],\n refs: [from.alias],\n });\n // Collapse same-named sibling fields into the one column name that entity hydration reads.\n for (const [column, aliases] of subtypeColumns) {\n if (aliases.length < 2) continue;\n selects.push({\n sql: `COALESCE(${aliases.map((alias) => `${safeKq(alias)}.${kq(column)}`).join(\", \")}) AS ${kq(column)}`,\n bindings: [],\n refs: aliases,\n });\n }\n // The first present subtype row identifies the concrete constructor; `_` means the base table itself.\n if (meta.subTypes.length > 0) {\n const subtypeAliases = joins.slice(meta.baseTypes.length).map((join) => join.source.alias);\n selects.push({\n sql: `CASE ${subtypeAliases.map((alias) => `WHEN ${safeKq(alias)}.${kq(\"id\")} IS NOT NULL THEN ?`).join(\" \")} ELSE '_' END AS ${kq(\"__class\")}`,\n bindings: meta.subTypes.map((subtype) => subtype.type),\n refs: subtypeAliases,\n });\n }\n return { joins, selects };\n}\n\n/** Adds the discriminator projection and subtype filter required by STI entity hydration. */\nfunction stiEntityPlan(\n q: AnyQuery,\n from: ParsedSource,\n): { selects: SqlFragment[] | undefined; conditions: ColumnCondition[] } {\n // As with CTI, only a table selected from itself requests entity hydration and inheritance behavior.\n if (!isEntityTable(q.select) || from.handle !== getTableMgmt(q.select)) return { selects: undefined, conditions: [] };\n const meta = getTableMetadata(q.select);\n if (meta.inheritanceType !== \"sti\") return { selects: undefined, conditions: [] };\n\n // STI stores the complete family in one row, so the ordinary physical projection already supplies its fields.\n const selects: SqlFragment[] = from.entitySelects.map((sql) => ({ sql, bindings: [], refs: [from.alias] }));\n // `table.*` includes the discriminator. An explicit lazy-safe projection might not, so append it for hydration.\n if (!(from.entitySelects.length === 1 && from.entitySelects[0] === kqStar(from.alias))) {\n const discriminator = getBaseMeta(meta).stiDiscriminatorColumnName!;\n selects.push({\n sql: `${safeKq(from.alias)}.${kq(discriminator)} AS ${kq(discriminator)}`,\n bindings: [],\n refs: [from.alias],\n });\n }\n // Root reads may hydrate any concrete class. Subtype reads must exclude sibling rows to preserve their result type.\n const condition = stiSubtypeFilter(meta, from.alias);\n return { selects, conditions: condition ? [condition] : [] };\n}\n\n/** Creates one mandatory CTI join through the selected source's primary key. */\nfunction ctiJoin(from: ParsedSource, meta: EntityMetadata, alias: string): ParsedJoin {\n const on = {\n sql: `${safeKq(from.alias)}.${kq(\"id\")} = ${safeKq(alias)}.${kq(\"id\")}`,\n bindings: [],\n refs: [from.alias, alias],\n };\n return {\n kind: \"left\",\n source: {\n handle: { tableName: meta.tableName, meta } as TableMgmt,\n alias,\n sql: `${kq(meta.tableName)} AS ${safeKq(alias)}`,\n bindings: [],\n refs: [],\n entitySelects: [],\n meta,\n },\n userOn: on,\n fullOn: on,\n keep: true,\n };\n}\n\n/** Selects one physical CTI table while preserving lazy-field exclusions. */\nfunction entitySelectFragments(meta: EntityMetadata, alias: string): SqlFragment[] {\n const selects = meta.hasLazyColumns ? lazyExcludedSelects(meta, alias) : [kqStar(alias)];\n return selects.map((sql) => ({ sql, bindings: [], refs: [alias] }));\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 = decodeValue(expr, 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\n/** Decodes a top-level projected SQL NULL using Joist's undefined convention. */\nfunction decodeValue(expr: BaseExpr, value: unknown): unknown {\n return value === null ? undefined : expr.decode(value);\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 entry.\n *\n * Expression entries retain bindings and alias references for join pruning. Undefined entries and\n * directions are omitted before expression references are collected.\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 sort, order, or nulls, so distinguish by the sort value.\n if (isExpr(entry.sort)) {\n const fragment = orderByToSql(entry, ctx);\n if (fragment) result.push(fragment);\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)\n ? select[subqueryBrand].columnKeys()\n : projectionOutput(select).columns.map(([key]) => key);\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\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 (isInQueryCondition(value)) {\n const q = normalizeQueryJoins(toQuery(value[inQueryCondition].query) as AnyQuery);\n checkCondition(normalizeWhere(q.where));\n return;\n }\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 (isInQueryCondition(cond)) {\n const { column, query } = cond[inQueryCondition];\n const value = createMaybeQueryValue(query as AnyQuery);\n if (value === undefined) return undefined;\n if (!isExpr(value)) return fail(\"An in query literal must select one expression\");\n return column.in(value);\n }\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/**\n * Checks structural pruning without resolving SQL or correlated aliases.\n *\n * Keeps individual predicates and applies ConditionBuilder's pruning policy (i.e. pruneIfUndefined) to groups.\n * I.e. an Author condition AND an omitted Book condition survives unless the group uses `any`.\n */\nfunction isPrunedQueryCondition(cond: QueryCondition | undefined): boolean {\n if (cond === undefined || cond === skipCondition) return true;\n if (isInQueryCondition(cond)) {\n const q = normalizeQueryJoins(cond[inQueryCondition].query as AnyQuery);\n return isPrunedQueryCondition(normalizeWhere(q.where));\n }\n if (\"and\" in cond || \"or\" in cond) {\n const children = (cond.and ?? cond.or ?? []).map(isPrunedQueryCondition);\n return (\n children.every((pruned) => pruned) ||\n (\"pruneIfUndefined\" in cond && cond.pruneIfUndefined === \"any\" && children.some((pruned) => pruned))\n );\n }\n if (\"exists\" in cond) return cond.exists === undefined;\n if (\"notExists\" in cond) return cond.notExists === undefined;\n return false;\n}\n\n/** Recognizes the direct query-literal condition created by EntityColumn.in. */\nfunction isInQueryCondition(value: unknown): value is InQueryCondition {\n return typeof value === \"object\" && value !== null && inQueryCondition in value;\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 *\n * CTEs prune on the same rule and through the same dependency map: a `with` entry nothing reads\n * anymore drops with the join that read it, and a CTE read only by another CTE survives with it.\n * A CTE joined into the query shares its alias with that join, so their dependencies are merged.\n *\n * The one join that never prunes is a recursive term's reference to its own CTE: PostgreSQL requires\n * it, so it is not the caller's optional filter (see `Ctx.recursiveSelf`).\n */\nfunction pruneJoins(\n q: AnyQuery,\n ctx: Ctx,\n from: ParsedSource,\n joins: ParsedJoin[],\n ctes: ParsedCte[],\n used: SqlFragment[],\n): { joins: ParsedJoin[]; ctes: ParsedCte[] } {\n if (q.pruneJoins === false) return { joins, ctes };\n const deps = new Map<string, string[]>();\n function addDeps(alias: string, refs: readonly string[]): void {\n const own = refs.filter((r) => r !== alias);\n const existing = deps.get(alias);\n if (existing) existing.push(...own);\n else deps.set(alias, own);\n }\n for (const j of joins) addDeps(j.source.alias, [...(j.userOn?.refs ?? []), ...j.source.refs]);\n for (const c of ctes) addDeps(c.alias, c.plan.outerRefs);\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 // A recursive term must keep its reference to its own CTE; PostgreSQL rejects a term without one,\n // and pruning it would quietly turn the recursion into a plain select over the base term's table.\n for (const j of joins) if (j.source.handle === ctx.recursiveSelf) markRequired(j.source.alias);\n return {\n joins: joins.filter((j) => required.has(j.source.alias)),\n ctes: ctes.filter((c) => required.has(c.alias)),\n };\n}\n\n/**\n * Names and parses each `with` entry, in declaration order.\n *\n * Each entry is in scope before the next is parsed, so a CTE can read an *earlier* sibling by name,\n * PostgreSQL's rule for a non-recursive WITH. A forward reference, or a CTE reading the query's own\n * `from`, fails as \"not in this query's from/join\", the same error any out-of-scope source gets.\n *\n * I.e. `with: [totals, ranked]` parses `totals` first, so `ranked` can join it, but not the reverse.\n */\nexport function registerCtes(q: { with?: WithInput }, ctx: Ctx, assigner: AliasAssigner): ParsedCte[] {\n const entries = q.with === undefined ? [] : Array.isArray(q.with) ? q.with : [q.with as WithSource];\n // Each entry is a `query(...)` proxy; unwrap it to its `SubqueryHandle`, the identity `ctx` keys on.\n const handles = entries.filter(isDefined).map(withEntryHandle);\n // Name every entry before parsing any body, so reading a later one is an error, not a silent inline.\n const aliases = handles.map((handle) => assigner.getLiteralAlias(handle.name ?? \"cte\"));\n handles.forEach((handle, i) => ctx.declareCte(handle, aliases[i]));\n return handles.map((handle, i) => {\n // A recursive CTE's step term reads the CTE itself, so promote it before parsing, not after.\n if (handle.recursive) ctx.promoteCte(handle);\n // Otherwise parse first, then promote: the body sees earlier siblings, but not itself or later ones.\n const plan = parseQuery(handle.q, ctx, assigner, handle.recursive ? handle : undefined);\n if (!handle.recursive) ctx.promoteCte(handle);\n return { alias: aliases[i], plan, recursive: handle.recursive };\n });\n}\n\n/** A CTE must be a table shape, so entity-mode and scalar values, which have no columns, are out. */\nfunction withEntryHandle(entry: unknown): SubqueryHandle {\n if (!isSubqueryValue(entry)) {\n fail(\n entry instanceof SubqueryExpr || isEntityQueryValue(entry)\n ? \"A `with` entry needs named columns; entity and scalar query(...) values have none\"\n : \"A `with` entry must be a query(...) value\",\n );\n }\n return readValueHandle(entry);\n}\n\n/**\n * Drops the CTEs that nothing reads, given the aliases the rest of the statement referenced.\n *\n * A CTE can only read earlier siblings, so going last to first means every CTE that could read this one\n * was already visited, and its own reads are already in `referenced`. That makes one pass enough; first\n * to last would have to repeat until the set stopped growing. `unshift` restores WITH order.\n */\nexport function pruneCtes(ctes: ParsedCte[], referenced: Set<string>): ParsedCte[] {\n const kept: ParsedCte[] = [];\n for (let i = ctes.length - 1; i >= 0; i--) {\n const cte = ctes[i];\n if (!referenced.has(cte.alias)) continue;\n for (const ref of cte.plan.outerRefs) referenced.add(ref);\n kept.unshift(cte);\n }\n return kept;\n}\n\n/**\n * Renders `WITH a AS (...), b AS (...) `, whose bindings lead the statement, as their SQL does.\n *\n * One recursive CTE makes the whole clause `WITH RECURSIVE`, PostgreSQL's rule: the keyword is on the\n * clause, not on the entry that needs it, and it does not force the other entries to be recursive.\n */\nexport function withFragment(ctes: ParsedCte[]): SqlFragment {\n const recursive = ctes.some((c) => c.recursive) ? \" RECURSIVE\" : \"\";\n const sql = ctes.map((c) => `${safeKq(c.alias)} AS (${c.plan.sql})`).join(\", \");\n return { sql: `WITH${recursive} ${sql} `, bindings: ctes.flatMap((c) => c.plan.bindings), refs: [] };\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\n/** Builds inline select expressions while leaving existing expression instances intact. */\nfunction asSelectExpr(value: unknown, where: string): BaseExpr {\n if (value instanceof BaseExpr) return value;\n if (isPlainSelect(value)) return buildExpr(value);\n return fail(`${where} must be a column, an expression, or an expression literal`);\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\n/** Lowers a relationship tree before SQL rendering or output nullability is calculated. */\nfunction normalizeQueryJoins(q: AnyQuery): AnyQuery {\n if (q.join === undefined || Array.isArray(q.join)) return q;\n const tree = compileJoinTree(q.from, q.join);\n return { ...q, join: tree.joins, where: { and: [tree.condition, normalizeWhere(q.where)] } };\n}\n\n/** Gives WHERE arrays the same pruning and validation as explicit AND groups. */\nfunction normalizeWhere(where: AnyQuery[\"where\"]): QueryCondition | undefined {\n return Array.isArray(where) ? { and: where } : (where as QueryCondition | undefined);\n}\n\n/** Creates the runtime query value after the public signature has checked its input. */\nfunction createQueryValue(q: AnyReadQuery): unknown {\n const handle = new SubqueryHandle(toQuery(q));\n const output = handle.output();\n if (output.kind === \"entity\") {\n return { [entityQueryBrand]: handle };\n } else if (output.kind === \"scalar\") {\n return new SubqueryExpr(handle);\n } else {\n return newSubqueryProxy(handle);\n }\n}\n\n/** Keeps shorthand declarations callable-only, without recursively copying sql's own shorthand properties. */\nfunction typedSql<R>(strings: TemplateStringsArray, ...values: unknown[]): Expr<R, never> {\n return new TemplateExpr(strings, values) as unknown as Expr<R, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,MAAa,gBAA+B,OAAO,gBAAgB;AACnE,MAAa,mBAAkC,OAAO,mBAAmB;AACzE,MAAa,mBAAkC,OAAO,mBAAmB;AA2uBzE,SAAgB,MAAM,GAA0B;CAC9C,OAAO,iBAAiB,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,WAKd,GAAkF;CAClF,OAAO,sBAAsB,CAAC;AAChC;;AAGA,SAAS,sBAAsB,GAAkC;CAC/D,MAAM,aAAa,oBAAoB,CAAC;CACxC,MAAM,QAAQ,eAAe,WAAW,KAAK;CAC7C,eAAe,KAAK;CACpB,OAAO,uBAAuB,KAAK,IAAI,KAAA,IAAY,iBAAiB,UAAU;AAChF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,eAMd,MACA,MACA,MACA,OAAyB,CAAC,GACwB;CAClD,IAAI,OAAO,SAAS,YAAY,SAAS,IAAI,KAAK,8BAA8B;CAChF,IAAI,KAAK,UAAU,KAAA,KAAa,KAAK,UAAU,SAAS,KAAK,UAAU,YACrE,KAAK,qDAAqD;CAG5D,MAAM,SAAS,IAAI,eAAe,QAAQ,IAAI,GAAG,IAAI;CACrD,IAAI,OAAO,OAAO,CAAC,CAAC,SAAS,QAAQ,KAAK,sDAAsD;CAChG,MAAM,OAAO,iBAAiB,MAAM;CACpC,MAA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