We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: SerializationException when running modeling-and-features demo from docs
### Description

Hi,

First of all thanks for developing Litestar, it proves to be a very useful piece of software here. Unfortunately I ran into an issue. 

I ran into an `msgspec_error` when requesting a page backed by sqlalchemy models which are connected via relationships. It seems that the database is correctly queried, a list of objects are returned, but then an exception is thrown when converting the objects to JSON.

I ran into this issue on my production code but when isolating an MCVE I noticed that the provided example in the documentation also shows the same unexpected behaviour on tested on two different machines.  One crucial change to the code is however adding an author to the database.

Since this is quite a show-stopper for me: Thanks in advance for having a look at this!

### URL to code causing the issue

https://docs.litestar.dev/2/tutorials/repository-tutorial/01-modeling-and-features.html

### MCVE

```python
from datetime import date
from typing import TYPE_CHECKING
from uuid import UUID

from sqlalchemy import ForeignKey, select
from sqlalchemy.orm import Mapped, mapped_column, relationship

from litestar import Litestar, get
from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase
from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin

if TYPE_CHECKING:
    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession


# the SQLAlchemy base includes a declarative model for you to use in your models.
# The `Base` class includes a `UUID` based primary key (`id`)
class Author(UUIDBase):
    name: Mapped[str]
    dob: Mapped[date]
    books: Mapped[list["Book"]] = relationship(back_populates="author", lazy="selectin")


# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
# record created, and `updated_at` is the last time the record was modified.
class Book(UUIDAuditBase):
    title: Mapped[str]
    author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
    author: Mapped[Author] = relationship(lazy="joined", innerjoin=True, viewonly=True)


session_config = AsyncSessionConfig(expire_on_commit=False)
sqlalchemy_config = SQLAlchemyAsyncConfig(
    connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config
)  # Create 'async_session' dependency.
sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)


async def on_startup() -> None:
    """Initializes the database."""
    async with sqlalchemy_config.get_engine().begin() as conn:
        await conn.run_sync(UUIDBase.metadata.create_all)
        
    #crucially there needs to be an author in the table for the error to appear
    await conn.execute(Author.__table__.insert().values(name="F. Scott Fitzgerald"))


@get(path="/authors")
async def get_authors(db_session: "AsyncSession", db_engine: "AsyncEngine") -> list[Author]:
    """Interact with SQLAlchemy engine and session."""
    return list(await db_session.scalars(select(Author)))


app = Litestar(
    route_handlers=[get_authors],
    on_startup=[on_startup],
    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
    debug=True
)
```


### Steps to reproduce

```bash
1. Go to the https://docs.litestar.dev/2/tutorials/repository-tutorial/01-modeling-and-features.html page
2. Download the code
3. Run the demo with minimal requirements installed and go to http://localhost:8000/authors
4. See the error
```


### Screenshots

_No response_

### Logs

```bash
File "/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py", line 143, in encode_json
    raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class '__main__.Author'>
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py", line 141, in encode_json
    return msgspec.json.encode(value, enc_hook=serializer) if serializer else _msgspec_json_encoder.encode(value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py", line 88, in default_serializer
    raise TypeError(f"Unsupported type: {type(value)!r}")
TypeError: Unsupported type: <class '__main__.Author'>
 
The above exception was the direct cause of the following exception:
 
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/litestar/middleware/exceptions/middleware.py", line 219, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/litestar/routes/http.py", line 82, in handle
    response = await self._get_response_for_request(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/routes/http.py", line 134, in _get_response_for_request
    return await self._call_handler_function(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/routes/http.py", line 158, in _call_handler_function
    response: ASGIApp = await route_handler.to_response(app=scope["app"], data=response_data, request=request)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/handlers/http_handlers/base.py", line 557, in to_response
    return await response_handler(app=app, data=data, request=request)  # type: ignore[call-arg]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/handlers/http_handlers/_utils.py", line 79, in handler
    return response.to_asgi_response(app=None, request=request, headers=normalize_headers(headers), cookies=cookies)  # pyright: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/response/base.py", line 451, in to_asgi_response
    body=self.render(self.content, media_type, get_serializer(type_encoders)),
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/response/base.py", line 392, in render
    return encode_json(content, enc_hook)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py", line 143, in encode_json
    raise SerializationException(str(msgspec_error)) from msgspec_error
litestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class '__main__.Author'>
INFO:     127.0.0.1:44906 - "GET /authors HTTP/1.1" 500 Internal Server Error
```


