@danceroutine/tango-orm 1.11.8 → 1.11.10

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 (35) hide show
  1. package/dist/{QuerySetState-CjyvAUBs.d.ts → QuerySetState-DRL9-rKQ.d.ts} +2 -1
  2. package/dist/{SqliteAdapter-6oyUmoJf.js → SqliteAdapter-CrUhpTDb.js} +33 -13
  3. package/dist/SqliteAdapter-CrUhpTDb.js.map +1 -0
  4. package/dist/connection/index.d.ts +1 -1
  5. package/dist/connection/index.js +2 -2
  6. package/dist/{connection-D-E6_Yf1.js → connection-B2cDwZ72.js} +4 -4
  7. package/dist/{connection-D-E6_Yf1.js.map → connection-B2cDwZ72.js.map} +1 -1
  8. package/dist/{defaultRuntime-CdTX8cXm.js → defaultRuntime-WIsxnh8K.js} +19 -17
  9. package/dist/defaultRuntime-WIsxnh8K.js.map +1 -0
  10. package/dist/{index-rjKca3U_.d.ts → index-CCvYeJt4.d.ts} +2 -2
  11. package/dist/{index-D9B6gKez.d.ts → index-CJlkeldS.d.ts} +4 -3
  12. package/dist/{index-B-aibguC.d.ts → index-o2LFpJ8S.d.ts} +15 -3
  13. package/dist/index.d.ts +5 -5
  14. package/dist/index.js +7 -7
  15. package/dist/manager/index.d.ts +3 -3
  16. package/dist/manager/index.js +2 -2
  17. package/dist/{manager-CiYqAYpn.js → manager-GMmYq4lC.js} +2 -2
  18. package/dist/{manager-CiYqAYpn.js.map → manager-GMmYq4lC.js.map} +1 -1
  19. package/dist/query/index.d.ts +1 -1
  20. package/dist/query/index.js +1 -1
  21. package/dist/{query-CP1UMIX6.js → query-B-ooqvSG.js} +37 -2
  22. package/dist/query-B-ooqvSG.js.map +1 -0
  23. package/dist/{registerModelObjects-DZfZ20fa.js → registerModelObjects-BKGs2c_m.js} +13 -3
  24. package/dist/registerModelObjects-BKGs2c_m.js.map +1 -0
  25. package/dist/{registerModelObjects-C-MliIiM.d.ts → registerModelObjects-CEqCRlVY.d.ts} +2 -2
  26. package/dist/runtime/index.d.ts +2 -2
  27. package/dist/runtime/index.js +2 -2
  28. package/dist/transaction/index.js +1 -1
  29. package/dist/{transaction-2_2m7VUo.js → transaction-DpDXQq5V.js} +2 -2
  30. package/dist/{transaction-2_2m7VUo.js.map → transaction-DpDXQq5V.js.map} +1 -1
  31. package/package.json +6 -6
  32. package/dist/SqliteAdapter-6oyUmoJf.js.map +0 -1
  33. package/dist/defaultRuntime-CdTX8cXm.js.map +0 -1
  34. package/dist/query-CP1UMIX6.js.map +0 -1
  35. package/dist/registerModelObjects-DZfZ20fa.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-CP1UMIX6.js","names":["SqlPlanKind","SqlPlanKind","Q","projectedRows"],"sources":["../src/query/domain/RelationMeta.ts","../src/query/domain/internal/InternalPrefetchQueryKind.ts","../src/query/domain/internal/InternalQNodeType.ts","../src/query/domain/internal/InternalLookupType.ts","../src/validation/internal/InternalSqlValidationPlanKind.ts","../src/validation/internal/InternalValidatedFilterDescriptorKind.ts","../src/validation/OrmSqlSafetyAdapter.ts","../src/query/domain/RelationTyping.ts","../src/query/planning/QueryPlanner.ts","../src/query/compiler/QueryCompiler.ts","../src/query/compiler/index.ts","../src/query/domain/QueryResult.ts","../src/query/domain/internal/InternalRelationKind.ts","../src/query/domain/TableMetaFactory.ts","../src/query/domain/index.ts","../src/query/domain/internal/InternalDirection.ts","../src/query/internal/isQNodeLike.ts","../src/query/QBuilder.ts","../src/query/QuerySet.ts","../src/query/ModelQuerySet.ts","../src/query/index.ts"],"sourcesContent":["import type { InternalRelationKind } from './internal/InternalRelationKind';\nimport type { RelationHydrationCardinality } from './RelationTyping';\nimport type { TableMeta } from './TableMeta';\n\nexport type RelationKind = (typeof InternalRelationKind)[keyof typeof InternalRelationKind];\nexport const InternalRelationHydrationLoadMode = {\n JOIN: 'join',\n PREFETCH: 'prefetch',\n} as const;\n\nexport type RelationHydrationLoadMode =\n (typeof InternalRelationHydrationLoadMode)[keyof typeof InternalRelationHydrationLoadMode];\n\nexport interface RelationHydrationCapabilities {\n queryable: boolean;\n hydratable: boolean;\n joinable: boolean;\n prefetchable: boolean;\n}\n\n/**\n * Runtime relation metadata consumed by validation, planning, compilation, and\n * hydration.\n */\nexport interface RelationMeta {\n /** Stable edge identity from the resolved relation graph. */\n edgeId: string;\n /** Model key that owns the public relation name. */\n sourceModelKey: string;\n /** Model key reached by traversing this relation. */\n targetModelKey: string;\n /** Public relation kind such as belongsTo or hasMany. */\n kind: RelationKind;\n /** Hydration cardinality used by eager-loading APIs. */\n cardinality: RelationHydrationCardinality;\n /** Capability flags distilled from the resolved relation graph. */\n capabilities: RelationHydrationCapabilities;\n /** Physical table storing the target model rows. */\n table: string;\n /** Owner-side column used to attach or query related rows. */\n sourceKey: string;\n /** Target-side column matched against the source key. */\n targetKey: string;\n /** Many-to-many through table name when applicable. */\n throughTable?: string;\n throughModelKey?: string;\n /** Many-to-many through column that matches the owner source key. */\n throughSourceKey?: string;\n /** Many-to-many through column that matches the target primary key. */\n throughTargetKey?: string;\n throughSourceColumnType?: string;\n throughTargetColumnType?: string;\n /** Primary key column for the target model. */\n targetPrimaryKey: string;\n /** Target model columns and their storage types. */\n targetColumns: Record<string, string>;\n /** Deterministic alias base used by join compilation. */\n alias: string;\n /** Recursive target metadata used for nested planning. */\n targetMeta?: TableMeta;\n}\n","/**\n * Discriminator strings for compiled prefetch hydration: how `QueryCompiler.compilePrefetch`\n * batches related rows for hydration (`CompiledPrefetchQuery`).\n */\nexport const InternalPrefetchQueryKind = {\n /**\n * Single-query prefetch against the related table (`SELECT … FROM target WHERE fk IN (...)`).\n * Used when each related row is reachable from one physical table via a foreign key or\n * symmetric join path (belongsTo, hasMany, hasOne, reverse one-to-one).\n */\n DIRECT: 'direct',\n\n /**\n * Two-phase many-to-many prefetch: first query reads join (through) rows pairing owner ids to\n * target ids (`throughSql`), then target rows load by primary key (`compileManyToManyTargets`).\n * Distinct from relation metadata’s `manyToMany` relation *kind* on an endpoint—this marks the\n * compiled prefetch *strategy*, not the schema edge type.\n */\n MANY_TO_MANY: 'manyToMany',\n} as const;\n\nexport type PrefetchQueryKind = (typeof InternalPrefetchQueryKind)[keyof typeof InternalPrefetchQueryKind];\n","export const InternalQNodeType = {\n ATOM: 'atom',\n AND: 'and',\n OR: 'or',\n NOT: 'not',\n} as const;\n","export const InternalLookupType = {\n EXACT: 'exact',\n LT: 'lt',\n LTE: 'lte',\n GT: 'gt',\n GTE: 'gte',\n IN: 'in',\n ISNULL: 'isnull',\n CONTAINS: 'contains',\n ICONTAINS: 'icontains',\n STARTSWITH: 'startswith',\n ISTARTSWITH: 'istartswith',\n ENDSWITH: 'endswith',\n IENDSWITH: 'iendswith',\n} as const;\n","/**\n * Discriminator strings for {@link SqlValidationPlan} / {@link ValidatedSqlPlan}: which validation\n * branch {@link OrmSqlSafetyAdapter} runs before SQL is assembled or executed.\n */\nexport const InternalSqlValidationPlanKind = {\n /**\n * Read/query validation: table metadata, projected columns, `WHERE` filter keys, ordering, and\n * optional relation handles. Used when compiling selects (including M2M through-table selects\n * issued inside prefetch compilation).\n */\n SELECT: 'select',\n\n /**\n * Insert validation: resolved write columns for `INSERT … VALUES`.\n */\n INSERT: 'insert',\n\n /**\n * Update validation: resolved write columns for `UPDATE … SET`.\n */\n UPDATE: 'update',\n\n /**\n * Delete validation: scope delete-by-primary-key against validated table metadata.\n */\n DELETE: 'delete',\n} as const;\n\nexport type SqlValidationPlanKind = (typeof InternalSqlValidationPlanKind)[keyof typeof InternalSqlValidationPlanKind];\n","export const InternalValidatedFilterDescriptorKind = {\n COLUMN: 'column',\n RELATION: 'relation',\n} as const;\n","import { SqlSafetyEngine, type SqlIdentifierRequest } from '@danceroutine/tango-core';\nimport type { LookupType } from '../query/domain/LookupType';\nimport type { TableMeta } from '../query/domain/TableMeta';\nimport { InternalLookupType } from '../query/domain/internal/InternalLookupType';\nimport type {\n SQLValidationEngine,\n ValidatedDeleteSqlPlan,\n ValidatedFilterDescriptor,\n ValidatedInsertSqlPlan,\n ValidatedRelationMeta,\n ValidatedTableMeta,\n ValidatedSelectSqlPlan,\n ValidatedSqlPlan,\n ValidatedUpdateSqlPlan,\n} from './SQLValidationEngine';\nimport type {\n DeleteSqlValidationPlan,\n InsertSqlValidationPlan,\n SelectSqlValidationPlan,\n SqlValidationPlan,\n UpdateSqlValidationPlan,\n} from './SqlValidationPlan';\nimport { InternalSqlValidationPlanKind as SqlPlanKind } from './internal/InternalSqlValidationPlanKind';\nimport { InternalValidatedFilterDescriptorKind } from './internal/InternalValidatedFilterDescriptorKind';\n\nconst ALLOWED_LOOKUPS = Object.values(InternalLookupType) as readonly string[];\n\n/**\n * ORM-local adapter that translates query validation plans into the\n * shared Tango SQL safety engine.\n */\nexport class OrmSqlSafetyAdapter implements SQLValidationEngine {\n static readonly BRAND = 'tango.orm.orm_sql_safety_adapter' as const;\n readonly __tangoBrand: typeof OrmSqlSafetyAdapter.BRAND = OrmSqlSafetyAdapter.BRAND;\n\n constructor(private readonly engine: SqlSafetyEngine = new SqlSafetyEngine()) {}\n\n validate(plan: SelectSqlValidationPlan): ValidatedSelectSqlPlan;\n validate(plan: InsertSqlValidationPlan): ValidatedInsertSqlPlan;\n validate(plan: UpdateSqlValidationPlan): ValidatedUpdateSqlPlan;\n validate(plan: DeleteSqlValidationPlan): ValidatedDeleteSqlPlan;\n validate(plan: SqlValidationPlan): ValidatedSqlPlan {\n switch (plan.kind) {\n case SqlPlanKind.SELECT: {\n const meta = this.validateTableMeta(plan.meta, plan.relationNames ?? []);\n return {\n kind: SqlPlanKind.SELECT,\n meta,\n selectFields: Object.fromEntries(\n (plan.selectFields ?? []).map((field) => [\n field,\n `${meta.table}.${this.resolveColumn(meta, field)}`,\n ])\n ),\n filterKeys: Object.fromEntries(\n (plan.filterKeys ?? []).map((rawKey) => [\n rawKey,\n this.validateFilterKey(meta, plan.meta, rawKey),\n ])\n ),\n orderFields: Object.fromEntries(\n (plan.orderFields ?? []).map((field) => [\n field,\n `${meta.table}.${this.resolveColumn(meta, field)}`,\n ])\n ),\n relations: Object.fromEntries(\n (plan.relationNames ?? []).map((relationName) => [\n relationName,\n this.resolveRelation(meta, relationName),\n ])\n ),\n };\n }\n case SqlPlanKind.INSERT: {\n const meta = this.validateTableMeta(plan.meta);\n return {\n kind: SqlPlanKind.INSERT,\n meta,\n writeKeys: plan.writeKeys.map((key) => this.resolveColumn(meta, key)),\n };\n }\n case SqlPlanKind.UPDATE: {\n const meta = this.validateTableMeta(plan.meta);\n return {\n kind: SqlPlanKind.UPDATE,\n meta,\n writeKeys: plan.writeKeys.map((key) => this.resolveColumn(meta, key)),\n };\n }\n case SqlPlanKind.DELETE: {\n return {\n kind: SqlPlanKind.DELETE,\n meta: this.validateTableMeta(plan.meta),\n };\n }\n }\n }\n\n private validateTableMeta(meta: TableMeta, relationNames: readonly string[] = []): ValidatedTableMeta {\n const columnNames = Object.keys(meta.columns);\n const validated = this.engine.validate({\n identifiers: [\n { key: 'table', role: 'table', value: meta.table },\n { key: 'pk', role: 'primaryKey', value: meta.pk, allowlist: columnNames },\n ...columnNames.map<SqlIdentifierRequest>((column) => ({\n key: `column:${column}`,\n role: 'column',\n value: column,\n })),\n ],\n });\n\n const validatedMeta: ValidatedTableMeta = {\n table: validated.identifiers.table!.value,\n pk: validated.identifiers.pk!.value,\n columns: Object.fromEntries(\n columnNames.map((column) => [validated.identifiers[`column:${column}`]!.value, meta.columns[column]!])\n ),\n };\n\n if (!(validatedMeta.pk in validatedMeta.columns)) {\n throw new Error(`Unknown column '${validatedMeta.pk}' for table '${validatedMeta.table}'.`);\n }\n\n if (relationNames.length > 0) {\n validatedMeta.relations = Object.fromEntries(\n relationNames.map((relationName) => [\n relationName,\n this.validateRelationMeta(validatedMeta, relationName, meta.relations),\n ])\n );\n }\n\n return validatedMeta;\n }\n\n private validateRelationMeta(\n meta: ValidatedTableMeta,\n relationName: string,\n relations: TableMeta['relations']\n ): ValidatedRelationMeta {\n const relation = relations?.[relationName];\n if (!relation) {\n throw new Error(`Unknown relation '${relationName}' for table '${meta.table}'.`);\n }\n if (!(relation.targetKey in relation.targetColumns)) {\n throw new Error(`Unknown relation target key '${relation.targetKey}' for relation '${relationName}'.`);\n }\n\n const validated = this.engine.validate({\n identifiers: [\n { key: 'table', role: 'relationTable', value: relation.table },\n { key: 'alias', role: 'alias', value: relation.alias },\n { key: 'targetKey', role: 'relationTargetPrimaryKey', value: relation.targetKey },\n { key: 'targetPrimaryKey', role: 'relationTargetPrimaryKey', value: relation.targetPrimaryKey },\n ...(relation.throughTable\n ? [\n {\n key: 'throughTable',\n role: 'table',\n value: relation.throughTable,\n } satisfies SqlIdentifierRequest,\n ]\n : []),\n ...(relation.throughSourceKey\n ? [\n {\n key: 'throughSourceKey',\n role: 'column',\n value: relation.throughSourceKey,\n } satisfies SqlIdentifierRequest,\n ]\n : []),\n ...(relation.throughTargetKey\n ? [\n {\n key: 'throughTargetKey',\n role: 'column',\n value: relation.throughTargetKey,\n } satisfies SqlIdentifierRequest,\n ]\n : []),\n ...Object.keys(relation.targetColumns).map<SqlIdentifierRequest>((column) => ({\n key: `targetColumn:${column}`,\n role: 'column',\n value: column,\n })),\n ],\n });\n\n return {\n ...relation,\n table: validated.identifiers.table!.value,\n alias: validated.identifiers.alias!.value,\n sourceKey: this.resolveColumn(meta, relation.sourceKey),\n targetKey: validated.identifiers.targetKey!.value,\n targetPrimaryKey: validated.identifiers.targetPrimaryKey!.value,\n targetColumns: Object.fromEntries(\n Object.keys(relation.targetColumns).map((column) => [\n validated.identifiers[`targetColumn:${column}`]!.value,\n relation.targetColumns[column]!,\n ])\n ),\n throughTable: validated.identifiers.throughTable?.value,\n throughSourceKey: validated.identifiers.throughSourceKey?.value,\n throughTargetKey: validated.identifiers.throughTargetKey?.value,\n };\n }\n\n private validateFilterKey(meta: ValidatedTableMeta, rawMeta: TableMeta, rawKey: string): ValidatedFilterDescriptor {\n const segments = rawKey.split('__');\n if (segments.length === 0 || segments.some((segment) => segment.length === 0)) {\n throw new Error(`Invalid SQL lookup key: '${rawKey}'.`);\n }\n\n const lookupToken = segments.at(-1)!;\n const hasExplicitLookup = ALLOWED_LOOKUPS.includes(lookupToken);\n const lookup = (hasExplicitLookup ? lookupToken : InternalLookupType.EXACT) as LookupType;\n const pathSegments = hasExplicitLookup ? segments.slice(0, -1) : segments;\n\n if (pathSegments.length === 0) {\n throw new Error(`Invalid SQL lookup key: '${rawKey}'.`);\n }\n\n const validated = this.engine.validate({\n lookupTokens: [{ key: rawKey, lookup, allowed: ALLOWED_LOOKUPS }],\n });\n\n if (pathSegments.length === 1) {\n const field = pathSegments[0]!;\n return {\n kind: InternalValidatedFilterDescriptorKind.COLUMN,\n rawKey,\n field,\n lookup: validated.lookupTokens[rawKey]!.lookup as LookupType,\n qualifiedColumn: `${meta.table}.${this.resolveColumn(meta, field)}`,\n };\n }\n\n const rootSegment = pathSegments[0]!;\n const hasRootColumn = rootSegment in rawMeta.columns;\n const hasRootRelation = rootSegment in (rawMeta.relations ?? {});\n if (!hasExplicitLookup && hasRootColumn && !hasRootRelation) {\n throw new Error(`Invalid SQL lookup key: '${rawKey}'.`);\n }\n\n const field = pathSegments.at(-1)!;\n const relationSegments = pathSegments.slice(0, -1);\n const relationChain: ValidatedRelationMeta[] = [];\n let currentValidatedMeta = meta;\n let currentRawMeta = rawMeta;\n\n for (const relationName of relationSegments) {\n const relation = currentRawMeta.relations?.[relationName];\n if (!relation) {\n throw new Error(`Unknown relation '${relationName}' for table '${currentValidatedMeta.table}'.`);\n }\n if (!relation.targetMeta) {\n throw new Error(\n `Relation '${relationName}' for table '${currentValidatedMeta.table}' is missing target metadata.`\n );\n }\n\n const validatedRelation = this.validateRelationMeta(\n currentValidatedMeta,\n relationName,\n currentRawMeta.relations\n );\n relationChain.push(validatedRelation);\n currentRawMeta = relation.targetMeta;\n currentValidatedMeta = this.validateTableMeta(currentRawMeta);\n }\n\n return {\n kind: InternalValidatedFilterDescriptorKind.RELATION,\n rawKey,\n field,\n lookup: validated.lookupTokens[rawKey]!.lookup as LookupType,\n relationPath: relationSegments.join('__'),\n relationChain,\n terminalColumn: this.resolveColumn(currentValidatedMeta, field),\n };\n }\n\n private resolveColumn(meta: ValidatedTableMeta, field: string): string {\n if (!(field in meta.columns)) {\n throw new Error(`Unknown column '${field}' for table '${meta.table}'.`);\n }\n\n return field;\n }\n\n private resolveRelation(meta: ValidatedTableMeta, relationName: string): ValidatedRelationMeta {\n const relation = meta.relations?.[relationName];\n if (!relation) {\n throw new Error(`Unknown relation '${relationName}' for table '${meta.table}'.`);\n }\n\n return relation;\n }\n}\n","import type { z } from 'zod';\nimport type { Model, PersistedModelOutput } from '@danceroutine/tango-schema/domain';\nimport type {\n DecoratedFieldKind,\n InternalDecoratedFieldKind,\n RelationDecoratedSchema,\n} from '@danceroutine/tango-schema/model';\nimport type { ManyToManyRelatedManager } from '../../manager/relations/ManyToManyRelatedManager';\n\nexport const InternalRelationHydrationCardinality = {\n SINGLE: 'single',\n MANY: 'many',\n} as const;\n\nexport type RelationHydrationCardinality =\n (typeof InternalRelationHydrationCardinality)[keyof typeof InternalRelationHydrationCardinality];\nexport type SingleRelationHydrationCardinality = typeof InternalRelationHydrationCardinality.SINGLE;\nexport type ManyRelationHydrationCardinality = typeof InternalRelationHydrationCardinality.MANY;\n\nexport type HydratedQueryResult<TBase extends Record<string, unknown>, THydrated extends Record<string, unknown>> =\n // No relation hydration requested: keep the base projection exactly as-is.\n [keyof THydrated] extends [never] ? TBase : Omit<TBase, keyof THydrated> & THydrated;\n\ndeclare global {\n // oxlint-disable-next-line no-empty-object-type\n interface TangoGeneratedRelationRegistry {}\n}\n\n// A model's own schema is the only source TypeScript can inspect without codegen or an ambient registry.\n// These helpers progressively peel that schema apart into field definitions and persisted row shapes.\n// \"AnyModel\" is a structural upper bound for model values when the exact schema/key is not important.\ntype AnyModel = Model<z.ZodObject<z.ZodRawShape>, string>;\n// If the caller gave us a Tango Model type, infer the Zod schema type stored inside it.\ntype ModelSchema<TModel> =\n TModel extends Model<infer TSchema extends z.ZodObject<z.ZodRawShape>, string> ? TSchema : never;\n// If we have a Zod object schema, infer its raw object shape so we can inspect individual fields.\ntype ModelShape<TModel> = ModelSchema<TModel> extends z.ZodObject<infer TShape> ? TShape : never;\n// Convert the inferred model schema back into the persisted row shape applications receive from the ORM.\ntype ModelRow<TModel> =\n TModel extends Model<infer TSchema extends z.ZodObject<z.ZodRawShape>, string>\n ? PersistedModelOutput<TSchema>\n : never;\n\n// Relation typing only works when model keys remain literal. Once a model key widens to plain string,\n// TypeScript can no longer prove that one relation target matches another model.\n// This conditional rejects widened strings while accepting literal keys such as \"blog/User\".\ntype IsLiteralString<TValue> = TValue extends string ? (string extends TValue ? false : true) : false;\n// A model has strict relation typing only when its model key is still a literal type.\ntype HasStrictModelKey<TModel> =\n TModel extends Model<z.ZodObject<z.ZodRawShape>, infer TKey> ? IsLiteralString<TKey> : false;\n\n// Extract the literal model key from a Tango Model type. The generated\n// relation registry is indexed by these stable ids.\ntype ModelKey<TModel> = TModel extends Model<z.ZodObject<z.ZodRawShape>, infer TKey extends string> ? TKey : never;\n\n// Merge one-hydration-per-path object fragments into one final hydrated map.\ntype UnionToIntersection<TValue> = (TValue extends unknown ? (value: TValue) => void : never) extends (\n value: infer TIntersection\n) => void\n ? TIntersection\n : never;\n\ntype JoinPathSegments<TSegments extends readonly string[]> = TSegments extends readonly [\n infer THead extends string,\n ...infer TRest extends string[],\n]\n ? TRest['length'] extends 0\n ? THead\n : `${THead}__${JoinPathSegments<TRest>}`\n : never;\n\n// Split a Django-style path into tuple segments so recursive conditional types\n// can walk one relation hop at a time.\ntype SplitPath<TPath extends string> = TPath extends `${infer THead}__${infer TRest}`\n ? [THead, ...SplitPath<TRest>]\n : [TPath];\n\ntype TailTuple<TTuple extends readonly unknown[]> = TTuple extends readonly [unknown, ...infer TRest] ? TRest : [];\n// Generated typing allows four recursive revisits before it falls back to\n// weaker typing. Runtime traversal can still go deeper than this budget.\ntype DefaultGeneratedCycleBudget = readonly [1, 1, 1, 1];\ntype GeneratedRelationRegistry = TangoGeneratedRelationRegistry;\ntype GeneratedRelationKeys<TSourceModel> = Extract<keyof GeneratedRelations<TSourceModel>, string>;\n\n// Only read from the ambient generated registry when the caller supplied a\n// model whose key remains a literal type.\ntype GeneratedRelations<TSourceModel> =\n HasStrictModelKey<TSourceModel> extends true\n ? ModelKey<TSourceModel> extends keyof GeneratedRelationRegistry\n ? GeneratedRelationRegistry[ModelKey<TSourceModel>]\n : // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {}\n : // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {};\n\ntype NextSeenModels<TSeen extends readonly string[], TTargetModel> =\n ModelKey<TTargetModel> extends string ? [...TSeen, ModelKey<TTargetModel>] : TSeen;\n\n// Revisiting a model is allowed while the cycle budget still has entries.\ntype CanTraverseGeneratedTarget<\n TTargetModel,\n TSeen extends readonly string[],\n TCycleBudget extends readonly unknown[],\n> = ModelKey<TTargetModel> extends TSeen[number] ? (TCycleBudget extends [] ? false : true) : true;\n\n// Only consume budget when the next edge revisits a model already on the path.\ntype NextGeneratedCycleBudget<TTargetModel, TSeen extends readonly string[], TCycleBudget extends readonly unknown[]> =\n ModelKey<TTargetModel> extends TSeen[number] ? TailTuple<TCycleBudget> : TCycleBudget;\n\ntype GeneratedCardinalityIncludesMany<TCardinality extends RelationHydrationCardinality> =\n TCardinality extends typeof InternalRelationHydrationCardinality.MANY ? true : false;\n\n/**\n * Generated path keys accepted by `selectRelated(...)`.\n *\n * Walks the ambient relation registry one hop at a time. Each hop contributes:\n * (a) the bare relation key (e.g. `author`) as a valid path terminus, and\n * (b) a dunder-joined extension (`author__profile`, ...) that recurses into\n * the target model.\n *\n * Because `selectRelated` only composes single-valued hops, the mapped type\n * filters relations whose `cardinality` is not `SINGLE`. The `TSeen` tuple\n * tracks which model keys the recursion has visited so cyclic schemas\n * (`manager -> manager`) are allowed a bounded number of revisits before\n * typing falls back to `never`. `TCycleBudget` is that revisit budget; see\n * `CanTraverseGeneratedTarget` / `NextGeneratedCycleBudget` for how it\n * shrinks only when the next hop actually re-enters a seen model.\n */\nexport type GeneratedSelectRelatedPathKeys<\n TSourceModel,\n TSeen extends readonly string[] = [ModelKey<TSourceModel>],\n TCycleBudget extends readonly unknown[] = DefaultGeneratedCycleBudget,\n> = {\n [TKey in GeneratedRelationKeys<TSourceModel>]: GeneratedRelations<TSourceModel>[TKey] extends {\n target: infer TTarget extends AnyModel;\n cardinality: typeof InternalRelationHydrationCardinality.SINGLE;\n }\n ?\n | TKey\n | (CanTraverseGeneratedTarget<TTarget, TSeen, TCycleBudget> extends true\n ? `${TKey}__${GeneratedSelectRelatedPathKeys<\n TTarget,\n NextSeenModels<TSeen, TTarget>,\n NextGeneratedCycleBudget<TTarget, TSeen, TCycleBudget>\n >}`\n : never)\n : never;\n}[GeneratedRelationKeys<TSourceModel>];\n\n/**\n * Generated path keys accepted by `prefetchRelated(...)`.\n *\n * Similar in shape to {@link GeneratedSelectRelatedPathKeys}, but relaxes two\n * constraints because prefetch can cross and continue past collection edges:\n * 1. Any hop whose cardinality is `MANY` is a valid terminus. The\n * `THasMany` flag threads through recursion so once a collection edge\n * has been crossed, every subsequent hop is also a valid terminus\n * (matches Django's `prefetch_related` semantics).\n * 2. Single-valued hops are still accepted as terminators so paths like\n * `posts__author` survive the join.\n *\n * Cycle handling reuses the same `TSeen` / `TCycleBudget` machinery described\n * in {@link GeneratedSelectRelatedPathKeys}: cyclic schemas are typed up to\n * the bound, then fall back to weaker typing rather than failing.\n */\nexport type GeneratedPrefetchRelatedPathKeys<\n TSourceModel,\n THasMany extends boolean = false,\n TSeen extends readonly string[] = [ModelKey<TSourceModel>],\n TCycleBudget extends readonly unknown[] = DefaultGeneratedCycleBudget,\n> = {\n [TKey in GeneratedRelationKeys<TSourceModel>]: GeneratedRelations<TSourceModel>[TKey] extends {\n target: infer TTarget extends AnyModel;\n cardinality: infer TCardinality extends RelationHydrationCardinality;\n }\n ?\n | (THasMany extends true\n ? TKey\n : GeneratedCardinalityIncludesMany<TCardinality> extends true\n ? TKey\n : never)\n | (CanTraverseGeneratedTarget<TTarget, TSeen, TCycleBudget> extends true\n ? `${TKey}__${GeneratedPrefetchRelatedPathKeys<\n TTarget,\n THasMany extends true ? true : GeneratedCardinalityIncludesMany<TCardinality>,\n NextSeenModels<TSeen, TTarget>,\n NextGeneratedCycleBudget<TTarget, TSeen, TCycleBudget>\n >}`\n : never)\n : never;\n}[GeneratedRelationKeys<TSourceModel>];\n\n/**\n * Generated relation-path filter keys accepted by `filter(...)`, `exclude(...)`,\n * and `Q(...)`.\n *\n * This stays intentionally lighter than the eager-loading path typing:\n * applications with generated relation registries get completion for the\n * relation path prefix, while the terminal field and lookup suffix remain a\n * string tail so the compiler does not explode on deep recursive field\n * extraction.\n */\nexport type GeneratedRelationFilterKeys<TSourceModel> =\n | `${GeneratedSelectRelatedPathKeys<TSourceModel>}__${string}`\n | `${GeneratedPrefetchRelatedPathKeys<TSourceModel>}__${string}`;\n\n// Hydrated target values recurse through the remaining path suffix, so a path\n// like `posts__author` becomes `{ posts: Array<{ author: ... }> }`.\ntype GeneratedHydratedTarget<TDescriptor, TPath extends string | never> = TDescriptor extends {\n target: infer TTarget extends AnyModel;\n}\n ? [TPath] extends [never]\n ? ModelRow<TTarget>\n : HydratedQueryResult<ModelRow<TTarget>, GeneratedHydratedRelationMap<TTarget, TPath>>\n : never;\n\ntype GeneratedHydratedValue<TDescriptor, TPath extends string | never> = TDescriptor extends {\n target: infer TTarget extends AnyModel;\n kind: 'manyToMany';\n}\n ? ManyToManyRelatedManager<ModelRow<TTarget>>\n : TDescriptor extends { cardinality: infer TCardinality extends RelationHydrationCardinality }\n ? TCardinality extends typeof InternalRelationHydrationCardinality.SINGLE\n ? GeneratedHydratedTarget<TDescriptor, TPath> | null\n : GeneratedHydratedTarget<TDescriptor, TPath>[]\n : never;\n\n// Turn one path string into the object fragment it contributes before all path\n// fragments are merged into the final hydrated relation map.\ntype GeneratedHydrationForPath<TSourceModel, TPath extends string> =\n SplitPath<TPath> extends [infer THead extends string, ...infer TRest extends string[]]\n ? THead extends GeneratedRelationKeys<TSourceModel>\n ? {\n [TKey in THead]: GeneratedHydratedValue<\n GeneratedRelations<TSourceModel>[THead],\n JoinPathSegments<TRest>\n >;\n }\n : // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {}\n : // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {};\n\nexport type GeneratedHydratedRelationMap<TSourceModel, TPaths extends string | never> = ([TPaths] extends [never]\n ? Record<never, never>\n : UnionToIntersection<TPaths extends string ? GeneratedHydrationForPath<TSourceModel, TPaths> : never>) &\n Record<never, never>;\n\nexport type HasStrictRelationTyping<TSourceModel> = HasStrictModelKey<TSourceModel>;\n\n// Reverse relation typing compares the literal model key carried by the target field against the source model key.\ntype ModelKeysMatch<TCandidate, TExpected> =\n TCandidate extends Model<z.ZodObject<z.ZodRawShape>, infer TCandidateKey>\n ? // The candidate relation target is a Tango model. Now check whether the expected source is also a model.\n TExpected extends Model<z.ZodObject<z.ZodRawShape>, infer TExpectedKey>\n ? // Both sides must keep literal keys, otherwise a plain string could accidentally match anything.\n IsLiteralString<TCandidateKey> extends true\n ? IsLiteralString<TExpectedKey> extends true\n ? // Tuple wrapping avoids distributive conditional behavior and compares the keys as whole values.\n [TCandidateKey] extends [TExpectedKey]\n ? true\n : false\n : false\n : false\n : false\n : false;\n\n// Keep this in sync with RelationDescriptorNormalizer.deriveNamingHint(...), which currently recognizes\n// camelCase \"Id\" and snake_case \"_id\" suffixes but does not treat lowercase \"id\" as a relation suffix.\ntype FieldNamingHint<TKey extends string> = TKey extends `${infer TBase}Id`\n ? // Convert authorId -> author for relation names when the decorator did not configure name explicitly.\n TBase\n : TKey extends `${infer TBase}_id`\n ? // Convert author_id -> author for snake_case field names.\n TBase\n : // Otherwise the field key is already the best available relation-name hint.\n TKey;\n\n// Prefer an explicitly configured forward relation name. Fall back to the field-name heuristic.\ntype RelationName<TKey extends string, TName> = TName extends string ? TName : FieldNamingHint<TKey>;\n// Reverse relations cannot be inferred without an explicit relatedName, so missing names become never.\ntype RelatedName<TName> = TName extends string ? TName : never;\n\n// Relation decorators brand their Zod field with type-only metadata. The next group extracts that metadata:\n// relation target, configured forward name, configured reverse name, and relation kind.\ntype RelationTarget<TField> =\n TField extends RelationDecoratedSchema<\n z.ZodTypeAny,\n DecoratedFieldKind,\n infer TTarget,\n string | undefined,\n string | undefined\n >\n ? // infer TTarget captures the typed model target carried by direct refs, callbacks, or t.modelRef<TModel>(...).\n TTarget\n : never;\n\ntype RelationConfiguredName<TField> =\n TField extends RelationDecoratedSchema<z.ZodTypeAny, DecoratedFieldKind, AnyModel, infer TName, string | undefined>\n ? // infer TName captures config.name when the decorator call used a literal string.\n TName\n : undefined;\n\ntype RelationConfiguredRelatedName<TField> =\n TField extends RelationDecoratedSchema<\n z.ZodTypeAny,\n DecoratedFieldKind,\n AnyModel,\n string | undefined,\n infer TRelatedName\n >\n ? // infer TRelatedName captures config.relatedName when the decorator call used a literal string.\n TRelatedName\n : undefined;\n\ntype RelationKindOf<TField> =\n TField extends RelationDecoratedSchema<z.ZodTypeAny, infer TKind, AnyModel, string | undefined, string | undefined>\n ? // infer TKind tells us whether the field was branded by foreignKey, oneToOne, or manyToMany.\n TKind\n : never;\n\n// Forward relations live on the source model's own schema. A foreign key and a one-to-one field are both\n// single-valued from the source model's point of view, so both hydrate through selectRelated(...).\nexport type ForwardSingleRelations<TSourceModel> =\n HasStrictModelKey<TSourceModel> extends true\n ? // Strict source model: inspect its own schema and emit only fields that are forward single relations.\n {\n [TKey in keyof ModelShape<TSourceModel> as TKey extends string\n ? // Non-relation fields have no decorator brand and therefore map to never.\n [RelationKindOf<ModelShape<TSourceModel>[TKey]>] extends [never]\n ? never\n : // foreignKey and oneToOne are both single-valued when loaded from the source model.\n RelationKindOf<ModelShape<TSourceModel>[TKey]> extends\n | typeof InternalDecoratedFieldKind.FOREIGN_KEY\n | typeof InternalDecoratedFieldKind.ONE_TO_ONE\n ? // The relation must carry a typed model target; plain string refs cannot hydrate a typed result.\n RelationTarget<ModelShape<TSourceModel>[TKey]> extends AnyModel\n ? // The mapped-type key is the public relation name accepted by selectRelated(...).\n RelationName<TKey, RelationConfiguredName<ModelShape<TSourceModel>[TKey]>>\n : never\n : never\n : never]: {\n kind: typeof InternalDecoratedFieldKind.FOREIGN_KEY;\n target: RelationTarget<ModelShape<TSourceModel>[TKey]>;\n };\n }\n : // Weak source model: allow runtime strings but do not add precise hydrated result properties.\n Record<string, { kind: typeof InternalDecoratedFieldKind.FOREIGN_KEY; target: AnyModel }>;\n\n// A reverse single relation is only visible when the caller supplies the target model generic. We inspect that\n// target model for a one-to-one field pointing back to the source model and use its relatedName.\nexport type ReverseSingleRelations<TSourceModel, TTargetModel> =\n HasStrictModelKey<TSourceModel> extends true\n ? // Reverse typing needs both the current source model and the away/target model to keep literal keys.\n HasStrictModelKey<TTargetModel> extends true\n ? {\n [TKey in keyof ModelShape<TTargetModel> as [RelationKindOf<ModelShape<TTargetModel>[TKey]>] extends [\n never,\n ]\n ? // Ignore ordinary fields on the away model.\n never\n : // Only oneToOne creates a single-valued reverse relation.\n RelationKindOf<\n ModelShape<TTargetModel>[TKey]\n > extends typeof InternalDecoratedFieldKind.ONE_TO_ONE\n ? // The away model's oneToOne target must point back at the current source model.\n ModelKeysMatch<RelationTarget<ModelShape<TTargetModel>[TKey]>, TSourceModel> extends true\n ? // The reverse call-site key is the away field's configured relatedName.\n RelatedName<RelationConfiguredRelatedName<ModelShape<TTargetModel>[TKey]>>\n : never\n : never]: {\n kind: typeof InternalDecoratedFieldKind.ONE_TO_ONE;\n target: TTargetModel;\n };\n }\n : // A widened target model cannot prove reverse relation names.\n // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {}\n : // Weak source model: allow runtime strings but do not add precise hydrated result properties.\n Record<string, { kind: typeof InternalDecoratedFieldKind.ONE_TO_ONE; target: AnyModel }>;\n\n// A reverse collection relation follows the same target-model inspection path, but only foreign keys produce hasMany.\nexport type ReverseCollectionRelations<TSourceModel, TTargetModel> =\n HasStrictModelKey<TSourceModel> extends true\n ? // Reverse collection typing also needs both model keys to remain literal.\n HasStrictModelKey<TTargetModel> extends true\n ? {\n [TKey in keyof ModelShape<TTargetModel> as [RelationKindOf<ModelShape<TTargetModel>[TKey]>] extends [\n never,\n ]\n ? // Ignore ordinary fields on the away model.\n never\n : // A foreign key on the away model creates a hasMany collection from the source model.\n RelationKindOf<\n ModelShape<TTargetModel>[TKey]\n > extends typeof InternalDecoratedFieldKind.FOREIGN_KEY\n ? // The away model's foreign key must point back at the current source model.\n ModelKeysMatch<RelationTarget<ModelShape<TTargetModel>[TKey]>, TSourceModel> extends true\n ? // The reverse call-site key is the away field's configured relatedName.\n RelatedName<RelationConfiguredRelatedName<ModelShape<TTargetModel>[TKey]>>\n : never\n : never]: {\n kind: typeof InternalDecoratedFieldKind.FOREIGN_KEY;\n target: TTargetModel;\n };\n }\n : // A widened target model cannot prove reverse relation names.\n // oxlint-disable-next-line typescript/ban-types, typescript/no-empty-object-type\n {}\n : // Weak source model: allow runtime strings but do not add precise hydrated result properties.\n Record<string, { kind: typeof InternalDecoratedFieldKind.FOREIGN_KEY; target: AnyModel }>;\n\nexport type SelectRelatedRelations<TSourceModel, TTargetModel> = [TTargetModel] extends [undefined]\n ? // No target generic: selectRelated(...) can only use forward relations from the source schema.\n ForwardSingleRelations<TSourceModel>\n : // Target generic supplied: include reverse hasOne relations discovered on that target model.\n ForwardSingleRelations<TSourceModel> & ReverseSingleRelations<TSourceModel, TTargetModel>;\n\n// prefetchRelated(...) only loads collection relations in this pass, so it only accepts reverse hasMany metadata.\nexport type PrefetchRelatedRelations<TSourceModel, TTargetModel> = ReverseCollectionRelations<\n TSourceModel,\n TTargetModel\n>;\n\n// QuerySet method parameters need a string union of accepted relation names.\nexport type RelationKeys<TRelations> = Extract<keyof TRelations, string>;\n\n// Convert a selected relation-key union into the result object that fetch(...) exposes.\nexport type HydratedRelationMap<TRelations, TKeys extends string, TCardinality extends RelationHydrationCardinality> = {\n [TKey in TKeys]: TKey extends keyof TRelations\n ? // The relation map value carries the target model; infer that target so we can derive its row type.\n TRelations[TKey] extends { target: infer TTarget }\n ? // Single-valued relation hydration returns the target model or null when the join finds no row.\n TCardinality extends typeof InternalRelationHydrationCardinality.SINGLE\n ? ModelRow<TTarget> | null\n : // Collection relation hydration returns zero or more target model rows.\n ModelRow<TTarget>[]\n : never\n : never;\n};\n\nexport type MaybeHydratedRelationMap<\n TSourceModel,\n TRelations,\n TKeys extends string,\n TCardinality extends RelationHydrationCardinality,\n> =\n HasStrictModelKey<TSourceModel> extends true\n ? // Strict source model: materialize the requested hydrated relation properties into the fetched result type.\n HydratedRelationMap<TRelations, TKeys, TCardinality>\n : // Weak source model: preserve runtime support, but avoid pretending we know the hydrated result shape.\n Record<never, never>;\n","import type { QuerySetState } from '../domain/QuerySetState';\nimport type { TableMeta } from '../domain/TableMeta';\nimport { InternalRelationHydrationLoadMode, type RelationMeta } from '../domain/RelationMeta';\nimport { InternalRelationHydrationCardinality } from '../domain/RelationTyping';\nimport type { QueryHydrationPlanNode, QueryHydrationPlanRoot } from './domain/QueryHydrationPlan';\n\ntype RequestedMode = 'select' | 'prefetch';\n\ntype TraversalTrieNode = {\n segment: string;\n relationEdge: RelationMeta;\n relationPath: string;\n targetMeta: TableMeta;\n provenance: Set<string>;\n children: Map<string, TraversalTrieNode>;\n};\n\n/**\n * Parse, validate, normalize, and plan recursive relation hydration paths.\n */\nexport class QueryPlanner {\n static readonly BRAND = 'tango.orm.query_planner' as const;\n readonly __tangoBrand: typeof QueryPlanner.BRAND = QueryPlanner.BRAND;\n\n constructor(private readonly meta: TableMeta) {}\n\n static isQueryPlanner(value: unknown): value is QueryPlanner {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === QueryPlanner.BRAND\n );\n }\n\n plan<T, TSourceModel = unknown>(state: QuerySetState<T, TSourceModel>): QueryHydrationPlanRoot {\n const requestedPaths = Array.from(new Set([...(state.selectRelated ?? []), ...(state.prefetchRelated ?? [])]));\n if (requestedPaths.length === 0) {\n return {\n joinNodes: [],\n prefetchNodes: [],\n requestedPaths: [],\n };\n }\n\n const rootChildren = new Map<string, TraversalTrieNode>();\n for (const relationPath of new Set(state.selectRelated ?? [])) {\n this.addPath(rootChildren, relationPath, 'select');\n }\n for (const relationPath of new Set(state.prefetchRelated ?? [])) {\n this.addPath(rootChildren, relationPath, 'prefetch');\n }\n\n const { joinNodes, prefetchNodes } = this.buildPlannedChildren(rootChildren);\n return {\n joinNodes,\n prefetchNodes,\n requestedPaths,\n };\n }\n\n private addPath(rootChildren: Map<string, TraversalTrieNode>, relationPath: string, mode: RequestedMode): void {\n const segments = relationPath.split('__').filter(Boolean);\n if (segments.length === 0) {\n throw new Error(`Invalid empty relation path '${relationPath}'.`);\n }\n\n let currentMeta = this.meta;\n let currentChildren = rootChildren;\n let builtPath = '';\n\n for (const segment of segments) {\n const relation = currentMeta.relations?.[segment];\n if (!relation) {\n throw new Error(`Unknown relation path '${relationPath}' for table '${currentMeta.table}'.`);\n }\n if (segment in currentMeta.columns && relation.sourceKey !== segment) {\n throw new Error(\n `Relation path '${relationPath}' collides with an existing field on table '${currentMeta.table}'.`\n );\n }\n if (!relation.capabilities.queryable || !relation.capabilities.hydratable) {\n throw new Error(`Relation path '${relationPath}' cannot be hydrated.`);\n }\n\n if (mode === 'select') {\n if (\n relation.cardinality !== InternalRelationHydrationCardinality.SINGLE ||\n !relation.capabilities.joinable\n ) {\n throw new Error(`Relation path '${relationPath}' cannot be loaded with selectRelated(...).`);\n }\n } else if (relation.cardinality === InternalRelationHydrationCardinality.MANY) {\n if (!relation.capabilities.prefetchable) {\n throw new Error(`Relation path '${relationPath}' cannot be loaded with prefetchRelated(...).`);\n }\n } else if (!relation.capabilities.joinable) {\n throw new Error(`Relation path '${relationPath}' cannot be loaded with prefetchRelated(...).`);\n }\n\n const targetMeta = relation.targetMeta;\n if (!targetMeta) {\n throw new Error(`Relation path '${relationPath}' is missing target metadata.`);\n }\n\n builtPath = builtPath.length > 0 ? `${builtPath}__${segment}` : segment;\n const existing = currentChildren.get(segment);\n const nextNode =\n existing ??\n ({\n segment,\n relationEdge: relation,\n relationPath: builtPath,\n targetMeta,\n provenance: new Set<string>(),\n children: new Map<string, TraversalTrieNode>(),\n } satisfies TraversalTrieNode);\n nextNode.provenance.add(relationPath);\n currentChildren.set(segment, nextNode);\n currentChildren = nextNode.children;\n currentMeta = targetMeta;\n }\n }\n\n private buildPlannedChildren(children: Map<string, TraversalTrieNode>): {\n joinNodes: QueryHydrationPlanNode[];\n prefetchNodes: QueryHydrationPlanNode[];\n } {\n const joinNodes: QueryHydrationPlanNode[] = [];\n const prefetchNodes: QueryHydrationPlanNode[] = [];\n\n for (const child of children.values()) {\n const { joinNodes: joinChildren, prefetchNodes: prefetchChildren } = this.buildPlannedChildren(\n child.children\n );\n const plannedNode: QueryHydrationPlanNode = {\n nodeId: child.relationPath,\n relationName: child.segment,\n relationPath: child.relationPath,\n ownerModelKey: child.relationEdge.sourceModelKey,\n relationEdge: child.relationEdge,\n targetModelKey: child.relationEdge.targetModelKey,\n loadMode:\n child.relationEdge.cardinality === InternalRelationHydrationCardinality.SINGLE\n ? InternalRelationHydrationLoadMode.JOIN\n : InternalRelationHydrationLoadMode.PREFETCH,\n cardinality: child.relationEdge.cardinality,\n provenance: [...child.provenance],\n joinChildren,\n prefetchChildren,\n };\n\n if (plannedNode.loadMode === InternalRelationHydrationLoadMode.JOIN) {\n joinNodes.push(plannedNode);\n } else {\n prefetchNodes.push(plannedNode);\n }\n }\n\n return { joinNodes, prefetchNodes };\n }\n}\n","import { isError } from '@danceroutine/tango-core';\nimport type { LookupType } from '../domain/LookupType';\nimport type { QuerySetState } from '../domain/QuerySetState';\nimport type { TableMeta } from '../domain/TableMeta';\nimport type { QNode } from '../domain/QNode';\nimport type {\n CompiledHydrationNode,\n CompiledHydrationPlanRoot,\n CompiledJoinHydrationDescriptor,\n CompiledPrefetchQuery,\n CompiledQuery,\n} from '../domain/CompiledQuery';\nimport type { WhereClause } from '../domain/WhereClause';\nimport type { FilterInput } from '../domain/FilterInput';\nimport type { Adapter, SqlPlaceholders } from '../../connection/adapters/Adapter';\nimport { InternalRelationHydrationLoadMode } from '../domain/RelationMeta';\nimport { InternalDialect } from '../domain/internal/InternalDialect';\nimport { InternalPrefetchQueryKind } from '../domain/internal/InternalPrefetchQueryKind';\nimport { InternalQNodeType } from '../domain/internal/InternalQNodeType';\nimport { InternalLookupType } from '../domain/internal/InternalLookupType';\nimport { InternalSqlValidationPlanKind as SqlPlanKind } from '../../validation/internal/InternalSqlValidationPlanKind';\nimport { InternalValidatedFilterDescriptorKind } from '../../validation/internal/InternalValidatedFilterDescriptorKind';\nimport { OrmSqlSafetyAdapter } from '../../validation';\nimport type { ValidatedFilterDescriptor, ValidatedRelationMeta } from '../../validation/SQLValidationEngine';\nimport { QueryPlanner } from '../planning';\nimport type { QueryHydrationPlanNode } from '../planning';\n\nconst sqlSafetyAdapter = new OrmSqlSafetyAdapter();\n\ntype JoinCollection = {\n selects: string[];\n joins: string[];\n};\n\n/**\n * Compiles immutable `QuerySet` state into parameterized SQL and recursive\n * hydration execution artifacts.\n */\nexport class QueryCompiler {\n static readonly BRAND = 'tango.orm.query_compiler' as const;\n readonly __tangoBrand: typeof QueryCompiler.BRAND = QueryCompiler.BRAND;\n\n private readonly placeholders: SqlPlaceholders;\n\n constructor(\n private meta: TableMeta,\n private adapter: Adapter\n ) {\n this.placeholders = adapter.placeholders;\n }\n\n static isQueryCompiler(value: unknown): value is QueryCompiler {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === QueryCompiler.BRAND\n );\n }\n\n compile<T, TSourceModel = unknown>(state: QuerySetState<T, TSourceModel>): CompiledQuery {\n const hydrationPlan = new QueryPlanner(this.meta).plan(state);\n const validatedPlan = sqlSafetyAdapter.validate({\n kind: SqlPlanKind.SELECT,\n meta: this.meta,\n selectFields: state.select?.map(String),\n filterKeys: this.collectStateFilterKeys(state),\n orderFields: state.order?.map((order) => String(order.by)),\n relationNames: [],\n });\n const table = validatedPlan.meta.table;\n const whereParts: string[] = [];\n const params: unknown[] = [];\n\n if (state.q) {\n const result = this.compileQNode(state.q, params.length + 1, validatedPlan.filterKeys);\n if (result.sql) {\n whereParts.push(result.sql);\n params.push(...result.params);\n }\n }\n\n state.excludes?.forEach((exclude) => {\n const result = this.compileQNode(\n { kind: InternalQNodeType.NOT, node: exclude },\n params.length + 1,\n validatedPlan.filterKeys\n );\n if (result.sql) {\n whereParts.push(result.sql);\n params.push(...result.params);\n }\n });\n\n const baseSelects = state.select?.length\n ? state.select.map((field) => validatedPlan.selectFields[String(field)]!)\n : [`${table}.*`];\n const joinCollection: JoinCollection = { selects: [], joins: [] };\n const hiddenRootAliases: string[] = [];\n\n const compiledJoinNodes = hydrationPlan.joinNodes.map((node) =>\n this.compileHydrationNode(node, {\n rootTable: table,\n ownerMeta: this.meta,\n ownerAlias: table,\n collectRootJoins: true,\n rootSelectedFields: state.select?.map(String) ?? undefined,\n hiddenRootAliases,\n joinCollection,\n })\n );\n const compiledPrefetchNodes = hydrationPlan.prefetchNodes.map((node) =>\n this.compileHydrationNode(node, {\n rootTable: table,\n ownerMeta: this.meta,\n ownerAlias: table,\n collectRootJoins: false,\n rootSelectedFields: state.select?.map(String) ?? undefined,\n hiddenRootAliases,\n joinCollection,\n })\n );\n\n const select = [\n ...baseSelects,\n ...joinCollection.selects,\n ...this.buildRootHiddenSelects(compiledPrefetchNodes, table),\n ].join(', ');\n const whereSQL = whereParts.length ? ` WHERE ${whereParts.join(' AND ')}` : '';\n const orderSQL = ` ORDER BY ${\n state.order?.length\n ? state.order\n .map((order) => `${validatedPlan.orderFields[String(order.by)]!} ${order.dir.toUpperCase()}`)\n .join(', ')\n : `${table}.${validatedPlan.meta.pk} ASC`\n }`;\n const limitSQL = state.limit ? ` LIMIT ${state.limit}` : '';\n const offsetSQL = state.offset ? ` OFFSET ${state.offset}` : '';\n const sql = `SELECT ${select} FROM ${table}${joinCollection.joins.length ? ` ${joinCollection.joins.join(' ')}` : ''}${whereSQL}${orderSQL}${limitSQL}${offsetSQL}`;\n\n const compiledHydrationPlan: CompiledHydrationPlanRoot | undefined =\n compiledJoinNodes.length > 0 || compiledPrefetchNodes.length > 0\n ? {\n requestedPaths: hydrationPlan.requestedPaths,\n hiddenRootAliases: [...new Set(hiddenRootAliases)],\n joinNodes: compiledJoinNodes,\n prefetchNodes: compiledPrefetchNodes,\n }\n : undefined;\n\n return {\n sql,\n params,\n hydrationPlan: compiledHydrationPlan,\n };\n }\n\n compilePrefetch(node: CompiledHydrationNode, sourceValues: readonly (string | number)[]): CompiledPrefetchQuery {\n if (node.throughTable && node.throughSourceKey && node.throughTargetKey) {\n return this.compileManyToManyPrefetch(node, sourceValues);\n }\n\n const placeholders = this.placeholders.list(sourceValues.length);\n const validatedTarget = this.validatePrefetchTarget(node);\n const baseAlias = this.buildPrefetchBaseAlias(node.relationPath);\n const joinCollection: JoinCollection = { selects: [], joins: [] };\n\n for (const joinChild of node.joinChildren) {\n this.collectNestedJoinSql(joinChild, baseAlias, validatedTarget.columns, joinCollection);\n }\n\n const baseSelects = Object.keys(validatedTarget.columns).map((column) => `${baseAlias}.${column} AS ${column}`);\n return {\n kind: InternalPrefetchQueryKind.DIRECT,\n sql: `SELECT ${[...baseSelects, ...joinCollection.selects].join(', ')} FROM ${validatedTarget.table} ${baseAlias}${joinCollection.joins.length ? ` ${joinCollection.joins.join(' ')}` : ''} WHERE ${baseAlias}.${validatedTarget.targetKey} IN (${placeholders}) ORDER BY ${baseAlias}.${validatedTarget.targetKey} ASC, ${baseAlias}.${validatedTarget.primaryKey} ASC`,\n params: sourceValues,\n targetKey: validatedTarget.targetKey,\n targetColumns: validatedTarget.columns,\n };\n }\n\n compileManyToManyTargets(\n node: CompiledHydrationNode,\n targetIds: readonly (string | number)[]\n ): { sql: string; params: readonly unknown[] } {\n const placeholders = this.placeholders.list(targetIds.length);\n const validatedTarget = this.validatePrefetchTarget(node);\n const baseAlias = this.buildPrefetchBaseAlias(node.relationPath);\n const joinCollection: JoinCollection = { selects: [], joins: [] };\n\n for (const joinChild of node.joinChildren) {\n this.collectNestedJoinSql(joinChild, baseAlias, validatedTarget.columns, joinCollection);\n }\n\n const baseSelects = Object.keys(validatedTarget.columns).map((column) => `${baseAlias}.${column} AS ${column}`);\n return {\n sql: `SELECT ${[...baseSelects, ...joinCollection.selects].join(', ')} FROM ${validatedTarget.table} ${baseAlias}${joinCollection.joins.length ? ` ${joinCollection.joins.join(' ')}` : ''} WHERE ${baseAlias}.${validatedTarget.primaryKey} IN (${placeholders}) ORDER BY ${baseAlias}.${validatedTarget.primaryKey} ASC`,\n params: targetIds,\n };\n }\n\n private compileManyToManyPrefetch(\n node: CompiledHydrationNode,\n sourceValues: readonly (string | number)[]\n ): CompiledPrefetchQuery {\n const placeholders = this.placeholders.list(sourceValues.length);\n const throughValidated = sqlSafetyAdapter.validate({\n kind: SqlPlanKind.SELECT,\n meta: {\n table: node.throughTable!,\n pk: node.throughSourceKey!,\n columns: {\n [node.throughSourceKey!]: node.throughSourceColumnType ?? 'int',\n [node.throughTargetKey!]: node.throughTargetColumnType ?? 'int',\n },\n },\n filterKeys: [node.throughSourceKey!, node.throughTargetKey!],\n relationNames: [],\n });\n const ownerAlias = this.validateInternalAlias('__tango_m2m_owner');\n const targetAlias = this.validateInternalAlias('__tango_m2m_target');\n const throughSourceColumn = throughValidated.filterKeys[node.throughSourceKey!]!.field;\n const throughTargetColumn = throughValidated.filterKeys[node.throughTargetKey!]!.field;\n return {\n kind: InternalPrefetchQueryKind.MANY_TO_MANY,\n throughSql: `SELECT ${throughValidated.meta.table}.${throughSourceColumn} AS ${ownerAlias}, ${throughValidated.meta.table}.${throughTargetColumn} AS ${targetAlias} FROM ${throughValidated.meta.table} WHERE ${throughValidated.meta.table}.${throughSourceColumn} IN (${placeholders}) ORDER BY ${throughValidated.meta.table}.${throughSourceColumn} ASC, ${throughValidated.meta.table}.${throughTargetColumn} ASC`,\n throughParams: sourceValues,\n ownerAlias,\n targetAlias,\n targetTable: node.targetTable,\n targetPrimaryKey: node.targetPrimaryKey,\n targetColumns: node.targetColumns,\n };\n }\n\n private compileHydrationNode(\n node: QueryHydrationPlanNode,\n context: {\n rootTable: string;\n ownerMeta: TableMeta;\n ownerAlias: string;\n collectRootJoins: boolean;\n rootSelectedFields?: readonly string[];\n hiddenRootAliases: string[];\n joinCollection: JoinCollection;\n }\n ): CompiledHydrationNode {\n const validatedRelation = this.validateHydrationRelation(context.ownerMeta, node.relationName);\n const targetColumns = validatedRelation.targetColumns;\n const targetMeta = node.relationEdge.targetMeta;\n if (!targetMeta) {\n throw new Error(`Relation path '${node.relationPath}' is missing target metadata.`);\n }\n const compiledJoinChildren = node.joinChildren.map((child) =>\n this.compileHydrationNode(child, {\n ...context,\n ownerMeta: targetMeta,\n ownerAlias: this.buildJoinAlias(node.relationPath),\n collectRootJoins: context.collectRootJoins,\n })\n );\n const compiledPrefetchChildren = node.prefetchChildren.map((child) =>\n this.compileHydrationNode(child, {\n ...context,\n ownerMeta: targetMeta,\n ownerAlias: this.buildJoinAlias(node.relationPath),\n collectRootJoins: false,\n })\n );\n\n let joinDescriptor: CompiledJoinHydrationDescriptor | undefined;\n if (node.loadMode === InternalRelationHydrationLoadMode.JOIN) {\n joinDescriptor = {\n alias: this.buildJoinAlias(node.relationPath),\n columns: Object.fromEntries(\n Object.keys(targetColumns).map((column) => [\n column,\n this.buildHydrationColumnAlias(node.relationPath, column),\n ])\n ),\n };\n\n if (context.collectRootJoins) {\n context.joinCollection.joins.push(\n `LEFT JOIN ${validatedRelation.table} ${joinDescriptor.alias} ON ${joinDescriptor.alias}.${validatedRelation.targetKey} = ${context.ownerAlias}.${validatedRelation.sourceKey}`\n );\n context.joinCollection.selects.push(\n ...Object.entries(joinDescriptor.columns).map(\n ([column, alias]) => `${joinDescriptor!.alias}.${column} AS ${alias}`\n )\n );\n }\n }\n\n const ownerSourceAccessor =\n node.loadMode === InternalRelationHydrationLoadMode.PREFETCH &&\n context.collectRootJoins === false &&\n context.ownerAlias === context.rootTable &&\n context.rootSelectedFields?.length &&\n !context.rootSelectedFields.includes(validatedRelation.sourceKey)\n ? this.buildPrefetchSourceAlias(node.relationPath, validatedRelation.sourceKey)\n : validatedRelation.sourceKey;\n\n if (\n node.loadMode === InternalRelationHydrationLoadMode.PREFETCH &&\n ownerSourceAccessor !== validatedRelation.sourceKey\n ) {\n context.hiddenRootAliases.push(ownerSourceAccessor);\n }\n\n return {\n nodeId: node.nodeId,\n relationName: node.relationName,\n relationPath: node.relationPath,\n ownerModelKey: node.ownerModelKey,\n targetModelKey: node.targetModelKey,\n loadMode: node.loadMode,\n cardinality: node.cardinality,\n sourceKey: validatedRelation.sourceKey,\n ownerSourceAccessor,\n targetKey: validatedRelation.targetKey,\n targetTable: validatedRelation.table,\n targetPrimaryKey: node.relationEdge.targetPrimaryKey,\n throughTable: node.relationEdge.throughTable,\n throughSourceKey: node.relationEdge.throughSourceKey,\n throughTargetKey: node.relationEdge.throughTargetKey,\n throughSourceColumnType: node.relationEdge.throughSourceColumnType,\n throughTargetColumnType: node.relationEdge.throughTargetColumnType,\n targetColumns,\n provenance: node.provenance,\n joinChildren: compiledJoinChildren,\n prefetchChildren: compiledPrefetchChildren,\n join: joinDescriptor,\n };\n }\n\n private validateHydrationRelation(\n ownerMeta: TableMeta,\n relationName: string\n ): NonNullable<TableMeta['relations']>[string] {\n return sqlSafetyAdapter.validate({\n kind: SqlPlanKind.SELECT,\n meta: ownerMeta,\n relationNames: [relationName],\n }).relations[relationName]!;\n }\n\n private buildRootHiddenSelects(nodes: readonly CompiledHydrationNode[], table: string): string[] {\n return nodes.flatMap((node) => {\n const select =\n node.ownerSourceAccessor !== node.sourceKey\n ? [`${table}.${node.sourceKey} AS ${node.ownerSourceAccessor}`]\n : [];\n return [...select, ...this.buildRootHiddenSelects(node.prefetchChildren, table)];\n });\n }\n\n private validatePrefetchTarget(node: CompiledHydrationNode): {\n table: string;\n primaryKey: string;\n targetKey: string;\n columns: Record<string, string>;\n } {\n try {\n const validated = sqlSafetyAdapter.validate({\n kind: SqlPlanKind.SELECT,\n meta: {\n table: node.targetTable,\n pk: node.targetPrimaryKey,\n columns: node.targetColumns,\n },\n filterKeys: [node.targetKey],\n });\n\n return {\n table: validated.meta.table,\n primaryKey: validated.meta.pk,\n targetKey: validated.filterKeys[node.targetKey]!.field,\n columns: validated.meta.columns,\n };\n } catch (error) {\n const message = isError(error) ? error.message : String(error);\n throw new Error(`Compiled prefetch query failed validation: ${message}`, { cause: error });\n }\n }\n\n private collectNestedJoinSql(\n node: CompiledHydrationNode,\n ownerAlias: string,\n ownerColumns: Record<string, string>,\n collection: JoinCollection\n ): void {\n if (!node.join) {\n return;\n }\n\n const validatedTarget = this.validatePrefetchJoinTarget(node, ownerColumns);\n const validatedJoinAlias = this.validateInternalAlias(node.join.alias);\n const validatedJoinColumns = Object.fromEntries(\n Object.entries(node.join.columns).map(([column, alias]) => {\n if (!(column in validatedTarget.columns)) {\n throw new Error(\n `Compiled prefetch query failed validation: unknown nested join column '${column}'.`\n );\n }\n return [column, this.validateInternalAlias(alias)];\n })\n );\n\n collection.joins.push(\n `LEFT JOIN ${validatedTarget.table} ${validatedJoinAlias} ON ${validatedJoinAlias}.${validatedTarget.targetKey} = ${ownerAlias}.${node.sourceKey}`\n );\n collection.selects.push(\n ...Object.entries(validatedJoinColumns).map(\n ([column, alias]) => `${validatedJoinAlias}.${column} AS ${alias}`\n )\n );\n\n for (const child of node.joinChildren) {\n this.collectNestedJoinSql(child, validatedJoinAlias, validatedTarget.columns, collection);\n }\n }\n\n private validatePrefetchJoinTarget(\n node: CompiledHydrationNode,\n ownerColumns: Record<string, string>\n ): {\n table: string;\n primaryKey: string;\n targetKey: string;\n columns: Record<string, string>;\n } {\n if (!(node.sourceKey in ownerColumns)) {\n throw new Error(\n `Compiled prefetch query failed validation: unknown owner column '${node.sourceKey}' for nested join.`\n );\n }\n\n return this.validatePrefetchTarget(node);\n }\n\n private validateInternalAlias(alias: string): string {\n if (!/^__tango_[A-Za-z0-9_]+$/.test(alias)) {\n throw new Error(`Compiled prefetch query failed validation: invalid internal alias '${alias}'.`);\n }\n\n return alias;\n }\n\n private buildJoinAlias(relationPath: string): string {\n return this.assertInternalAliasDoesNotCollide(`__tango_join_${this.sanitizeRelationPath(relationPath)}`);\n }\n\n private buildPrefetchBaseAlias(relationPath: string): string {\n return this.assertInternalAliasDoesNotCollide(\n `__tango_prefetch_base_${this.sanitizeRelationPath(relationPath)}`\n );\n }\n\n private buildHydrationColumnAlias(relationPath: string, column: string): string {\n return this.assertInternalAliasDoesNotCollide(\n `__tango_hydrate_${this.sanitizeRelationPath(relationPath)}_${column}`\n );\n }\n\n private buildPrefetchSourceAlias(relationPath: string, sourceKey: string): string {\n return this.assertInternalAliasDoesNotCollide(\n `__tango_prefetch_${this.sanitizeRelationPath(relationPath)}_${sourceKey}`\n );\n }\n\n private buildFilterAlias(relationPath: string, suffix: string): string {\n return this.assertInternalAliasDoesNotCollide(\n `__tango_filter_${this.sanitizeRelationPath(relationPath)}_${suffix}`\n );\n }\n\n private sanitizeRelationPath(relationPath: string): string {\n return relationPath.replace(/[^a-zA-Z0-9]+/g, '_');\n }\n\n private assertInternalAliasDoesNotCollide(alias: string): string {\n if (alias in this.meta.columns) {\n throw new Error(`Internal query alias '${alias}' collides with a field on table '${this.meta.table}'.`);\n }\n return alias;\n }\n\n private compileQNode<T>(\n node: QNode<T>,\n paramIndex: number,\n filterKeys: Record<string, ValidatedFilterDescriptor>\n ): WhereClause {\n switch (node.kind) {\n case InternalQNodeType.ATOM:\n return this.compileAtom(node.where || {}, paramIndex, filterKeys);\n case InternalQNodeType.AND:\n return this.compileAnd(node.nodes || [], paramIndex, filterKeys);\n case InternalQNodeType.OR:\n return this.compileOr(node.nodes || [], paramIndex, filterKeys);\n case InternalQNodeType.NOT:\n return this.compileNot(node.node!, paramIndex, filterKeys);\n default:\n return { sql: '', params: [] };\n }\n }\n\n private compileAtom<T>(\n where: FilterInput<T>,\n paramIndex: number,\n filterKeys: Record<string, ValidatedFilterDescriptor>\n ): WhereClause {\n const entries = Object.entries(where).filter(([, value]) => value !== undefined);\n\n const { parts, params } = entries.reduce<{ parts: string[]; params: unknown[] }>(\n (accumulator, [key, value]) => {\n const descriptor = filterKeys[String(key)]!;\n const idx = paramIndex + accumulator.params.length;\n const clause =\n descriptor.kind === InternalValidatedFilterDescriptorKind.COLUMN\n ? this.lookupToSQL(descriptor.qualifiedColumn, descriptor.lookup, value, idx)\n : this.compileRelationFilter(descriptor, value, idx);\n accumulator.parts.push(clause.sql);\n accumulator.params.push(...clause.params);\n return accumulator;\n },\n { parts: [], params: [] }\n );\n\n return {\n sql: parts.length ? `(${parts.join(' AND ')})` : '',\n params,\n };\n }\n\n private compileAnd<T>(\n nodes: QNode<T>[],\n paramIndex: number,\n filterKeys: Record<string, ValidatedFilterDescriptor>\n ): WhereClause {\n const { parts, params } = nodes.reduce<{ parts: string[]; params: unknown[] }>(\n (accumulator, node) => {\n const result = this.compileQNode(node, paramIndex + accumulator.params.length, filterKeys);\n if (result.sql) {\n accumulator.parts.push(result.sql);\n accumulator.params.push(...result.params);\n }\n return accumulator;\n },\n { parts: [], params: [] }\n );\n\n return {\n sql: parts.length ? `(${parts.join(' AND ')})` : '',\n params,\n };\n }\n\n private compileOr<T>(\n nodes: QNode<T>[],\n paramIndex: number,\n filterKeys: Record<string, ValidatedFilterDescriptor>\n ): WhereClause {\n const { parts, params } = nodes.reduce<{ parts: string[]; params: unknown[] }>(\n (accumulator, node) => {\n const result = this.compileQNode(node, paramIndex + accumulator.params.length, filterKeys);\n if (result.sql) {\n accumulator.parts.push(result.sql);\n accumulator.params.push(...result.params);\n }\n return accumulator;\n },\n { parts: [], params: [] }\n );\n\n return {\n sql: parts.length ? `(${parts.join(' OR ')})` : '',\n params,\n };\n }\n\n private compileNot<T>(\n node: QNode<T>,\n paramIndex: number,\n filterKeys: Record<string, ValidatedFilterDescriptor>\n ): WhereClause {\n const result = this.compileQNode(node, paramIndex, filterKeys);\n if (!result.sql) {\n return { sql: '', params: [] };\n }\n\n return {\n sql: `(NOT ${result.sql})`,\n params: result.params,\n };\n }\n\n private compileRelationFilter(\n descriptor: Extract<ValidatedFilterDescriptor, { kind: typeof InternalValidatedFilterDescriptorKind.RELATION }>,\n value: unknown,\n paramIndex: number\n ): WhereClause {\n return this.buildRelationFilterExists(\n this.meta.table,\n descriptor.relationChain,\n descriptor.terminalColumn,\n descriptor.lookup,\n value,\n paramIndex,\n descriptor.relationPath\n );\n }\n\n private buildRelationFilterExists(\n ownerAlias: string,\n relationChain: readonly ValidatedRelationMeta[],\n terminalColumn: string,\n lookup: LookupType,\n value: unknown,\n paramIndex: number,\n relationPath: string\n ): WhereClause {\n const [relation, ...rest] = relationChain;\n if (!relation) {\n throw new Error(`Cannot compile empty relation filter path '${relationPath}'.`);\n }\n\n const targetAlias = this.buildFilterAlias(relationPath, `target_${relation.alias}_${rest.length}`);\n const targetPredicate =\n rest.length === 0\n ? this.lookupToSQL(`${targetAlias}.${terminalColumn}`, lookup, value, paramIndex)\n : this.buildRelationFilterExists(\n targetAlias,\n rest,\n terminalColumn,\n lookup,\n value,\n paramIndex,\n relationPath\n );\n\n if (relation.throughTable && relation.throughSourceKey && relation.throughTargetKey) {\n const throughAlias = this.buildFilterAlias(relationPath, `through_${relation.alias}_${rest.length}`);\n return {\n sql: `EXISTS (SELECT 1 FROM ${relation.throughTable} ${throughAlias} INNER JOIN ${relation.table} ${targetAlias} ON ${targetAlias}.${relation.targetKey} = ${throughAlias}.${relation.throughTargetKey} WHERE ${throughAlias}.${relation.throughSourceKey} = ${ownerAlias}.${relation.sourceKey} AND ${targetPredicate.sql})`,\n params: targetPredicate.params,\n };\n }\n\n return {\n sql: `EXISTS (SELECT 1 FROM ${relation.table} ${targetAlias} WHERE ${targetAlias}.${relation.targetKey} = ${ownerAlias}.${relation.sourceKey} AND ${targetPredicate.sql})`,\n params: targetPredicate.params,\n };\n }\n\n private lookupToSQL(col: string, lookup: LookupType, value: unknown, paramIndex: number): WhereClause {\n const placeholder = this.placeholders.at(paramIndex);\n const normalized = this.normalizeParam(value);\n\n switch (lookup) {\n case InternalLookupType.EXACT:\n if (value === null) {\n return { sql: `${col} IS NULL`, params: [] };\n }\n return { sql: `${col} = ${placeholder}`, params: [normalized] };\n case InternalLookupType.LT:\n return { sql: `${col} < ${placeholder}`, params: [normalized] };\n case InternalLookupType.LTE:\n return { sql: `${col} <= ${placeholder}`, params: [normalized] };\n case InternalLookupType.GT:\n return { sql: `${col} > ${placeholder}`, params: [normalized] };\n case InternalLookupType.GTE:\n return { sql: `${col} >= ${placeholder}`, params: [normalized] };\n case InternalLookupType.IN: {\n const entries = (Array.isArray(value) ? value : [value]).map((entry) => this.normalizeParam(entry));\n if (entries.length === 0) {\n return { sql: '1=0', params: [] };\n }\n const placeholders = this.placeholders.listFromOffset(entries.length, paramIndex - 1);\n return { sql: `${col} IN (${placeholders})`, params: entries };\n }\n case InternalLookupType.ISNULL:\n return { sql: value ? `${col} IS NULL` : `${col} IS NOT NULL`, params: [] };\n case InternalLookupType.CONTAINS:\n return { sql: `${col} LIKE ${placeholder}`, params: [`%${value}%`] };\n case InternalLookupType.ICONTAINS: {\n const lowerCol = this.adapter.dialect === InternalDialect.POSTGRES ? `LOWER(${col})` : `${col}`;\n return { sql: `${lowerCol} LIKE ${placeholder}`, params: [`%${String(value).toLowerCase()}%`] };\n }\n case InternalLookupType.STARTSWITH:\n return { sql: `${col} LIKE ${placeholder}`, params: [`${value}%`] };\n case InternalLookupType.ISTARTSWITH: {\n const lowerCol = this.adapter.dialect === InternalDialect.POSTGRES ? `LOWER(${col})` : `${col}`;\n return { sql: `${lowerCol} LIKE ${placeholder}`, params: [`${String(value).toLowerCase()}%`] };\n }\n case InternalLookupType.ENDSWITH:\n return { sql: `${col} LIKE ${placeholder}`, params: [`%${value}`] };\n case InternalLookupType.IENDSWITH: {\n const lowerCol = this.adapter.dialect === InternalDialect.POSTGRES ? `LOWER(${col})` : `${col}`;\n return { sql: `${lowerCol} LIKE ${placeholder}`, params: [`%${String(value).toLowerCase()}`] };\n }\n default:\n throw new Error(`Unknown lookup: ${lookup}`);\n }\n }\n\n private normalizeParam(value: unknown): unknown {\n if (this.adapter.dialect === InternalDialect.SQLITE && typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n }\n\n private collectStateFilterKeys<T, TSourceModel = unknown>(state: QuerySetState<T, TSourceModel>): string[] {\n const filterKeys = new Set<string>();\n if (state.q) {\n this.collectNodeFilterKeys(state.q, filterKeys);\n }\n\n state.excludes?.forEach((exclude) => this.collectNodeFilterKeys(exclude, filterKeys));\n return [...filterKeys];\n }\n\n private collectNodeFilterKeys<T, TSourceModel = unknown>(\n node: QNode<T, TSourceModel>,\n filterKeys: Set<string>\n ): void {\n Object.keys(node.where ?? {}).forEach((key) => filterKeys.add(key));\n node.nodes?.forEach((child) => this.collectNodeFilterKeys(child, filterKeys));\n if (node.node) {\n this.collectNodeFilterKeys(node.node, filterKeys);\n }\n }\n}\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { QueryCompiler } from './QueryCompiler';\n","import { getLogger } from '@danceroutine/tango-core';\n\nlet didWarnDeprecatedResults = false;\n\n/**\n * Values materialized by {@link QuerySet.fetch}, iterable like an array plus `length`, `map`, `at`, and `toArray`.\n *\n * Prefer iteration or `items` over the deprecated `results` getter, which warns once per process when accessed.\n */\nexport class QueryResult<T> implements Iterable<T> {\n static readonly BRAND = 'tango.orm.query_result' as const;\n readonly __tangoBrand: typeof QueryResult.BRAND = QueryResult.BRAND;\n\n readonly items: readonly T[];\n\n constructor(items: readonly T[]) {\n this.items = items;\n }\n\n /**\n * Runtime narrowing for values that may be a plain array or a `QueryResult` instance.\n */\n static isQueryResult<T>(value: unknown): value is QueryResult<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === QueryResult.BRAND\n );\n }\n\n /**\n * Sync iteration over materialized rows.\n */\n [Symbol.iterator](): Iterator<T> {\n return this.items[Symbol.iterator]();\n }\n\n /** Number of materialized rows. */\n get length(): number {\n return this.items.length;\n }\n\n /** Same as `Array#map` on the materialized rows. */\n map<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: unknown): U[] {\n return this.items.map(callbackfn, thisArg);\n }\n\n /** Indexed read with support for negative indices, like `Array#at`. */\n at(index: number): T | undefined {\n return this.items.at(index);\n }\n\n /** Returns a shallow copy of the materialized rows as a plain array. */\n toArray(): T[] {\n return [...this.items];\n }\n\n /**\n * @deprecated Use iteration, `length`, `map`, or `toArray()` instead.\n */\n get results(): readonly T[] {\n if (!didWarnDeprecatedResults) {\n didWarnDeprecatedResults = true;\n getLogger('tango.orm.query_result').warn(\n '`QueryResult.results` is deprecated. Use iteration, `length`, `map`, or `toArray()` instead.'\n );\n }\n return this.items;\n }\n}\n","export const InternalRelationKind = {\n HAS_MANY: 'hasMany',\n BELONGS_TO: 'belongsTo',\n HAS_ONE: 'hasOne',\n MANY_TO_MANY: 'manyToMany',\n} as const;\n","import { ModelRegistry } from '@danceroutine/tango-schema';\nimport type { Model as SchemaModel } from '@danceroutine/tango-schema/domain';\nimport type { TableMeta } from './TableMeta';\nimport type { RelationMeta } from './RelationMeta';\nimport { InternalRelationKind } from './internal/InternalRelationKind';\n\n/**\n * Build registry-backed recursive table metadata for query planning and\n * hydration execution.\n */\nexport class TableMetaFactory {\n static create(model: SchemaModel): TableMeta {\n const owner = model.metadata.key ? ModelRegistry.getOwner(model) : undefined;\n const cache = new Map<string, TableMeta>();\n return TableMetaFactory.createWithCache(model, owner, cache);\n }\n\n private static createWithCache(\n model: SchemaModel,\n owner: ModelRegistry | undefined,\n cache: Map<string, TableMeta>\n ): TableMeta {\n if (model.metadata.key) {\n const cached = cache.get(model.metadata.key);\n if (cached) {\n return cached;\n }\n }\n\n const pkField = model.metadata.fields.find((field) => field.primaryKey);\n if (!pkField) {\n throw new Error(`Model '${model.metadata.name}' cannot attach a manager without a primary key field.`);\n }\n\n const tableMeta: TableMeta = {\n modelKey: model.metadata.key,\n table: model.metadata.table,\n pk: pkField.name,\n columns: Object.fromEntries(model.metadata.fields.map((field) => [field.name, field.type])),\n };\n\n if (model.metadata.key) {\n cache.set(model.metadata.key, tableMeta);\n }\n\n if (!model.metadata.key || !owner) {\n return tableMeta;\n }\n\n const relations = owner.getResolvedRelationGraph().byModel.get(model.metadata.key);\n if (!relations || relations.size === 0) {\n return tableMeta;\n }\n\n tableMeta.relations = Object.fromEntries(\n Array.from(relations.entries())\n .filter(([, relation]) => relation.capabilities.queryable && relation.capabilities.hydratable)\n .map(([name, relation]) => {\n const targetModel = owner.getByKey(relation.targetModelKey)!;\n const targetMeta = TableMetaFactory.createWithCache(targetModel, owner, cache);\n const { queryable, hydratable } = relation.capabilities;\n const isSingleRelation =\n relation.kind === InternalRelationKind.BELONGS_TO ||\n relation.kind === InternalRelationKind.HAS_ONE;\n const targetColumns = Object.fromEntries(\n targetModel.metadata.fields.map((field) => [field.name, field.type])\n );\n let throughSourceColumnType: string | undefined;\n let throughTargetColumnType: string | undefined;\n if (\n relation.kind === InternalRelationKind.MANY_TO_MANY &&\n relation.throughModelKey &&\n relation.throughSourceKey &&\n relation.throughTargetKey\n ) {\n const throughModel = owner.getByKey(relation.throughModelKey);\n throughSourceColumnType = throughModel?.metadata.fields.find(\n (field) => field.name === relation.throughSourceKey\n )?.type;\n throughTargetColumnType = throughModel?.metadata.fields.find(\n (field) => field.name === relation.throughTargetKey\n )?.type;\n }\n const capabilities: RelationMeta['capabilities'] = {\n queryable,\n hydratable,\n joinable: isSingleRelation && queryable && hydratable,\n prefetchable: queryable && hydratable,\n };\n const sourceKey =\n relation.kind === InternalRelationKind.MANY_TO_MANY\n ? tableMeta.pk\n : relation.kind === InternalRelationKind.BELONGS_TO\n ? relation.localFieldName\n : relation.targetFieldName;\n const targetKey =\n relation.kind === InternalRelationKind.MANY_TO_MANY\n ? targetMeta.pk\n : relation.kind === InternalRelationKind.BELONGS_TO\n ? relation.targetFieldName\n : relation.localFieldName;\n\n return [\n name,\n {\n edgeId: relation.edgeId,\n sourceModelKey: relation.sourceModelKey,\n targetModelKey: relation.targetModelKey,\n kind: relation.kind as RelationMeta['kind'],\n cardinality: isSingleRelation ? 'single' : 'many',\n capabilities,\n table: targetModel.metadata.table,\n sourceKey: sourceKey as string,\n targetKey: targetKey as string,\n throughTable: relation.throughTable,\n throughModelKey: relation.throughModelKey,\n throughSourceKey: relation.throughSourceKey,\n throughTargetKey: relation.throughTargetKey,\n throughSourceColumnType,\n throughTargetColumnType,\n targetPrimaryKey: targetMeta.pk,\n targetColumns,\n alias: relation.alias,\n targetMeta,\n } satisfies RelationMeta,\n ];\n })\n );\n\n return tableMeta;\n }\n}\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport type { CompiledQuery } from './CompiledQuery';\nexport type { Dialect } from './Dialect';\nexport type { Direction } from './Direction';\nexport type { FilterInput } from './FilterInput';\nexport type { FilterKey } from './FilterKey';\nexport type { FilterValue } from './FilterValue';\nexport type { LookupType } from './LookupType';\nexport type { OrderSpec } from './OrderSpec';\nexport type { OrderToken } from './OrderToken';\nexport type { QNode } from './QNode';\nexport { QueryResult } from './QueryResult';\nexport type { QuerySetState } from './QuerySetState';\nexport type { RelationMeta } from './RelationMeta';\nexport type {\n ForwardSingleRelations,\n GeneratedRelationFilterKeys,\n GeneratedHydratedRelationMap,\n GeneratedPrefetchRelatedPathKeys,\n GeneratedSelectRelatedPathKeys,\n HydratedQueryResult,\n HydratedRelationMap,\n ManyRelationHydrationCardinality,\n MaybeHydratedRelationMap,\n PrefetchRelatedRelations,\n RelationKeys,\n RelationHydrationCardinality,\n ReverseCollectionRelations,\n ReverseSingleRelations,\n SelectRelatedRelations,\n SingleRelationHydrationCardinality,\n} from './RelationTyping';\nexport { InternalRelationHydrationCardinality } from './RelationTyping';\nexport type { TableMeta } from './TableMeta';\nexport { TableMetaFactory } from './TableMetaFactory';\nexport type { WhereClause } from './WhereClause';\n","export const InternalDirection = {\n ASC: 'asc',\n DESC: 'desc',\n} as const;\n","import type { FilterInput } from '../domain/FilterInput';\nimport type { QNode } from '../domain/QNode';\nimport { InternalQNodeType } from '../domain/internal/InternalQNodeType';\n\nexport function isQNodeLike<T>(value: FilterInput<T> | QNode<T>): value is QNode<T> {\n if (typeof value !== 'object' || value === null || '__tangoBrand' in value) {\n return false;\n }\n\n switch ((value as { kind?: unknown }).kind) {\n case InternalQNodeType.ATOM:\n return 'where' in value;\n case InternalQNodeType.AND:\n case InternalQNodeType.OR:\n return Array.isArray((value as { nodes?: unknown }).nodes);\n case InternalQNodeType.NOT:\n return 'node' in value;\n default:\n return false;\n }\n}\n","import type { QNode } from './domain/QNode';\nimport type { FilterInput } from './domain/FilterInput';\nimport { InternalQNodeType } from './domain/internal/InternalQNodeType';\nimport { isQNodeLike } from './internal/isQNodeLike';\n\n/**\n * Static builder for composing boolean query expressions.\n *\n * This mirrors Django's `Q(...)` composition patterns and is intended\n * for ergonomic construction of nested `AND`/`OR`/`NOT` trees.\n */\nexport class QBuilder {\n static readonly BRAND = 'tango.orm.q_builder' as const;\n readonly __tangoBrand: typeof QBuilder.BRAND = QBuilder.BRAND;\n\n /**\n * Narrow an unknown value to `QBuilder`.\n */\n static isQBuilder(value: unknown): value is QBuilder {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === QBuilder.BRAND\n );\n }\n\n /**\n * Combine multiple filter fragments using logical `AND`.\n */\n static and<T, TSourceModel = unknown>(\n ...nodes: Array<FilterInput<T, TSourceModel> | QNode<T, TSourceModel>>\n ): QNode<T, TSourceModel> {\n return {\n kind: InternalQNodeType.AND,\n nodes: nodes.map(QBuilder.wrapNode),\n };\n }\n\n /**\n * Combine multiple filter fragments using logical `OR`.\n */\n static or<T, TSourceModel = unknown>(\n ...nodes: Array<FilterInput<T, TSourceModel> | QNode<T, TSourceModel>>\n ): QNode<T, TSourceModel> {\n return {\n kind: InternalQNodeType.OR,\n nodes: nodes.map(QBuilder.wrapNode),\n };\n }\n\n /**\n * Negate a filter fragment using logical `NOT`.\n */\n static not<T, TSourceModel = unknown>(\n node: FilterInput<T, TSourceModel> | QNode<T, TSourceModel>\n ): QNode<T, TSourceModel> {\n return {\n kind: InternalQNodeType.NOT,\n node: QBuilder.wrapNode(node),\n };\n }\n\n private static wrapNode<T, TSourceModel = unknown>(\n input: FilterInput<T, TSourceModel> | QNode<T, TSourceModel>\n ): QNode<T, TSourceModel> {\n if (isQNodeLike(input)) {\n return input;\n }\n return {\n kind: InternalQNodeType.ATOM,\n where: input as FilterInput<T, TSourceModel>,\n };\n }\n}\n","import type { DBClient } from '../connection/clients/DBClient';\nimport type { Adapter } from '../connection/adapters/Adapter';\nimport type { QuerySetState } from './domain/QuerySetState';\nimport type { TableMeta } from './domain/TableMeta';\nimport type { QNode } from './domain/QNode';\nimport { NotFoundError, MultipleObjectsReturned } from '@danceroutine/tango-core';\nimport { QueryResult } from './domain/QueryResult';\nimport type { OrderToken } from './domain/OrderToken';\nimport type { OrderSpec } from './domain/OrderSpec';\nimport type { FilterInput } from './domain/FilterInput';\nimport type { CompiledQuery } from './domain/CompiledQuery';\nimport type { CompiledHydrationNode } from './domain/CompiledQuery';\nimport type {\n GeneratedHydratedRelationMap,\n GeneratedPrefetchRelatedPathKeys,\n GeneratedSelectRelatedPathKeys,\n HydratedQueryResult,\n ManyRelationHydrationCardinality,\n MaybeHydratedRelationMap,\n PrefetchRelatedRelations,\n RelationKeys,\n SelectRelatedRelations,\n SingleRelationHydrationCardinality,\n} from './domain/RelationTyping';\nimport { InternalRelationHydrationCardinality } from './domain/RelationTyping';\nimport { InternalQNodeType } from './domain/internal/InternalQNodeType';\nimport { InternalDirection } from './domain/internal/InternalDirection';\nimport { InternalDialect } from './domain/internal/InternalDialect';\nimport { InternalPrefetchQueryKind } from './domain/internal/InternalPrefetchQueryKind';\nimport { QBuilder as Q } from './QBuilder';\nimport { QueryCompiler } from './compiler';\nimport { isQNodeLike } from './internal/isQNodeLike';\n// TODO revisit this later. QuerySet is getting very heavy between handling query building, prefetching, canonicalization, and hydration, and caching.\n/**\n * Query execution seam consumed by `QuerySet`.\n *\n * Application code usually reaches this through `Model.objects` or testing\n * fixtures rather than implementing it directly.\n *\n * @template TModel - The model row type returned by the database client\n */\nexport interface QueryExecutor<TModel> {\n meta: TableMeta;\n client: DBClient;\n adapter: Adapter;\n run(compiled: CompiledQuery): Promise<TModel[]>;\n // TODO revisit this and determine if we have enough complexity to justify a recordfactory\n /**\n * Optional hook invoked by `QuerySet` after a record has been\n * materialized so executors can attach related-manager accessors\n * (such as the many-to-many related manager) onto the record.\n *\n * The optional `modelKey` argument lets the executor route the attach\n * call to the correct model when the record belongs to a related\n * model rather than the executor's own source model. Implementations\n * must not overwrite existing properties on the record so prior\n * hydration assignments survive the attach pass.\n */\n attachPersistedRecordAccessors?(record: Record<string, unknown>, modelKey?: string): void;\n}\n\ntype QueryShapeFunction<TInput, TOutput> = (row: TInput) => TOutput;\n\ntype QueryShapeParser<TInput, TOutput> = {\n parse: (row: TInput) => TOutput;\n};\n\ntype QueryShape<TInput> = QueryShapeFunction<TInput, unknown> | QueryShapeParser<TInput, unknown>;\n\ntype QueryShapeOutput<TInput, TShape> =\n TShape extends QueryShapeFunction<TInput, infer TOutput>\n ? TOutput\n : TShape extends QueryShapeParser<TInput, infer TOutput>\n ? TOutput\n : never;\n\ntype TargetColumnMetadata = {\n targetColumns: Record<string, string>;\n};\n\ntype ProjectedResult<\n TModel extends Record<string, unknown>,\n TKeys extends readonly (keyof TModel)[],\n> = number extends TKeys['length'] ? TModel : [TKeys[number]] extends [never] ? TModel : Pick<TModel, TKeys[number]>;\n\n/**\n * Django-inspired query builder for constructing and executing database queries.\n * Provides a fluent API for filtering, ordering, pagination, projection, and\n * nested relation hydration.\n *\n * @template TModel - The full model row type used for query composition\n * @template TBaseResult - The selected base-row shape returned by execution methods\n * @template TSourceModel - The source Tango model used for typed relation metadata\n * @template THydrated - Relation properties accumulated by eager-loading calls\n *\n * @example\n * ```typescript\n * const users = await TodoModel.objects\n * .query()\n * .filter({ active: true })\n * .filter(Q.or({ role: 'admin' }, { role: 'moderator' }))\n * .orderBy('-createdAt')\n * .limit(10)\n * .fetch();\n * ```\n */\nexport abstract class QuerySet<\n TModel extends Record<string, unknown>,\n TBaseResult extends Record<string, unknown> = TModel,\n TSourceModel = unknown,\n THydrated extends Record<string, unknown> = Record<never, never>,\n> implements AsyncIterable<HydratedQueryResult<TBaseResult, THydrated>> {\n static readonly BRAND = 'tango.orm.query_set' as const;\n readonly __tangoBrand: typeof QuerySet.BRAND = QuerySet.BRAND;\n private evaluationCache?: Promise<QueryResult<HydratedQueryResult<TBaseResult, THydrated>>>;\n\n constructor(\n protected executor: QueryExecutor<TModel>,\n protected state: QuerySetState<TModel, TSourceModel> = {}\n ) {}\n\n /**\n * Create another queryset of the same runtime family with the supplied\n * query state. Concrete subclasses implement this so fluent calls keep\n * their subclass-specific execution behavior instead of falling back to\n * the standard queryset implementation.\n */\n protected abstract spawn<\n TNextBaseResult extends Record<string, unknown> = TBaseResult,\n TNextHydrated extends Record<string, unknown> = THydrated,\n >(state: QuerySetState<TModel, TSourceModel>): QuerySet<TModel, TNextBaseResult, TSourceModel, TNextHydrated>;\n\n /**\n * Narrow an unknown value to `QuerySet`.\n */\n static isQuerySet<TModel extends Record<string, unknown>, TResult extends Record<string, unknown> = TModel>(\n value: unknown\n ): value is QuerySet<TModel, TResult> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === QuerySet.BRAND\n );\n }\n\n /**\n * Translate user-facing order tokens like `'name'` or `'-createdAt'` into\n * the internal `OrderSpec` array used by `QuerySetState`.\n *\n * Exposed as `protected` so subclasses can compose the same parse logic\n * when they need to return their own concrete type from `orderBy` without\n * reaching into a base-class instance's protected state.\n */\n protected static buildOrderSpecs<T extends Record<string, unknown>>(\n tokens: readonly OrderToken<T>[]\n ): OrderSpec<T>[] {\n return tokens.map((t) => {\n const str = String(t);\n if (str.startsWith('-')) {\n return { by: str.slice(1) as keyof T, dir: InternalDirection.DESC };\n }\n return { by: t as keyof T, dir: InternalDirection.ASC };\n });\n }\n\n private static invertOrderSpec<T extends Record<string, unknown>>(\n order: QuerySetState<T>['order']\n ): NonNullable<QuerySetState<T>['order']> {\n if (!order?.length) {\n return [];\n }\n return order.map((spec) => ({\n by: spec.by,\n dir: spec.dir === InternalDirection.ASC ? InternalDirection.DESC : InternalDirection.ASC,\n }));\n }\n\n /**\n * Add a filter expression to the query.\n *\n * Multiple `filter()` calls are composed with `AND`.\n */\n filter(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>\n ): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n const wrapped: QNode<TModel, TSourceModel> = isQNodeLike(q)\n ? q\n : { kind: InternalQNodeType.ATOM, where: q as FilterInput<TModel, TSourceModel> };\n const merged = this.state.q ? Q.and(this.state.q, wrapped) : wrapped;\n return this.spawn({ ...this.state, q: merged });\n }\n\n /**\n * Add an exclusion expression to the query.\n *\n * Exclusions are translated to `NOT (...)` predicates.\n */\n exclude(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>\n ): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n const wrapped: QNode<TModel, TSourceModel> = isQNodeLike(q)\n ? q\n : { kind: InternalQNodeType.ATOM, where: q as FilterInput<TModel, TSourceModel> };\n const excludes = [...(this.state.excludes ?? []), wrapped];\n return this.spawn({ ...this.state, excludes });\n }\n\n /**\n * Apply ordering tokens such as `'name'` or `'-createdAt'`.\n */\n orderBy(...tokens: OrderToken<TModel>[]): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n return this.spawn({ ...this.state, order: QuerySet.buildOrderSpecs<TModel>(tokens) });\n }\n\n /**\n * Limit the maximum number of rows returned.\n */\n limit(n: number): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n return this.spawn({ ...this.state, limit: n });\n }\n\n /**\n * Skip the first `n` rows.\n */\n offset(n: number): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n return this.spawn({ ...this.state, offset: n });\n }\n\n /**\n * Restrict selected fields and narrow the fetched row type when the\n * selected keys are known precisely at the call site.\n *\n * Empty selections reset back to the full model row, and repeated\n * `select(...)` calls replace the previous projection rather than\n * intersecting it.\n */\n select<const TKeys extends readonly (keyof TModel)[]>(\n fields: TKeys\n ): QuerySet<TModel, ProjectedResult<TModel, TKeys>, TSourceModel, THydrated>;\n select(\n fields: readonly (keyof TModel)[]\n ): QuerySet<TModel, ProjectedResult<TModel, readonly (keyof TModel)[]>, TSourceModel, THydrated>;\n select(\n fields: readonly (keyof TModel)[]\n ): QuerySet<TModel, ProjectedResult<TModel, readonly (keyof TModel)[]>, TSourceModel, THydrated> {\n return this.spawn<ProjectedResult<TModel, readonly (keyof TModel)[]>, THydrated>({\n ...this.state,\n select: [...fields] as (keyof TModel)[],\n });\n }\n\n /**\n * Hydrate single-valued relation paths through SQL joins.\n *\n * Forward `belongsTo` relations can be inferred from the source model's\n * field-authored relation metadata. Reverse `hasOne` relations can be\n * selected with a target model generic when the target model points back to\n * the source model. Generated relation typing also enables nested `__`\n * path keys for applications that keep the app-local registry current.\n */\n selectRelated<\n TTargetModel = undefined,\n const TRelationName extends\n | RelationKeys<SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>\n | GeneratedSelectRelatedPathKeys<TSourceModel> =\n | RelationKeys<SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>\n | GeneratedSelectRelatedPathKeys<TSourceModel>,\n >(\n ...rels: readonly TRelationName[]\n ): QuerySet<\n TModel,\n TBaseResult,\n TSourceModel,\n THydrated &\n MaybeHydratedRelationMap<\n TSourceModel,\n SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>,\n Extract<TRelationName, RelationKeys<SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>>,\n SingleRelationHydrationCardinality\n > &\n GeneratedHydratedRelationMap<\n TSourceModel,\n Extract<TRelationName, GeneratedSelectRelatedPathKeys<TSourceModel>>\n >\n > {\n return this.spawn<\n TBaseResult,\n THydrated &\n MaybeHydratedRelationMap<\n TSourceModel,\n SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>,\n Extract<TRelationName, RelationKeys<SelectRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>>,\n SingleRelationHydrationCardinality\n > &\n GeneratedHydratedRelationMap<\n TSourceModel,\n Extract<TRelationName, GeneratedSelectRelatedPathKeys<TSourceModel>>\n >\n >({ ...this.state, selectRelated: [...rels] });\n }\n\n /**\n * Hydrate collection-rooted relation paths with follow-up queries.\n *\n * Reverse `hasMany` relations can be prefetched with a target model generic\n * when the target model points back to the source model. Generated relation\n * typing also enables nested `__` path keys for applications that keep the\n * app-local registry current.\n */\n prefetchRelated<\n TTargetModel = undefined,\n const TRelationName extends\n | RelationKeys<PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>\n | GeneratedPrefetchRelatedPathKeys<TSourceModel> =\n | RelationKeys<PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>\n | GeneratedPrefetchRelatedPathKeys<TSourceModel>,\n >(\n ...rels: readonly TRelationName[]\n ): QuerySet<\n TModel,\n TBaseResult,\n TSourceModel,\n THydrated &\n MaybeHydratedRelationMap<\n TSourceModel,\n PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>,\n Extract<TRelationName, RelationKeys<PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>>,\n ManyRelationHydrationCardinality\n > &\n GeneratedHydratedRelationMap<\n TSourceModel,\n Extract<TRelationName, GeneratedPrefetchRelatedPathKeys<TSourceModel>>\n >\n > {\n return this.spawn<\n TBaseResult,\n THydrated &\n MaybeHydratedRelationMap<\n TSourceModel,\n PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>,\n Extract<TRelationName, RelationKeys<PrefetchRelatedRelations<TSourceModel, NoInfer<TTargetModel>>>>,\n ManyRelationHydrationCardinality\n > &\n GeneratedHydratedRelationMap<\n TSourceModel,\n Extract<TRelationName, GeneratedPrefetchRelatedPathKeys<TSourceModel>>\n >\n >({ ...this.state, prefetchRelated: [...rels] });\n }\n\n all(): QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n return this.spawn({ ...this.state });\n }\n\n /**\n * Execute the query and optionally shape each row.\n *\n * When the queryset has been narrowed by `select(...)`, rows passed to the\n * shaping callback or parser use that narrowed fetched-row type.\n */\n async fetch(): Promise<QueryResult<HydratedQueryResult<TBaseResult, THydrated>>>;\n async fetch<Out>(\n shape: QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<QueryResult<Out>>;\n async fetch<Out>(\n shape: QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<QueryResult<Out>>;\n async fetch<TShape extends QueryShape<HydratedQueryResult<TBaseResult, THydrated>> | undefined>(\n shape: TShape\n ): Promise<\n QueryResult<\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>\n >\n >;\n async fetch<Out>(\n shape?:\n | QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n | QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<QueryResult<HydratedQueryResult<TBaseResult, THydrated> | Out>> {\n const baseResult = await this.getOrCreateEvaluationCache();\n if (!shape) {\n return baseResult;\n }\n\n const results: Array<HydratedQueryResult<TBaseResult, THydrated> | Out> =\n typeof shape === 'function'\n ? baseResult.items.map(shape)\n : this.normalizeHydratedRowsForParserShape(baseResult.items).map((row) => shape.parse(row));\n\n return new QueryResult(results);\n }\n\n /**\n * Async iterable surface for `for await (... of queryset)`.\n *\n * Evaluates this queryset on first use by awaiting `fetch()` without\n * arguments, then yields each element from that materialized result.\n * Later async iterations over the same queryset instance reuse the cached\n * materialized result instead of issuing another database round-trip.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<HydratedQueryResult<TBaseResult, THydrated>> {\n const result = await this.fetch();\n for (const row of result) {\n yield row;\n }\n }\n\n /**\n * Execute the query and return the first row, or `null`.\n *\n * As with `fetch(...)`, parser and function overloads receive the current\n * fetched-row type after any `select(...)` projection narrowing.\n */\n async fetchOne(): Promise<HydratedQueryResult<TBaseResult, THydrated> | null>;\n async fetchOne<Out>(\n shape: QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<Out | null>;\n async fetchOne<Out>(shape: QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>): Promise<Out | null>;\n async fetchOne<TShape extends QueryShape<HydratedQueryResult<TBaseResult, THydrated>> | undefined>(\n shape: TShape\n ): Promise<\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>\n | null\n >;\n async fetchOne<Out>(\n shape?:\n | QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n | QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<HydratedQueryResult<TBaseResult, THydrated> | Out | null> {\n const limited = this.limit(1);\n const result = !shape\n ? await limited.fetch()\n : typeof shape === 'function'\n ? await limited.fetch(shape)\n : await limited.fetch(shape);\n for (const row of result) {\n return row;\n }\n return null;\n }\n\n async first(): Promise<HydratedQueryResult<TBaseResult, THydrated> | null>;\n async first<Out>(shape: QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>): Promise<Out | null>;\n async first<Out>(shape: QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>): Promise<Out | null>;\n async first<TShape extends QueryShape<HydratedQueryResult<TBaseResult, THydrated>> | undefined>(\n shape?: TShape\n ): Promise<\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>\n | null\n > {\n return this.fetchOne(shape as never);\n }\n\n async last(): Promise<HydratedQueryResult<TBaseResult, THydrated> | null>;\n async last<Out>(shape: QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>): Promise<Out | null>;\n async last<Out>(shape: QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>): Promise<Out | null>;\n async last<TShape extends QueryShape<HydratedQueryResult<TBaseResult, THydrated>> | undefined>(\n shape?: TShape\n ): Promise<\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>\n | null\n > {\n if (this.state.limit !== undefined || this.state.offset !== undefined) {\n const page = await this.fetch();\n const row = page.at(-1);\n if (!row) {\n return null;\n }\n return this.shapeFetchedRow(row, shape as never) as\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>;\n }\n\n const invertedOrder = QuerySet.invertOrderSpec(this.state.order);\n const effectiveOrder =\n invertedOrder.length > 0\n ? invertedOrder\n : [{ by: this.executor.meta.pk as keyof TModel, dir: InternalDirection.DESC }];\n const qs = this.spawn({ ...this.state, order: effectiveOrder });\n return qs.limit(1).fetchOne(shape as never);\n }\n\n async get(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>\n ): Promise<HydratedQueryResult<TBaseResult, THydrated>>;\n async get<Out>(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>,\n shape: QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<Out>;\n async get<Out>(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>,\n shape: QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): Promise<Out>;\n async get<TShape extends QueryShape<HydratedQueryResult<TBaseResult, THydrated>> | undefined>(\n q: FilterInput<TModel, TSourceModel> | QNode<TModel, TSourceModel>,\n shape?: TShape\n ): Promise<\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>\n > {\n const limited = this.filter(q).limit(2);\n const page = await limited.fetch();\n const rows = page.items;\n\n if (rows.length === 0) {\n throw new NotFoundError(`${this.executor.meta.table}: no matching record`);\n }\n if (rows.length > 1) {\n throw new MultipleObjectsReturned(`${this.executor.meta.table}: more than one matching record`);\n }\n\n return this.shapeFetchedRow(rows[0]!, shape as never) as\n | HydratedQueryResult<TBaseResult, THydrated>\n | QueryShapeOutput<HydratedQueryResult<TBaseResult, THydrated>, NonNullable<TShape>>;\n }\n\n /**\n * Execute a `COUNT(*)` query for the current filtered state.\n */\n async count(): Promise<number> {\n const compiler = new QueryCompiler(this.executor.meta, this.executor.adapter);\n const compiled = compiler.compile(this.withoutHydrationState());\n const countQuery = `SELECT COUNT(*) as count FROM (${compiled.sql}) AS tango_count_subquery`;\n const rows = await this.executor.client.query<{ count: number }>(countQuery, compiled.params);\n return Number(rows.rows[0]?.count ?? 0);\n }\n\n /**\n * Return whether at least one row matches the current query state.\n */\n async exists(): Promise<boolean> {\n const count = await this.count();\n return count > 0;\n }\n\n private shapeFetchedRow<Out>(\n row: HydratedQueryResult<TBaseResult, THydrated>,\n shape?:\n | QueryShapeFunction<HydratedQueryResult<TBaseResult, THydrated>, Out>\n | QueryShapeParser<HydratedQueryResult<TBaseResult, THydrated>, Out>\n ): HydratedQueryResult<TBaseResult, THydrated> | Out {\n if (!shape) {\n return row;\n }\n\n if (typeof shape === 'function') {\n return shape(row);\n }\n\n const normalizedRow = this.normalizeHydratedRowsForParserShape([row])[0] ?? row;\n return shape.parse(normalizedRow);\n }\n\n private getOrCreateEvaluationCache(): Promise<QueryResult<HydratedQueryResult<TBaseResult, THydrated>>> {\n if (!this.evaluationCache) {\n this.evaluationCache = this.evaluateRows().catch((error) => {\n this.evaluationCache = undefined;\n throw error;\n });\n }\n return this.evaluationCache;\n }\n\n private async evaluateRows(): Promise<QueryResult<HydratedQueryResult<TBaseResult, THydrated>>> {\n const compiler = new QueryCompiler(this.executor.meta, this.executor.adapter);\n const compiled = compiler.compile(this.state);\n const rows = await this.executor.run(compiled);\n const normalizedRows = this.normalizeRowsForSchemaParsing(rows);\n const hydratedRows = await this.hydrateRows(normalizedRows as unknown as Record<string, unknown>[], compiled);\n this.attachRootRecordAccessors(hydratedRows);\n const projectedRows = hydratedRows as Array<HydratedQueryResult<TBaseResult, THydrated>>;\n return new QueryResult(projectedRows);\n }\n\n private normalizeRowsForSchemaParsing(rows: readonly TModel[]): TModel[] {\n if (this.executor.adapter.dialect !== InternalDialect.SQLITE) {\n return [...rows];\n }\n\n const booleanColumns = Object.entries(this.executor.meta.columns)\n .filter(([, value]) => this.isBooleanColumnType(value))\n .map(([column]) => column);\n\n if (booleanColumns.length === 0) {\n return [...rows];\n }\n\n return rows.map((row) => this.normalizeBooleanColumns(row, booleanColumns));\n }\n\n private normalizeHydratedRowsForParserShape(\n rows: readonly HydratedQueryResult<TBaseResult, THydrated>[]\n ): Array<HydratedQueryResult<TBaseResult, THydrated>> {\n if (this.executor.adapter.dialect !== InternalDialect.SQLITE) {\n return [...rows];\n }\n\n const booleanColumns = Object.entries(this.executor.meta.columns)\n .filter(([, value]) => this.isBooleanColumnType(value))\n .map(([column]) => column);\n\n if (booleanColumns.length === 0) {\n return [...rows];\n }\n\n return rows.map((row) => this.normalizeBooleanColumns(row, booleanColumns));\n }\n\n private async hydrateRows(\n rows: Record<string, unknown>[],\n compiled: CompiledQuery\n ): Promise<Record<string, unknown>[]> {\n if (!compiled.hydrationPlan) {\n return rows;\n }\n\n // Hydration mutates row objects by attaching related entities and\n // stripping internal alias columns. Copy once here so the executor's\n // raw rows remain untouched throughout the recursive hydration pass.\n const hydratedRows = rows.map((row) => ({ ...row }));\n // Canonicalize by model key and primary key so one database row maps to\n // one in-memory object even when multiple hydration paths reach it.\n this.attachRootRecordAccessors(hydratedRows);\n const canonicalEntities = new Map<string, Map<string | number, Record<string, unknown>>>();\n const queuedJoinPrefetchOwners = new Map<CompiledHydrationNode, Set<Record<string, unknown>>>();\n const compiler = new QueryCompiler(this.executor.meta, this.executor.adapter);\n\n for (const row of hydratedRows) {\n this.hydrateJoinNodesForOwner(\n row,\n row,\n compiled.hydrationPlan.joinNodes,\n canonicalEntities,\n queuedJoinPrefetchOwners\n );\n }\n\n for (const node of compiled.hydrationPlan.prefetchNodes) {\n await this.hydratePrefetchNode(node, hydratedRows, canonicalEntities, compiler);\n }\n\n for (const [node, owners] of queuedJoinPrefetchOwners.entries()) {\n await this.hydratePrefetchNode(node, [...owners], canonicalEntities, compiler);\n }\n\n for (const row of hydratedRows) {\n for (const alias of compiled.hydrationPlan.hiddenRootAliases) {\n delete row[alias];\n }\n }\n\n return hydratedRows;\n }\n\n private primeManyToManyOwnerCache(\n owner: Record<string, unknown>,\n relationName: string,\n bucket: readonly Record<string, unknown>[]\n ): void {\n const existing = owner[relationName];\n if (existing && typeof (existing as { primePrefetchCache?: unknown }).primePrefetchCache === 'function') {\n (existing as { primePrefetchCache: (rows: readonly Record<string, unknown>[]) => void }).primePrefetchCache(\n bucket\n );\n return;\n }\n owner[relationName] = bucket.slice();\n }\n\n private attachRootRecordAccessors(rows: readonly Record<string, unknown>[]): void {\n if (!this.executor.attachPersistedRecordAccessors) {\n return;\n }\n const sourceModelKey = this.executor.meta.modelKey;\n for (const row of rows) {\n this.executor.attachPersistedRecordAccessors(row, sourceModelKey);\n }\n }\n\n private hydrateJoinNodesForOwner(\n owner: Record<string, unknown>,\n rawRow: Record<string, unknown>,\n nodes: readonly CompiledHydrationNode[],\n canonicalEntities: Map<string, Map<string | number, Record<string, unknown>>>,\n queuedJoinPrefetchOwners?: Map<CompiledHydrationNode, Set<Record<string, unknown>>>\n ): void {\n // Join-backed descendants already live on the current SQL row. This\n // pass reads the aliased columns, materializes the related entity, and\n // then recurses into any join-backed children on the same row payload.\n for (const node of nodes) {\n if (!node.join) {\n continue;\n }\n\n const target: Record<string, unknown> = {};\n let hasTargetValue = false;\n\n for (const [column, alias] of Object.entries(node.join.columns)) {\n const value = rawRow[alias];\n delete rawRow[alias];\n target[column] = this.normalizeColumnValue(node.targetColumns[column], value);\n if (value !== null && value !== undefined) {\n hasTargetValue = true;\n }\n }\n\n if (!hasTargetValue) {\n owner[node.relationName] = null;\n continue;\n }\n\n const canonical = this.canonicalizeEntity(node, target, canonicalEntities);\n owner[node.relationName] = canonical;\n for (const childNode of node.prefetchChildren) {\n const queuedOwners = queuedJoinPrefetchOwners?.get(childNode);\n if (queuedOwners) {\n queuedOwners.add(canonical);\n continue;\n }\n\n queuedJoinPrefetchOwners?.set(childNode, new Set([canonical]));\n }\n this.hydrateJoinNodesForOwner(\n canonical,\n rawRow,\n node.joinChildren,\n canonicalEntities,\n queuedJoinPrefetchOwners\n );\n }\n }\n\n private async hydratePrefetchNode(\n node: CompiledHydrationNode,\n owners: readonly Record<string, unknown>[],\n canonicalEntities: Map<string, Map<string | number, Record<string, unknown>>>,\n compiler: QueryCompiler\n ): Promise<void> {\n if (owners.length === 0) {\n return;\n }\n\n // Prefetch-backed descendants run as follow-up queries keyed by the\n // owner rows produced so far. Initialize defaults first so missing\n // children still hydrate to [] or null deterministically.\n const groupedOwners = this.groupOwnersByAccessor(owners, node.ownerSourceAccessor);\n const sourceValues = [...groupedOwners.keys()];\n const isManyToMany = !!node.throughTable;\n if (!isManyToMany) {\n for (const owner of owners) {\n owner[node.relationName] = node.cardinality === InternalRelationHydrationCardinality.MANY ? [] : null;\n }\n }\n\n if (sourceValues.length === 0) {\n return;\n }\n\n const sourceChunks = this.chunkValues(sourceValues, 500);\n const compiledPrefetch = compiler.compilePrefetch(node, sourceChunks[0]!);\n if (compiledPrefetch.kind === InternalPrefetchQueryKind.MANY_TO_MANY) {\n const idsByOwner = new Map<string | number, Array<string | number>>();\n const uniqueTargetIds = new Set<string | number>();\n\n for (const chunk of sourceChunks) {\n const chunkCompiled = compiler.compilePrefetch(node, chunk) as Extract<\n typeof compiledPrefetch,\n { kind: typeof InternalPrefetchQueryKind.MANY_TO_MANY }\n >;\n const throughResult = await this.executor.client.query<Record<string, unknown>>(\n chunkCompiled.throughSql,\n chunkCompiled.throughParams\n );\n\n for (const row of throughResult.rows) {\n const ownerId = row[chunkCompiled.ownerAlias];\n const targetId = row[chunkCompiled.targetAlias];\n if (\n (typeof ownerId !== 'string' && typeof ownerId !== 'number') ||\n (typeof targetId !== 'string' && typeof targetId !== 'number')\n ) {\n continue;\n }\n const bucket = idsByOwner.get(ownerId) ?? [];\n bucket.push(targetId);\n idsByOwner.set(ownerId, bucket);\n uniqueTargetIds.add(targetId);\n }\n }\n\n const targets: Record<string | number, Record<string, unknown>> = {};\n const targetIds = [...uniqueTargetIds.values()];\n if (targetIds.length > 0) {\n for (const targetChunk of this.chunkValues(targetIds, 500)) {\n const targetQuery = compiler.compileManyToManyTargets(node, targetChunk);\n const targetResult = await this.executor.client.query<Record<string, unknown>>(\n targetQuery.sql,\n targetQuery.params\n );\n\n for (const rawTargetRow of targetResult.rows) {\n const normalized = this.normalizeTargetRow(\n { targetColumns: compiledPrefetch.targetColumns },\n rawTargetRow\n );\n const canonical = this.canonicalizeEntity(node, normalized, canonicalEntities);\n this.hydrateJoinNodesForOwner(canonical, normalized, node.joinChildren, canonicalEntities);\n const primaryKey = canonical[node.targetPrimaryKey];\n if (typeof primaryKey === 'string' || typeof primaryKey === 'number') {\n targets[primaryKey] = canonical;\n }\n }\n }\n }\n\n const canonicalChildren = new Map<string | number, Record<string, unknown>>();\n const handledOwners = new Set<Record<string, unknown>>();\n for (const [ownerId, ids] of idsByOwner.entries()) {\n const bucket = ids\n .map((id) => targets[id])\n .filter((value): value is Record<string, unknown> => !!value);\n for (const owner of groupedOwners.get(ownerId) ?? []) {\n this.primeManyToManyOwnerCache(owner, node.relationName, bucket);\n handledOwners.add(owner);\n }\n for (const child of bucket) {\n canonicalChildren.set(child[node.targetPrimaryKey] as string | number, child);\n }\n }\n for (const owner of owners) {\n if (!handledOwners.has(owner)) {\n this.primeManyToManyOwnerCache(owner, node.relationName, []);\n }\n }\n\n const childOwners = [...canonicalChildren.values()];\n for (const childNode of node.prefetchChildren) {\n await this.hydratePrefetchNode(childNode, childOwners, canonicalEntities, compiler);\n }\n return;\n }\n\n const canonicalChildren = new Map<string | number, Record<string, unknown>>();\n for (const chunk of sourceChunks) {\n const chunkCompiled = compiler.compilePrefetch(node, chunk) as Extract<\n typeof compiledPrefetch,\n { kind: typeof InternalPrefetchQueryKind.DIRECT }\n >;\n const result = await this.executor.client.query<Record<string, unknown>>(\n chunkCompiled.sql,\n chunkCompiled.params\n );\n\n for (const rawResultRow of result.rows) {\n const normalized = this.normalizeTargetRow(chunkCompiled, rawResultRow);\n const canonical = this.canonicalizeEntity(node, normalized, canonicalEntities);\n this.hydrateJoinNodesForOwner(canonical, normalized, node.joinChildren, canonicalEntities);\n\n const key = normalized[chunkCompiled.targetKey];\n if (typeof key !== 'string' && typeof key !== 'number') {\n continue;\n }\n\n for (const owner of groupedOwners.get(key) ?? []) {\n if (node.cardinality === InternalRelationHydrationCardinality.MANY) {\n (owner[node.relationName] as Record<string, unknown>[]).push(canonical);\n } else if (owner[node.relationName] === null) {\n owner[node.relationName] = canonical;\n }\n }\n\n const childPrimaryKey = canonical[node.targetPrimaryKey];\n if (typeof childPrimaryKey === 'string' || typeof childPrimaryKey === 'number') {\n canonicalChildren.set(childPrimaryKey, canonical);\n }\n }\n }\n\n const childOwners = [...canonicalChildren.values()];\n for (const childNode of node.prefetchChildren) {\n await this.hydratePrefetchNode(childNode, childOwners, canonicalEntities, compiler);\n }\n }\n\n private chunkValues<T>(values: readonly T[], size: number): T[][] {\n if (values.length === 0) {\n return [];\n }\n if (values.length <= size) {\n return [Array.from(values)];\n }\n const chunks: T[][] = [];\n for (let i = 0; i < values.length; i += size) {\n chunks.push(values.slice(i, i + size) as T[]);\n }\n return chunks;\n }\n\n private groupOwnersByAccessor(\n owners: readonly Record<string, unknown>[],\n accessor: string\n ): Map<string | number, Record<string, unknown>[]> {\n const grouped = new Map<string | number, Record<string, unknown>[]>();\n\n for (const owner of owners) {\n const key = owner[accessor];\n if (typeof key !== 'string' && typeof key !== 'number') {\n continue;\n }\n const bucket = grouped.get(key) ?? [];\n bucket.push(owner);\n grouped.set(key, bucket);\n }\n\n return grouped;\n }\n\n private canonicalizeEntity(\n node: CompiledHydrationNode,\n row: Record<string, unknown>,\n canonicalEntities: Map<string, Map<string | number, Record<string, unknown>>>\n ): Record<string, unknown> {\n // Mixed join/prefetch traversal can encounter the same related row more\n // than once. Canonicalization ensures all later descendants attach to\n // one stable object graph instead of competing copies.\n const primaryKeyValue = row[node.targetPrimaryKey];\n if (typeof primaryKeyValue !== 'string' && typeof primaryKeyValue !== 'number') {\n return row;\n }\n\n const byModel =\n canonicalEntities.get(node.targetModelKey) ?? new Map<string | number, Record<string, unknown>>();\n const existing = byModel.get(primaryKeyValue);\n if (existing) {\n Object.assign(existing, row);\n return existing;\n }\n\n byModel.set(primaryKeyValue, row);\n canonicalEntities.set(node.targetModelKey, byModel);\n this.executor.attachPersistedRecordAccessors?.(row, node.targetModelKey);\n return row;\n }\n\n private normalizeTargetRow(prefetch: TargetColumnMetadata, row: Record<string, unknown>): Record<string, unknown> {\n if (this.executor.adapter.dialect !== InternalDialect.SQLITE) {\n return row;\n }\n\n let normalized: Record<string, unknown> | null = null;\n for (const [column, type] of Object.entries(prefetch.targetColumns)) {\n if (!this.isBooleanColumnType(type)) {\n continue;\n }\n const next = this.normalizeSqliteBoolean(row[column]);\n if (next === row[column]) {\n continue;\n }\n normalized ??= { ...row };\n normalized[column] = next;\n }\n return normalized ?? row;\n }\n\n private normalizeColumnValue(columnType: string | undefined, value: unknown): unknown {\n return this.executor.adapter.dialect === InternalDialect.SQLITE && this.isBooleanColumnType(columnType)\n ? this.normalizeSqliteBoolean(value)\n : value;\n }\n\n private isBooleanColumnType(value: unknown): boolean {\n return typeof value === 'string' && ['bool', 'boolean'].includes(value.trim().toLowerCase());\n }\n\n private normalizeSqliteBoolean(value: unknown): unknown {\n if (value === 0 || value === '0') {\n return false;\n }\n if (value === 1 || value === '1') {\n return true;\n }\n return value;\n }\n\n private normalizeBooleanColumns<TRow extends Record<string, unknown>>(row: TRow, columns: readonly string[]): TRow {\n let normalized: TRow | null = null;\n\n for (const column of columns) {\n const current = (row as Record<string, unknown>)[column];\n const next = this.normalizeSqliteBoolean(current);\n if (next === current) {\n continue;\n }\n if (!normalized) {\n normalized = { ...row };\n }\n (normalized as Record<string, unknown>)[column] = next;\n }\n\n return normalized ?? row;\n }\n\n private withoutHydrationState(): QuerySetState<TModel, TSourceModel> {\n const { selectRelated: _selectRelated, prefetchRelated: _prefetchRelated, ...rest } = this.state;\n return rest;\n }\n}\n","/**\n * Maintainer note: model-backed and specialized relation-backed querysets\n * share the fluent API through `QuerySet.spawn(...)`. This concrete class\n * owns the direct \"compile the accumulated state and execute it\" path, while\n * subclasses preserve specialized execution behavior by returning their own\n * queryset family from `spawn(...)`.\n */\nimport type { QuerySetState } from './domain/QuerySetState';\nimport type { QueryExecutor } from './QuerySet';\nimport { QuerySet } from './QuerySet';\n\n/**\n * Concrete `QuerySet` implementation returned by `Model.objects.query()`.\n *\n * It executes the accumulated queryset state directly against the bound\n * model executor.\n */\nexport class ModelQuerySet<\n TModel extends Record<string, unknown>,\n TBaseResult extends Record<string, unknown> = TModel,\n TSourceModel = unknown,\n THydrated extends Record<string, unknown> = Record<never, never>,\n> extends QuerySet<TModel, TBaseResult, TSourceModel, THydrated> {\n constructor(executor: QueryExecutor<TModel>, state: QuerySetState<TModel, TSourceModel> = {}) {\n super(executor, state);\n }\n\n protected override spawn<\n TNextBaseResult extends Record<string, unknown> = TBaseResult,\n TNextHydrated extends Record<string, unknown> = THydrated,\n >(state: QuerySetState<TModel, TSourceModel>): ModelQuerySet<TModel, TNextBaseResult, TSourceModel, TNextHydrated> {\n return new ModelQuerySet<TModel, TNextBaseResult, TSourceModel, TNextHydrated>(this.executor, state);\n }\n}\n","/**\n * Domain boundary barrel: exposes namespaced exports for Django-style drill-down\n * imports and curated flat exports for TS-native ergonomics.\n */\n\nexport * as compiler from './compiler/index';\nexport * as domain from './domain/index';\n\nexport type * from './domain/index';\nexport type { TableMeta } from './domain/index';\nexport { QueryResult } from './domain/index';\nexport { QuerySet } from './QuerySet';\nexport { ModelQuerySet } from './ModelQuerySet';\nexport type { QueryExecutor } from './QuerySet';\nexport { QBuilder, QBuilder as Q } from './QBuilder';\nexport { QueryCompiler } from './compiler/index';\n"],"mappings":";;;;;AAKA,MAAa,oCAAoC;CAC7C,MAAM;CACN,UAAU;AACd;;;;;;;ACJA,MAAa,4BAA4B;;;;;;CAMrC,QAAQ;;;;;;;CAQR,cAAc;AAClB;;;ACnBA,MAAa,oBAAoB;CAC7B,MAAM;CACN,KAAK;CACL,IAAI;CACJ,KAAK;AACT;;;ACLA,MAAa,qBAAqB;CAC9B,OAAO;CACP,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,QAAQ;CACR,UAAU;CACV,WAAW;CACX,YAAY;CACZ,aAAa;CACb,UAAU;CACV,WAAW;AACf;;;;;;;ACVA,MAAa,gCAAgC;;;;;;CAMzC,QAAQ;;;;CAKR,QAAQ;;;;CAKR,QAAQ;;;;CAKR,QAAQ;AACZ;;;AC1BA,MAAa,wCAAwC;CACjD,QAAQ;CACR,UAAU;AACd;;;ACsBA,MAAM,kBAAkB,OAAO,OAAO,kBAAkB;;;;;AAMxD,IAAa,sBAAb,MAAa,oBAAmD;CAI/B;CAH7B,OAAgB,QAAQ;CACxB,eAA0D,oBAAoB;CAE9E,YAAY,SAA2C,IAAI,gBAAgB,GAA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