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