Skip to content

Commit

Permalink
Fix drift when FKs have same columns
Browse files Browse the repository at this point in the history
fixes prisma/prisma#23043

based on #1904
  • Loading branch information
Druue committed May 24, 2024
1 parent f742678 commit b8b14bc
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,22 @@ impl<'schema, 'b> TableDiffer<'schema, 'b> {
}

pub(crate) fn foreign_key_pairs(&self) -> impl Iterator<Item = MigrationPair<ForeignKeyWalker<'schema>>> + '_ {
self.previous_foreign_keys().filter_map(move |previous_fk| {
let singular_fks = self.previous_foreign_keys().filter(move |left| {
let number_of_identical_fks = self
.previous_foreign_keys()
.filter(|right| {
left.referenced_columns().len() == right.referenced_columns().len()
&& left
.referenced_columns()
.zip(right.referenced_columns())
.all(|(a, b)| a.name() == b.name())
})
.count();

number_of_identical_fks == 1
});

singular_fks.filter_map(move |previous_fk| {
self.next_foreign_keys()
.find(move |next_fk| foreign_keys_match(MigrationPair::new(&previous_fk, next_fk), self.db))
.map(move |next_fk| MigrationPair::new(previous_fk, next_fk))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,48 @@ fn indexes_on_same_columns_with_different_names_should_work(api: TestApi) {
assert!(output.drift.is_none());
}

#[test_connector]
fn foreign_keys_on_same_columns_should_work(api: TestApi) {
let directory = api.create_migrations_directory();

let dm = api.datamodel_with_provider(
r#"
model prisma_bug_1 {
id1 BigInt
id2 BigInt
prisma_bug_2_a prisma_bug_2[] @relation("a")
prisma_bug_2_b prisma_bug_2[] @relation("b")
@@id([id1, id2])
}
model prisma_bug_2 {
id BigInt @id
prisma_bug_1_id1 BigInt
prisma_bug_1_id2 BigInt
prisma_bug_1_a prisma_bug_1 @relation("a", fields: [prisma_bug_1_id1, prisma_bug_1_id2], references: [id1, id2], map: "prisma_bug_1_a_fk")
prisma_bug_1_b prisma_bug_1? @relation("b", fields: [prisma_bug_1_id1, prisma_bug_1_id2], references: [id1, id2], map: "prisma_bug_1_b_fk")
}
"#,
);

api.create_migration("initial", &dm, &directory).send_sync();

api.apply_migrations(&directory)
.send_sync()
.assert_applied_migrations(&["initial"]);

let output = api
.diagnose_migration_history(&directory)
.opt_in_to_shadow_database(true)
.send_sync()
.into_output();

assert!(output.drift.is_none());
}

#[test_connector(tags(Postgres))]
fn default_dbgenerated_should_not_cause_drift(api: TestApi) {
let migrations_directory = api.create_migrations_directory();
Expand Down

0 comments on commit b8b14bc

Please sign in to comment.