### Litestar Version

2.8.2

### Platform

- [X] Linux
- [X] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)

<!-- 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 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/3464">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/3464/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/3464/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/sqlalchemy_declarative_models.py`
Content:
```
1 from datetime import date
2 from typing import TYPE_CHECKING
3 from uuid import UUID
4 
5 from sqlalchemy import ForeignKey, select
6 from sqlalchemy.orm import Mapped, mapped_column, relationship
7 
8 from litestar import Litestar, get
9 from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase
10 from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
11 
12 if TYPE_CHECKING:
13     from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
14 
15 
16 # the SQLAlchemy base includes a declarative model for you to use in your models.
17 # The `Base` class includes a `UUID` based primary key (`id`)
18 class Author(UUIDBase):
19     name: Mapped[str]
20     dob: Mapped[date]
21     books: Mapped[list["Book"]] = relationship(back_populates="author", lazy="selectin")
22 
23 
24 # The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
25 # additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
26 # record created, and `updated_at` is the last time the record was modified.
27 class Book(UUIDAuditBase):
28     title: Mapped[str]
29     author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
30     author: Mapped[Author] = relationship(lazy="joined", innerjoin=True, viewonly=True)
31 
32 
33 session_config = AsyncSessionConfig(expire_on_commit=False)
34 sqlalchemy_config = SQLAlchemyAsyncConfig(
35     connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config
36 )  # Create 'async_session' dependency.
37 sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
38 
39 
40 async def on_startup() -> None:
41     """Initializes the database."""
42     async with sqlalchemy_config.get_engine().begin() as conn:
43         await conn.run_sync(UUIDBase.metadata.create_all)
44 
45 
46 @get(path="/authors")
47 async def get_authors(db_session: "AsyncSession", db_engine: "AsyncEngine") -> list[Author]:
48     """Interact with SQLAlchemy engine and session."""
49     return list(await db_session.scalars(select(Author)))
50 
51 
52 app = Litestar(
53     route_handlers=[get_authors],
54     on_startup=[on_startup],
55     plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
56 )
57
```
--- 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/sqlalchemy_declarative_models.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py
@@ -1,16 +1,17 @@
+from __future__ import annotations
+
+import uuid
 from datetime import date
-from typing import TYPE_CHECKING
+from typing import List
 from uuid import UUID
 
-from sqlalchemy import ForeignKey, select
+from sqlalchemy import ForeignKey, func, select
+from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
 from sqlalchemy.orm import Mapped, mapped_column, relationship
 
 from litestar import Litestar, get
 from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase
-from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin
-
-if TYPE_CHECKING:
-    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
+from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin
 
 
 # the SQLAlchemy base includes a declarative model for you to use in your models.
@@ -18,7 +19,7 @@
 class Author(UUIDBase):
     name: Mapped[str]
     dob: Mapped[date]
-    books: Mapped[list["Book"]] = relationship(back_populates="author", lazy="selectin")
+    books: Mapped[List[Book]] = relationship(back_populates="author", lazy="selectin")
 
 
 # The `AuditBase` class includes the same UUID` based primary key (`id`) and 2
@@ -32,19 +33,24 @@
 
 session_config = AsyncSessionConfig(expire_on_commit=False)
 sqlalchemy_config = SQLAlchemyAsyncConfig(
-    connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config
+    connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config, create_all=True
 )  # Create 'async_session' dependency.
-sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
 
 
 async def on_startup() -> None:
