Skip to content

Commit

Permalink
Postgres: allow foreign key column without unique constraint
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Apr 29, 2024
1 parent c6aee41 commit be508c2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/postgres/query/constraints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,19 @@ impl SchemaQueryBuilder {
.equals((rcsq.clone(), RefC::ConstraintName)),
)
.add(
// Only join when the referenced primary key position matches position_in_unique_constraint for the foreign key column
Expr::col((Schema::KeyColumnUsage, Kcuf::PositionInUniqueConstraint))
.equals((rcsq.clone(), Kcuf::OrdinalPosition)),
Condition::any()
.add(
// Only join when the referenced primary key position matches position_in_unique_constraint for the foreign key column
Expr::col((
Schema::KeyColumnUsage,
Kcuf::PositionInUniqueConstraint,
))
.equals((rcsq.clone(), Kcuf::OrdinalPosition)),
)
.add(
// Allow foreign key column without unique constraint
Expr::col((rcsq.clone(), Kcuf::OrdinalPosition)).is_null(),
),
),
)
.and_where(
Expand Down
44 changes: 44 additions & 0 deletions tests/live/postgres/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,24 @@ async fn main() {
create_parent_table(),
create_child_table(),
create_db_types_table(),
create_table1(),
create_table2(),
];

for tbl_create_stmt in tbl_create_stmts.iter() {
let sql = tbl_create_stmt.to_string(PostgresQueryBuilder);
println!("{};", sql);
println!();
sqlx::query(&sql).execute(&mut *executor).await.unwrap();
if sql.starts_with(r#"CREATE TABLE "table1""#) {
let sql = Index::create()
.table(Alias::new("table1"))
.name("IDX_table1_unique_u")
.col(Alias::new("u"))
.unique()
.to_string(PostgresQueryBuilder);
sqlx::query(&sql).execute(&mut *executor).await.unwrap();
}
}

let schema_discovery = SchemaDiscovery::new(connection, "public");
Expand Down Expand Up @@ -456,3 +467,36 @@ fn create_db_types_table() -> TableCreateStatement {
)
.to_owned()
}

fn create_table1() -> TableCreateStatement {
Table::create()
.table(Alias::new("table1"))
.col(
ColumnDef::new(Alias::new("id"))
.integer()
.not_null()
.auto_increment(),
)
.col(ColumnDef::new(Alias::new("u")).integer().not_null())
.to_owned()
}

fn create_table2() -> TableCreateStatement {
Table::create()
.table(Alias::new("table2"))
.col(
ColumnDef::new(Alias::new("fk_u"))
.integer()
.not_null()
.auto_increment(),
)
.foreign_key(
ForeignKey::create()
.name("FK_tabl2_table1")
.from(Alias::new("table2"), Alias::new("fk_u"))
.to(Alias::new("table1"), Alias::new("u"))
.on_delete(ForeignKeyAction::Cascade)
.on_update(ForeignKeyAction::Cascade),
)
.to_owned()
}

0 comments on commit be508c2

Please sign in to comment.