We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Documentation: Unnecessary use of sync_to_thread=True
The following are calling object constructors with no I/O, so should be right to run sync.

https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L120

https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L154

https://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L170



<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]  
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and 
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.

<a href="https://polar.sh/litestar-org/litestar/issues/2508">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py`
Content:
```
1 from __future__ import annotations
2 
3 from typing import TYPE_CHECKING
4 
5 from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
6 
7 from litestar import Litestar, post
8 from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
9 from litestar.dto import dto_field
10 
11 if TYPE_CHECKING:
12     from typing import List
13 
14 
15 class Base(DeclarativeBase):
16     ...
17 
18 
19 class TodoItem(Base):
20     __tablename__ = "todo_item"
21     title: Mapped[str] = mapped_column(primary_key=True)
22     done: Mapped[bool]
23     super_secret_value: Mapped[str] = mapped_column(info=dto_field("private"))
24 
25 
26 @post("/", sync_to_thread=True)
27 def add_item(data: TodoItem) -> List[TodoItem]:
28     data.super_secret_value = "This is a secret"
29     return [data]
30 
31 
32 app = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])
33
```

Path: `docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py`
Content:
```
1 from __future__ import annotations
2 
3 from typing import TYPE_CHECKING
4 
5 from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
6 
7 from litestar import Litestar, post
8 from litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin
9 
10 if TYPE_CHECKING:
11     from typing import List
12 
13 
14 class Base(DeclarativeBase):
15     ...
16 
17 
18 class TodoItem(Base):
19     __tablename__ = "todo_item"
20     title: Mapped[str] = mapped_column(primary_key=True)
21     done: Mapped[bool]
22 
23 
24 @post("/", sync_to_thread=True)
25 def add_item(data: TodoItem) -> List[TodoItem]:
26     return [data]
27 
28 
29 app = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])
30
```

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

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py
@@ -21,7 +21,7 @@
     done: Mapped[bool]
 
 
-@post("/", sync_to_thread=True)
+@post("/", sync_to_thread=False)
 def add_item(data: TodoItem) -> List[TodoItem]:
     return [data]
 
diff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py
@@ -23,7 +23,7 @@
     super_secret_value: Mapped[str] = mapped_column(info=dto_field("private"))
 
 
-@post("/", sync_to_thread=True)
+@post("/", sync_to_thread=False)
 def add_item(data: TodoItem) -> List[TodoItem]:
     data.super_secret_value = "This is a secret"
     return [data]
diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py
@@ -117,7 +117,7 @@
 class AuthorController(Controller):
     """Author CRUD"""
 
-    dependencies = {"authors_repo": Provide(provide_authors_repo, sync_to_thread=True)}
+    dependencies = {"authors_repo": Provide(provide_authors_repo, sync_to_thread=False)}
 
     @get(path="/authors")
     def list_authors(
@@ -151,7 +151,7 @@
     # we override the authors_repo to use the version that joins the Books in
     @get(
         path="/authors/{author_id:uuid}",
-        dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=True)},
+        dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
     )
     def get_author(
         self,
@@ -167,7 +167,7 @@
 
     @patch(
         path="/authors/{author_id:uuid}",
-        dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=True)},
+        dependencies={"authors_repo": Provide(provide_author_details_repo, sync_to_thread=False)},
     )
     def update_author(
         self,

{"golden_diff": "diff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py\n--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py\n+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py\n@@ -21,7 +21,7 @@\n     done: Mapped[bool]\n \n \n-@post(\"/\", sync_to_thread=True)\n+@post(\"/\", sync_to_thread=False)\n def add_item(data: TodoItem) -> List[TodoItem]:\n     return [data]\n \ndiff --git a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py\n--- a/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py\n+++ b/docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py\n@@ -23,7 +23,7 @@\n     super_secret_value: Mapped[str] = mapped_column(info=dto_field(\"private\"))\n \n \n-@post(\"/\", sync_to_thread=True)\n+@post(\"/\", sync_to_thread=False)\n def add_item(data: TodoItem) -> List[TodoItem]:\n     data.super_secret_value = \"This is a secret\"\n     return [data]\ndiff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py\n--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py\n+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py\n@@ -117,7 +117,7 @@\n class AuthorController(Controller):\n     \"\"\"Author CRUD\"\"\"\n \n-    dependencies = {\"authors_repo\": Provide(provide_authors_repo, sync_to_thread=True)}\n+    dependencies = {\"authors_repo\": Provide(provide_authors_repo, sync_to_thread=False)}\n \n     @get(path=\"/authors\")\n     def list_authors(\n@@ -151,7 +151,7 @@\n     # we override the authors_repo to use the version that joins the Books in\n     @get(\n         path=\"/authors/{author_id:uuid}\",\n-        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=True)},\n+        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=False)},\n     )\n     def get_author(\n         self,\n@@ -167,7 +167,7 @@\n \n     @patch(\n         path=\"/authors/{author_id:uuid}\",\n-        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=True)},\n+        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=False)},\n     )\n     def update_author(\n         self,\n", "issue": "Documentation: Unnecessary use of sync_to_thread=True\nThe following are calling object constructors with no I/O, so should be right to run sync.\r\n\r\nhttps://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L120\r\n\r\nhttps://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L154\r\n\r\nhttps://github.com/litestar-org/litestar/blob/0d4fe01a9d361e09748f71aa7adf70672b97c822/docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py#L170\r\n\r\n\n\n<!-- POLAR PLEDGE BADGE START -->\n---\n> [!NOTE]  \n> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and \n> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.\n>\n> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)\n> * If you would like to see an issue prioritized, make a pledge towards it!\n> * We receive the pledge once the issue is completed & verified\n> * This, along with engagement in the community, helps us know which features are a priority to our users.\n\n<a href=\"https://polar.sh/litestar-org/litestar/issues/2508\">\n<picture>\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg?darkmode=1\">\n  <img alt=\"Fund with Polar\" src=\"https://polar.sh/api/github/litestar-org/litestar/issues/2508/pledge.svg\">\n</picture>\n</a>\n<!-- POLAR PLEDGE BADGE END -->\n\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n\nfrom litestar import Litestar, post\nfrom litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin\nfrom litestar.dto import dto_field\n\nif TYPE_CHECKING:\n    from typing import List\n\n\nclass Base(DeclarativeBase):\n    ...\n\n\nclass TodoItem(Base):\n    __tablename__ = \"todo_item\"\n    title: Mapped[str] = mapped_column(primary_key=True)\n    done: Mapped[bool]\n    super_secret_value: Mapped[str] = mapped_column(info=dto_field(\"private\"))\n\n\n@post(\"/\", sync_to_thread=True)\ndef add_item(data: TodoItem) -> List[TodoItem]:\n    data.super_secret_value = \"This is a secret\"\n    return [data]\n\n\napp = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])\n", "path": "docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py"}, {"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n\nfrom litestar import Litestar, post\nfrom litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin\n\nif TYPE_CHECKING:\n    from typing import List\n\n\nclass Base(DeclarativeBase):\n    ...\n\n\nclass TodoItem(Base):\n    __tablename__ = \"todo_item\"\n    title: Mapped[str] = mapped_column(primary_key=True)\n    done: Mapped[bool]\n\n\n@post(\"/\", sync_to_thread=True)\ndef add_item(data: TodoItem) -> List[TodoItem]:\n    return [data]\n\n\napp = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])\n", "path": "docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py"}, {"content": "from __future__ import annotations\n\nfrom datetime import date\nfrom typing import TYPE_CHECKING\nfrom uuid import UUID\n\nfrom pydantic import BaseModel as _BaseModel\nfrom pydantic import TypeAdapter\nfrom sqlalchemy import ForeignKey, select\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload\n\nfrom litestar import Litestar, get\nfrom litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\nfrom litestar.contrib.sqlalchemy.plugins.init import SQLAlchemyInitPlugin, SQLAlchemySyncConfig\nfrom litestar.contrib.sqlalchemy.repository import SQLAlchemySyncRepository\nfrom litestar.controller import Controller\nfrom litestar.di import Provide\nfrom litestar.handlers.http_handlers.decorators import delete, patch, post\nfrom litestar.pagination import OffsetPagination\nfrom litestar.params import Parameter\nfrom litestar.repository.filters import LimitOffset\n\nif TYPE_CHECKING:\n    from sqlalchemy.orm import Session\n\n\nclass BaseModel(_BaseModel):\n    \"\"\"Extend Pydantic's BaseModel to enable ORM mode\"\"\"\n\n    model_config = {\"from_attributes\": True}\n\n\n# the SQLAlchemy base includes a declarative model for you to use in your models.\n# The `Base` class includes a `UUID` based primary key (`id`)\nclass AuthorModel(UUIDBase):\n    # we can optionally provide the table name instead of auto-generating it\n    __tablename__ = \"author\"  #  type: ignore[assignment]\n    name: Mapped[str]\n    dob: Mapped[date | None]\n    books: Mapped[list[BookModel]] = relationship(back_populates=\"author\", lazy=\"noload\")\n\n\n# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\n# additional columns: `created` and `updated`. `created` is a timestamp of when the\n# record created, and `updated` is the last time the record was modified.\nclass BookModel(UUIDAuditBase):\n    __tablename__ = \"book\"  #  type: ignore[assignment]\n    title: Mapped[str]\n    author_id: Mapped[UUID] = mapped_column(ForeignKey(\"author.id\"))\n    author: Mapped[AuthorModel] = relationship(lazy=\"joined\", innerjoin=True, viewonly=True)\n\n\n# we will explicitly define the schema instead of using DTO objects for clarity.\n\n\nclass Author(BaseModel):\n    id: UUID | None\n    name: str\n    dob: date | None = None\n\n\nclass AuthorCreate(BaseModel):\n    name: str\n    dob: date | None = None\n\n\nclass AuthorUpdate(BaseModel):\n    name: str | None = None\n    dob: date | None = None\n\n\nclass AuthorRepository(SQLAlchemySyncRepository[AuthorModel]):\n    \"\"\"Author repository.\"\"\"\n\n    model_type = AuthorModel\n\n\nasync def provide_authors_repo(db_session: Session) -> AuthorRepository:\n    \"\"\"This provides the default Authors repository.\"\"\"\n    return AuthorRepository(session=db_session)\n\n\n# we can optionally override the default `select` used for the repository to pass in\n# specific SQL options such as join details\nasync def provide_author_details_repo(db_session: Session) -> AuthorRepository:\n    \"\"\"This provides a simple example demonstrating how to override the join options\n    for the repository.\"\"\"\n    return AuthorRepository(\n        statement=select(AuthorModel).options(selectinload(AuthorModel.books)),\n        session=db_session,\n    )\n\n\ndef provide_limit_offset_pagination(\n    current_page: int = Parameter(ge=1, query=\"currentPage\", default=1, required=False),\n    page_size: int = Parameter(\n        query=\"pageSize\",\n        ge=1,\n        default=10,\n        required=False,\n    ),\n) -> LimitOffset:\n    \"\"\"Add offset/limit pagination.\n\n    Return type consumed by `Repository.apply_limit_offset_pagination()`.\n\n    Parameters\n    ----------\n    current_page : int\n        LIMIT to apply to select.\n    page_size : int\n        OFFSET to apply to select.\n    \"\"\"\n    return LimitOffset(page_size, page_size * (current_page - 1))\n\n\nclass AuthorController(Controller):\n    \"\"\"Author CRUD\"\"\"\n\n    dependencies = {\"authors_repo\": Provide(provide_authors_repo, sync_to_thread=True)}\n\n    @get(path=\"/authors\")\n    def list_authors(\n        self,\n        authors_repo: AuthorRepository,\n        limit_offset: LimitOffset,\n    ) -> OffsetPagination[Author]:\n        \"\"\"List authors.\"\"\"\n        results, total = authors_repo.list_and_count(limit_offset)\n        type_adapter = TypeAdapter(list[Author])\n        return OffsetPagination[Author](\n            items=type_adapter.validate_python(results),\n            total=total,\n            limit=limit_offset.limit,\n            offset=limit_offset.offset,\n        )\n\n    @post(path=\"/authors\")\n    def create_author(\n        self,\n        authors_repo: AuthorRepository,\n        data: AuthorCreate,\n    ) -> Author:\n        \"\"\"Create a new author.\"\"\"\n        obj = authors_repo.add(\n            AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),\n        )\n        authors_repo.session.commit()\n        return Author.model_validate(obj)\n\n    # we override the authors_repo to use the version that joins the Books in\n    @get(\n        path=\"/authors/{author_id:uuid}\",\n        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=True)},\n    )\n    def get_author(\n        self,\n        authors_repo: AuthorRepository,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to retrieve.\",\n        ),\n    ) -> Author:\n        \"\"\"Get an existing author.\"\"\"\n        obj = authors_repo.get(author_id)\n        return Author.model_validate(obj)\n\n    @patch(\n        path=\"/authors/{author_id:uuid}\",\n        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=True)},\n    )\n    def update_author(\n        self,\n        authors_repo: AuthorRepository,\n        data: AuthorUpdate,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to update.\",\n        ),\n    ) -> Author:\n        \"\"\"Update an author.\"\"\"\n        raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)\n        raw_obj.update({\"id\": author_id})\n        obj = authors_repo.update(AuthorModel(**raw_obj))\n        authors_repo.session.commit()\n        return Author.model_validate(obj)\n\n    @delete(path=\"/authors/{author_id:uuid}\")\n    def delete_author(\n        self,\n        authors_repo: AuthorRepository,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to delete.\",\n        ),\n    ) -> None:\n        \"\"\"Delete a author from the system.\"\"\"\n        _ = authors_repo.delete(author_id)\n        authors_repo.session.commit()\n\n\nsqlalchemy_config = SQLAlchemySyncConfig(connection_string=\"sqlite:///test.sqlite\")  # Create 'db_session' dependency.\nsqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)\n\n\ndef on_startup() -> None:\n    \"\"\"Initializes the database.\"\"\"\n    with sqlalchemy_config.get_engine().begin() as conn:\n        UUIDBase.metadata.create_all(conn)\n\n\napp = Litestar(\n    route_handlers=[AuthorController],\n    on_startup=[on_startup],\n    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],\n    dependencies={\"limit_offset\": Provide(provide_limit_offset_pagination)},\n)\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n\nfrom litestar import Litestar, post\nfrom litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin\nfrom litestar.dto import dto_field\n\nif TYPE_CHECKING:\n    from typing import List\n\n\nclass Base(DeclarativeBase):\n    ...\n\n\nclass TodoItem(Base):\n    __tablename__ = \"todo_item\"\n    title: Mapped[str] = mapped_column(primary_key=True)\n    done: Mapped[bool]\n    super_secret_value: Mapped[str] = mapped_column(info=dto_field(\"private\"))\n\n\n@post(\"/\", sync_to_thread=False)\ndef add_item(data: TodoItem) -> List[TodoItem]:\n    data.super_secret_value = \"This is a secret\"\n    return [data]\n\n\napp = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])\n", "path": "docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin_marking_fields.py"}, {"content": "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n\nfrom litestar import Litestar, post\nfrom litestar.contrib.sqlalchemy.plugins import SQLAlchemySerializationPlugin\n\nif TYPE_CHECKING:\n    from typing import List\n\n\nclass Base(DeclarativeBase):\n    ...\n\n\nclass TodoItem(Base):\n    __tablename__ = \"todo_item\"\n    title: Mapped[str] = mapped_column(primary_key=True)\n    done: Mapped[bool]\n\n\n@post(\"/\", sync_to_thread=False)\ndef add_item(data: TodoItem) -> List[TodoItem]:\n    return [data]\n\n\napp = Litestar(route_handlers=[add_item], plugins=[SQLAlchemySerializationPlugin()])\n", "path": "docs/examples/contrib/sqlalchemy/plugins/sqlalchemy_sync_serialization_plugin.py"}, {"content": "from __future__ import annotations\n\nfrom datetime import date\nfrom typing import TYPE_CHECKING\nfrom uuid import UUID\n\nfrom pydantic import BaseModel as _BaseModel\nfrom pydantic import TypeAdapter\nfrom sqlalchemy import ForeignKey, select\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload\n\nfrom litestar import Litestar, get\nfrom litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\nfrom litestar.contrib.sqlalchemy.plugins.init import SQLAlchemyInitPlugin, SQLAlchemySyncConfig\nfrom litestar.contrib.sqlalchemy.repository import SQLAlchemySyncRepository\nfrom litestar.controller import Controller\nfrom litestar.di import Provide\nfrom litestar.handlers.http_handlers.decorators import delete, patch, post\nfrom litestar.pagination import OffsetPagination\nfrom litestar.params import Parameter\nfrom litestar.repository.filters import LimitOffset\n\nif TYPE_CHECKING:\n    from sqlalchemy.orm import Session\n\n\nclass BaseModel(_BaseModel):\n    \"\"\"Extend Pydantic's BaseModel to enable ORM mode\"\"\"\n\n    model_config = {\"from_attributes\": True}\n\n\n# the SQLAlchemy base includes a declarative model for you to use in your models.\n# The `Base` class includes a `UUID` based primary key (`id`)\nclass AuthorModel(UUIDBase):\n    # we can optionally provide the table name instead of auto-generating it\n    __tablename__ = \"author\"  #  type: ignore[assignment]\n    name: Mapped[str]\n    dob: Mapped[date | None]\n    books: Mapped[list[BookModel]] = relationship(back_populates=\"author\", lazy=\"noload\")\n\n\n# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\n# additional columns: `created` and `updated`. `created` is a timestamp of when the\n# record created, and `updated` is the last time the record was modified.\nclass BookModel(UUIDAuditBase):\n    __tablename__ = \"book\"  #  type: ignore[assignment]\n    title: Mapped[str]\n    author_id: Mapped[UUID] = mapped_column(ForeignKey(\"author.id\"))\n    author: Mapped[AuthorModel] = relationship(lazy=\"joined\", innerjoin=True, viewonly=True)\n\n\n# we will explicitly define the schema instead of using DTO objects for clarity.\n\n\nclass Author(BaseModel):\n    id: UUID | None\n    name: str\n    dob: date | None = None\n\n\nclass AuthorCreate(BaseModel):\n    name: str\n    dob: date | None = None\n\n\nclass AuthorUpdate(BaseModel):\n    name: str | None = None\n    dob: date | None = None\n\n\nclass AuthorRepository(SQLAlchemySyncRepository[AuthorModel]):\n    \"\"\"Author repository.\"\"\"\n\n    model_type = AuthorModel\n\n\nasync def provide_authors_repo(db_session: Session) -> AuthorRepository:\n    \"\"\"This provides the default Authors repository.\"\"\"\n    return AuthorRepository(session=db_session)\n\n\n# we can optionally override the default `select` used for the repository to pass in\n# specific SQL options such as join details\nasync def provide_author_details_repo(db_session: Session) -> AuthorRepository:\n    \"\"\"This provides a simple example demonstrating how to override the join options\n    for the repository.\"\"\"\n    return AuthorRepository(\n        statement=select(AuthorModel).options(selectinload(AuthorModel.books)),\n        session=db_session,\n    )\n\n\ndef provide_limit_offset_pagination(\n    current_page: int = Parameter(ge=1, query=\"currentPage\", default=1, required=False),\n    page_size: int = Parameter(\n        query=\"pageSize\",\n        ge=1,\n        default=10,\n        required=False,\n    ),\n) -> LimitOffset:\n    \"\"\"Add offset/limit pagination.\n\n    Return type consumed by `Repository.apply_limit_offset_pagination()`.\n\n    Parameters\n    ----------\n    current_page : int\n        LIMIT to apply to select.\n    page_size : int\n        OFFSET to apply to select.\n    \"\"\"\n    return LimitOffset(page_size, page_size * (current_page - 1))\n\n\nclass AuthorController(Controller):\n    \"\"\"Author CRUD\"\"\"\n\n    dependencies = {\"authors_repo\": Provide(provide_authors_repo, sync_to_thread=False)}\n\n    @get(path=\"/authors\")\n    def list_authors(\n        self,\n        authors_repo: AuthorRepository,\n        limit_offset: LimitOffset,\n    ) -> OffsetPagination[Author]:\n        \"\"\"List authors.\"\"\"\n        results, total = authors_repo.list_and_count(limit_offset)\n        type_adapter = TypeAdapter(list[Author])\n        return OffsetPagination[Author](\n            items=type_adapter.validate_python(results),\n            total=total,\n            limit=limit_offset.limit,\n            offset=limit_offset.offset,\n        )\n\n    @post(path=\"/authors\")\n    def create_author(\n        self,\n        authors_repo: AuthorRepository,\n        data: AuthorCreate,\n    ) -> Author:\n        \"\"\"Create a new author.\"\"\"\n        obj = authors_repo.add(\n            AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),\n        )\n        authors_repo.session.commit()\n        return Author.model_validate(obj)\n\n    # we override the authors_repo to use the version that joins the Books in\n    @get(\n        path=\"/authors/{author_id:uuid}\",\n        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=False)},\n    )\n    def get_author(\n        self,\n        authors_repo: AuthorRepository,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to retrieve.\",\n        ),\n    ) -> Author:\n        \"\"\"Get an existing author.\"\"\"\n        obj = authors_repo.get(author_id)\n        return Author.model_validate(obj)\n\n    @patch(\n        path=\"/authors/{author_id:uuid}\",\n        dependencies={\"authors_repo\": Provide(provide_author_details_repo, sync_to_thread=False)},\n    )\n    def update_author(\n        self,\n        authors_repo: AuthorRepository,\n        data: AuthorUpdate,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to update.\",\n        ),\n    ) -> Author:\n        \"\"\"Update an author.\"\"\"\n        raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)\n        raw_obj.update({\"id\": author_id})\n        obj = authors_repo.update(AuthorModel(**raw_obj))\n        authors_repo.session.commit()\n        return Author.model_validate(obj)\n\n    @delete(path=\"/authors/{author_id:uuid}\")\n    def delete_author(\n        self,\n        authors_repo: AuthorRepository,\n        author_id: UUID = Parameter(\n            title=\"Author ID\",\n            description=\"The author to delete.\",\n        ),\n    ) -> None:\n        \"\"\"Delete a author from the system.\"\"\"\n        _ = authors_repo.delete(author_id)\n        authors_repo.session.commit()\n\n\nsqlalchemy_config = SQLAlchemySyncConfig(connection_string=\"sqlite:///test.sqlite\")  # Create 'db_session' dependency.\nsqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)\n\n\ndef on_startup() -> None:\n    \"\"\"Initializes the database.\"\"\"\n    with sqlalchemy_config.get_engine().begin() as conn:\n        UUIDBase.metadata.create_all(conn)\n\n\napp = Litestar(\n    route_handlers=[AuthorController],\n    on_startup=[on_startup],\n    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],\n    dependencies={\"limit_offset\": Provide(provide_limit_offset_pagination)},\n)\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_sync_repository.py"}]}