Coverage for docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py: 100%
54 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 sqlmodel import Field, Session, SQLModel, create_engine 1abc
4class Hero(SQLModel, table=True): 1abc
5 id: int | None = Field(default=None, primary_key=True) 1abc
6 name: str 1abc
7 secret_name: str 1abc
8 age: int | None = None 1abc
11sqlite_file_name = "database.db" 1abc
12sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc
14engine = create_engine(sqlite_url, echo=True) 1abc
17def create_db_and_tables(): 1abc
18 SQLModel.metadata.create_all(engine) 1abc
21def create_heroes(): 1abc
22 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") 1abc
23 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abc
24 hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) 1abc
26 print("Before interacting with the database") 1abc
27 print("Hero 1:", hero_1) 1abc
28 print("Hero 2:", hero_2) 1abc
29 print("Hero 3:", hero_3) 1abc
31 with Session(engine) as session: 1abc
32 session.add(hero_1) 1abc
33 session.add(hero_2) 1abc
34 session.add(hero_3) 1abc
36 print("After adding to the session") 1abc
37 print("Hero 1:", hero_1) 1abc
38 print("Hero 2:", hero_2) 1abc
39 print("Hero 3:", hero_3) 1abc
41 session.commit() 1abc
43 print("After committing the session") 1abc
44 print("Hero 1:", hero_1) 1abc
45 print("Hero 2:", hero_2) 1abc
46 print("Hero 3:", hero_3) 1abc
48 print("After committing the session, show IDs") 1abc
49 print("Hero 1 ID:", hero_1.id) 1abc
50 print("Hero 2 ID:", hero_2.id) 1abc
51 print("Hero 3 ID:", hero_3.id) 1abc
53 print("After committing the session, show names") 1abc
54 print("Hero 1 name:", hero_1.name) 1abc
55 print("Hero 2 name:", hero_2.name) 1abc
56 print("Hero 3 name:", hero_3.name) 1abc
58 session.refresh(hero_1) 1abc
59 session.refresh(hero_2) 1abc
60 session.refresh(hero_3) 1abc
62 print("After refreshing the heroes") 1abc
63 print("Hero 1:", hero_1) 1abc
64 print("Hero 2:", hero_2) 1abc
65 print("Hero 3:", hero_3) 1abc
67 print("After the session closes") 1abc
68 print("Hero 1:", hero_1) 1abc
69 print("Hero 2:", hero_2) 1abc
70 print("Hero 3:", hero_3) 1abc
73def main(): 1abc
74 create_db_and_tables() 1abc
75 create_heroes() 1abc
78if __name__ == "__main__": 1abc
79 main()