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

46 statements  

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

1from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc

2 

3 

4class Team(SQLModel, table=True): 1abc

5 id: int | None = Field(default=None, primary_key=True) 1abc

6 name: str = Field(index=True) 1abc

7 headquarters: str 1abc

8 

9 

10class Hero(SQLModel, table=True): 1abc

11 id: int | None = Field(default=None, primary_key=True) 1abc

12 name: str = Field(index=True) 1abc

13 secret_name: str 1abc

14 age: int | None = Field(default=None, index=True) 1abc

15 

16 team_id: int | None = Field(default=None, foreign_key="team.id") 1abc

17 

18 

19sqlite_file_name = "database.db" 1abc

20sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc

21 

22engine = create_engine(sqlite_url, echo=True) 1abc

23 

24 

25def create_db_and_tables(): 1abc

26 SQLModel.metadata.create_all(engine) 1abc

27 

28 

29def create_heroes(): 1abc

30 with Session(engine) as session: 1abc

31 team_preventers = Team(name="Preventers", headquarters="Sharp Tower") 1abc

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

33 session.add(team_preventers) 1abc

34 session.add(team_z_force) 1abc

35 session.commit() 1abc

36 

37 hero_deadpond = Hero( 1abc

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

39 ) 

40 hero_rusty_man = Hero( 1abc

41 name="Rusty-Man", 

42 secret_name="Tommy Sharp", 

43 age=48, 

44 team_id=team_preventers.id, 

45 ) 

46 hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abc

47 session.add(hero_deadpond) 1abc

48 session.add(hero_rusty_man) 1abc

49 session.add(hero_spider_boy) 1abc

50 session.commit() 1abc

51 

52 session.refresh(hero_deadpond) 1abc

53 session.refresh(hero_rusty_man) 1abc

54 session.refresh(hero_spider_boy) 1abc

55 

56 print("Created hero:", hero_deadpond) 1abc

57 print("Created hero:", hero_rusty_man) 1abc

58 print("Created hero:", hero_spider_boy) 1abc

59 

60 

61def select_heroes(): 1abc

62 with Session(engine) as session: 1abc

63 statement = select(Hero, Team).join(Team).where(Team.name == "Preventers") 1abc

64 results = session.exec(statement) 1abc

65 for hero, team in results: 1abc

66 print("Preventer Hero:", hero, "Team:", team) 1abc

67 

68 

69def main(): 1abc

70 create_db_and_tables() 1abc

71 create_heroes() 1abc

72 select_heroes() 1abc

73 

74 

75if __name__ == "__main__": 1abc

76 main()