Coverage for docs_src/advanced/uuid/tutorial001_py310.py: 100%

45 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-27 00:03 +0000

1import uuid 1abcdefgh

2 

3from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcdefgh

4 

5 

6class Hero(SQLModel, table=True): 1abcdefgh

7 id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) 1abcdefgh

8 name: str = Field(index=True) 1abcdefgh

9 secret_name: str 1abcdefgh

10 age: int | None = Field(default=None, index=True) 1abcdefgh

11 

12 

13sqlite_file_name = "database.db" 1abcdefgh

14sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdefgh

15 

16engine = create_engine(sqlite_url, echo=True) 1abcdefgh

17 

18 

19def create_db_and_tables(): 1abcdefgh

20 SQLModel.metadata.create_all(engine) 1abcdefgh

21 

22 

23def create_hero(): 1abcdefgh

24 with Session(engine) as session: 1abcdefgh

25 hero = Hero(name="Deadpond", secret_name="Dive Wilson") 1abcdefgh

26 print("The hero before saving in the DB") 1abcdefgh

27 print(hero) 1abcdefgh

28 print("The hero ID was already set") 1abcdefgh

29 print(hero.id) 1abcdefgh

30 session.add(hero) 1abcdefgh

31 session.commit() 1abcdefgh

32 session.refresh(hero) 1abcdefgh

33 print("After saving in the DB") 1abcdefgh

34 print(hero) 1abcdefgh

35 

36 

37def select_hero(): 1abcdefgh

38 with Session(engine) as session: 1abcdefgh

39 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abcdefgh

40 session.add(hero_2) 1abcdefgh

41 session.commit() 1abcdefgh

42 session.refresh(hero_2) 1abcdefgh

43 hero_id = hero_2.id 1abcdefgh

44 print("Created hero:") 1abcdefgh

45 print(hero_2) 1abcdefgh

46 print("Created hero ID:") 1abcdefgh

47 print(hero_id) 1abcdefgh

48 

49 statement = select(Hero).where(Hero.id == hero_id) 1abcdefgh

50 selected_hero = session.exec(statement).one() 1abcdefgh

51 print("Selected hero:") 1abcdefgh

52 print(selected_hero) 1abcdefgh

53 print("Selected hero ID:") 1abcdefgh

54 print(selected_hero.id) 1abcdefgh

55 

56 

57def main() -> None: 1abcdefgh

58 create_db_and_tables() 1abcdefgh

59 create_hero() 1abcdefgh

60 select_hero() 1abcdefgh

61 

62 

63if __name__ == "__main__": 1abcdefgh

64 main()