Debian Codegraph @

docs/examples/contrib/sqlalchemy/sqlalchemy_repository_crud.py

raw
1 from __future__ import annotations
2
3 from contextlib import asynccontextmanager
4 from datetime import date, datetime
5 from typing import AsyncIterator
6 from uuid import UUID
7
8 import anyio
9 from rich import get_console
10 from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
11 from sqlalchemy.orm import Mapped
12
13 from litestar.plugins.sqlalchemy import base, repository
14
15 console = get_console()
16
17
18 # the SQLAlchemy base includes a declarative model for you to use in your models.
19 # The `Base` class includes a `UUID` based primary key (`id`)
20 class Author(base.UUIDBase):
21 name: Mapped[str]
22 dob: Mapped[date]
23 dod: Mapped[date | None]
24
25
26 class AuthorRepository(repository.SQLAlchemyAsyncRepository[Author]):
27 """Author repository."""
28
29 model_type = Author
30
31
32 engine = create_async_engine(
33 "sqlite+aiosqlite:///test.sqlite",
34 future=True,
35 )
36 session_factory = async_sessionmaker(engine, expire_on_commit=False)
37
38
39 # let's make a simple context manager as an example here.
40 @asynccontextmanager
41 async def repository_factory() -> AsyncIterator[AuthorRepository]:
42 async with session_factory() as db_session:
43 try:
44 yield AuthorRepository(session=db_session)
45 except Exception: # noqa: BLE001
46 await db_session.rollback()
47 else:
48 await db_session.commit()
49
50
51 async def create_author() -> Author:
52 async with repository_factory() as repo:
53 obj = await repo.add(
54 Author(
55 name="F. Scott Fitzgerald",
56 dob=datetime.strptime("1896-09-24", "%Y-%m-%d").date(),
57 )
58 )
59 console.print(f"Created Author record for {obj.name} with primary key {obj.id}.")
60 return obj
61
62
63 async def update_author(obj: Author) -> Author:
64 async with repository_factory() as repo:
65 obj = await repo.update(obj)
66 console.print(f"Updated Author record for {obj.name} with primary key {obj.id}.")
67 return obj
68
69
70 async def remove_author(id: UUID) -> Author:
71 async with repository_factory() as repo:
72 obj = await repo.delete(id)
73 console.print(f"Deleted Author record for {obj.name} with primary key {obj.id}.")
74 return obj
75
76
77 async def get_author_if_exists(id: UUID) -> Author | None:
78 async with repository_factory() as repo:
79 obj = await repo.get_one_or_none(id=id)
80 if obj is not None:
81 console.print(f"Found Author record for {obj.name} with primary key {obj.id}.")
82 else:
83 console.print(f"Could not find Author with primary key {id}.")
84 return obj
85
86
87 async def run_script() -> None:
88 """Load data from a fixture."""
89 async with engine.begin() as conn:
90 await conn.run_sync(base.UUIDBase.metadata.create_all)
91
92 # 1) create a new Author record.
93 console.print("1) Adding a new record")
94 author = await create_author()
95 author_id = author.id
96
97 # 2) Let's update the Author record.
98 console.print("2) Updating a record.")
99 author.dod = datetime.strptime("1940-12-21", "%Y-%m-%d").date()
100 await update_author(author)
101
102 # 3) Let's delete the record we just created.
103 console.print("3) Removing a record.")
104 await remove_author(author_id)
105
106 # 4) Let's verify the record no longer exists.
107 console.print("4) Select one or none.")
108 _should_be_none = await get_author_if_exists(author_id)
109
110
111 if __name__ == "__main__":
112 anyio.run(run_script)