-
-
Notifications
You must be signed in to change notification settings - Fork 721
✨ Add support for SQLAlchemy polymorphic models #1226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PaleNeutron
wants to merge
24
commits into
fastapi:main
Choose a base branch
from
PaleNeutron:sqlalchemy_polymorphic_support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
6d93a46
support sqlalchemy polymorphic
589237b
improve docs
4071b0f
fix polymorphic_on check
48f2a88
fix polymorphic_on check
e6ad74d
fix lint
277953a
fix pydantic v1 support
4aade03
fix type hint for <3.10
a3044bb
add needs_pydanticv2 mark to test
015601c
improve code structure
66c1d93
lint
0efd1bf
remove effort of pydantic v1
7173b44
Merge branch 'main' into sqlalchemy_polymorphic_support
PaleNeutron 84d739e
Update sqlmodel/_compat.py
PaleNeutron dbd0101
fix default value is InstrumentedAttribute in inherit
88670a5
Merge branch 'sqlalchemy_polymorphic_support' of https://github.com/P…
b1ed8c3
fix inherit order
5d1bf5c
support python < 3.9
ccbb92a
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] d0d0288
skip polymorphic in pydantic v1
525373d
Merge branch 'sqlalchemy_polymorphic_support' of https://github.com/P…
ab965f0
Merge branch 'main' into sqlalchemy_polymorphic_support
PaleNeutron 68963e7
Merge branch 'main' into sqlalchemy_polymorphic_support
svlandeg 95c6a1e
Merge branch 'main' into sqlalchemy_polymorphic_support
svlandeg c1dff79
disable pydantic warning during polymorphic
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
from typing import Optional | ||
|
||
from sqlalchemy import ForeignKey | ||
from sqlalchemy.orm import mapped_column | ||
from sqlmodel import Field, Session, SQLModel, create_engine, select | ||
|
||
from tests.conftest import needs_pydanticv2 | ||
|
||
|
||
@needs_pydanticv2 | ||
def test_polymorphic_joined_table(clear_sqlmodel) -> None: | ||
class Hero(SQLModel, table=True): | ||
__tablename__ = "hero" | ||
id: Optional[int] = Field(default=None, primary_key=True) | ||
hero_type: str = Field(default="hero") | ||
|
||
__mapper_args__ = { | ||
"polymorphic_on": "hero_type", | ||
"polymorphic_identity": "hero", | ||
} | ||
|
||
class DarkHero(Hero): | ||
__tablename__ = "dark_hero" | ||
id: Optional[int] = Field( | ||
default=None, | ||
sa_column=mapped_column(ForeignKey("hero.id"), primary_key=True), | ||
) | ||
dark_power: str = Field( | ||
default="dark", | ||
sa_column=mapped_column( | ||
nullable=False, use_existing_column=True, default="dark" | ||
), | ||
) | ||
|
||
__mapper_args__ = { | ||
"polymorphic_identity": "dark", | ||
} | ||
|
||
engine = create_engine("sqlite:///:memory:", echo=True) | ||
SQLModel.metadata.create_all(engine) | ||
with Session(engine) as db: | ||
hero = Hero() | ||
db.add(hero) | ||
dark_hero = DarkHero() | ||
db.add(dark_hero) | ||
db.commit() | ||
statement = select(DarkHero) | ||
result = db.exec(statement).all() | ||
assert len(result) == 1 | ||
assert isinstance(result[0].dark_power, str) | ||
|
||
|
||
@needs_pydanticv2 | ||
def test_polymorphic_joined_table_with_sqlmodel_field(clear_sqlmodel) -> None: | ||
class Hero(SQLModel, table=True): | ||
__tablename__ = "hero" | ||
id: Optional[int] = Field(default=None, primary_key=True) | ||
hero_type: str = Field(default="hero") | ||
|
||
__mapper_args__ = { | ||
"polymorphic_on": "hero_type", | ||
"polymorphic_identity": "hero", | ||
} | ||
|
||
class DarkHero(Hero): | ||
__tablename__ = "dark_hero" | ||
id: Optional[int] = Field( | ||
default=None, | ||
primary_key=True, | ||
foreign_key="hero.id", | ||
) | ||
dark_power: str = Field( | ||
default="dark", | ||
sa_column=mapped_column( | ||
nullable=False, use_existing_column=True, default="dark" | ||
), | ||
) | ||
|
||
__mapper_args__ = { | ||
"polymorphic_identity": "dark", | ||
} | ||
|
||
engine = create_engine("sqlite:///:memory:", echo=True) | ||
SQLModel.metadata.create_all(engine) | ||
with Session(engine) as db: | ||
hero = Hero() | ||
db.add(hero) | ||
dark_hero = DarkHero() | ||
db.add(dark_hero) | ||
db.commit() | ||
statement = select(DarkHero) | ||
result = db.exec(statement).all() | ||
assert len(result) == 1 | ||
assert isinstance(result[0].dark_power, str) | ||
|
||
|
||
@needs_pydanticv2 | ||
def test_polymorphic_single_table(clear_sqlmodel) -> None: | ||
class Hero(SQLModel, table=True): | ||
__tablename__ = "hero" | ||
id: Optional[int] = Field(default=None, primary_key=True) | ||
hero_type: str = Field(default="hero") | ||
|
||
__mapper_args__ = { | ||
"polymorphic_on": "hero_type", | ||
"polymorphic_identity": "hero", | ||
} | ||
|
||
class DarkHero(Hero): | ||
dark_power: str = Field( | ||
default="dark", | ||
sa_column=mapped_column( | ||
nullable=False, use_existing_column=True, default="dark" | ||
), | ||
) | ||
|
||
__mapper_args__ = { | ||
"polymorphic_identity": "dark", | ||
} | ||
|
||
engine = create_engine("sqlite:///:memory:", echo=True) | ||
SQLModel.metadata.create_all(engine) | ||
with Session(engine) as db: | ||
hero = Hero() | ||
db.add(hero) | ||
dark_hero = DarkHero(dark_power="pokey") | ||
db.add(dark_hero) | ||
db.commit() | ||
statement = select(DarkHero) | ||
result = db.exec(statement).all() | ||
assert len(result) == 1 | ||
assert isinstance(result[0].dark_power, str) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would love to see a syntax that's more focused on what the user wants and hides implementation details.
Example:
You can then perform metaprogramming magic inside the
sqlmodel
decorator to compute exactly the same class definitions you have in the PR here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Polymorphic orm has a lot of details, and these details are not concerned at dataclass level. So I think keep the origin sqlalchemy syntax is the best choice for early version. Maybe we can improve it at next PR.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the key phrase in your comment is for early version. If
sqlalchemy
syntax was good enough,sqlmodel
wouldn't exist :)How other ORMs are doing it:
I think the key points are:
fquery.sqlmodel
already hasone_to_many()
. Perhaps it could be enhanced withone_to_many("hero_type")
But like you say - probably best done in two steps.