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
|
from sqlmodel import Field, Session, SQLModel, create_engine, select
from sqlmodel.pool import StaticPool
def test_fields() -> None:
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
food: str | None = None
engine = create_engine(
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(Hero(name="Deadpond", secret_name="Dive Wilson"))
session.add(
Hero(name="Spider-Boy", secret_name="Pedro Parqueador", food="pizza")
)
session.add(Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48))
session.commit()
# check typing of select with 3 fields
with Session(engine) as session:
statement_3 = select(Hero.id, Hero.name, Hero.secret_name)
results_3 = session.exec(statement_3)
for hero_3 in results_3:
assert len(hero_3) == 3
name_3: str = hero_3[1]
assert type(name_3) is str
assert type(hero_3[0]) is int
assert type(hero_3[2]) is str
# check typing of select with 4 fields
with Session(engine) as session:
statement_4 = select(Hero.id, Hero.name, Hero.secret_name, Hero.age)
results_4 = session.exec(statement_4)
for hero_4 in results_4:
assert len(hero_4) == 4
name_4: str = hero_4[1]
assert type(name_4) is str
assert type(hero_4[0]) is int
assert type(hero_4[2]) is str
assert type(hero_4[3]) in [int, type(None)]
# check typing of select with 5 fields: currently runs but doesn't pass mypy
# with Session(engine) as session:
# statement_5 = select(Hero.id, Hero.name, Hero.secret_name, Hero.age, Hero.food)
# results_5 = session.exec(statement_5)
# for hero_5 in results_5:
# assert len(hero_5) == 5
# name_5: str = hero_5[1]
# assert type(name_5) is str
# assert type(hero_5[0]) is int
# assert type(hero_5[2]) is str
# assert type(hero_5[3]) in [int, type(None)]
# assert type(hero_5[4]) in [str, type(None)]
|