Coverage for docs_src/tutorial/update/tutorial003_py310.py: 100%
53 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, select 1abc
4class Hero(SQLModel, table=True): 1abc
5 id: int | None = Field(default=None, primary_key=True) 1abc
6 name: str = Field(index=True) 1abc
7 secret_name: str 1abc
8 age: int | None = Field(default=None, index=True) 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
25 hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32) 1abc
26 hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35) 1abc
27 hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36) 1abc
28 hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93) 1abc
30 with Session(engine) as session: 1abc
31 session.add(hero_1) 1abc
32 session.add(hero_2) 1abc
33 session.add(hero_3) 1abc
34 session.add(hero_4) 1abc
35 session.add(hero_5) 1abc
36 session.add(hero_6) 1abc
37 session.add(hero_7) 1abc
39 session.commit() 1abc
42def update_heroes(): 1abc
43 with Session(engine) as session: 1abc
44 statement = select(Hero).where(Hero.name == "Spider-Boy") 1abc
45 results = session.exec(statement) 1abc
46 hero_1 = results.one() 1abc
47 print("Hero 1:", hero_1) 1abc
49 statement = select(Hero).where(Hero.name == "Captain North America") 1abc
50 results = session.exec(statement) 1abc
51 hero_2 = results.one() 1abc
52 print("Hero 2:", hero_2) 1abc
54 hero_1.age = 16 1abc
55 hero_1.name = "Spider-Youngster" 1abc
56 session.add(hero_1) 1abc
58 hero_2.name = "Captain North America Except Canada" 1abc
59 hero_2.age = 110 1abc
60 session.add(hero_2) 1abc
62 session.commit() 1abc
63 session.refresh(hero_1) 1abc
64 session.refresh(hero_2) 1abc
66 print("Updated hero 1:", hero_1) 1abc
67 print("Updated hero 2:", hero_2) 1abc
70def main(): 1abc
71 create_db_and_tables() 1abc
72 create_heroes() 1abc
73 update_heroes() 1abc
76if __name__ == "__main__": 1abc
77 main()