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

45 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

1import uuid 1abcdef

2from typing import Union 1abcdef

3 

4from sqlmodel import Field, Session, SQLModel, create_engine 1abcdef

5 

6 

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

12 

13 

14sqlite_file_name = "database.db" 1abcdef

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

16 

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

18 

19 

20def create_db_and_tables(): 1abcdef

21 SQLModel.metadata.create_all(engine) 1abcdef

22 

23 

24def create_hero(): 1abcdef

25 with Session(engine) as session: 1abcdef

26 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") 1abcdef

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

28 print(hero_1) 1abcdef

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

30 print(hero_1.id) 1abcdef

31 session.add(hero_1) 1abcdef

32 session.commit() 1abcdef

33 session.refresh(hero_1) 1abcdef

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

35 print(hero_1) 1abcdef

36 

37 

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

49 

50 selected_hero = session.get(Hero, hero_id) 1abcdef

51 print("Selected hero:") 1abcdef

52 print(selected_hero) 1abcdef

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

54 print(selected_hero.id) 1abcdef

55 

56 

57def main() -> None: 1abcdef

58 create_db_and_tables() 1abcdef

59 create_hero() 1abcdef

60 select_hero() 1abcdef

61 

62 

63if __name__ == "__main__": 1abcdef

64 main()