Skip to content

Commit

Permalink
Fix incorrect discovery of composite foreign keys in PostgreSQL
Browse files Browse the repository at this point in the history
* Fixes SeaQL#100
* Should also fix SeaQL/sea-orm#1690
  • Loading branch information
julmaxi committed Jan 14, 2024
1 parent 6b5fbdc commit 15c53df
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions src/postgres/query/constraints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,18 +147,42 @@ impl SchemaQueryBuilder {
(Schema::ConstraintColumnUsage, Kcuf::TableName),
(Schema::ConstraintColumnUsage, Kcuf::ColumnName),
])
.columns(vec![
// Extract the ordinal position of the referenced primary keys
(Schema::KeyColumnUsage, Kcuf::OrdinalPosition)
])
.from((Schema::Schema, Schema::ReferentialConstraints))
.left_join(
(Schema::Schema, Schema::ConstraintColumnUsage),
Expr::col((Schema::ReferentialConstraints, RefC::ConstraintName))
.equals((Schema::ConstraintColumnUsage, Kcuf::ConstraintName)),
)
.left_join(
// Join the key_column_usage rows for the referenced primary keys
(Schema::Schema, Schema::KeyColumnUsage),
Condition::all()
.add(
Expr::col((Schema::ConstraintColumnUsage, Kcuf::ColumnName))
.equals((Schema::KeyColumnUsage, Kcuf::ColumnName)),
).add(
Expr::col((Schema::ReferentialConstraints, RefC::UniqueConstraintName))
.equals((Schema::KeyColumnUsage, Kcuf::ConstraintName))
).add(
Expr::col((Schema::ReferentialConstraints, RefC::UniqueConstraintSchema))
.equals((Schema::KeyColumnUsage, Kcuf::ConstraintSchema))
)
)
.take(),
rcsq.clone(),
Expr::col((Schema::TableConstraints, Tcf::ConstraintName))
.equals((rcsq.clone(), RefC::ConstraintName)),
)
.and_where(
Condition::all().add(
Expr::col((Schema::TableConstraints, Tcf::ConstraintName))
.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))
))
.and_where(
Expr::col((Schema::TableConstraints, Tcf::TableSchema)).eq(schema.to_string()),
)
.and_where(Expr::col((Schema::TableConstraints, Tcf::TableName)).eq(table.to_string()))
Expand Down

0 comments on commit 15c53df

Please sign in to comment.