Debian Codegraph @

docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py

raw
1 from __future__ import annotations
2
3 from datetime import date
4 from typing import TYPE_CHECKING, Annotated
5 from uuid import UUID
6
7 from pydantic import BaseModel as _BaseModel
8 from pydantic import TypeAdapter
9 from sqlalchemy import ForeignKey, select
10 from sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload
11
12 from litestar import Litestar, get
13 from litestar.controller import Controller
14 from litestar.di import Provide
15 from litestar.handlers.http_handlers.decorators import delete, patch, post
16 from litestar.pagination import OffsetPagination
17 from litestar.params import PathParameter, QueryParameter
18 from litestar.plugins.sqlalchemy import (
19 SQLAlchemyInitPlugin,
20 SQLAlchemySyncConfig,
21 base,
22 repository,
23 )
24 from litestar.repository.filters import LimitOffset
25
26 if TYPE_CHECKING:
27 from sqlalchemy.orm import Session
28
29
30 class BaseModel(_BaseModel):
31 """Extend Pydantic's BaseModel to enable ORM mode"""
32
33 model_config = {"from_attributes": True}
34
35
36 # The SQLAlchemy base includes a declarative model for you to use in your models.
37 # The `UUIDBase` class includes a `UUID` based primary key (`id`)
38 class AuthorModel(base.UUIDBase):
39 # we can optionally provide the table name instead of auto-generating it
40 __tablename__ = "author" # type: ignore[assignment]
41 name: Mapped[str]
42 dob: Mapped[date | None]
43 books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload")
44
45
46 # The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
47 # additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
48 # record created, and `updated_at` is the last time the record was modified.
49 class BookModel(base.UUIDAuditBase):
50 __tablename__ = "book" # type: ignore[assignment]
51 title: Mapped[str]
52 author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
53 author: Mapped[AuthorModel] = relationship(lazy="joined", innerjoin=True, viewonly=True)
54
55
56 # we will explicitly define the schema instead of using DTO objects for clarity.
57
58
59 class Author(BaseModel):
60 id: UUID | None
61 name: str
62 dob: date | None = None
63
64
65 class AuthorCreate(BaseModel):
66 name: str
67 dob: date | None = None
68
69
70 class AuthorUpdate(BaseModel):
71 name: str | None = None
72 dob: date | None = None
73
74
75 class AuthorRepository(repository.SQLAlchemySyncRepository[AuthorModel]):
76 """Author repository."""
77
78 model_type = AuthorModel
79
80
81 async def provide_authors_repo(db_session: Session) -> AuthorRepository:
82 """This provides the default Authors repository."""
83 return AuthorRepository(session=db_session)
84
85
86 # we can optionally override the default `select` used for the repository to pass in
87 # specific SQL options such as join details
88 async def provide_author_details_repo(db_session: Session) -> AuthorRepository:
89 """This provides a simple example demonstrating how to override the join options
90 for the repository."""
91 return AuthorRepository(
92 statement=select(AuthorModel).options(selectinload(AuthorModel.books)),
93 session=db_session,
94 )
95
96
97 def provide_limit_offset_pagination(
98 current_page: Annotated[int, QueryParameter(name="currentPage", ge=1, required=False)] = 1,
99 page_size: Annotated[int, QueryParameter(name="pageSize", ge=1, required=False)] = 10,
100 ) -> LimitOffset:
101 """Add offset/limit pagination.
102
103 Return type consumed by `Repository.apply_limit_offset_pagination()`.
104
105 Parameters
106 ----------
107 current_page : int
108 LIMIT to apply to select.
109 page_size : int
110 OFFSET to apply to select.
111 """
112 return LimitOffset(page_size, page_size * (current_page - 1))
113
114
115 class AuthorController(Controller):
116 """Author CRUD"""
117
118 dependencies = {"authors_repo": Provide(provide_authors_repo, sync_to_thread=False)}
119
120 @get(path="/authors")
121 def list_authors(
122 self,
123 authors_repo: AuthorRepository,
124 limit_offset: LimitOffset,
125 ) -> OffsetPagination[Author]:
126 """List authors."""
127 results, total = authors_repo.list_and_count(limit_offset)
128 type_adapter = TypeAdapter(list[Author])
129 return OffsetPagination[Author](
130 items=type_adapter.validate_python(results),
131 total=total,
132 limit=limit_offset.limit,
133 offset=limit_offset.offset,
134 )
135
136 @post(path="/authors")
137 def create_author(
138 self,
139 authors_repo: AuthorRepository,
140 data: AuthorCreate,
141 ) -> Author:
142 """Create a new author."""
143 obj = authors_repo.add(
144 AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),
145 )
146 authors_repo.session.commit()
147 return Author.model_validate(obj)
148
149 # we override the authors_repo to use the version that joins the Books in
150 @get(
151 path="/authors/{author_id:uuid}",
152 dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
153 )
154 def get_author(
155 self,
156 authors_repo: AuthorRepository,
157 author_id: Annotated[
158 UUID,
159 PathParameter(
160 title="Author ID",
161 description="The author to retrieve.",
162 ),
163 ],
164 ) -> Author:
165 """Get an existing author."""
166 obj = authors_repo.get(author_id)
167 return Author.model_validate(obj)
168
169 @patch(
170 path="/authors/{author_id:uuid}",
171 dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
172 )
173 def update_author(
174 self,
175 authors_repo: AuthorRepository,
176 data: AuthorUpdate,
177 author_id: Annotated[
178 UUID,
179 PathParameter(
180 title="Author ID",
181 description="The author to update.",
182 ),
183 ],
184 ) -> Author:
185 """Update an author."""
186 raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)
187 raw_obj.update({"id": author_id})
188 obj = authors_repo.update(AuthorModel(**raw_obj))
189 authors_repo.session.commit()
190 return Author.model_validate(obj)
191
192 @delete(path="/authors/{author_id:uuid}")
193 def delete_author(
194 self,
195 authors_repo: AuthorRepository,
196 author_id: Annotated[
197 UUID,
198 PathParameter(
199 title="Author ID",
200 description="The author to delete.",
201 ),
202 ],
203 ) -> None:
204 """Delete a author from the system."""
205 _ = authors_repo.delete(author_id)
206 authors_repo.session.commit()
207
208
209 sqlalchemy_config = SQLAlchemySyncConfig(connection_string="sqlite:///test.sqlite") # Create 'db_session' dependency.
210 sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
211
212
213 def on_startup() -> None:
214 """Initializes the database."""
215 with sqlalchemy_config.get_engine().begin() as conn:
216 base.UUIDBase.metadata.create_all(conn)
217
218
219 app = Litestar(
220 route_handlers=[AuthorController],
221 on_startup=[on_startup],
222 plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
223 dependencies={"limit_offset": Provide(provide_limit_offset_pagination)},
224 )