Coverage for docs_src/advanced/decimal/tutorial001.py: 100%

39 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

1from decimal import Decimal 1abcdef

2from typing import Optional 1abcdef

3 

4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcdef

5 

6 

7class Hero(SQLModel, table=True): 1abcdef

8 id: Optional[int] = Field(default=None, primary_key=True) 1abcdef

9 name: str = Field(index=True) 1abcdef

10 secret_name: str 1abcdef

11 age: Optional[int] = Field(default=None, index=True) 1abcdef

12 money: Decimal = Field(default=0, max_digits=5, decimal_places=3) 1abcdef

13 

14 

15sqlite_file_name = "database.db" 1abcdef

16sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdef

17 

18engine = create_engine(sqlite_url, echo=True) 1abcdef

19 

20 

21def create_db_and_tables(): 1abcdef

22 SQLModel.metadata.create_all(engine) 1abcdef

23 

24 

25def create_heroes(): 1abcdef

26 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson", money=1.1) 1abcdef

27 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", money=0.001) 1abcdef

28 hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48, money=2.2) 1abcdef

29 

30 with Session(engine) as session: 1abcdef

31 session.add(hero_1) 1abcdef

32 session.add(hero_2) 1abcdef

33 session.add(hero_3) 1abcdef

34 

35 session.commit() 1abcdef

36 

37 

38def select_heroes(): 1abcdef

39 with Session(engine) as session: 1abcdef

40 statement = select(Hero).where(Hero.name == "Deadpond") 1abcdef

41 results = session.exec(statement) 1abcdef

42 hero_1 = results.one() 1abcdef

43 print("Hero 1:", hero_1) 1abcdef

44 

45 statement = select(Hero).where(Hero.name == "Rusty-Man") 1abcdef

46 results = session.exec(statement) 1abcdef

47 hero_2 = results.one() 1abcdef

48 print("Hero 2:", hero_2) 1abcdef

49 

50 total_money = hero_1.money + hero_2.money 1abcdef

51 print(f"Total money: {total_money}") 1abcdef

52 

53 

54def main(): 1abcdef

55 create_db_and_tables() 1abcdef

56 create_heroes() 1abcdef

57 select_heroes() 1abcdef

58 

59 

60if __name__ == "__main__": 1abcdef

61 main()