Coverage for docs_src/advanced/uuid/tutorial001_py310.py: 100%
45 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
1import uuid 1abc
3from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc
6class Hero(SQLModel, table=True): 1abc
7 id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) 1abc
8 name: str = Field(index=True) 1abc
9 secret_name: str 1abc
10 age: int | None = Field(default=None, index=True) 1abc
13sqlite_file_name = "database.db" 1abc
14sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc
16engine = create_engine(sqlite_url, echo=True) 1abc
19def create_db_and_tables(): 1abc
20 SQLModel.metadata.create_all(engine) 1abc
23def create_hero(): 1abc
24 with Session(engine) as session: 1abc
25 hero = Hero(name="Deadpond", secret_name="Dive Wilson") 1abc
26 print("The hero before saving in the DB") 1abc
27 print(hero) 1abc
28 print("The hero ID was already set") 1abc
29 print(hero.id) 1abc
30 session.add(hero) 1abc
31 session.commit() 1abc
32 session.refresh(hero) 1abc
33 print("After saving in the DB") 1abc
34 print(hero) 1abc
37def select_hero(): 1abc
38 with Session(engine) as session: 1abc
39 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abc
40 session.add(hero_2) 1abc
41 session.commit() 1abc
42 session.refresh(hero_2) 1abc
43 hero_id = hero_2.id 1abc
44 print("Created hero:") 1abc
45 print(hero_2) 1abc
46 print("Created hero ID:") 1abc
47 print(hero_id) 1abc
49 statement = select(Hero).where(Hero.id == hero_id) 1abc
50 selected_hero = session.exec(statement).one() 1abc
51 print("Selected hero:") 1abc
52 print(selected_hero) 1abc
53 print("Selected hero ID:") 1abc
54 print(selected_hero.id) 1abc
57def main() -> None: 1abc
58 create_db_and_tables() 1abc
59 create_hero() 1abc
60 select_hero() 1abc
63if __name__ == "__main__": 1abc
64 main()