Coverage for docs_src/advanced/decimal/tutorial001_py310.py: 100%
38 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
1from decimal import Decimal 1abc
3from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc
6class Hero(SQLModel, table=True): 1abc
7 id: int | None = Field(default=None, primary_key=True) 1abc
8 name: str = Field(index=True) 1abc
9 secret_name: str 1abc
10 age: int | None = Field(default=None, index=True) 1abc
11 money: Decimal = Field(default=0, max_digits=5, decimal_places=3) 1abc
14sqlite_file_name = "database.db" 1abc
15sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc
17engine = create_engine(sqlite_url, echo=True) 1abc
20def create_db_and_tables(): 1abc
21 SQLModel.metadata.create_all(engine) 1abc
24def create_heroes(): 1abc
25 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson", money=1.1) 1abc
26 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", money=0.001) 1abc
27 hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48, money=2.2) 1abc
29 with Session(engine) as session: 1abc
30 session.add(hero_1) 1abc
31 session.add(hero_2) 1abc
32 session.add(hero_3) 1abc
34 session.commit() 1abc
37def select_heroes(): 1abc
38 with Session(engine) as session: 1abc
39 statement = select(Hero).where(Hero.name == "Deadpond") 1abc
40 results = session.exec(statement) 1abc
41 hero_1 = results.one() 1abc
42 print("Hero 1:", hero_1) 1abc
44 statement = select(Hero).where(Hero.name == "Rusty-Man") 1abc
45 results = session.exec(statement) 1abc
46 hero_2 = results.one() 1abc
47 print("Hero 2:", hero_2) 1abc
49 total_money = hero_1.money + hero_2.money 1abc
50 print(f"Total money: {total_money}") 1abc
53def main(): 1abc
54 create_db_and_tables() 1abc
55 create_heroes() 1abc
56 select_heroes() 1abc
59if __name__ == "__main__": 1abc
60 main()