1 import { CrossModuleJoinSpec } from "@medusajs/types"
2 import { composeTableName } from "@medusajs/utils"
3 import { GraphCatalog } from "../catalog"
4 import { resolveFieldAliasEntry } from "../helpers"
5 import { InternalJoinerServiceConfig } from "../types"
6 import { ChainLevel, ChainResolution, Hop } from "./types"
7
8 type ChainContext = {
9 rootConfig: InternalJoinerServiceConfig
10 catalog: GraphCatalog
11 }
12
13 /**
14 * Where the chain currently stands while consuming hops: the table and key
15 * the next level must correlate against, and the module that table belongs
16 * to. Starts at the root entity and advances to each level's target.
17 */
18 type ChainPosition = {
19 correlateKey: string
20 currentTable?: string
21 serviceName: string
22 }
23
24 /**
25 * One consumed hop shape, mapped to a join level. The dispatcher attaches
26 * `parent` and advances the position.
27 */
28 type ChainStep = {
29 spec: CrossModuleJoinSpec
30 entity?: string
31 properties: string[]
32 serviceName: string
33 consumedHops: 1 | 2
34 }
35
36 /**
37 * Resolves a relation path all the way to a pushable join chain, classifying
38 * paths that cannot be pushed (see {@link ChainResolution}).
39 */
40 export function resolveChain(
41 params: {
42 rootConfig: InternalJoinerServiceConfig
43 pathSegments: string[]
44 },
45 catalog: GraphCatalog
46 ): ChainResolution {
47 const hops = resolvePathHops(params, catalog)
48
49 if (!hops || !crossesModules(hops, params.rootConfig)) {
50 return { outcome: "native" }
51 }
52
53 const levels = buildChainLevels({
54 hops,
55 rootConfig: params.rootConfig,
56 catalog,
57 })
58
59 return levels ? { outcome: "pushable", levels } : { outcome: "residual" }
60 }
61
62 /**
63 * Resolves an alias-form relation path into per-hop info, expanding
64 * fieldAlias shortcuts (e.g. `price_set` -> `price_set_link.price_set`) the
65 * same way compile's parseProperties does. A segment resolves either to a
66 * module-internal DML relation (from alias `__internal.relations` metadata)
67 * or to a catalog relationship (link modules, read-only links). Returns
68 * undefined when a segment resolves to neither, or when the graph schema
69 * disagrees with the DML relation metadata.
70 */
71 export function resolvePathHops(
72 params: {
73 rootConfig: InternalJoinerServiceConfig
74 pathSegments: string[]
75 },
76 catalog: GraphCatalog
77 ): Hop[] | undefined {
78 const { rootConfig, pathSegments } = params
79
80 const hops: Hop[] = []
81 let currentConfig = rootConfig
82 let entity = rootConfig.entity
83 let internalTrail: string[] = []
84
85 for (const segment of pathSegments) {
86 const aliasEntry = resolveFieldAliasEntry(
87 currentConfig.fieldAlias?.[segment],
88 entity
89 )
90 const realSegments = aliasEntry ? aliasEntry.path.split(".") : [segment]
91
92 for (const realSegment of realSegments) {
93 const internalRelation =
94 catalog.getAliasMetadata(entity)?.relations?.[realSegment]
95
96 if (internalRelation) {
97 // The graph schema must agree with the DML relation. Modules that
98 // remap relations in a custom schema (e.g. order.items resolves to
99 // OrderLineItem while the DML relation targets OrderItem) cannot be
100 // traversed from the derived metadata.
101 const schemaEntity = entity
102 ? catalog.getEntity(entity, realSegment)
103 : undefined
104 if (schemaEntity && schemaEntity !== internalRelation.entity) {
105 return undefined
106 }
107
108 hops.push({
109 kind: "internal",
110 property: realSegment,
111 serviceConfig: currentConfig,
112 entity: internalRelation.entity,
113 internal: internalRelation,
114 internalTrail: [...internalTrail],
115 })
116
117 internalTrail.push(realSegment)
118 entity = internalRelation.entity
119 continue
120 }
121
122 let hopEntity = entity
123 ? catalog.getEntity(entity, realSegment) ?? entity
124 : entity
125
126 const relationship = catalog.getEntityRelationship({
127 parentServiceConfig: currentConfig,
128 property: realSegment,
129 entity: hopEntity,
130 })
131
132 if (!relationship) {
133 return undefined
134 }
135
136 hopEntity = relationship.entity ?? hopEntity
137
138 const nextConfig = catalog.getServiceConfig({
139 serviceName: relationship.serviceName,
140 entity: relationship.entity,
141 })
142
143 if (!nextConfig) {
144 return undefined
145 }
146
147 hops.push({
148 kind: "relationship",
149 property: realSegment,
150 relationship,
151 serviceConfig: nextConfig,
152 entity: hopEntity,
153 internalTrail: [...internalTrail],
154 })
155
156 internalTrail = []
157 currentConfig = nextConfig
158 entity = hopEntity
159 }
160 }
161
162 return hops.length ? hops : undefined
163 }
164
165 function crossesModules(
166 hops: Hop[] | undefined,
167 rootConfig: InternalJoinerServiceConfig
168 ): boolean {
169 return !!hops?.some(
170 (hop) => hop.serviceConfig.serviceName !== rootConfig.serviceName
171 )
172 }
173
174 /**
175 * Maps the resolved hops onto {@link CrossModuleJoinSpec}s, chaining via
176 * `parent`. Three hop shapes are supported, one builder each:
177 *
178 * - (link module -> target) pairs: the link table joins the current position
179 * to an entity of another module.
180 * - Read-only link hops: an FK column on the current position's table points
181 * at another module's entity. When the FK follows an internal hasMany hop,
182 * both fuse into a single spec with the internal child table acting as the
183 * link table (e.g. cart -> items -> product becomes
184 * `cart_line_item(cart_id -> product_id) -> product`).
185 * - Module-internal DML relation hops (hasMany/belongsTo), standing alone as
186 * self-join levels so deeper levels can chain on them.
187 */
188 export function buildChainLevels(params: {
189 hops: Hop[]
190 rootConfig: InternalJoinerServiceConfig
191 catalog: GraphCatalog
192 }): ChainLevel[] | undefined {
193 const { hops, rootConfig, catalog } = params
194
195 if (!hops.length) {
196 return undefined
197 }
198
199 const context: ChainContext = { rootConfig, catalog }
200 const levels: ChainLevel[] = []
201 const realPath: string[] = []
202
203 // The DAL correlates the root EXISTS against the entity's "id" column and
204 // chained joins against the parent target's primaryKey.
205 const position: ChainPosition = {
206 correlateKey: "id",
207 currentTable: catalog.getAliasMetadata(rootConfig.entity)?.tableName,
208 serviceName: rootConfig.serviceName,
209 }
210 let parentTable: string | undefined
211
212 let i = 0
213 while (i < hops.length) {
214 const hop = hops[i]
215 const next = hops[i + 1]
216
217 const step =
218 hop.kind === "internal"
219 ? buildInternalRelationStep(hop, next, position, context)
220 : hop.serviceConfig.isLink
221 ? buildLinkModuleStep(hop, next, position, context)
222 : buildReadOnlyLinkStep(hop, position, context)
223
224 if (!step) {
225 return undefined
226 }
227
228 realPath.push(...step.properties)
229 levels.push({
230 realPathKey: realPath.join("."),
231 entity: step.entity,
232 spec: parentTable ? { parent: parentTable, ...step.spec } : step.spec,
233 })
234
235 parentTable = step.spec.target.table
236 position.correlateKey = step.spec.target.primaryKey ?? "id"
237 position.currentTable = parentTable
238 position.serviceName = step.serviceName
239 i += step.consumedHops
240 }
241
242 return levels
243 }
244
245 /**
246 * Module-internal DML relation hops. A hasMany hop followed by a read-only
247 * link fuses into a single spec (the child table acts as the link table);
248 * standing alone it becomes a self-join level, and belongsTo joins off the
249 * current position's table.
250 */
251 function buildInternalRelationStep(
252 hop: Hop,
253 next: Hop | undefined,
254 position: ChainPosition,
255 context: ChainContext
256 ): ChainStep | undefined {
257 const { catalog } = context
258 const relation = hop.internal!
259 const tableMetadata = catalog.getAliasMetadata(hop.entity)
260
261 if (!tableMetadata?.tableName || !isSimpleKey(relation.foreignKey)) {
262 return undefined
263 }
264
265 if (relation.foreignKeyOwner === "target") {
266 // hasMany: the child's FK column references the parent's id column.
267 if (position.correlateKey !== "id") {
268 return undefined
269 }
270
271 const isFusableNext =
272 next?.kind === "relationship" && !next.serviceConfig.isLink
273
274 if (isFusableNext) {
275 const fkHop = resolveFkHopParts(next, position, context)
276 if (!fkHop) {
277 return undefined
278 }
279
280 // Only forward read-only links fuse (their FK column lives on this
281 // internal child table). Inverse ones chain off the child's own PK, so
282 // the standalone self-join below is emitted and the loop consumes the
283 // read-only hop on its own.
284 if (fkHop.direction === "forward") {
285 return {
286 spec: {
287 link: {
288 table: tableMetadata.tableName,
289 sourceKey: relation.foreignKey,
290 targetKey: fkHop.column,
291 },
292 target: fkHop.target,
293 },
294 entity: next.entity,
295 properties: [hop.property, next.property],
296 serviceName: next.serviceConfig.serviceName,
297 consumedHops: 2,
298 }
299 }
300 }
301
302 // Standalone internal hop: a self-join level deeper levels chain on.
303 return {
304 spec: {
305 link: {
306 table: tableMetadata.tableName,
307 sourceKey: relation.foreignKey,
308 targetKey: "id",
309 },
310 target: {
311 table: tableMetadata.tableName,
312 ...(tableMetadata.schema ? { schema: tableMetadata.schema } : {}),
313 primaryKey: "id",
314 },
315 },
316 entity: hop.entity,
317 properties: [hop.property],
318 serviceName: position.serviceName,
319 consumedHops: 1,
320 }
321 }
322
323 // belongsTo: the FK column lives on the current position's table.
324 if (!position.currentTable) {
325 return undefined
326 }
327
328 return {
329 spec: {
330 link: {
331 table: position.currentTable,
332 sourceKey: position.correlateKey,
333 targetKey: relation.foreignKey,
334 },
335 target: {
336 table: tableMetadata.tableName,
337 ...(tableMetadata.schema ? { schema: tableMetadata.schema } : {}),
338 primaryKey: "id",
339 },
340 },
341 entity: hop.entity,
342 properties: [hop.property],
343 serviceName: position.serviceName,
344 consumedHops: 1,
345 }
346 }
347
348 /**
349 * (link module -> target) pairs: the link table joins the current position to
350 * an entity of another module.
351 */
352 function buildLinkModuleStep(
353 hop: Hop,
354 targetHop: Hop | undefined,
355 position: ChainPosition,
356 context: ChainContext
357 ): ChainStep | undefined {
358 const { rootConfig, catalog } = context
359 const linkConfig = hop.serviceConfig
360
361 if (!targetHop || targetHop.kind !== "relationship") {
362 return undefined
363 }
364
365 const linkRel = hop.relationship!
366 const targetRel = targetHop.relationship!
367
368 if (linkRel.inverse || targetRel.inverse) {
369 return undefined
370 }
371
372 if (
373 !isSimpleKey(linkRel.primaryKey) ||
374 !isSimpleKey(linkRel.foreignKey) ||
375 !isSimpleKey(targetRel.primaryKey) ||
376 !isSimpleKey(targetRel.foreignKey)
377 ) {
378 return undefined
379 }
380
381 if (linkRel.foreignKey !== position.correlateKey) {
382 return undefined
383 }
384
385 // The root and target modules must live in the same database. Link modules
386 // are not compared: they always run on the app's shared connection and
387 // their resolved databaseClientUrl is not reliable.
388 if (
389 targetHop.serviceConfig.databaseClientUrl !== rootConfig.databaseClientUrl
390 ) {
391 return undefined
392 }
393
394 const metadata = catalog.getAliasMetadata(targetHop.entity)
395 if (!metadata?.tableName) {
396 return undefined
397 }
398
399 const linkTable = resolveLinkTableName(linkConfig)
400 if (!linkTable) {
401 return undefined
402 }
403
404 return {
405 spec: {
406 link: {
407 table: linkTable,
408 sourceKey: linkRel.primaryKey,
409 targetKey: targetRel.foreignKey,
410 },
411 target: {
412 table: metadata.tableName,
413 ...(metadata.schema ? { schema: metadata.schema } : {}),
414 primaryKey: targetRel.primaryKey,
415 },
416 },
417 entity: targetHop.entity,
418 properties: [hop.property, targetHop.property],
419 serviceName: targetHop.serviceConfig.serviceName,
420 consumedHops: 2,
421 }
422 }
423
424 /**
425 * Read-only link hop directly off the current position.
426 */
427 function buildReadOnlyLinkStep(
428 hop: Hop,
429 position: ChainPosition,
430 context: ChainContext
431 ): ChainStep | undefined {
432 const fkHop = resolveFkHopParts(hop, position, context)
433
434 if (!fkHop) {
435 return undefined
436 }
437
438 if (fkHop.direction === "inverse") {
439 // Self-join on the target table: the target-side column correlates to
440 // the current position while deeper levels chain on the target's PK.
441 return {
442 spec: {
443 link: {
444 table: fkHop.target.table,
445 ...(fkHop.target.schema ? { schema: fkHop.target.schema } : {}),
446 sourceKey: fkHop.targetColumn,
447 targetKey: "id",
448 },
449 target: fkHop.target,
450 },
451 entity: hop.entity,
452 properties: [hop.property],
453 serviceName: hop.serviceConfig.serviceName,
454 consumedHops: 1,
455 }
456 }
457
458 if (!position.currentTable) {
459 return undefined
460 }
461
462 return {
463 spec: {
464 link: {
465 table: position.currentTable,
466 sourceKey: position.correlateKey,
467 targetKey: fkHop.column,
468 },
469 target: fkHop.target,
470 },
471 entity: hop.entity,
472 properties: [hop.property],
473 serviceName: hop.serviceConfig.serviceName,
474 consumedHops: 1,
475 }
476 }
477
478 type FkHopParts =
479 | {
480 /** The FK column lives on the current position's side. */
481 direction: "forward"
482 column: string
483 target: CrossModuleJoinSpec["target"]
484 }
485 | {
486 /** The join column lives on the target table. */
487 direction: "inverse"
488 targetColumn: string
489 target: CrossModuleJoinSpec["target"]
490 }
491
492 /**
493 * Validates a read-only link hop and resolves its join columns and target
494 * table. Read-only links come in two directions:
495 *
496 * - forward: the FK column lives on the current position's side and the
497 * relationship's `primaryKey` is the target's PK (e.g.
498 * `cart_line_item.product_id -> product.id`).
499 * - inverse: the join column lives on the target table (e.g.
500 * `organization.id -> project.organization_id`), in which case the parent
501 * side must be the current correlate column.
502 */
503 function resolveFkHopParts(
504 hop: Hop,
505 position: ChainPosition,
506 context: ChainContext
507 ): FkHopParts | undefined {
508 const { rootConfig, catalog } = context
509 const relationship = hop.relationship!
510
511 if (relationship.inverse) {
512 return undefined
513 }
514
515 // Same-service relationship hops are only traversable through internal
516 // relation metadata; alias-generated relationships carry fabricated keys.
517 if (relationship.serviceName === position.serviceName) {
518 return undefined
519 }
520
521 const fkSegments = relationship.foreignKey.split(".")
522 const column = fkSegments[fkSegments.length - 1]
523 const prefix = fkSegments.slice(0, -1)
524
525 // The dotted prefix declares the relation path the FK column lives on
526 // (e.g. `items.product_id`) — it must match the internal hops traversed to
527 // reach this position.
528 if (prefix.join(".") !== hop.internalTrail.join(".")) {
529 return undefined
530 }
531
532 if (column.includes(",") || !isSimpleKey(relationship.primaryKey)) {
533 return undefined
534 }
535
536 const targetMetadata = catalog.getAliasMetadata(hop.entity)
537 if (!targetMetadata?.tableName) {
538 return undefined
539 }
540
541 // The resolved entity must actually belong to the relationship's target
542 // module, otherwise the table would be wrong.
543 const entityConfig = hop.entity
544 ? catalog.getServiceConfig({ entity: hop.entity })
545 : undefined
546 if (entityConfig?.serviceName !== relationship.serviceName) {
547 return undefined
548 }
549
550 if (hop.serviceConfig.databaseClientUrl !== rootConfig.databaseClientUrl) {
551 return undefined
552 }
553
554 // The target's PK is always "id" for the spec so deeper levels chain on
555 // the real primary key regardless of the link direction.
556 const target = {
557 table: targetMetadata.tableName,
558 ...(targetMetadata.schema ? { schema: targetMetadata.schema } : {}),
559 primaryKey: "id",
560 }
561
562 if (relationship.primaryKey === "id") {
563 return { direction: "forward", column, target }
564 }
565
566 // Inverse: `primaryKey` is the join column on the target table, and the
567 // parent-side column must correlate directly to the current position.
568 if (column !== position.correlateKey) {
569 return undefined
570 }
571
572 return {
573 direction: "inverse",
574 targetColumn: relationship.primaryKey,
575 target,
576 }
577 }
578
579 function resolveLinkTableName(
580 linkConfig: InternalJoinerServiceConfig
581 ): string | undefined {
582 if (linkConfig.databaseConfig?.tableName) {
583 return linkConfig.databaseConfig.tableName
584 }
585
586 const relationships = linkConfig.relationships
587 ? Array.from(linkConfig.relationships.values()).flat()
588 : []
589
590 // Exclude the alias-generated self relationships the catalog adds.
591 const moduleRelationships = relationships.filter(
592 (rel) => rel.serviceName !== linkConfig.serviceName
593 )
594
595 if (moduleRelationships.length !== 2) {
596 return undefined
597 }
598
599 const [primary, foreign] = moduleRelationships
600
601 // Mirrors the default naming in link-modules' generateEntity.
602 return composeTableName(
603 primary.serviceName,
604 primary.foreignKey,
605 foreign.serviceName,
606 foreign.foreignKey
607 ).toLowerCase()
608 }
609
610 function isSimpleKey(key: string): boolean {
611 return !key.includes(",") && !key.includes(".")
612 }