forked from fastapi/sqlmodel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_future_annotations.py
More file actions
63 lines (46 loc) · 1.8 KB
/
test_future_annotations.py
File metadata and controls
63 lines (46 loc) · 1.8 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
from __future__ import annotations
from typing import Annotated, Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
def test_model_with_future_annotations(clear_sqlmodel):
class Hero(SQLModel, table=True):
id: Annotated[Optional[int], Field(primary_key=True)] = None
name: str
secret_name: str
age: Optional[int] = None
hero = Hero(name="Deadpond", secret_name="Dive Wilson", age=25)
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(hero)
session.commit()
session.refresh(hero)
assert hero.id is not None
assert hero.name == "Deadpond"
assert hero.secret_name == "Dive Wilson"
assert hero.age == 25
with Session(engine) as session:
heroes = session.exec(select(Hero)).all()
assert len(heroes) == 1
assert heroes[0].name == "Deadpond"
def test_model_with_string_annotations(clear_sqlmodel):
class Team(SQLModel, table=True):
id: Annotated[Optional[int], Field(primary_key=True)] = None
name: str
class Player(SQLModel, table=True):
id: Annotated[Optional[int], Field(primary_key=True)] = None
name: str
team_id: Annotated[Optional[int], Field(foreign_key="team.id")] = None
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
team = Team(name="Champions")
player = Player(name="Alice", team_id=None)
with Session(engine) as session:
session.add(team)
session.commit()
session.refresh(team)
player.team_id = team.id
session.add(player)
session.commit()
session.refresh(player)
assert team.id is not None
assert player.team_id == team.id