|
| 1 | +"""Test that Python type annotations map to correct SQLAlchemy column types""" |
| 2 | + |
| 3 | +from typing import Dict, Optional |
| 4 | + |
| 5 | +from sqlalchemy import JSON, Boolean, Date, DateTime, Float, Integer |
| 6 | +from sqlalchemy.sql.sqltypes import LargeBinary |
| 7 | +from sqlmodel import Field, SQLModel |
| 8 | +from sqlmodel.sql.sqltypes import AutoString |
| 9 | +from typing_extensions import TypedDict |
| 10 | + |
| 11 | + |
| 12 | +def test_dict_maps_to_json(clear_sqlmodel): |
| 13 | + """Test that plain dict annotation maps to JSON column type""" |
| 14 | + |
| 15 | + class Model(SQLModel, table=True): |
| 16 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 17 | + data: dict |
| 18 | + |
| 19 | + assert isinstance(Model.data.type, JSON) # type: ignore |
| 20 | + |
| 21 | + |
| 22 | +def test_typing_dict_maps_to_json(clear_sqlmodel): |
| 23 | + """Test that typing.Dict annotation maps to JSON column type""" |
| 24 | + |
| 25 | + class Model(SQLModel, table=True): |
| 26 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 27 | + data: Dict[str, int] |
| 28 | + |
| 29 | + assert isinstance(Model.data.type, JSON) # type: ignore |
| 30 | + |
| 31 | + |
| 32 | +def test_typeddict_maps_to_json(clear_sqlmodel): |
| 33 | + """Test that TypedDict annotation maps to JSON column type""" |
| 34 | + |
| 35 | + class MyDict(TypedDict): |
| 36 | + name: str |
| 37 | + count: int |
| 38 | + |
| 39 | + class Model(SQLModel, table=True): |
| 40 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 41 | + data: MyDict |
| 42 | + |
| 43 | + assert isinstance(Model.data.type, JSON) # type: ignore |
| 44 | + |
| 45 | + |
| 46 | +def test_other_type_mappings(clear_sqlmodel): |
| 47 | + """Test that other common types map correctly""" |
| 48 | + from datetime import date, datetime |
| 49 | + |
| 50 | + class Model(SQLModel, table=True): |
| 51 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 52 | + name: str |
| 53 | + count: int |
| 54 | + price: float |
| 55 | + active: bool |
| 56 | + created: datetime |
| 57 | + birth_date: date |
| 58 | + data_bytes: bytes |
| 59 | + |
| 60 | + # Verify the type mappings |
| 61 | + assert isinstance(Model.name.type, AutoString) # type: ignore |
| 62 | + assert isinstance(Model.count.type, Integer) # type: ignore |
| 63 | + assert isinstance(Model.price.type, Float) # type: ignore |
| 64 | + assert isinstance(Model.active.type, Boolean) # type: ignore |
| 65 | + assert isinstance(Model.created.type, DateTime) # type: ignore |
| 66 | + assert isinstance(Model.birth_date.type, Date) # type: ignore |
| 67 | + assert isinstance(Model.data_bytes.type, LargeBinary) # type: ignore |
0 commit comments