We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `litestar/contrib/sqlalchemy/dto.py`
Content:
```
1 from __future__ import annotations
2 
3 from functools import singledispatchmethod
4 from typing import TYPE_CHECKING, Generic, TypeVar
5 
6 from sqlalchemy import Column, inspect, orm, sql
7 from sqlalchemy.ext.associationproxy import AssociationProxy, AssociationProxyExtensionType
8 from sqlalchemy.ext.hybrid import HybridExtensionType, hybrid_property
9 from sqlalchemy.orm import (
10     ColumnProperty,
11     DeclarativeBase,
12     InspectionAttr,
13     Mapped,
14     NotExtension,
15     QueryableAttribute,
16     RelationshipProperty,
17 )
18 
19 from litestar.dto.factory.abc import AbstractDTOFactory
20 from litestar.dto.factory.data_structures import FieldDefinition
21 from litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark
22 from litestar.dto.factory.utils import get_model_type_hints
23 from litestar.types.empty import Empty
24 from litestar.utils.helpers import get_fully_qualified_class_name
25 from litestar.utils.signature import ParsedSignature
26 
27 if TYPE_CHECKING:
28     from typing import Any, ClassVar, Collection, Generator
29 
30     from typing_extensions import TypeAlias
31 
32     from litestar.typing import ParsedType
33 
34 __all__ = ("SQLAlchemyDTO",)
35 
36 T = TypeVar("T", bound="DeclarativeBase | Collection[DeclarativeBase]")
37 ElementType: TypeAlias = "Column[Any] | RelationshipProperty[Any]"
38 
39 SQLA_NS = {**vars(orm), **vars(sql)}
40 
41 
42 class SQLAlchemyDTO(AbstractDTOFactory[T], Generic[T]):
43     """Support for domain modelling with SQLAlchemy."""
44 
45     __slots__ = ()
46 
47     model_type: ClassVar[type[DeclarativeBase]]
48 
49     @singledispatchmethod
50     @classmethod
51     def handle_orm_descriptor(
52         cls,
53         extension_type: NotExtension | AssociationProxyExtensionType | HybridExtensionType,
54         orm_descriptor: InspectionAttr,
55         key: str,
56         model_type_hints: dict[str, ParsedType],
57         model_name: str,
58     ) -> list[FieldDefinition]:
59         raise NotImplementedError(f"Unsupported extension type: {extension_type}")
60 
61     @handle_orm_descriptor.register(NotExtension)
62     @classmethod
63     def _(
64         cls,
65         extension_type: NotExtension,
66         key: str,
67         orm_descriptor: InspectionAttr,
68         model_type_hints: dict[str, ParsedType],
69         model_name: str,
70     ) -> list[FieldDefinition]:
71         if not isinstance(orm_descriptor, QueryableAttribute):
72             raise NotImplementedError(f"Unexpected descriptor type for '{extension_type}': '{orm_descriptor}'")
73 
74         elem: ElementType
75         if isinstance(orm_descriptor.property, ColumnProperty):
76             if not isinstance(orm_descriptor.property.expression, Column):
77                 raise NotImplementedError(f"Expected 'Column', got: '{orm_descriptor.property.expression}'")
78             elem = orm_descriptor.property.expression
79         elif isinstance(orm_descriptor.property, RelationshipProperty):
80             elem = orm_descriptor.property
81         else:
82             raise NotImplementedError(f"Unhandled property type: '{orm_descriptor.property}'")
83 
84         default, default_factory = _detect_defaults(elem)
85 
86         if (parsed_type := model_type_hints[key]).origin is Mapped:
87             (parsed_type,) = parsed_type.inner_types
88         else:
89             raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
90 
91         return [
92             FieldDefinition(
93                 name=key,
94                 default=default,
95                 parsed_type=parsed_type,
96                 default_factory=default_factory,
97                 dto_field=elem.info.get(DTO_FIELD_META_KEY, DTOField()),
98                 unique_model_name=model_name,
99                 dto_for=None,
100             )
101         ]
102 
103     @handle_orm_descriptor.register(AssociationProxyExtensionType)
104     @classmethod
105     def _(
106         cls,
107         extension_type: AssociationProxyExtensionType,
108         key: str,
109         orm_descriptor: InspectionAttr,
110         model_type_hints: dict[str, ParsedType],
111         model_name: str,
112     ) -> list[FieldDefinition]:
113         if not isinstance(orm_descriptor, AssociationProxy):
114             raise NotImplementedError(f"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'")
115 
116         if (parsed_type := model_type_hints[key]).origin is AssociationProxy:
117             (parsed_type,) = parsed_type.inner_types
118         else:
119             raise NotImplementedError(f"Expected 'AssociationProxy' origin, got: '{parsed_type.origin}'")
120 
121         return [
122             FieldDefinition(
123                 name=key,
124                 default=Empty,
125                 parsed_type=parsed_type,
126                 default_factory=None,
127                 dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),
128                 unique_model_name=model_name,
129                 dto_for=None,
130             )
131         ]
132 
133     @handle_orm_descriptor.register(HybridExtensionType)
134     @classmethod
135     def _(
136         cls,
137         extension_type: HybridExtensionType,
138         key: str,
139         orm_descriptor: InspectionAttr,
140         model_type_hints: dict[str, ParsedType],
141         model_name: str,
142     ) -> list[FieldDefinition]:
143         if not isinstance(orm_descriptor, hybrid_property):
144             raise NotImplementedError(f"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'")
145 
146         getter_sig = ParsedSignature.from_fn(orm_descriptor.fget, {})
147 
148         field_defs = [
149             FieldDefinition(
150                 name=orm_descriptor.__name__,
151                 default=Empty,
152                 parsed_type=getter_sig.return_type,
153                 default_factory=None,
154                 dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),
155                 unique_model_name=model_name,
156                 dto_for="return",
157             )
158         ]
159 
160         if orm_descriptor.fset is not None:
161             setter_sig = ParsedSignature.from_fn(orm_descriptor.fset, {})
162             field_defs.append(
163                 FieldDefinition(
164                     name=orm_descriptor.__name__,
165                     default=Empty,
166                     parsed_type=next(iter(setter_sig.parameters.values())).parsed_type,
167                     default_factory=None,
168                     dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.WRITE_ONLY)),
169                     unique_model_name=model_name,
170                     dto_for="data",
171                 )
172             )
173 
174         return field_defs
175 
176     @classmethod
177     def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Generator[FieldDefinition, None, None]:
178         if (mapper := inspect(model_type)) is None:  # pragma: no cover
179             raise RuntimeError("Unexpected `None` value for mapper.")
180 
181         # includes SQLAlchemy names and other mapped class names in the forward reference resolution namespace
182         namespace = {**SQLA_NS, **{m.class_.__name__: m.class_ for m in mapper.registry.mappers if m is not mapper}}
183         model_type_hints = get_model_type_hints(model_type, namespace=namespace)
184         model_name = get_fully_qualified_class_name(model_type)
185 
186         # the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once
187         # for each method name it is bound to. We only need to see it once, so track views of it here.
188         seen_hybrid_descriptors: set[hybrid_property] = set()
189         for key, orm_descriptor in mapper.all_orm_descriptors.items():
190             if isinstance(orm_descriptor, hybrid_property):
191                 if orm_descriptor in seen_hybrid_descriptors:
192                     continue
193                 seen_hybrid_descriptors.add(orm_descriptor)
194 
195             yield from cls.handle_orm_descriptor(
196                 orm_descriptor.extension_type, key, orm_descriptor, model_type_hints, model_name
197             )
198 
199     @classmethod
200     def detect_nested_field(cls, parsed_type: ParsedType) -> bool:
201         return parsed_type.is_subclass_of(DeclarativeBase)
202 
203 
204 def _detect_defaults(elem: ElementType) -> tuple[Any, Any]:
205     default: Any = Empty
206     default_factory: Any = None  # pyright:ignore
207     if sqla_default := getattr(elem, "default", None):
208         if sqla_default.is_scalar:
209             default = sqla_default.arg
210         elif sqla_default.is_callable:
211 
212             def default_factory(d: Any = sqla_default) -> Any:
213                 return d.arg({})
214 
215         else:
216             raise ValueError("Unexpected default type")
217     else:
218         if getattr(elem, "nullable", False):
219             default = None
220     return default, default_factory
221
```
--- 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/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py
--- a/litestar/contrib/sqlalchemy/dto.py
+++ b/litestar/contrib/sqlalchemy/dto.py
@@ -20,6 +20,7 @@
 from litestar.dto.factory.data_structures import FieldDefinition
 from litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark
 from litestar.dto.factory.utils import get_model_type_hints
