-
-
Notifications
You must be signed in to change notification settings - Fork 783
✨ Support SQLAlchemy keyed dict models with Pydantic v2 #1287
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
nkrishnaswami
wants to merge
17
commits into
fastapi:main
Choose a base branch
from
nkrishnaswami:allow-dict-relationship
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 12 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
43108bf
Minimal change to allow `attribute_keyed_dict` + test
nkrishnaswami 88d3b2f
Remove `StrEnum`
nkrishnaswami 70fdb49
Remove type union pipe syntax
nkrishnaswami fa69e6c
Use `Dict[]` instead of `dict[]`
3b6eb6c
Remove superfluous index in test case
nkrishnaswami c22321e
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] 3f11b80
Make dict get_relationship_to more robust
nkrishnaswami 9076de0
Limit dict-with-bad-type-args test to 3.10+
nkrishnaswami d49fd6f
Limit dict-with-bad-type-args test to 3.10+
nkrishnaswami a801312
Mark test as requiring pydantic v2
nkrishnaswami 16ee026
Incorporate review feedback
d9c45e0
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] 6f1bafe
Update tests/test_attribute_keyed_dict.py
nkrishnaswami 8855492
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] 26bda61
Update tests/test_attribute_keyed_dict.py
nkrishnaswami f404ecd
Remove zero-arg generic dict test
f9227b1
Remove comment on needs_py39
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import re | ||
| from enum import Enum | ||
| from typing import Dict, Optional | ||
|
|
||
| import pytest | ||
| from sqlalchemy.orm.collections import attribute_keyed_dict | ||
| from sqlmodel import Field, Relationship, Session, SQLModel, create_engine | ||
|
|
||
| from tests.conftest import needs_py310, needs_pydanticv2 | ||
|
|
||
|
|
||
| def test_attribute_keyed_dict_works(clear_sqlmodel): | ||
| class Color(str, Enum): | ||
| Orange = "Orange" | ||
| Blue = "Blue" | ||
|
|
||
| class Child(SQLModel, table=True): | ||
| __tablename__ = "children" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| parent_id: int = Field(foreign_key="parents.id") | ||
| color: Color | ||
| value: int | ||
|
|
||
| class Parent(SQLModel, table=True): | ||
| __tablename__ = "parents" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| children_by_color: Dict[Color, Child] = Relationship( | ||
| sa_relationship_kwargs={"collection_class": attribute_keyed_dict("color")} | ||
| ) | ||
|
|
||
| engine = create_engine("sqlite://") | ||
| SQLModel.metadata.create_all(engine) | ||
| with Session(engine) as session: | ||
| parent = Parent() | ||
| session.add(parent) | ||
| session.commit() | ||
| session.refresh(parent) | ||
| session.add(Child(parent_id=parent.id, color=Color.Orange, value=1)) | ||
| session.add(Child(parent_id=parent.id, color=Color.Blue, value=2)) | ||
| session.commit() | ||
| session.refresh(parent) | ||
| assert parent.children_by_color[Color.Orange].parent_id == parent.id | ||
| assert parent.children_by_color[Color.Orange].color == Color.Orange | ||
| assert parent.children_by_color[Color.Orange].value == 1 | ||
| assert parent.children_by_color[Color.Blue].parent_id == parent.id | ||
| assert parent.children_by_color[Color.Blue].color == Color.Blue | ||
| assert parent.children_by_color[Color.Blue].value == 2 | ||
|
|
||
|
|
||
| # typing.Dict throws if it receives the wrong number of type arguments, but dict | ||
| # (3.10+) does not; and Pydantic v1 fails to process models with dicts with no | ||
| # type arguments. | ||
| @needs_pydanticv2 | ||
| @needs_py310 | ||
nkrishnaswami marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| def test_dict_relationship_throws_on_missing_annotation_arg(clear_sqlmodel): | ||
nkrishnaswami marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| class Color(str, Enum): | ||
| Orange = "Orange" | ||
| Blue = "Blue" | ||
|
|
||
| class Child(SQLModel, table=True): | ||
| __tablename__ = "children" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| parent_id: int = Field(foreign_key="parents.id") | ||
| color: Color | ||
| value: int | ||
|
|
||
| error_msg_fmt = "Dict/Mapping relationship field 'children_by_color' has {count} type arguments. Exactly two required (e.g., dict[str, Model])" | ||
|
|
||
| # No type args | ||
| with pytest.raises(ValueError, match=re.escape(error_msg_fmt.format(count=0))): | ||
|
|
||
| class Parent(SQLModel, table=True): | ||
| __tablename__ = "parents" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| children_by_color: dict[()] = Relationship( | ||
YuriiMotov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| sa_relationship_kwargs={ | ||
| "collection_class": attribute_keyed_dict("color") | ||
| } | ||
| ) | ||
|
|
||
| # One type arg | ||
| with pytest.raises(ValueError, match=re.escape(error_msg_fmt.format(count=1))): | ||
|
|
||
| class Parent(SQLModel, table=True): | ||
| __tablename__ = "parents" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| children_by_color: dict[Color] = Relationship( | ||
| sa_relationship_kwargs={ | ||
| "collection_class": attribute_keyed_dict("color") | ||
| } | ||
| ) | ||
|
|
||
| # Three type args | ||
| with pytest.raises(ValueError, match=re.escape(error_msg_fmt.format(count=3))): | ||
|
|
||
| class Parent(SQLModel, table=True): | ||
| __tablename__ = "parents" | ||
|
|
||
| id: Optional[int] = Field(primary_key=True, default=None) | ||
| children_by_color: dict[Color, Child, str] = Relationship( | ||
| sa_relationship_kwargs={ | ||
| "collection_class": attribute_keyed_dict("color") | ||
| } | ||
| ) | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.