Coverage for docs_src/tutorial/automatic_id_none_refresh/tutorial002.py: 100%
55 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 typing import Optional 1abcdef
3from sqlmodel import Field, Session, SQLModel, create_engine 1abcdef
6class Hero(SQLModel, table=True): 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
13sqlite_file_name = "database.db" 1abcdef
14sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdef
16engine = create_engine(sqlite_url, echo=True) 1abcdef
19def create_db_and_tables(): 1abcdef
20 SQLModel.metadata.create_all(engine) 1abcdef
23def create_heroes(): 1abcdef
24 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") # (1)! 1abcdef
25 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") # (2)! 1abcdef
26 hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) # (3)! 1abcdef
28 print("Before interacting with the database") # (4)! 1abcdef
29 print("Hero 1:", hero_1) # (5)! 1abcdef
30 print("Hero 2:", hero_2) # (6)! 1abcdef
31 print("Hero 3:", hero_3) # (7)! 1abcdef
33 with Session(engine) as session: # (8)! 1abcdef
34 session.add(hero_1) # (9)! 1abcdef
35 session.add(hero_2) # (10)! 1abcdef
36 session.add(hero_3) # (11)! 1abcdef
38 print("After adding to the session") # (12)! 1abcdef
39 print("Hero 1:", hero_1) # (13)! 1abcdef
40 print("Hero 2:", hero_2) # (14)! 1abcdef
41 print("Hero 3:", hero_3) # (15)! 1abcdef
43 session.commit() # (16)! 1abcdef
45 print("After committing the session") # (17)! 1abcdef
46 print("Hero 1:", hero_1) # (18)! 1abcdef
47 print("Hero 2:", hero_2) # (19)! 1abcdef
48 print("Hero 3:", hero_3) # (20)! 1abcdef
50 print("After committing the session, show IDs") # (21)! 1abcdef
51 print("Hero 1 ID:", hero_1.id) # (22)! 1abcdef
52 print("Hero 2 ID:", hero_2.id) # (23)! 1abcdef
53 print("Hero 3 ID:", hero_3.id) # (24)! 1abcdef
55 print("After committing the session, show names") # (25)! 1abcdef
56 print("Hero 1 name:", hero_1.name) # (26)! 1abcdef
57 print("Hero 2 name:", hero_2.name) # (27)! 1abcdef
58 print("Hero 3 name:", hero_3.name) # (28)! 1abcdef
60 session.refresh(hero_1) # (29)! 1abcdef
61 session.refresh(hero_2) # (30)! 1abcdef
62 session.refresh(hero_3) # (31)! 1abcdef
64 print("After refreshing the heroes") # (32)! 1abcdef
65 print("Hero 1:", hero_1) # (33)! 1abcdef
66 print("Hero 2:", hero_2) # (34)! 1abcdef
67 print("Hero 3:", hero_3) # (35)! 1abcdef
68 # (36)!
70 print("After the session closes") # (37)! 1abcdef
71 print("Hero 1:", hero_1) # (38)! 1abcdef
72 print("Hero 2:", hero_2) # (39)! 1abcdef
73 print("Hero 3:", hero_3) # (40)! 1abcdef
76def main(): 1abcdef
77 create_db_and_tables() 1abcdef
78 create_heroes() 1abcdef
81if __name__ == "__main__": 1abcdef
82 main()