|
| 1 | +from typing import Any, Dict, Optional |
| 2 | + |
| 3 | +from sqlmodel import Field, Session, SQLModel, create_engine |
| 4 | +from typing_extensions import TypedDict |
| 5 | + |
| 6 | + |
| 7 | +def test_dict_maps_to_json(clear_sqlmodel): |
| 8 | + class Resource(SQLModel, table=True): |
| 9 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 10 | + name: str |
| 11 | + data: dict[str, Any] |
| 12 | + |
| 13 | + engine = create_engine("sqlite://") |
| 14 | + SQLModel.metadata.create_all(engine) |
| 15 | + |
| 16 | + resource = Resource(name="test", data={"key": "value", "num": 42}) |
| 17 | + |
| 18 | + with Session(engine) as session: |
| 19 | + session.add(resource) |
| 20 | + session.commit() |
| 21 | + session.refresh(resource) |
| 22 | + |
| 23 | + assert resource.data["key"] == "value" |
| 24 | + assert resource.data["num"] == 42 |
| 25 | + |
| 26 | + |
| 27 | +def test_typing_dict_maps_to_json(clear_sqlmodel): |
| 28 | + """Test if typing.Dict type annotation works without explicit sa_type""" |
| 29 | + |
| 30 | + class Resource(SQLModel, table=True): |
| 31 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 32 | + name: str |
| 33 | + data: Dict[str, int] |
| 34 | + |
| 35 | + engine = create_engine("sqlite://") |
| 36 | + SQLModel.metadata.create_all(engine) |
| 37 | + |
| 38 | + resource = Resource(name="test", data={"count": 100}) |
| 39 | + |
| 40 | + with Session(engine) as session: |
| 41 | + session.add(resource) |
| 42 | + session.commit() |
| 43 | + session.refresh(resource) |
| 44 | + |
| 45 | + assert resource.data["count"] == 100 |
| 46 | + |
| 47 | + |
| 48 | +class Metadata(TypedDict): |
| 49 | + name: str |
| 50 | + email: str |
| 51 | + |
| 52 | + |
| 53 | +def test_typeddict_automatic_json_mapping(clear_sqlmodel): |
| 54 | + """ |
| 55 | + Test that TypedDict fields automatically map to JSON type. |
| 56 | +
|
| 57 | + This fixes the original error: |
| 58 | + ValueError: <class 'app.models.NeonMetadata'> has no matching SQLAlchemy type |
| 59 | + """ |
| 60 | + |
| 61 | + class ConnectedResource(SQLModel, table=True): |
| 62 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 63 | + name: str |
| 64 | + neon_metadata: Metadata |
| 65 | + |
| 66 | + engine = create_engine("sqlite://") |
| 67 | + SQLModel.metadata.create_all(engine) |
| 68 | + |
| 69 | + resource = ConnectedResource( |
| 70 | + name="my-resource", |
| 71 | + neon_metadata={ "name": "John Doe", "email": "[email protected]"}, |
| 72 | + ) |
| 73 | + |
| 74 | + with Session(engine) as session: |
| 75 | + session.add(resource) |
| 76 | + session.commit() |
| 77 | + session.refresh(resource) |
| 78 | + |
| 79 | + assert resource.neon_metadata["name"] == "John Doe" |
| 80 | + assert resource. neon_metadata[ "email"] == "[email protected]" |
0 commit comments