@rebasepro/server-postgres 0.10.1-canary.ed8caed → 0.10.1-canary.g4db1bb1

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 (42) hide show
  1. package/dist/auth/schema-version.d.ts +106 -0
  2. package/dist/collections/validate-relations.d.ts +53 -0
  3. package/dist/data-transformer.d.ts +3 -3
  4. package/dist/{ensure-collection-tables-BVvtkkRm.js → ensure-collection-tables-DGMYK0fr.js} +5 -5
  5. package/dist/ensure-collection-tables-DGMYK0fr.js.map +1 -0
  6. package/dist/index.es.js +610 -313
  7. package/dist/index.es.js.map +1 -1
  8. package/dist/services/RelationService.d.ts +9 -8
  9. package/dist/services/cdc/junction-tables.d.ts +38 -0
  10. package/dist/services/nested-path.d.ts +3 -3
  11. package/dist/services/realtimeService.d.ts +19 -0
  12. package/dist/services/row-pipeline.d.ts +2 -2
  13. package/dist/{src-lcfUP4xg.js → src-3VmUJ8Xn.js} +135 -247
  14. package/dist/src-3VmUJ8Xn.js.map +1 -0
  15. package/dist/{src-CBgtrPhJ.js → src-D5xBTl32.js} +12 -2
  16. package/dist/src-D5xBTl32.js.map +1 -0
  17. package/dist/utils/drizzle-conditions.d.ts +35 -23
  18. package/package.json +6 -6
  19. package/src/PostgresBootstrapper.ts +15 -2
  20. package/src/auth/ensure-tables.ts +23 -0
  21. package/src/auth/schema-version.ts +260 -0
  22. package/src/cli-errors.ts +1 -1
  23. package/src/cli-helpers.ts +4 -3
  24. package/src/collections/PostgresCollectionRegistry.ts +9 -4
  25. package/src/collections/buildRegistry.ts +7 -0
  26. package/src/collections/validate-relations.ts +280 -0
  27. package/src/data-transformer.ts +28 -38
  28. package/src/schema/doctor.ts +8 -8
  29. package/src/schema/generate-drizzle-schema-logic.ts +49 -101
  30. package/src/schema/generate-postgres-ddl-logic.ts +9 -9
  31. package/src/schema/introspect-db-logic.ts +19 -23
  32. package/src/services/FetchService.ts +12 -12
  33. package/src/services/PersistService.ts +23 -27
  34. package/src/services/RelationService.ts +65 -83
  35. package/src/services/cdc/junction-tables.ts +91 -0
  36. package/src/services/nested-path.ts +24 -9
  37. package/src/services/realtimeService.ts +60 -0
  38. package/src/services/row-pipeline.ts +5 -6
  39. package/src/utils/drizzle-conditions.ts +177 -382
  40. package/dist/ensure-collection-tables-BVvtkkRm.js.map +0 -1
  41. package/dist/src-CBgtrPhJ.js.map +0 -1
  42. package/dist/src-lcfUP4xg.js.map +0 -1
@@ -1,6 +1,9 @@
1
1
  import { and, eq, or, sql, SQL, ilike, inArray } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable, PgVarchar, PgText, PgChar } from "drizzle-orm/pg-core";
3
- import { FilterValues, WhereFilterOp, Relation, JoinStep, LogicalCondition, FilterCondition } from "@rebasepro/types";
3
+ import {
4
+ FilterValues, WhereFilterOp, JoinStep, LogicalCondition, FilterCondition,
5
+ ResolvedRelation, ResolvedBelongsTo, ResolvedHasOne, ResolvedHasMany
6
+ } from "@rebasepro/types";
4
7
  import { getColumnName, normalizeToEntityRelation, resolveCollectionRelations } from "@rebasepro/common";
5
8
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
6
9
  import { ConditionBuilderStatic } from "../interfaces";
