-
Notifications
You must be signed in to change notification settings - Fork 279
Description
Things to check first
-
I have searched the existing issues and didn't find my bug already reported there
-
I have checked that my bug is still present in the latest release
Sqlacodegen version
master branch as of 2025.Febr.26 11:14 UTC
SQLAlchemy version
2.0.38
RDBMS vendor
MSSQL
What happened?
The SQLModel does not include foreign_keys argument in Relationships. This resulted in a AmbiguousForeignKeysError as I have multiple columns that are foreign keys on the same table.
Here are the results on the Lines table:
Generated by SQLModelGenerator:
point_a: Optional["Points"] = Relationship(back_populates="Lines")
point_b: Optional["Points"] = Relationship(back_populates="Lines_")Generated by DeclarativeGenerator:
point_a: Mapped['Points'] = relationship('Points', foreign_keys=[point_a_id], back_populates='Lines')
point_b: Mapped['Points'] = relationship('Points', foreign_keys=[point_b_id], back_populates='Lines_')Manual solution for SQLModel (or something similar):
point_a: Points = Relationship(back_populates="Lines", sa_relationship_kwargs={"foreign_keys": "Lines.point_a_id"})
point_b: Points = Relationship(back_populates="Lines_", sa_relationship_kwargs={"foreign_keys": "Lines.point_b_id"})Note: These are not exact tables I'm working with, but due to a company policy and confidentiality I cannot share that, so these are similar examples
Potential solution idea:
Use the sa_relationship arg in Relationship() with output generated with the Declarative Generator:
point_a: Optional['Points'] = Relationship(sa_relationship=relationship('Points', foreign_keys=[point_a_id], back_populates='Lines'))
point_b: Optional['Points'] = Relationship(sa_relationship=relationship('Points', foreign_keys=[point_b_id], back_populates='Lines_'))Database schema for reproducing the bug
-- I cannot share the exact tables as per company policy, but something similar should cause the same issue
CREATE TABLE dbo.Points
(
id int identity NOT NULL,
CONSTRAINT PK_Points PRIMARY KEY (id)
)
CREATE TABLE dbo.Lines
(
id int identity NOT NULL,
point_a_id int NOT NULL CONSTRAINT FK__POINT_A__Lines__Points REFERENCES dbo.Points(id),
point_b_id int NOT NULL CONSTRAINT FK__POINT_B__Lines__Points REFERENCES dbo.Points(id),
CONSTRAINT PK_Lines PRIMARY KEY (id)
)