-    """Initializes the database."""
-    async with sqlalchemy_config.get_engine().begin() as conn:
-        await conn.run_sync(UUIDBase.metadata.create_all)
+    """Adds some dummy data if no data is present."""
+    async with sqlalchemy_config.get_session() as session:
+        statement = select(func.count()).select_from(Author)
+        count = await session.execute(statement)
+        if not count.scalar():
+            author_id = uuid.uuid4()
+            session.add(Author(name="Stephen King", dob=date(1954, 9, 21), id=author_id))
+            session.add(Book(title="It", author_id=author_id))
+            await session.commit()
 
 
 @get(path="/authors")
-async def get_authors(db_session: "AsyncSession", db_engine: "AsyncEngine") -> list[Author]:
+async def get_authors(db_session: AsyncSession, db_engine: AsyncEngine) -> List[Author]:
     """Interact with SQLAlchemy engine and session."""
     return list(await db_session.scalars(select(Author)))
 
@@ -52,5 +58,6 @@
 app = Litestar(
     route_handlers=[get_authors],
     on_startup=[on_startup],
-    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
+    debug=True,
+    plugins=[SQLAlchemyPlugin(config=sqlalchemy_config)],
 )

{"golden_diff": "diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py\n--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py\n+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py\n@@ -1,16 +1,17 @@\n+from __future__ import annotations\n+\n+import uuid\n from datetime import date\n-from typing import TYPE_CHECKING\n+from typing import List\n from uuid import UUID\n \n-from sqlalchemy import ForeignKey, select\n+from sqlalchemy import ForeignKey, func, select\n+from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession\n from sqlalchemy.orm import Mapped, mapped_column, relationship\n \n from litestar import Litestar, get\n from litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\n-from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin\n-\n-if TYPE_CHECKING:\n-    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession\n+from litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin\n \n \n # the SQLAlchemy base includes a declarative model for you to use in your models.\n@@ -18,7 +19,7 @@\n class Author(UUIDBase):\n     name: Mapped[str]\n     dob: Mapped[date]\n-    books: Mapped[list[\"Book\"]] = relationship(back_populates=\"author\", lazy=\"selectin\")\n+    books: Mapped[List[Book]] = relationship(back_populates=\"author\", lazy=\"selectin\")\n \n \n # The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\n@@ -32,19 +33,24 @@\n \n session_config = AsyncSessionConfig(expire_on_commit=False)\n sqlalchemy_config = SQLAlchemyAsyncConfig(\n-    connection_string=\"sqlite+aiosqlite:///test.sqlite\", session_config=session_config\n+    connection_string=\"sqlite+aiosqlite:///test.sqlite\", session_config=session_config, create_all=True\n )  # Create 'async_session' dependency.\n-sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)\n \n \n async def on_startup() -> None:\n-    \"\"\"Initializes the database.\"\"\"\n-    async with sqlalchemy_config.get_engine().begin() as conn:\n-        await conn.run_sync(UUIDBase.metadata.create_all)\n+    \"\"\"Adds some dummy data if no data is present.\"\"\"\n+    async with sqlalchemy_config.get_session() as session:\n+        statement = select(func.count()).select_from(Author)\n+        count = await session.execute(statement)\n+        if not count.scalar():\n+            author_id = uuid.uuid4()\n+            session.add(Author(name=\"Stephen King\", dob=date(1954, 9, 21), id=author_id))\n+            session.add(Book(title=\"It\", author_id=author_id))\n+            await session.commit()\n \n \n @get(path=\"/authors\")\n-async def get_authors(db_session: \"AsyncSession\", db_engine: \"AsyncEngine\") -> list[Author]:\n+async def get_authors(db_session: AsyncSession, db_engine: AsyncEngine) -> List[Author]:\n     \"\"\"Interact with SQLAlchemy engine and session.\"\"\"\n     return list(await db_session.scalars(select(Author)))\n \n@@ -52,5 +58,6 @@\n app = Litestar(\n     route_handlers=[get_authors],\n     on_startup=[on_startup],\n-    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],\n+    debug=True,\n+    plugins=[SQLAlchemyPlugin(config=sqlalchemy_config)],\n )\n", "issue": "Bug: SerializationException when running modeling-and-features demo from docs\n### Description\r\n\r\nHi,\r\n\r\nFirst of all thanks for developing Litestar, it proves to be a very useful piece of software here. Unfortunately I ran into an issue. \r\n\r\nI ran into an `msgspec_error` when requesting a page backed by sqlalchemy models which are connected via relationships. It seems that the database is correctly queried, a list of objects are returned, but then an exception is thrown when converting the objects to JSON.\r\n\r\nI ran into this issue on my production code but when isolating an MCVE I noticed that the provided example in the documentation also shows the same unexpected behaviour on tested on two different machines.  One crucial change to the code is however adding an author to the database.\r\n\r\nSince this is quite a show-stopper for me: Thanks in advance for having a look at this!\r\n\r\n### URL to code causing the issue\r\n\r\nhttps://docs.litestar.dev/2/tutorials/repository-tutorial/01-modeling-and-features.html\r\n\r\n### MCVE\r\n\r\n```python\r\nfrom datetime import date\r\nfrom typing import TYPE_CHECKING\r\nfrom uuid import UUID\r\n\r\nfrom sqlalchemy import ForeignKey, select\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\n\r\nfrom litestar import Litestar, get\r\nfrom litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\r\nfrom litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin\r\n\r\nif TYPE_CHECKING:\r\n    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession\r\n\r\n\r\n# the SQLAlchemy base includes a declarative model for you to use in your models.\r\n# The `Base` class includes a `UUID` based primary key (`id`)\r\nclass Author(UUIDBase):\r\n    name: Mapped[str]\r\n    dob: Mapped[date]\r\n    books: Mapped[list[\"Book\"]] = relationship(back_populates=\"author\", lazy=\"selectin\")\r\n\r\n\r\n# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\r\n# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the\r\n# record created, and `updated_at` is the last time the record was modified.\r\nclass Book(UUIDAuditBase):\r\n    title: Mapped[str]\r\n    author_id: Mapped[UUID] = mapped_column(ForeignKey(\"author.id\"))\r\n    author: Mapped[Author] = relationship(lazy=\"joined\", innerjoin=True, viewonly=True)\r\n\r\n\r\nsession_config = AsyncSessionConfig(expire_on_commit=False)\r\nsqlalchemy_config = SQLAlchemyAsyncConfig(\r\n    connection_string=\"sqlite+aiosqlite:///test.sqlite\", session_config=session_config\r\n)  # Create 'async_session' dependency.\r\nsqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)\r\n\r\n\r\nasync def on_startup() -> None:\r\n    \"\"\"Initializes the database.\"\"\"\r\n    async with sqlalchemy_config.get_engine().begin() as conn:\r\n        await conn.run_sync(UUIDBase.metadata.create_all)\r\n        \r\n    #crucially there needs to be an author in the table for the error to appear\r\n    await conn.execute(Author.__table__.insert().values(name=\"F. Scott Fitzgerald\"))\r\n\r\n\r\n@get(path=\"/authors\")\r\nasync def get_authors(db_session: \"AsyncSession\", db_engine: \"AsyncEngine\") -> list[Author]:\r\n    \"\"\"Interact with SQLAlchemy engine and session.\"\"\"\r\n    return list(await db_session.scalars(select(Author)))\r\n\r\n\r\napp = Litestar(\r\n    route_handlers=[get_authors],\r\n    on_startup=[on_startup],\r\n    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],\r\n    debug=True\r\n)\r\n```\r\n\r\n\r\n### Steps to reproduce\r\n\r\n```bash\r\n1. Go to the https://docs.litestar.dev/2/tutorials/repository-tutorial/01-modeling-and-features.html page\r\n2. Download the code\r\n3. Run the demo with minimal requirements installed and go to http://localhost:8000/authors\r\n4. See the error\r\n```\r\n\r\n\r\n### Screenshots\r\n\r\n_No response_\r\n\r\n### Logs\r\n\r\n```bash\r\nFile \"/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py\", line 143, in encode_json\r\n    raise SerializationException(str(msgspec_error)) from msgspec_error\r\nlitestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class '__main__.Author'>\r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py\", line 141, in encode_json\r\n    return msgspec.json.encode(value, enc_hook=serializer) if serializer else _msgspec_json_encoder.encode(value)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py\", line 88, in default_serializer\r\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\r\nTypeError: Unsupported type: <class '__main__.Author'>\r\n \r\nThe above exception was the direct cause of the following exception:\r\n \r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/middleware/exceptions/middleware.py\", line 219, in __call__\r\n    await self.app(scope, receive, send)\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/routes/http.py\", line 82, in handle\r\n    response = await self._get_response_for_request(\r\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/routes/http.py\", line 134, in _get_response_for_request\r\n    return await self._call_handler_function(\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/routes/http.py\", line 158, in _call_handler_function\r\n    response: ASGIApp = await route_handler.to_response(app=scope[\"app\"], data=response_data, request=request)\r\n                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/handlers/http_handlers/base.py\", line 557, in to_response\r\n    return await response_handler(app=app, data=data, request=request)  # type: ignore[call-arg]\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/handlers/http_handlers/_utils.py\", line 79, in handler\r\n    return response.to_asgi_response(app=None, request=request, headers=normalize_headers(headers), cookies=cookies)  # pyright: ignore\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/response/base.py\", line 451, in to_asgi_response\r\n    body=self.render(self.content, media_type, get_serializer(type_encoders)),\r\n         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/response/base.py\", line 392, in render\r\n    return encode_json(content, enc_hook)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/site-packages/litestar/serialization/msgspec_hooks.py\", line 143, in encode_json\r\n    raise SerializationException(str(msgspec_error)) from msgspec_error\r\nlitestar.exceptions.base_exceptions.SerializationException: Unsupported type: <class '__main__.Author'>\r\nINFO:     127.0.0.1:44906 - \"GET /authors HTTP/1.1\" 500 Internal Server Error\r\n```\r\n\r\n\r\n### Litestar Version\r\n\r\n2.8.2\r\n\r\n### Platform\r\n\r\n- [X] Linux\r\n- [X] Mac\r\n- [ ] Windows\r\n- [ ] Other (Please specify in the description above)\r\n\r\n<!-- POLAR PLEDGE BADGE START -->\r\n---\r\n> [!NOTE]  \r\n> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and \r\n> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.\r\n>\r\n> Check out all issues funded or available for funding [on our Polar.sh dashboard](https://polar.sh/litestar-org)\r\n> * If you would like to see an issue prioritized, make a pledge towards it!\r\n> * We receive the pledge once the issue is completed & verified\r\n> * This, along with engagement in the community, helps us know which features are a priority to our users.\r\n\r\n<a href=\"https://polar.sh/litestar-org/litestar/issues/3464\">\r\n<picture>\r\n  <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://polar.sh/api/github/litestar-org/litestar/issues/3464/pledge.svg?darkmode=1\">\r\n  <img alt=\"Fund with Polar\" src=\"https://polar.sh/api/github/litestar-org/litestar/issues/3464/pledge.svg\">\r\n</picture>\r\n</a>\r\n<!-- POLAR PLEDGE BADGE END -->\r\n\n", "before_files": [{"content": "from datetime import date\nfrom typing import TYPE_CHECKING\nfrom uuid import UUID\n\nfrom sqlalchemy import ForeignKey, select\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\n\nfrom litestar import Litestar, get\nfrom litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\nfrom litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyInitPlugin\n\nif TYPE_CHECKING:\n    from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession\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 Author(UUIDBase):\n    name: Mapped[str]\n    dob: Mapped[date]\n    books: Mapped[list[\"Book\"]] = relationship(back_populates=\"author\", lazy=\"selectin\")\n\n\n# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\n# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the\n# record created, and `updated_at` is the last time the record was modified.\nclass Book(UUIDAuditBase):\n    title: Mapped[str]\n    author_id: Mapped[UUID] = mapped_column(ForeignKey(\"author.id\"))\n    author: Mapped[Author] = relationship(lazy=\"joined\", innerjoin=True, viewonly=True)\n\n\nsession_config = AsyncSessionConfig(expire_on_commit=False)\nsqlalchemy_config = SQLAlchemyAsyncConfig(\n    connection_string=\"sqlite+aiosqlite:///test.sqlite\", session_config=session_config\n)  # Create 'async_session' dependency.\nsqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)\n\n\nasync def on_startup() -> None:\n    \"\"\"Initializes the database.\"\"\"\n    async with sqlalchemy_config.get_engine().begin() as conn:\n        await conn.run_sync(UUIDBase.metadata.create_all)\n\n\n@get(path=\"/authors\")\nasync def get_authors(db_session: \"AsyncSession\", db_engine: \"AsyncEngine\") -> list[Author]:\n    \"\"\"Interact with SQLAlchemy engine and session.\"\"\"\n    return list(await db_session.scalars(select(Author)))\n\n\napp = Litestar(\n    route_handlers=[get_authors],\n    on_startup=[on_startup],\n    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],\n)\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py"}], "after_files": [{"content": "from __future__ import annotations\n\nimport uuid\nfrom datetime import date\nfrom typing import List\nfrom uuid import UUID\n\nfrom sqlalchemy import ForeignKey, func, select\nfrom sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\n\nfrom litestar import Litestar, get\nfrom litestar.contrib.sqlalchemy.base import UUIDAuditBase, UUIDBase\nfrom litestar.contrib.sqlalchemy.plugins import AsyncSessionConfig, SQLAlchemyAsyncConfig, SQLAlchemyPlugin\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 Author(UUIDBase):\n    name: Mapped[str]\n    dob: Mapped[date]\n    books: Mapped[List[Book]] = relationship(back_populates=\"author\", lazy=\"selectin\")\n\n\n# The `AuditBase` class includes the same UUID` based primary key (`id`) and 2\n# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the\n# record created, and `updated_at` is the last time the record was modified.\nclass Book(UUIDAuditBase):\n    title: Mapped[str]\n    author_id: Mapped[UUID] = mapped_column(ForeignKey(\"author.id\"))\n    author: Mapped[Author] = relationship(lazy=\"joined\", innerjoin=True, viewonly=True)\n\n\nsession_config = AsyncSessionConfig(expire_on_commit=False)\nsqlalchemy_config = SQLAlchemyAsyncConfig(\n    connection_string=\"sqlite+aiosqlite:///test.sqlite\", session_config=session_config, create_all=True\n)  # Create 'async_session' dependency.\n\n\nasync def on_startup() -> None:\n    \"\"\"Adds some dummy data if no data is present.\"\"\"\n    async with sqlalchemy_config.get_session() as session:\n        statement = select(func.count()).select_from(Author)\n        count = await session.execute(statement)\n        if not count.scalar():\n            author_id = uuid.uuid4()\n            session.add(Author(name=\"Stephen King\", dob=date(1954, 9, 21), id=author_id))\n            session.add(Book(title=\"It\", author_id=author_id))\n            await session.commit()\n\n\n@get(path=\"/authors\")\nasync def get_authors(db_session: AsyncSession, db_engine: AsyncEngine) -> List[Author]:\n    \"\"\"Interact with SQLAlchemy engine and session.\"\"\"\n    return list(await db_session.scalars(select(Author)))\n\n\napp = Litestar(\n    route_handlers=[get_authors],\n    on_startup=[on_startup],\n    debug=True,\n    plugins=[SQLAlchemyPlugin(config=sqlalchemy_config)],\n)\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_declarative_models.py"}]}