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

46 statements  

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

1import uuid 1abcdefghij

2from typing import Union 1abcdefghij

3 

4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcdefghij

5 

6 

7class Hero(SQLModel, table=True): 1abcdefghij

8 id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) 1abcdefghij

9 name: str = Field(index=True) 1abcdefghij

10 secret_name: str 1abcdefghij

11 age: Union[int, None] = Field(default=None, index=True) 1abcdefghij

12 

13 

14sqlite_file_name = "database.db" 1abcdefghij

15sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdefghij

16 

17engine = create_engine(sqlite_url, echo=True) 1abcdefghij

18 

19 

20def create_db_and_tables(): 1abcdefghij

21 SQLModel.metadata.create_all(engine) 1abcdefghij

22 

23 

24def create_hero(): 1abcdefghij

25 with Session(engine) as session: 1abcdefghij

26 hero = Hero(name="Deadpond", secret_name="Dive Wilson") 1abcdefghij

27 print("The hero before saving in the DB") 1abcdefghij

28 print(hero) 1abcdefghij

29 print("The hero ID was already set") 1abcdefghij

30 print(hero.id) 1abcdefghij

31 session.add(hero) 1abcdefghij

32 session.commit() 1abcdefghij

33 session.refresh(hero) 1abcdefghij

34 print("After saving in the DB") 1abcdefghij

35 print(hero) 1abcdefghij

36 

37 

38def select_hero(): 1abcdefghij

39 with Session(engine) as session: 1abcdefghij

40 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abcdefghij

41 session.add(hero_2) 1abcdefghij

42 session.commit() 1abcdefghij

43 session.refresh(hero_2) 1abcdefghij

44 hero_id = hero_2.id 1abcdefghij

45 print("Created hero:") 1abcdefghij

46 print(hero_2) 1abcdefghij

47 print("Created hero ID:") 1abcdefghij

48 print(hero_id) 1abcdefghij

49 

50 statement = select(Hero).where(Hero.id == hero_id) 1abcdefghij

51 selected_hero = session.exec(statement).one() 1abcdefghij

52 print("Selected hero:") 1abcdefghij

53 print(selected_hero) 1abcdefghij

54 print("Selected hero ID:") 1abcdefghij

55 print(selected_hero.id) 1abcdefghij

56 

57 

58def main() -> None: 1abcdefghij

59 create_db_and_tables() 1abcdefghij

60 create_hero() 1abcdefghij

61 select_hero() 1abcdefghij

62 

63 

64if __name__ == "__main__": 1abcdefghij

65 main()