-
-
Notifications
You must be signed in to change notification settings - Fork 845
Expand file tree
/
Copy pathtest_dict.py
More file actions
84 lines (58 loc) · 2.29 KB
/
test_dict.py
File metadata and controls
84 lines (58 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from typing import Dict, Optional
from sqlmodel import Field, Session, SQLModel, create_engine
from typing_extensions import TypedDict
from .conftest import needs_pydanticv2
pytestmark = needs_pydanticv2
def test_dict_maps_to_json(clear_sqlmodel):
class Resource(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
data: dict
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
resource = Resource(name="test", data={"key": "value", "num": 42})
with Session(engine) as session:
session.add(resource)
session.commit()
session.refresh(resource)
assert resource.data["key"] == "value"
assert resource.data["num"] == 42
def test_typing_dict_maps_to_json(clear_sqlmodel):
"""Test if typing.Dict type annotation works without explicit sa_type"""
class Resource(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
data: Dict[str, int]
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
resource = Resource(name="test", data={"count": 100})
with Session(engine) as session:
session.add(resource)
session.commit()
session.refresh(resource)
assert resource.data["count"] == 100
class Metadata(TypedDict):
name: str
email: str
def test_typeddict_automatic_json_mapping(clear_sqlmodel):
"""
Test that TypedDict fields automatically map to JSON type.
This fixes the original error:
ValueError: <class 'app.models.NeonMetadata'> has no matching SQLAlchemy type
"""
class ConnectedResource(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
neon_metadata: Metadata
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
resource = ConnectedResource(
name="my-resource",
neon_metadata={"name": "John Doe", "email": "john.doe@example.com"},
)
with Session(engine) as session:
session.add(resource)
session.commit()
session.refresh(resource)
assert resource.neon_metadata["name"] == "John Doe"
assert resource.neon_metadata["email"] == "john.doe@example.com"