Skip to content

Commit 8aabc28

Browse files
committed
Fix alias name generation
1 parent 14dce51 commit 8aabc28

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

drizzle-kit/src/cli/commands/introspect.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -835,7 +835,7 @@ export const relationsToTypeScript = (
835835
name: plural(toTable1),
836836
type: 'many-through',
837837
tableFrom: toTable2,
838-
columnsFrom: fk2.columnsFrom,
838+
columnsFrom: fk2.columnsTo,
839839
tableTo: toTable1,
840840
columnsTo: columnsTo2,
841841
tableThrough,
@@ -899,13 +899,27 @@ export const relationsToTypeScript = (
899899
(it, originIndex) => relationIndex !== originIndex && it.tableTo === relation.tableTo,
900900
);
901901
if (hasMultipleRelations) {
902-
relationName = relation.type === 'one'
903-
? `${relation.tableFrom}_${relation.columnsFrom.join('_')}_${relation.tableTo}_${
902+
// if one relation - we need to name a relation from this table to "many" table
903+
if (relation.type === 'one') {
904+
relationName = `${relation.tableFrom}_${relation.columnsFrom.join('_')}_${relation.tableTo}_${
904905
relation.columnsTo.join('_')
905-
}`
906-
: `${relation.tableTo}_${relation.columnsTo.join('_')}_${relation.tableFrom}_${
906+
}`;
907+
// if many relation - name in in different order, so alias names will match
908+
} else if (relation.type === 'many') {
909+
relationName = `${relation.tableTo}_${relation.columnsTo.join('_')}_${relation.tableFrom}_${
907910
relation.columnsFrom.join('_')
908911
}`;
912+
// if through relation - we need to name a relation from this table to "many" table and include "via"
913+
} else if (relation.type === 'through') {
914+
relationName = `${relation.tableFrom}_${relation.columnsFrom.join('_')}_${relation.tableTo}_${
915+
relation.columnsTo.join('_')
916+
}_via_${relation.tableThrough}`;
917+
// else is for many-through, meaning we need to reverse the order for tables and columns, but leave "via" the same
918+
} else {
919+
relationName = `${relation.tableTo}_${relation.columnsTo.join('_')}_${relation.tableFrom}_${
920+
relation.columnsFrom.join('_')
921+
}_via_${relation.tableThrough}`;
922+
}
909923
}
910924
const hasDuplicatedRelation = originArray.some(
911925
(it, originIndex) => relationIndex !== originIndex && it.name === relation.name,

0 commit comments

Comments
 (0)