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

1import uuid 1abcdef

2from typing import Union 1abcdef

3 

4from sqlmodel import Field, Session, SQLModel, create_engine, select 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 = 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

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 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

56 

57 

58def main() -> None: 1abcdef

59 create_db_and_tables() 1abcdef

60 create_hero() 1abcdef

61 select_hero() 1abcdef

62 

63 

64if __name__ == "__main__": 1abcdef

65 main()