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

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.
@@ -19,6 +19,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query
19
19
  import { DrizzleClient } from "../interfaces";
20
20
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
21
21
  import { toCmsRow, toRestRow, isJunctionRelation } from "./row-pipeline";
22
+ import { isNestedPath, resolveNestedPath, type NestedPathHop } from "./nested-path";
22
23
  import { logger } from "@rebasepro/server";
23
24
 
24
25
  /** Type-safe accessor for Drizzle's relational query API via dynamic table name */
@@ -279,7 +280,8 @@ export class FetchService {
279
280
  logical?: LogicalCondition;
280
281
  },
281
282
  collectionPath: string,
282
- withConfig?: Record<string, unknown>
283
+ withConfig?: Record<string, unknown>,
284
+ scopeCondition?: SQL
283
285
  ): Record<string, unknown> {
284
286
  const queryOpts: Record<string, unknown> = {};
285
287
 
@@ -288,6 +290,8 @@ export class FetchService {
288
290
  // Build where conditions
289
291
  const allConditions: SQL[] = [];
290
292
 
293
+ if (scopeCondition) allConditions.push(scopeCondition);
294
+
291
295
  if (options.searchString) {
292
296
  const collection = getCollectionByPath(collectionPath, this.registry);
293
297
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
@@ -391,6 +395,59 @@ export class FetchService {
391
395
  return [];
392
396
  }
393
397
 
398
+ /**
399
+ * Compile "rows reachable from this parent" into a `WHERE` condition on the
400
+ * target table, so a nested listing can run as an ordinary collection query.
401
+ */
402
+ private buildRelationScope(hop: NestedPathHop): SQL {
403
+ const parentPks = requirePrimaryKeys(hop.parentCollection, this.registry);
404
+ const parentIdInfo = parentPks[0];
405
+ const parsedParentId = parseIdValues(hop.parentId, parentPks)[parentIdInfo.fieldName];
406
+
407
+ const parent = () => {
408
+ const table = getTableForCollection(hop.parentCollection, this.registry);
409
+ const idColumn = table[parentIdInfo.fieldName as keyof typeof table] as AnyPgColumn;
410
+ if (!idColumn) {
411
+ throw new Error(`ID field '${parentIdInfo.fieldName}' not found in table for collection '${hop.parentCollection.slug}'`);
412
+ }
413
+ return { table,
414
+ idColumn };
415
+ };
416
+
417
+ const targetTable = getTableForCollection(hop.targetCollection, this.registry);
418
+ const targetPks = requirePrimaryKeys(hop.targetCollection, this.registry);
419
+ const targetIdColumn = targetTable[targetPks[0].fieldName as keyof typeof targetTable] as AnyPgColumn;
420
+ if (!targetIdColumn) {
421
+ throw new Error(`ID field '${targetPks[0].fieldName}' not found in table for collection '${hop.targetCollection.slug}'`);
422
+ }
423
+
424
+ return DrizzleConditionBuilder.buildRelationScopeCondition(
425
+ hop.relation,
426
+ parent,
427
+ parsedParentId as string | number,
428
+ targetTable,
429
+ targetIdColumn,
430
+ this.registry
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Whether `id` is actually reachable at `collectionPath`.
436
+ *
437
+ * Trivially true for a root path. For a nested one it is a real question:
438
+ * the path resolves to the target collection, and matching on the primary
439
+ * key alone made the parent segment decorative — `authors/1/posts/43`
440
+ * returned post 43 whoever wrote it, and the REST layer's delete then
441
+ * deleted it. A row that is not under this parent is reported as absent,
442
+ * which is what a caller addressing it through the parent should see.
443
+ */
444
+ private async isAddressableUnder(collectionPath: string, id: string | number): Promise<boolean> {
445
+ if (!isNestedPath(collectionPath)) return true;
446
+ const hop = resolveNestedPath(collectionPath, this.registry);
447
+ if (!hop) return true;
448
+ return this.relationService.isRelated(hop, id);
449
+ }
450
+
394
451
  /**
395
452
  * Fetch a single row by ID
396
453
  */
@@ -399,6 +456,8 @@ export class FetchService {
399
456
  id: string | number,
400
457
  databaseId?: string
401
458
  ): Promise<Record<string, unknown> | undefined> {
459
+ if (!await this.isAddressableUnder(collectionPath, id)) return undefined;
460
+
402
461
  const collection = getCollectionByPath(collectionPath, this.registry);
403
462
  const table = getTableForCollection(collection, this.registry);
404
463
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -516,8 +575,11 @@ export class FetchService {
516
575
  databaseId?: string;
517
576
  vectorSearch?: VectorSearchParams;
518
577
  logical?: LogicalCondition;
578
+ /** Narrow to the rows reachable from a parent through a relation. */
579
+ relatedTo?: NestedPathHop;
519
580
  } = {}
520
581
  ): Promise<Record<string, unknown>[]> {
582
+ const scopeCondition = options.relatedTo ? this.buildRelationScope(options.relatedTo) : undefined;
521
583
  const collection = getCollectionByPath(collectionPath, this.registry);
522
584
  const table = getTableForCollection(collection, this.registry);
523
585
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -545,7 +607,7 @@ export class FetchService {
545
607
  if (qb && !options.searchString && !hasRelations && !options.vectorSearch) {
546
608
  try {
547
609
  const queryOpts = this.buildDrizzleQueryOptions<M>(
548
- table, idField, idInfo, options, collectionPath, undefined
610
+ table, idField, idInfo, options, collectionPath, undefined, scopeCondition
549
611
  );
550
612
 
551
613
 
@@ -578,6 +640,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
578
640
  : this.db.select().from(table).$dynamic();
579
641
  const allConditions: SQL[] = [];
580
642
 
643
+ if (scopeCondition) allConditions.push(scopeCondition);
644
+
581
645
  if (options.searchString) {
582
646
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
583
647
  options.searchString, collection.properties, table
@@ -771,9 +835,13 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
771
835
  vectorSearch?: VectorSearchParams;
772
836
  } = {}
773
837
  ): Promise<Record<string, unknown>[]> {
774
- // Handle multi-segment paths by resolving through relations
775
- if (collectionPath.includes("/")) {
776
- return this.fetchCollectionFromPath<M>(collectionPath, options);
838
+ // A nested path is the target collection narrowed by a relation — the
839
+ // same query, one condition heavier. It used to be a separate builder
840
+ // that honoured `limit` and nothing else.
841
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
842
+ if (hop) {
843
+ return this.fetchRowsWithConditions<M>(hop.targetCollection.slug, { ...options,
844
+ relatedTo: hop });
777
845
  }
778
846
 
779
847
  return this.fetchRowsWithConditions<M>(collectionPath, options);
@@ -799,65 +867,6 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
799
867
  });
800
868
  }
801
869
 
802
- /**
803
- * Fetch collection from multi-segment path
804
- */
805
- private async fetchCollectionFromPath<M extends Record<string, unknown>>(
806
- path: string,
807
- options: {
808
- filter?: FilterValues<Extract<keyof M, string>>;
809
- orderBy?: string;
810
- order?: "desc" | "asc";
811
- limit?: number;
812
- startAfter?: Record<string, unknown>;
813
- searchString?: string;
814
- databaseId?: string;
815
- } = {}
816
- ): Promise<Record<string, unknown>[]> {
817
- const pathSegments = path.split("/").filter(p => p && p !== "undefined");
818
-
819
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {
820
- throw new Error(`Invalid relation path: ${path}. Expected format: collection/id/relation`);
821
- }
822
-
823
- const rootCollectionPath = pathSegments[0];
824
- let currentCollection = getCollectionByPath(rootCollectionPath, this.registry);
825
- let currentId: string | number = pathSegments[1];
826
-
827
- for (let i = 2; i < pathSegments.length; i += 2) {
828
- const relationKey = pathSegments[i];
829
- const resolvedRelations = resolveCollectionRelations(currentCollection);
830
- const relation = findRelation(resolvedRelations, relationKey);
831
-
832
- if (!relation) {
833
- throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
834
- }
835
-
836
- if (i === pathSegments.length - 1) {
837
- const rows = await this.relationService.fetchRelatedEntities<M>(
838
- currentCollection.slug,
839
- currentId,
840
- relationKey,
841
- options
842
- );
843
- // Flatten RelatedRow[] to rows: the target's columns, and only
844
- // those. Merging `row.id` in last overwrote a real `id` column,
845
- // and the address is derivable without it — a consumer resolves
846
- // this path ("posts/1/comments") to the target collection and
847
- // reads the key columns, which `values` carries.
848
- return rows.map(row => ({ ...row.values as Record<string, unknown> }));
849
- }
850
-
851
- if (i + 1 < pathSegments.length) {
852
- const nextEntityId = pathSegments[i + 1];
853
- currentCollection = relation.target();
854
- currentId = nextEntityId;
855
- }
856
- }
857
-
858
- throw new Error(`Unable to resolve path: ${path}`);
859
- }
860
-
861
870
  /**
862
871
  * Count rows in a collection
863
872
  */
@@ -869,16 +878,20 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
869
878
  databaseId?: string;
870
879
  } = {}
871
880
  ): Promise<number> {
872
- if (collectionPath.includes("/")) {
873
- return this.countEntitiesFromPath<M>(collectionPath, options);
874
- }
881
+ // Same narrowing as the listing — and, unlike the count it replaces,
882
+ // the same `filter` and `searchString` too, so `total` describes the
883
+ // rows that were actually served.
884
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
885
+ const effectivePath = hop ? hop.targetCollection.slug : collectionPath;
875
886
 
876
- const collection = getCollectionByPath(collectionPath, this.registry);
887
+ const collection = getCollectionByPath(effectivePath, this.registry);
877
888
  const table = getTableForCollection(collection, this.registry);
878
889
 
879
890
  let query = this.db.select({ count: count() }).from(table).$dynamic();
880
891
  const allConditions: SQL[] = [];
881
892
 
893
+ if (hop) allConditions.push(this.buildRelationScope(hop));
894
+
882
895
  if (options.searchString) {
883
896
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
884
897
  options.searchString, collection.properties, table
@@ -888,7 +901,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
888
901
  }
889
902
 
890
903
  if (options.filter) {
891
- const filterConditions = this.buildFilterConditions(options.filter, table, collectionPath);
904
+ const filterConditions = this.buildFilterConditions(options.filter, table, effectivePath);
892
905
  if (filterConditions.length > 0) allConditions.push(...filterConditions);
893
906
  }
894
907
 
@@ -901,50 +914,6 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
901
914
  return Number(result[0]?.count || 0);
902
915
  }
903
916
 
904
- /**
905
- * Count rows from multi-segment path
906
- */
907
- private async countEntitiesFromPath<M extends Record<string, unknown>>(
908
- path: string,
909
- options: { filter?: FilterValues<Extract<keyof M, string>>; databaseId?: string } = {}
910
- ): Promise<number> {
911
- const pathSegments = path.split("/").filter(p => p && p !== "undefined");
912
-
913
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {
914
- throw new Error(`Invalid relation path: ${path}`);
915
- }
916
-
917
- const rootCollectionPath = pathSegments[0];
918
- let currentCollection = getCollectionByPath(rootCollectionPath, this.registry);
919
- let currentId: string | number = pathSegments[1];
920
-
921
- for (let i = 2; i < pathSegments.length; i += 2) {
922
- const relationKey = pathSegments[i];
923
- const resolvedRelations = resolveCollectionRelations(currentCollection);
924
- const relation = findRelation(resolvedRelations, relationKey);
925
-
926
- if (!relation) {
927
- throw new Error(`Relation '${relationKey}' not found`);
928
- }
929
-
930
- if (i === pathSegments.length - 1) {
931
- return this.relationService.countRelatedEntities(
932
- currentCollection.slug,
933
- currentId,
934
- relationKey,
935
- options
936
- );
937
- }
938
-
939
- if (i + 1 < pathSegments.length) {
940
- currentCollection = relation.target();
941
- currentId = pathSegments[i + 1];
942
- }
943
- }
944
-
945
- throw new Error(`Unable to count for path: ${path}`);
946
- }
947
-
948
917
  /**
949
918
  * Check if a field value is unique
950
919
  */
@@ -1014,9 +983,25 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1014
983
  searchString?: string;
1015
984
  databaseId?: string;
1016
985
  vectorSearch?: VectorSearchParams;
986
+ /** Narrow to the rows reachable from a parent through a relation. */
987
+ relatedTo?: NestedPathHop;
1017
988
  } = {},
1018
989
  include?: string[]
1019
990
  ): Promise<Record<string, unknown>[]> {
991
+ // Resolve a nested path here rather than at the route, so `include`,
992
+ // `offset` and the rest reach a child listing by the same route they
993
+ // reach a root one.
994
+ if (isNestedPath(collectionPath)) {
995
+ const hop = resolveNestedPath(collectionPath, this.registry);
996
+ if (hop) {
997
+ return this.fetchCollectionForRest<M>(
998
+ hop.targetCollection.slug, { ...options,
999
+ relatedTo: hop }, include
1000
+ );
1001
+ }
1002
+ }
1003
+
1004
+ const scopeCondition = options.relatedTo ? this.buildRelationScope(options.relatedTo) : undefined;
1020
1005
  const collection = getCollectionByPath(collectionPath, this.registry);
1021
1006
  const table = getTableForCollection(collection, this.registry);
1022
1007
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -1039,7 +1024,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1039
1024
  : undefined;
1040
1025
 
1041
1026
  const queryOpts = this.buildDrizzleQueryOptions<M>(
1042
- table, idField, idInfo, options, collectionPath, withConfig
1027
+ table, idField, idInfo, options, collectionPath, withConfig, scopeCondition
1043
1028
  );
1044
1029
 
1045
1030
 
@@ -1123,6 +1108,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1123
1108
  include?: string[],
1124
1109
  databaseId?: string
1125
1110
  ): Promise<Record<string, unknown> | null> {
1111
+ if (!await this.isAddressableUnder(collectionPath, id)) return null;
1112
+
1126
1113
  const collection = getCollectionByPath(collectionPath, this.registry);
1127
1114
  const table = getTableForCollection(collection, this.registry);
1128
1115
  const idInfoArray = requirePrimaryKeys(collection, this.registry);
@@ -1229,6 +1216,7 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1229
1216
  startAfter?: Record<string, unknown>;
1230
1217
  searchString?: string;
1231
1218
  vectorSearch?: VectorSearchParams;
1219
+ relatedTo?: NestedPathHop;
1232
1220
  } = {}
1233
1221
  ): Promise<Record<string, unknown>[]> {
1234
1222
  const collection = getCollectionByPath(collectionPath, this.registry);
@@ -1248,6 +1236,8 @@ _distance: vectorMeta.distanceSelect }).from(table).$dynamic()
1248
1236
  : this.db.select().from(table).$dynamic();
1249
1237
  const allConditions: SQL[] = [];
1250
1238
 
1239
+ if (options.relatedTo) allConditions.push(this.buildRelationScope(options.relatedTo));
1240
+
1251
1241
  if (options.searchString) {
1252
1242
  const searchConditions = DrizzleConditionBuilder.buildSearchConditions(
1253
1243
  options.searchString, collection.properties, table
@@ -2,7 +2,7 @@ import { eq, and, sql, SQL } from "drizzle-orm";
2
2
  import { AnyPgColumn, PgTable } from "drizzle-orm/pg-core";
3
3
  // import { NodePgDatabase } from "drizzle-orm/node-postgres";
4
4
  import { CollectionConfig, Properties, Relation } from "@rebasepro/types";
5
- import { getTableName, resolveCollectionRelations, findRelation } from "@rebasepro/common";
5
+ import { getTableName, resolveCollectionRelations } from "@rebasepro/common";
6
6
  import { DrizzleConditionBuilder } from "../utils/drizzle-conditions";
7
7
  import {
8
8
  getCollectionByPath,
@@ -16,6 +16,13 @@ import { RelationService } from "./RelationService";
16
16
  import { FetchService } from "./FetchService";
17
17
  import { DrizzleClient } from "../interfaces";
18
18
  import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
19
+ import {
20
+ assertWritableThrough,
21
+ isJunctionBackedRelation,
22
+ isNestedPath,
23
+ resolveNestedPath,
24
+ type NestedPathHop
25
+ } from "./nested-path";
19
26
  import { ApiError, logger } from "@rebasepro/server";
20
27
  import { extractPgError, extractCauseMessage, pgErrorToFriendlyMessage } from "../utils/pg-error-utils";
21
28
 
@@ -80,6 +87,33 @@ export class PersistService {
80
87
  * Delete an row by ID
81
88
  */
82
89
  async delete(collectionPath: string, id: string | number, _databaseId?: string): Promise<void> {
90
+ // A nested address deletes *through* a relation, and what that removes
91
+ // depends on who owns the target row.
92
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
93
+ if (hop) {
94
+ assertWritableThrough(hop, collectionPath);
95
+
96
+ if (!await this.relationService.isRelated(hop, id)) {
97
+ throw ApiError.notFound(`No row "${id}" in "${collectionPath}" to delete.`);
98
+ }
99
+
100
+ if (isJunctionBackedRelation(hop.relation)) {
101
+ // Shared target: drop the link, not the row.
102
+ if (!hop.relation.through) {
103
+ throw ApiError.badRequest(
104
+ `"${collectionPath}" reaches '${hop.targetCollection.slug}' through a multi-hop joinPath, ` +
105
+ `so there is no single link to remove. Delete the row at "${hop.targetCollection.slug}" ` +
106
+ "directly if that is what you meant.",
107
+ "RELATION_NOT_UNLINKABLE"
108
+ );
109
+ }
110
+ await this.relationService.unlinkRelatedEntity(this.db, hop, id);
111
+ return;
112
+ }
113
+ // Owned child (inverse FK): deleting the row is the right meaning,
114
+ // and membership above has established it is this parent's child.
115
+ }
116
+
83
117
  const collection = getCollectionByPath(collectionPath, this.registry);
84
118
  const table = getTableForCollection(collection, this.registry);
85
119
  const idInfoArray = getPrimaryKeys(collection, this.registry);
@@ -113,6 +147,44 @@ export class PersistService {
113
147
  await this.db.delete(table);
114
148
  }
115
149
 
150
+ /**
151
+ * The column on the *target* table that records the parent, for a create
152
+ * under a nested one-to-many path.
153
+ *
154
+ * Returns `undefined` when the link is not a column at all (a multi-hop
155
+ * `joinPath`), so the caller writes the row without stamping anything.
156
+ *
157
+ * `relation.localKey` is deliberately not consulted: it names a column on
158
+ * the *source* table. Falling back to it here — which is what this used to
159
+ * do, and first — stamped the parent's own foreign key onto the child row.
160
+ */
161
+ private resolveParentForeignKeyColumn(hop: NestedPathHop): string | undefined {
162
+ const { relation, relationKey, targetCollection } = hop;
163
+
164
+ if (relation.foreignKeyOnTarget) return relation.foreignKeyOnTarget;
165
+
166
+ if (relation.joinPath && relation.joinPath.length === 1) {
167
+ const joinStep = relation.joinPath[0];
168
+ const targetTableName = getTableName(targetCollection);
169
+ if (joinStep.table !== targetTableName) {
170
+ logger.warn(`Join step for relation '${relationKey}' targets '${joinStep.table}', not the target table '${targetTableName}'.`);
171
+ }
172
+ return DrizzleConditionBuilder.getColumnNamesFromColumns(joinStep.on.to)[0];
173
+ }
174
+
175
+ if (relation.joinPath && relation.joinPath.length > 1) {
176
+ // Multi-hop: the link lives in an intermediate table, not in a
177
+ // column on the target. Nothing to stamp.
178
+ return undefined;
179
+ }
180
+
181
+ throw ApiError.badRequest(
182
+ `Relation '${relationKey}' on '${hop.parentCollection.slug}' cannot be written through: it declares no ` +
183
+ "`foreignKeyOnTarget` (the column on " + `'${targetCollection.slug}'` + " that records the parent) and no `joinPath`.",
184
+ "RELATION_NOT_WRITABLE"
185
+ );
186
+ }
187
+
116
188
  /**
117
189
  * Save an row (create or update)
118
190
  *
@@ -129,93 +201,59 @@ export class PersistService {
129
201
  databaseId?: string,
130
202
  options?: { upsert?: boolean }
131
203
  ): Promise<Record<string, unknown>> {
132
- // If saving under a nested relation path, resolve the parent and inject FK
204
+ // If saving under a nested relation path, resolve the relation it ends in.
133
205
  let effectiveCollectionPath = collectionPath;
134
206
  const effectiveValues: Partial<M> = { ...values };
135
207
  let junctionTableInfo: { parentCollection: CollectionConfig; parentId: string | number; relation: Relation; relationKey: string; } | undefined;
136
208
 
137
- if (collectionPath.includes("/")) {
138
- const segments = collectionPath.split("/").filter(Boolean);
139
- if (segments.length >= 3 && segments.length % 2 === 1) {
140
- const rootSegment = segments[0];
141
- let currentCollection = getCollectionByPath(rootSegment, this.registry);
142
- let currentId: string | number = segments[1];
143
-
144
- for (let i = 2; i < segments.length; i += 2) {
145
- const relationKey = segments[i];
146
- const resolvedRelations = resolveCollectionRelations(currentCollection);
147
- const relation = findRelation(resolvedRelations, relationKey);
148
-
149
- if (!relation) {
150
- const available = Object.keys(resolvedRelations).join(", ") || "(none)";
151
- throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'. Available relations: [${available}]`);
152
- }
153
-
154
- if (i === segments.length - 1) {
155
- const targetCollection = relation.target();
156
- effectiveCollectionPath = targetCollection.slug;
157
-
158
- // Handle many-to-many with junction table
159
- if (relation.cardinality === "many" && relation.through) {
160
- const parentIdInfoArray = getPrimaryKeys(currentCollection, this.registry);
161
- const parentIdInfo = parentIdInfoArray[0];
162
- const parsedParentIdObj = parseIdValues(currentId, parentIdInfoArray);
163
- const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
164
-
165
- junctionTableInfo = {
166
- parentCollection: currentCollection,
167
- parentId: parsedParentId,
168
- relation: relation,
169
- relationKey: relationKey
170
- };
171
- break;
172
- }
173
-
174
- // Find the FK column that should store the parent ID
175
- let targetColumnName: string;
176
-
177
- if (relation.localKey) {
178
- targetColumnName = relation.localKey;
179
- } else if (relation.foreignKeyOnTarget) {
180
- targetColumnName = relation.foreignKeyOnTarget;
181
- } else if (relation.joinPath && relation.joinPath.length === 1) {
182
- const targetTableName = getTableName(targetCollection);
183
- const relevantJoinStep = relation.joinPath.find(joinStep => joinStep.table === targetTableName);
184
-
185
- if (relevantJoinStep) {
186
- const targetColumnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(relevantJoinStep.on.to);
187
- targetColumnName = targetColumnNames[0];
188
- } else {
189
- logger.warn(`Could not find specific join step for target table ${targetTableName} in relation '${relationKey}'.`);
190
- const targetColumnNames = DrizzleConditionBuilder.getColumnNamesFromColumns(relation.joinPath[0].on.to);
191
- targetColumnName = targetColumnNames[0];
192
- }
193
- } else if (relation.joinPath && relation.joinPath.length > 1) {
194
- // For multi-hop relations (like many-to-many through a junction table),
195
- // there is no direct foreign key on the target table pointing to the parent.
196
- // The relationship is managed via the junction table.
197
- // We shouldn't inject the parent ID directly into the target row payload.
198
- break;
199
- } else {
200
- throw new Error(`Relation '${relationKey}' lacks configuration for path-based saving.`);
201
- }
202
-
203
- const parentIdInfoArray = getPrimaryKeys(currentCollection, this.registry);
204
- const parentIdInfo = parentIdInfoArray[0];
205
- const parsedParentIdObj = parseIdValues(currentId, parentIdInfoArray);
206
- const parsedParentId = parsedParentIdObj[parentIdInfo.fieldName];
207
-
208
- const existingValue = (effectiveValues as Record<string, unknown>)[targetColumnName];
209
- if (existingValue !== undefined && existingValue !== null && existingValue !== parsedParentId) {
210
- logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent id '${parsedParentId}'.`);
211
- }
212
- (effectiveValues as Record<string, unknown>)[targetColumnName] = parsedParentId;
213
- break;
214
- } else {
215
- const nextEntityId = segments[i + 1];
216
- currentCollection = relation.target();
217
- currentId = nextEntityId;
209
+ const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : undefined;
210
+
211
+ if (hop) {
212
+ assertWritableThrough(hop, collectionPath);
213
+ effectiveCollectionPath = hop.targetCollection.slug;
214
+
215
+ const parentIdForWrite = () => {
216
+ const parentPks = getPrimaryKeys(hop.parentCollection, this.registry);
217
+ return parseIdValues(hop.parentId, parentPks)[parentPks[0].fieldName];
218
+ };
219
+
220
+ if (hop.relation.through) {
221
+ // A junction path addresses set membership, so a write through it
222
+ // asserts "this row is in this parent's set" on create *and* on
223
+ // update. The junction row is written after the main write below,
224
+ // idempotently, which is what makes `PUT parent/id/child/childId`
225
+ // able to attach a row that already exists.
226
+ //
227
+ // Unlike an owning foreign key, this takes the row from nobody:
228
+ // its other parents keep it. That is why linking is safe here
229
+ // where reparenting (below) is not.
230
+ junctionTableInfo = {
231
+ parentCollection: hop.parentCollection,
232
+ parentId: parentIdForWrite(),
233
+ relation: hop.relation,
234
+ relationKey: hop.relationKey
235
+ };
236
+ } else if (id !== undefined) {
237
+ // Updating an existing row *through* an owning parent. The parent
238
+ // segment is an assertion about where the row already lives, not
239
+ // an instruction to move it there: injecting the FK here silently
240
+ // reparented whatever id was named, so `PUT authors/1/posts/43`
241
+ // stole post 43 from its real author. Check membership instead,
242
+ // and leave the FK to an explicit value in the body.
243
+ if (!await this.relationService.isRelated(hop, id)) {
244
+ throw ApiError.notFound(`No row "${id}" in "${collectionPath}" to update.`);
245
+ }
246
+ } else {
247
+ // One-to-many create: stamp the parent's id onto the child's FK.
248
+ const targetColumnName = this.resolveParentForeignKeyColumn(hop);
249
+
250
+ if (targetColumnName) {
251
+ const parsedParentId = parentIdForWrite();
252
+ const existingValue = (effectiveValues as Record<string, unknown>)[targetColumnName];
253
+ if (existingValue !== undefined && existingValue !== null && existingValue !== parsedParentId) {
254
+ logger.warn(`Overriding provided value '${existingValue}' for FK '${targetColumnName}' with path parent id '${parsedParentId}'.`);
218
255
  }
256
+ (effectiveValues as Record<string, unknown>)[targetColumnName] = parsedParentId;
219
257
  }
220
258
  }
221
259
  }
@@ -372,8 +410,12 @@ export class PersistService {
372
410
  await this.relationService.updateRelationsUsingJoins(tx, collection, currentId, relationValues);
373
411
  }
374
412
 
375
- // Handle junction table creation for many-to-many path-based saves
376
- if (junctionTableInfo && !id) {
413
+ // Attach the row to the parent's set. Runs for updates as well as
414
+ // creates it used to be gated on `!id`, which is why a row that
415
+ // already existed could never be added to a parent through its
416
+ // path. The insert is idempotent, so re-asserting a link is a
417
+ // no-op rather than a duplicate-key error.
418
+ if (junctionTableInfo) {
377
419
  await this.relationService.handleJunctionTableCreation(tx, currentId, junctionTableInfo);
378
420
  }
379
421