Coverage for docs_src/tutorial/select/tutorial002.py: 100%

31 statements  

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

1from typing import Optional 1abcdef

2 

3from sqlmodel import Field, Session, SQLModel, create_engine, select # (1)! 1abcdef

4 

5 

6class Hero(SQLModel, table=True): # (2)! 1abcdef

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

8 name: str 1abcdef

9 secret_name: str 1abcdef

10 age: Optional[int] = None 1abcdef

11 

12 

13sqlite_file_name = "database.db" 1abcdef

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

15 

16engine = create_engine(sqlite_url, echo=True) # (3)! 1abcdef

17 

18 

19def create_db_and_tables(): 1abcdef

20 SQLModel.metadata.create_all(engine) # (4)! 1abcdef

21 

22 

23def create_heroes(): 1abcdef

24 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") # (5)! 1abcdef

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

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

27 

28 with Session(engine) as session: # (6)! 1abcdef

29 session.add(hero_1) 1abcdef

30 session.add(hero_2) 1abcdef

31 session.add(hero_3) 1abcdef

32 

33 session.commit() 1abcdef

34 

35 

36def select_heroes(): 1abcdef

37 with Session(engine) as session: # (7)! 1abcdef

38 statement = select(Hero) # (8)! 1abcdef

39 results = session.exec(statement) # (9)! 1abcdef

40 for hero in results: # (10)! 1abcdef

41 print(hero) # (11)! 1abcdef

42 # (12)! 

43 

44 

45def main(): 1abcdef

46 create_db_and_tables() 1abcdef

47 create_heroes() 1abcdef

48 select_heroes() # (13)! 1abcdef

49 

50 

51if __name__ == "__main__": 1abcdef

52 main()