@@ -59,12 +62,12 @@ export class DrizzleConditionBuilder {
59
62
  * it and the final step correlating to the outer row.
60
63
  */
61
64
  static buildRelationScopeCondition(
62
- relation: Relation,
65
+ relation: ResolvedRelation,
63
66
  /**
64
- * Lazy: only `joinPath` and `localKey` relations need the parent's own
65
- * table. An inverse foreign key and a junction are both expressible
66
- * from the parent's *id* alone, and requiring the table for them would
67
- * make a child listing fail on a parent whose table isn't registered.
67
+ * Lazy: only `via` and `belongsTo` need the parent's own table. A
68
+ * foreign key on the target and a junction are both expressible from
69
+ * the parent's *id* alone, and requiring the table for them would make
70
+ * a child listing fail on a parent whose table isn't registered.
68
71
  */
69
72
  parent: () => { table: PgTable<any>; idColumn: AnyPgColumn },
70
73
  parentId: string | number,
@@ -72,50 +75,58 @@ export class DrizzleConditionBuilder {
72
75
  targetIdColumn: AnyPgColumn,
73
76
  registry: PostgresCollectionRegistry
74
77
  ): SQL {
75
- if (relation.joinPath && relation.joinPath.length > 0) {
76
- const { table, idColumn } = parent();
77
- return this.buildJoinPathScopeCondition(
78
- relation.joinPath, table, idColumn, parentId, targetIdColumn, registry
79
- );
80
- }
78
+ switch (relation.kind) {
79
+ case "via": {
80
+ const { table, idColumn } = parent();
81
+ return this.buildJoinPathScopeCondition(
82
+ relation.joinPath, table, idColumn, parentId, targetTable, registry
83
+ );
84
+ }
81
85
 
82
- if (relation.through) {
83
- const junctionTable = registry.getTable(relation.through.table);
84
- if (!junctionTable) {
85
- throw new Error(`Junction table not found: ${relation.through.table}`);
86
+ case "manyToMany": {
87
+ const { table: junctionName, sourceColumn, targetColumn } = relation.through;
88
+ const junctionTable = registry.getTable(junctionName);
89
+ if (!junctionTable) {
90
+ throw new Error(`Junction table not found: ${junctionName}`);
91
+ }
92
+ const sourceCol = junctionTable[sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
93
+ const targetCol = junctionTable[targetColumn as keyof typeof junctionTable] as AnyPgColumn;
94
+ if (!sourceCol || !targetCol) {
95
+ throw new Error(
96
+ `Junction columns '${sourceColumn}'/'${targetColumn}' not found in '${junctionName}'`
97
+ );
98
+ }
99
+ // Correlated, not joined: a join through a junction multiplies
100
+ // the target rows by the number of matching links and silently
101
+ // breaks `limit`/`offset`.
102
+ return sql`EXISTS (SELECT 1 FROM ${junctionTable} WHERE ${targetCol} = ${targetIdColumn} AND ${sourceCol} = ${parentId})`;
86
103
  }
87
- const sourceCol = junctionTable[relation.through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
88
- const targetCol = junctionTable[relation.through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
89
- if (!sourceCol || !targetCol) {
90
- throw new Error(
91
- `Junction columns '${relation.through.sourceColumn}'/'${relation.through.targetColumn}' not found in '${relation.through.table}'`
92
- );
104
+
105
+ case "hasOne":
106
+ case "hasMany": {
107
+ const fkColumn = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
108
+ if (!fkColumn) {
109
+ throw new Error(
110
+ `Foreign key column '${relation.foreignKeyOnTarget}' not found in the target table of ` +
111
+ `relation '${relation.relationName}'.`
112
+ );
113
+ }
114
+ return eq(fkColumn, parentId);
93
115
  }
94
- return sql`EXISTS (SELECT 1 FROM ${junctionTable} WHERE ${targetCol} = ${targetIdColumn} AND ${sourceCol} = ${parentId})`;
95
- }
96
116
 
97
- if (relation.foreignKeyOnTarget) {
98
- const fkColumn = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
99
- if (!fkColumn) {
100
- throw new Error(
101
- `Foreign key column '${relation.foreignKeyOnTarget}' not found in the target table of relation ` +
102
- `'${relation.relationName}'. A many-to-many relation needs \`through\` instead.`
103
- );
117
+ case "belongsTo": {
118
+ // The single target row the parent's foreign key points at.
119
+ const { table, idColumn } = parent();
120
+ return sql`${targetIdColumn} = (SELECT ${sql.identifier(relation.localKey)} FROM ${table} WHERE ${idColumn} = ${parentId})`;
104
121
  }
105
- return eq(fkColumn, parentId);
106
- }
107
122
 
108
- if (relation.localKey) {
109
- // A to-one owning relation read as a scope: the single target row is
110
- // the one the parent's foreign key points at.
111
- const { table, idColumn } = parent();
112
- return sql`${targetIdColumn} = (SELECT ${sql.identifier(relation.localKey)} FROM ${table} WHERE ${idColumn} = ${parentId})`;
123
+ default: {
124
+ // Exhaustive. There is no "declares nothing" case to fall
125
+ // through to any more — every kind names its own link.
126
+ const exhaustive: never = relation;
127
+ throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);
128
+ }
113
129
  }
114
-
115
- throw new Error(
116
- `Relation '${relation.relationName}' declares no \`foreignKeyOnTarget\`, \`through\`, \`joinPath\` or ` +
117
- "`localKey`, so there is no way to tell which target rows belong to a parent."
118
- );
119
130
  }
120
131
 
121
132
  /**
@@ -132,7 +143,7 @@ export class DrizzleConditionBuilder {
132
143
  parentTable: PgTable<any>,
133
144
  parentIdColumn: AnyPgColumn,
134
145
  parentId: string | number,
135
- targetIdColumn: AnyPgColumn,
146
+ targetTable: PgTable<any>,
136
147
  registry: PostgresCollectionRegistry
137
148
  ): SQL {
138
149
  const sourceAlias = "__rel_src";
@@ -166,15 +177,26 @@ export class DrizzleConditionBuilder {
166
177
 
167
178
  // The last step correlates to the outer row instead of joining the
168
179
  // target table into the subquery.
169
- const lastPairs = pairs(last);
170
- const correlation = lastPairs.length === 1
171
- ? sql`${fromRef(inner.length, lastPairs[0].from)} = ${targetIdColumn}`
172
- : sql.join(
173
- lastPairs.map(({ from, to }) =>
174
- sql`${fromRef(inner.length, from)} = ${sql.identifier(getColumnName(to))}`
175
- ),
176
- sql` AND `
177
- );
180
+ //
181
+ // On the step's own `to` column, which is not always the target's
182
+ // primary key: a one-step path like `{ table: "posts", on: { from:
183
+ // "id", to: "author_id" } }` correlates through a foreign key, and
184
+ // matching `authors.id = posts.id` there compares two unrelated
185
+ // identifiers — which returns nothing, quietly. Referencing the Drizzle
186
+ // column rather than a bare name also keeps it qualified, so it binds
187
+ // to the outer target and not to a table joined inside the EXISTS.
188
+ const targetColumn = (name: string): AnyPgColumn => {
189
+ const column = targetTable[getColumnName(name) as keyof typeof targetTable] as AnyPgColumn;
190
+ if (!column) {
191
+ throw new Error(`Join step column '${name}' not found in the target table of this joinPath`);
192
+ }
193
+ return column;
194
+ };
195
+
196
+ const correlation = sql.join(
197
+ pairs(last).map(({ from, to }) => sql`${fromRef(inner.length, from)} = ${targetColumn(to)}`),
198
+ sql` AND `
199
+ );
178
200
 
179
201
  const joinsSql = joins.length > 0 ? sql` ${sql.join(joins, sql` `)}` : sql``;
180
202
 
@@ -339,8 +361,22 @@ export class DrizzleConditionBuilder {
339
361
  /**
340
362
  * Build relation-based conditions for different relation types
341
363
  */
364
+ /**
365
+ * Joins and where-conditions that reach a relation's target rows.
366
+ *
367
+ * One case per kind. This used to be a chain of six `else if`s over
368
+ * `cardinality`/`direction`/`through`, ending in
369
+ * `findCorrespondingJunctionTable` — a search through the *target's* own
370
+ * relations to work out whether an "inverse many" was a one-to-many or the
371
+ * far side of a junction. That search is gone: the kind says which it is.
372
+ *
373
+ * The owning/inverse split for junctions is gone too. Both variants built
374
+ * the identical condition — `through` is always written from the declaring
375
+ * side's point of view — so the second was a distinction without a
376
+ * difference and one of the places the two could drift apart.
377
+ */
342
378
  static buildRelationConditions(
343
- relation: Relation,
379
+ relation: ResolvedRelation,
344
380
  parentId: string | number | (string | number)[],
345
381
  targetTable: PgTable<any>,
346
382
  parentTable: PgTable<any>,
@@ -351,110 +387,44 @@ export class DrizzleConditionBuilder {
351
387
  joinConditions: { table: PgTable<any>; condition: SQL }[];
352
388
  whereConditions: SQL[];
353
389
  } {
354
- console.debug("🔍 [buildRelationConditions] Building conditions for relation:", {
355
- relationName: relation.relationName,
356
- cardinality: relation.cardinality,
357
- direction: relation.direction,
358
- hasThrough: !!relation.through,
359
- hasForeignKeyOnTarget: !!relation.foreignKeyOnTarget,
360
- inverseRelationName: relation.inverseRelationName,
361
- parentId: parentId
362
- });
363
-
364
390
  const joinConditions: { table: PgTable<any>; condition: SQL }[] = [];
365
391
  const whereConditions: SQL[] = [];
366
392
 
367
- if (relation.joinPath && relation.joinPath.length > 0) {
368
- console.debug("🔍 [buildRelationConditions] Using joinPath logic");
369
- // Handle join path relations
370
- const {
371
- joins,
372
- finalCondition
373
- } = this.buildJoinPathConditions(
374
- relation.joinPath,
375
- targetTable,
376
- parentTable,
377
- parentIdColumn,
378
- parentId,
379
- registry
380
- );
381
- joinConditions.push(...joins);
382
- whereConditions.push(finalCondition);
383
-
384
- } else if (relation.through && relation.cardinality === "many" && relation.direction === "owning") {
385
- console.debug("🔍 [buildRelationConditions] Using owning many-to-many with explicit through");
386
- // Handle many-to-many relations with junction table
387
- const junctionResult = this.buildJunctionTableConditions(
388
- relation.through,
389
- targetIdColumn,
390
- parentId,
391
- registry
392
- );
393
- joinConditions.push(junctionResult.join);
394
- whereConditions.push(junctionResult.condition);
395
-
396
- } else if (relation.through && relation.cardinality === "many" && relation.direction === "inverse") {
397
- console.debug("🔍 [buildRelationConditions] Using inverse many-to-many with explicit through");
398
- // Handle inverse many-to-many relations with junction table
399
- const junctionResult = this.buildInverseJunctionTableConditions(
400
- relation.through,
401
- targetIdColumn,
402
- parentId,
403
- registry
404
- );
405
- joinConditions.push(junctionResult.join);
406
- whereConditions.push(junctionResult.condition);
407
-
408
- } else if (relation.cardinality === "many" && relation.direction === "inverse" && !relation.through) {
409
- console.debug("🔍 [buildRelationConditions] Handling inverse many relationship without explicit through");
410
-
411
- // First, try to find a junction table (for many-to-many relationships)
412
- const junctionInfo = this.findCorrespondingJunctionTable(relation, registry);
413
- if (junctionInfo) {
414
- console.debug("🔍 [buildRelationConditions] Found junction info for inverse many-to-many, building junction conditions");
415
- const junctionResult = this.buildInverseJunctionTableConditions(
416
- junctionInfo,
417
- targetIdColumn,
418
- parentId,
419
- registry
393
+ switch (relation.kind) {
394
+ case "via": {
395
+ const { joins, finalCondition } = this.buildJoinPathConditions(
396
+ relation.joinPath, targetTable, parentTable, parentIdColumn, parentId, registry
397
+ );
398
+ joinConditions.push(...joins);
399
+ whereConditions.push(finalCondition);
400
+ break;
401
+ }
402
+
403
+ case "manyToMany": {
404
+ const junctionResult = this.buildJunctionTableConditions(
405
+ relation.through, targetIdColumn, parentId, registry
420
406
  );
421
407
  joinConditions.push(junctionResult.join);
422
408
  whereConditions.push(junctionResult.condition);
423
- } else if (relation.foreignKeyOnTarget) {
424
- console.debug("🔍 [buildRelationConditions] No junction table found, treating as inverse one-to-many with foreign key on target");
425
- // This is a true inverse one-to-many relationship
426
- const simpleCondition = this.buildSimpleRelationCondition(
427
- relation,
428
- targetTable,
429
- parentTable,
430
- parentId
409
+ break;
410
+ }
411
+
412
+ case "hasOne":
413
+ case "hasMany":
414
+ case "belongsTo":
415
+ whereConditions.push(
416
+ this.buildSimpleRelationCondition(relation, targetTable, parentTable, parentId)
431
417
  );
432
- whereConditions.push(simpleCondition);
433
- } else {
434
- logger.error("🔍 [buildRelationConditions] Failed to find junction table info and no foreign key specified");
435
- throw new Error(`Cannot resolve inverse many relation '${relation.relationName}'. Either specify 'through' property, ensure corresponding owning relation exists with junction table configuration, or specify 'foreignKeyOnTarget' for one-to-many relationships.`);
418
+ break;
419
+
420
+ default: {
421
+ const exhaustive: never = relation;
422
+ throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);
436
423
  }
437
- } else {
438
- console.debug("🔍 [buildRelationConditions] Using simple relation logic - THIS IS WHERE THE ERROR MIGHT OCCUR");
439
- // Handle simple relations
440
- const simpleCondition = this.buildSimpleRelationCondition(
441
- relation,
442
- targetTable,
443
- parentTable,
444
- parentId
445
- );
446
- whereConditions.push(simpleCondition);
447
424
  }
448
425
 
449
- console.debug("🔍 [buildRelationConditions] Final result:", {
450
- joinConditionsCount: joinConditions.length,
451
- whereConditionsCount: whereConditions.length
452
- });
453
-
454
- return {
455
- joinConditions,
456
- whereConditions
457
- };
426
+ return { joinConditions,
427
+ whereConditions };
458
428
  }
459
429
 
460
430
  /**
@@ -754,109 +724,47 @@ export class DrizzleConditionBuilder {
754
724
  };
755
725
  }
756
726
 
757
- /**
758
- * Build conditions for inverse junction table (many-to-many) relations
759
- */
760
- private static buildInverseJunctionTableConditions(
761
- through: { table: string; sourceColumn: string; targetColumn: string },
762
- targetIdColumn: AnyPgColumn,
763
- parentId: string | number | (string | number)[],
764
- registry: PostgresCollectionRegistry
765
- ): { join: { table: PgTable<any>; condition: SQL }; condition: SQL } {
766
- const junctionTable = registry.getTable(through.table);
767
- if (!junctionTable) {
768
- throw new Error(`Junction table not found: ${through.table}`);
769
- }
770
-
771
- const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
772
- const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
773
-
774
- if (!junctionSourceCol) {
775
- throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
776
- }
777
- if (!junctionTargetCol) {
778
- throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
779
- }
780
-
781
- // For inverse relations, the parentId (tag ID) should match the sourceColumn (tag_id)
782
- // and we want to find target rows (posts) through the targetColumn (post_id)
783
- const condition = Array.isArray(parentId)
784
- ? inArray(junctionSourceCol, parentId)
785
- : eq(junctionSourceCol, parentId);
786
-
787
- return {
788
- join: {
789
- table: junctionTable,
790
- condition: eq(targetIdColumn, junctionTargetCol)
791
- },
792
- condition
793
- };
794
- }
795
727
 
796
728
  /**
797
- * Build conditions for simple relations (owning/inverse without join paths)
729
+ * The condition for a relation whose link is a single column.
730
+ *
731
+ * Two cases. It had five: two of them existed only to throw ("should not be
732
+ * called directly", "lacks proper configuration"), and one guessed a column
733
+ * name by appending `_id` to `inverseRelationName` when no foreign key had
734
+ * been resolved. All three were reachable only because the old type let a
735
+ * relation arrive here under-specified. It cannot now.
798
736
  */
799
737
  private static buildSimpleRelationCondition(
800
- relation: Relation,
738
+ relation: ResolvedBelongsTo | ResolvedHasOne | ResolvedHasMany,
801
739
  targetTable: PgTable<any>,
802
740
  parentTable: PgTable<any>,
803
741
  parentId: string | number | (string | number)[]
804
742
  ): SQL {
805
- if (relation.direction === "owning" && relation.localKey) {
806
- // For owning relations, the parentId is actually the foreign key value
807
- // that should match the target table's primary key
808
- const targetIdCol = Object.values(targetTable).find((col: Record<string, unknown>) => col.primary) as AnyPgColumn;
743
+ const match = (column: AnyPgColumn) =>
744
+ Array.isArray(parentId) ? inArray(column, parentId) : eq(column, parentId);
745
+
746
+ if (relation.kind === "belongsTo") {
747
+ // `parentId` is the foreign key's value, matched against the
748
+ // target's own key.
749
+ const targetIdCol =
750
+ (Object.values(targetTable).find((col: Record<string, unknown>) => col.primary)
751
+ ?? Object.values(targetTable).find((col: Record<string, unknown>) => col.name === "id")) as AnyPgColumn | undefined;
809
752
  if (!targetIdCol) {
810
- // Fallback to looking for an "id" column by name
811
- const idCol = Object.values(targetTable).find((col: Record<string, unknown>) => col.name === "id") as AnyPgColumn;
812
- if (!idCol) {
813
- throw new Error("No primary key or \"id\" column found in target table");
814
- }
815
- return Array.isArray(parentId)
816
- ? inArray(idCol, parentId)
817
- : eq(idCol, parentId);
818
- }
819
- return Array.isArray(parentId)
820
- ? inArray(targetIdCol, parentId)
821
- : eq(targetIdCol, parentId);
822
-
823
- } else if (relation.direction === "inverse" && relation.foreignKeyOnTarget) {
824
- // Inverse relation: use foreign key on target table
825
- const foreignKeyCol = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
826
- if (!foreignKeyCol) {
827
- // This could be a many-to-many relationship where foreignKeyOnTarget was set by sanitizeRelation
828
- // but the column doesn't actually exist. In this case, we should suggest using junction tables.
829
- throw new Error(`Foreign key column '${relation.foreignKeyOnTarget}' not found in target table. This might be a many-to-many relationship that requires a junction table. Consider using 'through' property or ensure the corresponding owning relation exists with junction table configuration.`);
830
- }
831
- return Array.isArray(parentId)
832
- ? inArray(foreignKeyCol, parentId)
833
- : eq(foreignKeyCol, parentId);
834
-
835
- } else if (relation.direction === "inverse" && relation.cardinality === "many" && relation.inverseRelationName) {
836
- // For inverse many-to-many relations, this should not be called directly
837
- // The buildRelationConditions method should handle finding the junction table
838
- // If we reach here, it means the junction table lookup failed
839
- throw new Error(`Inverse many-to-many relation '${relation.relationName}' requires a junction table. Either specify 'through' property or ensure the corresponding owning relation exists with junction table configuration.`);
840
-
841
- } else if (relation.direction === "inverse" && relation.cardinality === "one" && relation.inverseRelationName) {
842
- // Auto-infer foreign key column for inverse one-to-one relations
843
- // Pattern: {inverseRelationName}_id (e.g., "author" -> "author_id")
844
- const inferredForeignKeyName = `${relation.inverseRelationName}_id`;
845
- const foreignKeyCol = targetTable[inferredForeignKeyName as keyof typeof targetTable] as AnyPgColumn;
846
-
847
- if (!foreignKeyCol) {
848
- throw new Error(`Auto-inferred foreign key column '${inferredForeignKeyName}' not found in target table for inverse relation '${relation.relationName}'. Please specify 'foreignKeyOnTarget' explicitly.`);
753
+ throw new Error(
754
+ `No primary key or "id" column in the target table of relation '${relation.relationName}'.`
755
+ );
849
756
  }
757
+ return match(targetIdCol);
758
+ }
850
759
 
851
- console.debug(`🔍 [DrizzleConditionBuilder] Auto-inferred foreign key '${inferredForeignKeyName}' for inverse relation '${relation.relationName}'`);
852
-
853
- return Array.isArray(parentId)
854
- ? inArray(foreignKeyCol, parentId)
855
- : eq(foreignKeyCol, parentId);
856
-
857
- } else {
858
- throw new Error(`Relation '${relation.relationName}' lacks proper configuration. For many-to-many relations, use 'through' property. For simple relations, use 'localKey' or 'foreignKeyOnTarget'.`);
760
+ const foreignKeyCol = targetTable[relation.foreignKeyOnTarget as keyof typeof targetTable] as AnyPgColumn;
761
+ if (!foreignKeyCol) {
762
+ throw new Error(
763
+ `Foreign key column '${relation.foreignKeyOnTarget}' not found in the target table of relation ` +
764
+ `'${relation.relationName}'. A link through a junction is \`kind: "manyToMany"\`.`
765
+ );
859
766
  }
767
+ return match(foreignKeyCol);
860
768
  }
861
769
 
862
770
  /**
@@ -933,7 +841,7 @@ export class DrizzleConditionBuilder {
933
841
  */
934
842
  static buildRelationQuery<T extends DrizzleDynamicQuery>(
935
843
  baseQuery: T,
936
- relation: Relation,
844
+ relation: ResolvedRelation,
937
845
  parentId: string | number | (string | number)[],
938
846
  targetTable: PgTable<any>,
939
847
  parentTable: PgTable<any>,
@@ -974,11 +882,15 @@ export class DrizzleConditionBuilder {
974
882
  }
975
883
 
976
884
  /**
977
- * Build count query for relations with proper joins and conditions
885
+ * A count over a relation's target rows.
886
+ *
887
+ * The junction case counts `distinct` because the caller's query joins the
888
+ * junction; the owning/inverse pair that used to sit here built the same
889
+ * query twice.
978
890
  */
979
891
  static buildRelationCountQuery<T extends DrizzleDynamicQuery>(
980
892
  baseCountQuery: T,
981
- relation: Relation,
893
+ relation: ResolvedRelation,
982
894
  parentId: string | number,
983
895
  targetTable: PgTable<any>,
984
896
  parentTable: PgTable<any>,
@@ -987,51 +899,32 @@ export class DrizzleConditionBuilder {
987
899
  registry: PostgresCollectionRegistry,
988
900
  additionalFilters?: SQL[]
989
901
  ): T {
990
- // For count queries, we need to handle joins differently to avoid duplicates
991
- if (relation.joinPath && relation.joinPath.length > 0) {
992
- return this.buildJoinPathCountQuery(
993
- baseCountQuery,
994
- relation.joinPath,
995
- targetTable,
996
- parentTable,
997
- parentIdColumn,
998
- parentId,
999
- registry,
1000
- additionalFilters
1001
- );
1002
- } else if (relation.through && relation.cardinality === "many" && relation.direction === "owning") {
1003
- return this.buildJunctionCountQuery(
1004
- baseCountQuery,
1005
- relation.through,
1006
- targetIdColumn,
1007
- parentId,
1008
- registry,
1009
- additionalFilters
1010
- );
1011
- } else if (relation.through && relation.cardinality === "many" && relation.direction === "inverse") {
1012
- return this.buildInverseJunctionCountQuery(
1013
- baseCountQuery,
1014
- relation.through,
1015
- targetIdColumn,
1016
- parentId,
1017
- registry,
1018
- additionalFilters
1019
- );
1020
- } else {
1021
- // Simple relations
1022
- const simpleCondition = this.buildSimpleRelationCondition(
1023
- relation,
1024
- targetTable,
1025
- parentTable,
1026
- parentId
1027
- );
902
+ switch (relation.kind) {
903
+ case "via":
904
+ return this.buildJoinPathCountQuery(
905
+ baseCountQuery, relation.joinPath, targetTable, parentTable,
906
+ parentIdColumn, parentId, registry, additionalFilters
907
+ );
908
+
909
+ case "manyToMany":
910
+ return this.buildJunctionCountQuery(
911
+ baseCountQuery, relation.through, targetIdColumn, parentId, registry, additionalFilters
912
+ );
1028
913
 
1029
- const allConditions = [simpleCondition];
1030
- if (additionalFilters) {
1031
- allConditions.push(...additionalFilters);
914
+ case "belongsTo":
915
+ case "hasOne":
916
+ case "hasMany": {
917
+ const allConditions = [
918
+ this.buildSimpleRelationCondition(relation, targetTable, parentTable, parentId),
919
+ ...(additionalFilters ?? [])
920
+ ];
921
+ return baseCountQuery.where(and(...allConditions));
1032
922
  }
1033
923
 
1034
- return baseCountQuery.where(and(...allConditions));
924
+ default: {
925
+ const exhaustive: never = relation;
926
+ throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);
927
+ }
1035
928
  }
1036
929
  }
1037
930
 
@@ -1127,41 +1020,6 @@ export class DrizzleConditionBuilder {
1127
1020
  .where(and(...baseConditions));
1128
1021
  }
1129
1022
 
1130
- /**
1131
- * Build inverse junction table conditions for count queries
1132
- */
1133
- private static buildInverseJunctionCountQuery<T extends DrizzleDynamicQuery>(
1134
- baseCountQuery: T,
1135
- through: { table: string; sourceColumn: string; targetColumn: string },
1136
- targetIdColumn: AnyPgColumn,
1137
- parentId: string | number,
1138
- registry: PostgresCollectionRegistry,
1139
- additionalFilters?: SQL[]
1140
- ): T {
1141
- const junctionTable = registry.getTable(through.table);
1142
- if (!junctionTable) {
1143
- throw new Error(`Junction table not found: ${through.table}`);
1144
- }
1145
-
1146
- const junctionSourceCol = junctionTable[through.sourceColumn as keyof typeof junctionTable] as AnyPgColumn;
1147
- const junctionTargetCol = junctionTable[through.targetColumn as keyof typeof junctionTable] as AnyPgColumn;
1148
-
1149
- if (!junctionSourceCol) {
1150
- throw new Error(`Source column '${through.sourceColumn}' not found in junction table '${through.table}'`);
1151
- }
1152
- if (!junctionTargetCol) {
1153
- throw new Error(`Target column '${through.targetColumn}' not found in junction table '${through.table}'`);
1154
- }
1155
-
1156
- const baseConditions = [eq(junctionSourceCol, parentId)];
1157
- if (additionalFilters && additionalFilters.length > 0) {
1158
- baseConditions.push(...additionalFilters);
1159
- }
1160
-
1161
- return baseCountQuery
1162
- .innerJoin(junctionTable, eq(targetIdColumn, junctionTargetCol))
1163
- .where(and(...baseConditions));
1164
- }
1165
1023
 
1166
1024
  /**
1167
1025
  * Helper method to extract table names from columns
@@ -1183,69 +1041,6 @@ export class DrizzleConditionBuilder {
1183
1041
  return [getColumnName(columns)];
1184
1042
  }
1185
1043
 
1186
- /**
1187
- * Find the corresponding junction table for an inverse many-to-many relation
1188
- */
1189
- private static findCorrespondingJunctionTable(
1190
- relation: Relation,
1191
- registry: PostgresCollectionRegistry
1192
- ): { table: string; sourceColumn: string; targetColumn: string } | null {
1193
- try {
1194
- console.debug(`🔍 [findCorrespondingJunctionTable] Looking for junction table for inverse relation '${relation.relationName}' with inverseRelationName '${relation.inverseRelationName}'`);
1195
-
1196
- if (!relation.inverseRelationName) {
1197
- console.debug("🔍 [findCorrespondingJunctionTable] No inverseRelationName specified");
1198
- return null;
1199
- }
1200
-
1201
- // Get the target collection of the inverse relation
1202
- const targetCollection = relation.target();
1203
- console.debug(`🔍 [findCorrespondingJunctionTable] Target collection: ${targetCollection.slug}`);
1204
-
1205
- // Find the corresponding owning relation on the target collection
1206
- const targetCollectionRelations = resolveCollectionRelations(targetCollection);
1207
- console.debug("🔍 [findCorrespondingJunctionTable] Target collection relations:", Object.keys(targetCollectionRelations));
1208
-
1209
- // Look for the owning many-to-many relation that matches our inverseRelationName
1210
- const correspondingRelation = targetCollectionRelations[relation.inverseRelationName];
1211
-
1212
- if (!correspondingRelation) {
1213
- console.debug(`🔍 [findCorrespondingJunctionTable] No relation found with key '${relation.inverseRelationName}' on target collection`);
1214
- return null;
1215
- }
1216
-
1217
- console.debug("🔍 [findCorrespondingJunctionTable] Found relation:", {
1218
- relationName: correspondingRelation.relationName,
1219
- cardinality: correspondingRelation.cardinality,
1220
- direction: correspondingRelation.direction,
1221
- hasThrough: !!correspondingRelation.through
1222
- });
1223
-
1224
- // Verify it's an owning many-to-many relation with junction table
1225
- if (correspondingRelation.cardinality !== "many" ||
1226
- correspondingRelation.direction !== "owning" ||
1227
- !correspondingRelation.through) {
1228
- console.debug("🔍 [findCorrespondingJunctionTable] Relation is not an owning many-to-many with junction table");
1229
- return null;
1230
- }
1231
-
1232
- console.debug("🔍 [findCorrespondingJunctionTable] Found matching owning relation with junction table!");
1233
-
1234
- // For inverse relation, we need to swap source and target columns
1235
- const through = correspondingRelation.through;
1236
- const result = {
1237
- table: through.table,
1238
- sourceColumn: through.targetColumn, // Swapped for inverse relation
1239
- targetColumn: through.sourceColumn // Swapped for inverse relation
1240
- };
1241
-
1242
- console.debug("🔍 [findCorrespondingJunctionTable] Returning junction info:", result);
1243
- return result;
1244
- } catch (error) {
1245
- logger.error(`🔍 [findCorrespondingJunctionTable] Error finding corresponding junction table for relation '${relation.relationName}'`, { error: error });
1246
- return null;
1247
- }
1248
- }
1249
1044
 
1250
1045
  /**
1251
1046
  * Build vector similarity search expressions for pgvector.