+from litestar.exceptions import ImproperlyConfiguredException
 from litestar.types.empty import Empty
 from litestar.utils.helpers import get_fully_qualified_class_name
 from litestar.utils.signature import ParsedSignature
@@ -83,10 +84,15 @@
 
         default, default_factory = _detect_defaults(elem)
 
-        if (parsed_type := model_type_hints[key]).origin is Mapped:
-            (parsed_type,) = parsed_type.inner_types
-        else:
-            raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
+        try:
+            if (parsed_type := model_type_hints[key]).origin is Mapped:
+                (parsed_type,) = parsed_type.inner_types
+            else:
+                raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
+        except KeyError as e:
+            raise ImproperlyConfiguredException(
+                f"No type information found for '{orm_descriptor}'. Has a type annotation been added to the column?"
+            ) from e
 
         return [
             FieldDefinition(

{"golden_diff": "diff --git a/litestar/contrib/sqlalchemy/dto.py b/litestar/contrib/sqlalchemy/dto.py\n--- a/litestar/contrib/sqlalchemy/dto.py\n+++ b/litestar/contrib/sqlalchemy/dto.py\n@@ -20,6 +20,7 @@\n from litestar.dto.factory.data_structures import FieldDefinition\n from litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark\n from litestar.dto.factory.utils import get_model_type_hints\n+from litestar.exceptions import ImproperlyConfiguredException\n from litestar.types.empty import Empty\n from litestar.utils.helpers import get_fully_qualified_class_name\n from litestar.utils.signature import ParsedSignature\n@@ -83,10 +84,15 @@\n \n         default, default_factory = _detect_defaults(elem)\n \n-        if (parsed_type := model_type_hints[key]).origin is Mapped:\n-            (parsed_type,) = parsed_type.inner_types\n-        else:\n-            raise NotImplementedError(f\"Expected 'Mapped' origin, got: '{parsed_type.origin}'\")\n+        try:\n+            if (parsed_type := model_type_hints[key]).origin is Mapped:\n+                (parsed_type,) = parsed_type.inner_types\n+            else:\n+                raise NotImplementedError(f\"Expected 'Mapped' origin, got: '{parsed_type.origin}'\")\n+        except KeyError as e:\n+            raise ImproperlyConfiguredException(\n+                f\"No type information found for '{orm_descriptor}'. Has a type annotation been added to the column?\"\n+            ) from e\n \n         return [\n             FieldDefinition(\n", "issue": "StaticFilesConfig and virtual directories\nI'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. \r\n\r\nThis is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.\r\n\r\nhttps://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom functools import singledispatchmethod\nfrom typing import TYPE_CHECKING, Generic, TypeVar\n\nfrom sqlalchemy import Column, inspect, orm, sql\nfrom sqlalchemy.ext.associationproxy import AssociationProxy, AssociationProxyExtensionType\nfrom sqlalchemy.ext.hybrid import HybridExtensionType, hybrid_property\nfrom sqlalchemy.orm import (\n    ColumnProperty,\n    DeclarativeBase,\n    InspectionAttr,\n    Mapped,\n    NotExtension,\n    QueryableAttribute,\n    RelationshipProperty,\n)\n\nfrom litestar.dto.factory.abc import AbstractDTOFactory\nfrom litestar.dto.factory.data_structures import FieldDefinition\nfrom litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark\nfrom litestar.dto.factory.utils import get_model_type_hints\nfrom litestar.types.empty import Empty\nfrom litestar.utils.helpers import get_fully_qualified_class_name\nfrom litestar.utils.signature import ParsedSignature\n\nif TYPE_CHECKING:\n    from typing import Any, ClassVar, Collection, Generator\n\n    from typing_extensions import TypeAlias\n\n    from litestar.typing import ParsedType\n\n__all__ = (\"SQLAlchemyDTO\",)\n\nT = TypeVar(\"T\", bound=\"DeclarativeBase | Collection[DeclarativeBase]\")\nElementType: TypeAlias = \"Column[Any] | RelationshipProperty[Any]\"\n\nSQLA_NS = {**vars(orm), **vars(sql)}\n\n\nclass SQLAlchemyDTO(AbstractDTOFactory[T], Generic[T]):\n    \"\"\"Support for domain modelling with SQLAlchemy.\"\"\"\n\n    __slots__ = ()\n\n    model_type: ClassVar[type[DeclarativeBase]]\n\n    @singledispatchmethod\n    @classmethod\n    def handle_orm_descriptor(\n        cls,\n        extension_type: NotExtension | AssociationProxyExtensionType | HybridExtensionType,\n        orm_descriptor: InspectionAttr,\n        key: str,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        raise NotImplementedError(f\"Unsupported extension type: {extension_type}\")\n\n    @handle_orm_descriptor.register(NotExtension)\n    @classmethod\n    def _(\n        cls,\n        extension_type: NotExtension,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, QueryableAttribute):\n            raise NotImplementedError(f\"Unexpected descriptor type for '{extension_type}': '{orm_descriptor}'\")\n\n        elem: ElementType\n        if isinstance(orm_descriptor.property, ColumnProperty):\n            if not isinstance(orm_descriptor.property.expression, Column):\n                raise NotImplementedError(f\"Expected 'Column', got: '{orm_descriptor.property.expression}'\")\n            elem = orm_descriptor.property.expression\n        elif isinstance(orm_descriptor.property, RelationshipProperty):\n            elem = orm_descriptor.property\n        else:\n            raise NotImplementedError(f\"Unhandled property type: '{orm_descriptor.property}'\")\n\n        default, default_factory = _detect_defaults(elem)\n\n        if (parsed_type := model_type_hints[key]).origin is Mapped:\n            (parsed_type,) = parsed_type.inner_types\n        else:\n            raise NotImplementedError(f\"Expected 'Mapped' origin, got: '{parsed_type.origin}'\")\n\n        return [\n            FieldDefinition(\n                name=key,\n                default=default,\n                parsed_type=parsed_type,\n                default_factory=default_factory,\n                dto_field=elem.info.get(DTO_FIELD_META_KEY, DTOField()),\n                unique_model_name=model_name,\n                dto_for=None,\n            )\n        ]\n\n    @handle_orm_descriptor.register(AssociationProxyExtensionType)\n    @classmethod\n    def _(\n        cls,\n        extension_type: AssociationProxyExtensionType,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, AssociationProxy):\n            raise NotImplementedError(f\"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'\")\n\n        if (parsed_type := model_type_hints[key]).origin is AssociationProxy:\n            (parsed_type,) = parsed_type.inner_types\n        else:\n            raise NotImplementedError(f\"Expected 'AssociationProxy' origin, got: '{parsed_type.origin}'\")\n\n        return [\n            FieldDefinition(\n                name=key,\n                default=Empty,\n                parsed_type=parsed_type,\n                default_factory=None,\n                dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),\n                unique_model_name=model_name,\n                dto_for=None,\n            )\n        ]\n\n    @handle_orm_descriptor.register(HybridExtensionType)\n    @classmethod\n    def _(\n        cls,\n        extension_type: HybridExtensionType,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, hybrid_property):\n            raise NotImplementedError(f\"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'\")\n\n        getter_sig = ParsedSignature.from_fn(orm_descriptor.fget, {})\n\n        field_defs = [\n            FieldDefinition(\n                name=orm_descriptor.__name__,\n                default=Empty,\n                parsed_type=getter_sig.return_type,\n                default_factory=None,\n                dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),\n                unique_model_name=model_name,\n                dto_for=\"return\",\n            )\n        ]\n\n        if orm_descriptor.fset is not None:\n            setter_sig = ParsedSignature.from_fn(orm_descriptor.fset, {})\n            field_defs.append(\n                FieldDefinition(\n                    name=orm_descriptor.__name__,\n                    default=Empty,\n                    parsed_type=next(iter(setter_sig.parameters.values())).parsed_type,\n                    default_factory=None,\n                    dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.WRITE_ONLY)),\n                    unique_model_name=model_name,\n                    dto_for=\"data\",\n                )\n            )\n\n        return field_defs\n\n    @classmethod\n    def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Generator[FieldDefinition, None, None]:\n        if (mapper := inspect(model_type)) is None:  # pragma: no cover\n            raise RuntimeError(\"Unexpected `None` value for mapper.\")\n\n        # includes SQLAlchemy names and other mapped class names in the forward reference resolution namespace\n        namespace = {**SQLA_NS, **{m.class_.__name__: m.class_ for m in mapper.registry.mappers if m is not mapper}}\n        model_type_hints = get_model_type_hints(model_type, namespace=namespace)\n        model_name = get_fully_qualified_class_name(model_type)\n\n        # the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once\n        # for each method name it is bound to. We only need to see it once, so track views of it here.\n        seen_hybrid_descriptors: set[hybrid_property] = set()\n        for key, orm_descriptor in mapper.all_orm_descriptors.items():\n            if isinstance(orm_descriptor, hybrid_property):\n                if orm_descriptor in seen_hybrid_descriptors:\n                    continue\n                seen_hybrid_descriptors.add(orm_descriptor)\n\n            yield from cls.handle_orm_descriptor(\n                orm_descriptor.extension_type, key, orm_descriptor, model_type_hints, model_name\n            )\n\n    @classmethod\n    def detect_nested_field(cls, parsed_type: ParsedType) -> bool:\n        return parsed_type.is_subclass_of(DeclarativeBase)\n\n\ndef _detect_defaults(elem: ElementType) -> tuple[Any, Any]:\n    default: Any = Empty\n    default_factory: Any = None  # pyright:ignore\n    if sqla_default := getattr(elem, \"default\", None):\n        if sqla_default.is_scalar:\n            default = sqla_default.arg\n        elif sqla_default.is_callable:\n\n            def default_factory(d: Any = sqla_default) -> Any:\n                return d.arg({})\n\n        else:\n            raise ValueError(\"Unexpected default type\")\n    else:\n        if getattr(elem, \"nullable\", False):\n            default = None\n    return default, default_factory\n", "path": "litestar/contrib/sqlalchemy/dto.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom functools import singledispatchmethod\nfrom typing import TYPE_CHECKING, Generic, TypeVar\n\nfrom sqlalchemy import Column, inspect, orm, sql\nfrom sqlalchemy.ext.associationproxy import AssociationProxy, AssociationProxyExtensionType\nfrom sqlalchemy.ext.hybrid import HybridExtensionType, hybrid_property\nfrom sqlalchemy.orm import (\n    ColumnProperty,\n    DeclarativeBase,\n    InspectionAttr,\n    Mapped,\n    NotExtension,\n    QueryableAttribute,\n    RelationshipProperty,\n)\n\nfrom litestar.dto.factory.abc import AbstractDTOFactory\nfrom litestar.dto.factory.data_structures import FieldDefinition\nfrom litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark\nfrom litestar.dto.factory.utils import get_model_type_hints\nfrom litestar.exceptions import ImproperlyConfiguredException\nfrom litestar.types.empty import Empty\nfrom litestar.utils.helpers import get_fully_qualified_class_name\nfrom litestar.utils.signature import ParsedSignature\n\nif TYPE_CHECKING:\n    from typing import Any, ClassVar, Collection, Generator\n\n    from typing_extensions import TypeAlias\n\n    from litestar.typing import ParsedType\n\n__all__ = (\"SQLAlchemyDTO\",)\n\nT = TypeVar(\"T\", bound=\"DeclarativeBase | Collection[DeclarativeBase]\")\nElementType: TypeAlias = \"Column[Any] | RelationshipProperty[Any]\"\n\nSQLA_NS = {**vars(orm), **vars(sql)}\n\n\nclass SQLAlchemyDTO(AbstractDTOFactory[T], Generic[T]):\n    \"\"\"Support for domain modelling with SQLAlchemy.\"\"\"\n\n    __slots__ = ()\n\n    model_type: ClassVar[type[DeclarativeBase]]\n\n    @singledispatchmethod\n    @classmethod\n    def handle_orm_descriptor(\n        cls,\n        extension_type: NotExtension | AssociationProxyExtensionType | HybridExtensionType,\n        orm_descriptor: InspectionAttr,\n        key: str,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        raise NotImplementedError(f\"Unsupported extension type: {extension_type}\")\n\n    @handle_orm_descriptor.register(NotExtension)\n    @classmethod\n    def _(\n        cls,\n        extension_type: NotExtension,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, QueryableAttribute):\n            raise NotImplementedError(f\"Unexpected descriptor type for '{extension_type}': '{orm_descriptor}'\")\n\n        elem: ElementType\n        if isinstance(orm_descriptor.property, ColumnProperty):\n            if not isinstance(orm_descriptor.property.expression, Column):\n                raise NotImplementedError(f\"Expected 'Column', got: '{orm_descriptor.property.expression}'\")\n            elem = orm_descriptor.property.expression\n        elif isinstance(orm_descriptor.property, RelationshipProperty):\n            elem = orm_descriptor.property\n        else:\n            raise NotImplementedError(f\"Unhandled property type: '{orm_descriptor.property}'\")\n\n        default, default_factory = _detect_defaults(elem)\n\n        try:\n            if (parsed_type := model_type_hints[key]).origin is Mapped:\n                (parsed_type,) = parsed_type.inner_types\n            else:\n                raise NotImplementedError(f\"Expected 'Mapped' origin, got: '{parsed_type.origin}'\")\n        except KeyError as e:\n            raise ImproperlyConfiguredException(\n                f\"No type information found for '{orm_descriptor}'. Has a type annotation been added to the column?\"\n            ) from e\n\n        return [\n            FieldDefinition(\n                name=key,\n                default=default,\n                parsed_type=parsed_type,\n                default_factory=default_factory,\n                dto_field=elem.info.get(DTO_FIELD_META_KEY, DTOField()),\n                unique_model_name=model_name,\n                dto_for=None,\n            )\n        ]\n\n    @handle_orm_descriptor.register(AssociationProxyExtensionType)\n    @classmethod\n    def _(\n        cls,\n        extension_type: AssociationProxyExtensionType,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, AssociationProxy):\n            raise NotImplementedError(f\"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'\")\n\n        if (parsed_type := model_type_hints[key]).origin is AssociationProxy:\n            (parsed_type,) = parsed_type.inner_types\n        else:\n            raise NotImplementedError(f\"Expected 'AssociationProxy' origin, got: '{parsed_type.origin}'\")\n\n        return [\n            FieldDefinition(\n                name=key,\n                default=Empty,\n                parsed_type=parsed_type,\n                default_factory=None,\n                dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),\n                unique_model_name=model_name,\n                dto_for=None,\n            )\n        ]\n\n    @handle_orm_descriptor.register(HybridExtensionType)\n    @classmethod\n    def _(\n        cls,\n        extension_type: HybridExtensionType,\n        key: str,\n        orm_descriptor: InspectionAttr,\n        model_type_hints: dict[str, ParsedType],\n        model_name: str,\n    ) -> list[FieldDefinition]:\n        if not isinstance(orm_descriptor, hybrid_property):\n            raise NotImplementedError(f\"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'\")\n\n        getter_sig = ParsedSignature.from_fn(orm_descriptor.fget, {})\n\n        field_defs = [\n            FieldDefinition(\n                name=orm_descriptor.__name__,\n                default=Empty,\n                parsed_type=getter_sig.return_type,\n                default_factory=None,\n                dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),\n                unique_model_name=model_name,\n                dto_for=\"return\",\n            )\n        ]\n\n        if orm_descriptor.fset is not None:\n            setter_sig = ParsedSignature.from_fn(orm_descriptor.fset, {})\n            field_defs.append(\n                FieldDefinition(\n                    name=orm_descriptor.__name__,\n                    default=Empty,\n                    parsed_type=next(iter(setter_sig.parameters.values())).parsed_type,\n                    default_factory=None,\n                    dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.WRITE_ONLY)),\n                    unique_model_name=model_name,\n                    dto_for=\"data\",\n                )\n            )\n\n        return field_defs\n\n    @classmethod\n    def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Generator[FieldDefinition, None, None]:\n        if (mapper := inspect(model_type)) is None:  # pragma: no cover\n            raise RuntimeError(\"Unexpected `None` value for mapper.\")\n\n        # includes SQLAlchemy names and other mapped class names in the forward reference resolution namespace\n        namespace = {**SQLA_NS, **{m.class_.__name__: m.class_ for m in mapper.registry.mappers if m is not mapper}}\n        model_type_hints = get_model_type_hints(model_type, namespace=namespace)\n        model_name = get_fully_qualified_class_name(model_type)\n\n        # the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once\n        # for each method name it is bound to. We only need to see it once, so track views of it here.\n        seen_hybrid_descriptors: set[hybrid_property] = set()\n        for key, orm_descriptor in mapper.all_orm_descriptors.items():\n            if isinstance(orm_descriptor, hybrid_property):\n                if orm_descriptor in seen_hybrid_descriptors:\n                    continue\n                seen_hybrid_descriptors.add(orm_descriptor)\n\n            yield from cls.handle_orm_descriptor(\n                orm_descriptor.extension_type, key, orm_descriptor, model_type_hints, model_name\n            )\n\n    @classmethod\n    def detect_nested_field(cls, parsed_type: ParsedType) -> bool:\n        return parsed_type.is_subclass_of(DeclarativeBase)\n\n\ndef _detect_defaults(elem: ElementType) -> tuple[Any, Any]:\n    default: Any = Empty\n    default_factory: Any = None  # pyright:ignore\n    if sqla_default := getattr(elem, \"default\", None):\n        if sqla_default.is_scalar:\n            default = sqla_default.arg\n        elif sqla_default.is_callable:\n\n            def default_factory(d: Any = sqla_default) -> Any:\n                return d.arg({})\n\n        else:\n            raise ValueError(\"Unexpected default type\")\n    else:\n        if getattr(elem, \"nullable\", False):\n            default = None\n    return default, default_factory\n", "path": "litestar/contrib/sqlalchemy/dto.py"}]}