Skip to content

Commit

Permalink
fix: avoid join column on both side
Browse files Browse the repository at this point in the history
  • Loading branch information
magrinj committed Jun 26, 2024
1 parent acd15a9 commit cc18d67
Showing 1 changed file with 21 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,36 @@ export const getJoinColumn = (
return null;
}

const inverseSideTarget = relationMetadataArgs.inverseSideTarget();
const inverseSideJoinColumnsMetadataArgsCollection =
metadataArgsStorage.filterJoinColumns(inverseSideTarget);
const filteredJoinColumnsMetadataArgsCollection =
joinColumnsMetadataArgsCollection.filter(
(joinColumnsMetadataArgs) =>
joinColumnsMetadataArgs.relationName === relationMetadataArgs.name,
);
const oppositeFilteredJoinColumnsMetadataArgsCollection =
inverseSideJoinColumnsMetadataArgsCollection.filter(
(joinColumnsMetadataArgs) =>
joinColumnsMetadataArgs.relationName === relationMetadataArgs.name,
);

if (
relationMetadataArgs.type === RelationMetadataType.ONE_TO_ONE &&
filteredJoinColumnsMetadataArgsCollection.length === 0 &&
oppositeFilteredJoinColumnsMetadataArgsCollection.length === 0
) {
throw new Error(
`Join column for one-to-one ${relationMetadataArgs.name} relation is missing on both sides`,
);
}

// If we're in a ONE_TO_ONE relation and there are no join columns, we need to find the join column on the inverse side
if (
relationMetadataArgs.type === RelationMetadataType.ONE_TO_ONE &&
filteredJoinColumnsMetadataArgsCollection.length === 0 &&
!opposite
) {
const inverseSideTarget = relationMetadataArgs.inverseSideTarget();
const inverseSideJoinColumnsMetadataArgsCollection =
metadataArgsStorage.filterJoinColumns(inverseSideTarget);
const inverseSideRelationMetadataArgsCollection =
metadataArgsStorage.filterRelations(inverseSideTarget);
const inverseSideRelationMetadataArgs =
Expand All @@ -42,7 +57,7 @@ export const getJoinColumn = (

if (!inverseSideRelationMetadataArgs) {
throw new Error(
`Inverse side relation metadata args are missing for relation ${relationMetadataArgs.name}`,
`Inverse side join column of relation ${relationMetadataArgs.name} is missing`,
);
}

Expand All @@ -57,15 +72,15 @@ export const getJoinColumn = (
// Check if there are multiple join columns for the relation
if (filteredJoinColumnsMetadataArgsCollection.length > 1) {
throw new Error(
`Multiple join columns metadata args found for relation ${relationMetadataArgs.name}`,
`Multiple join columns found for relation ${relationMetadataArgs.name}`,
);
}

const joinColumnsMetadataArgs = filteredJoinColumnsMetadataArgsCollection[0];

if (!joinColumnsMetadataArgs) {
throw new Error(
`Join columns metadata args are missing for relation ${relationMetadataArgs.name}`,
`Join column is missing for relation ${relationMetadataArgs.name}`,
);
}

Expand Down

0 comments on commit cc18d67

Please sign in to comment.