Coverage for docs_src/tutorial/insert/tutorial003_py310.py: 100%

23 statements  

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

1from sqlmodel import Field, Session, SQLModel, create_engine 1abc

2 

3 

4class Hero(SQLModel, table=True): 1abc

5 id: int | None = Field(default=None, primary_key=True) 1abc

6 name: str 1abc

7 secret_name: str 1abc

8 age: int | None = None 1abc

9 

10 

11sqlite_file_name = "database.db" 1abc

12sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc

13 

14engine = create_engine(sqlite_url, echo=True) 1abc

15 

16 

17def create_db_and_tables(): 1abc

18 SQLModel.metadata.create_all(engine) 1abc

19 

20 

21def create_heroes(): # (1)! 1abc

22 hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") # (2)! 1abc

23 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abc

24 hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) 1abc

25 

26 with Session(engine) as session: # (3)! 1abc

27 session.add(hero_1) # (4)! 1abc

28 session.add(hero_2) 1abc

29 session.add(hero_3) 1abc

30 

31 session.commit() # (5)! 1abc

32 # (6)! 

33 

34 

35def main(): # (7)! 1abc

36 create_db_and_tables() # (8)! 1abc

37 create_heroes() # (9)! 1abc

38 

39 

40if __name__ == "__main__": # (10)! 1abc

41 main() # (11)!