Coverage for docs_src/tutorial/connect/select/tutorial003.py: 100%

47 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 1abcdef

4 

5 

6class Team(SQLModel, table=True): 1abcdef

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

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

9 headquarters: str 1abcdef

10 

11 

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

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

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

15 secret_name: str 1abcdef

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

17 

18 team_id: Optional[int] = Field(default=None, foreign_key="team.id") 1abcdef

19 

20 

21sqlite_file_name = "database.db" 1abcdef

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

23 

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

25 

26 

27def create_db_and_tables(): 1abcdef

28 SQLModel.metadata.create_all(engine) 1abcdef

29 

30 

31def create_heroes(): 1abcdef

32 with Session(engine) as session: 1abcdef

33 team_preventers = Team(name="Preventers", headquarters="Sharp Tower") 1abcdef

34 team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar") 1abcdef

35 session.add(team_preventers) 1abcdef

36 session.add(team_z_force) 1abcdef

37 session.commit() 1abcdef

38 

39 hero_deadpond = Hero( 1abcdef

40 name="Deadpond", secret_name="Dive Wilson", team_id=team_z_force.id 

41 ) 

42 hero_rusty_man = Hero( 1abcdef

43 name="Rusty-Man", 

44 secret_name="Tommy Sharp", 

45 age=48, 

46 team_id=team_preventers.id, 

47 ) 

48 hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abcdef

49 session.add(hero_deadpond) 1abcdef

50 session.add(hero_rusty_man) 1abcdef

51 session.add(hero_spider_boy) 1abcdef

52 session.commit() 1abcdef

53 

54 session.refresh(hero_deadpond) 1abcdef

55 session.refresh(hero_rusty_man) 1abcdef

56 session.refresh(hero_spider_boy) 1abcdef

57 

58 print("Created hero:", hero_deadpond) 1abcdef

59 print("Created hero:", hero_rusty_man) 1abcdef

60 print("Created hero:", hero_spider_boy) 1abcdef

61 

62 

63def select_heroes(): 1abcdef

64 with Session(engine) as session: 1abcdef

65 statement = select(Hero, Team).join(Team, isouter=True) 1abcdef

66 results = session.exec(statement) 1abcdef

67 for hero, team in results: 1abcdef

68 print("Hero:", hero, "Team:", team) 1abcdef

69 

70 

71def main(): 1abcdef

72 create_db_and_tables() 1abcdef

73 create_heroes() 1abcdef

74 select_heroes() 1abcdef

75 

76 

77if __name__ == "__main__": 1abcdef

78 main()