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, Optional, 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     RelationshipDirection,
17     RelationshipProperty,
18 )
19 
20 from litestar.dto.factory.abc import AbstractDTOFactory
21 from litestar.dto.factory.data_structures import FieldDefinition
22 from litestar.dto.factory.field import DTO_FIELD_META_KEY, DTOField, Mark
23 from litestar.dto.factory.utils import get_model_type_hints
24 from litestar.exceptions import ImproperlyConfiguredException
25 from litestar.types.empty import Empty
26 from litestar.typing import ParsedType
27 from litestar.utils.helpers import get_fully_qualified_class_name
28 from litestar.utils.signature import ParsedSignature
29 
30 if TYPE_CHECKING:
31     from typing import Any, ClassVar, Collection, Generator
32 
33     from typing_extensions import TypeAlias
34 
35 __all__ = ("SQLAlchemyDTO",)
36 
37 T = TypeVar("T", bound="DeclarativeBase | Collection[DeclarativeBase]")
38 ElementType: TypeAlias = "Column[Any] | RelationshipProperty[Any]"
39 
40 SQLA_NS = {**vars(orm), **vars(sql)}
41 
42 
43 class SQLAlchemyDTO(AbstractDTOFactory[T], Generic[T]):
44     """Support for domain modelling with SQLAlchemy."""
45 
46     __slots__ = ()
47 
48     model_type: ClassVar[type[DeclarativeBase]]
49 
50     @singledispatchmethod
51     @classmethod
52     def handle_orm_descriptor(
53         cls,
54         extension_type: NotExtension | AssociationProxyExtensionType | HybridExtensionType,
55         orm_descriptor: InspectionAttr,
56         key: str,
57         model_type_hints: dict[str, ParsedType],
58         model_name: str,
59     ) -> list[FieldDefinition]:
60         raise NotImplementedError(f"Unsupported extension type: {extension_type}")
61 
62     @handle_orm_descriptor.register(NotExtension)
63     @classmethod
64     def _(
65         cls,
66         extension_type: NotExtension,
67         key: str,
68         orm_descriptor: InspectionAttr,
69         model_type_hints: dict[str, ParsedType],
70         model_name: str,
71     ) -> list[FieldDefinition]:
72         if not isinstance(orm_descriptor, QueryableAttribute):
73             raise NotImplementedError(f"Unexpected descriptor type for '{extension_type}': '{orm_descriptor}'")
74 
75         elem: ElementType
76         if isinstance(orm_descriptor.property, ColumnProperty):
77             if not isinstance(orm_descriptor.property.expression, Column):
78                 raise NotImplementedError(f"Expected 'Column', got: '{orm_descriptor.property.expression}'")
79             elem = orm_descriptor.property.expression
80         elif isinstance(orm_descriptor.property, RelationshipProperty):
81             elem = orm_descriptor.property
82         else:
83             raise NotImplementedError(f"Unhandled property type: '{orm_descriptor.property}'")
84 
85         default, default_factory = _detect_defaults(elem)
86 
87         try:
88             if (parsed_type := model_type_hints[key]).origin is Mapped:
89                 (parsed_type,) = parsed_type.inner_types
90             else:
91                 raise NotImplementedError(f"Expected 'Mapped' origin, got: '{parsed_type.origin}'")
92         except KeyError:
93             parsed_type = parse_type_from_element(elem)
94 
95         return [
96             FieldDefinition(
97                 name=key,
98                 default=default,
99                 parsed_type=parsed_type,
100                 default_factory=default_factory,
101                 dto_field=elem.info.get(DTO_FIELD_META_KEY, DTOField()),
102                 unique_model_name=model_name,
103                 dto_for=None,
104             )
105         ]
106 
107     @handle_orm_descriptor.register(AssociationProxyExtensionType)
108     @classmethod
109     def _(
110         cls,
111         extension_type: AssociationProxyExtensionType,
112         key: str,
113         orm_descriptor: InspectionAttr,
114         model_type_hints: dict[str, ParsedType],
115         model_name: str,
116     ) -> list[FieldDefinition]:
117         if not isinstance(orm_descriptor, AssociationProxy):
118             raise NotImplementedError(f"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'")
119 
120         if (parsed_type := model_type_hints[key]).origin is AssociationProxy:
121             (parsed_type,) = parsed_type.inner_types
122         else:
123             raise NotImplementedError(f"Expected 'AssociationProxy' origin, got: '{parsed_type.origin}'")
124 
125         return [
126             FieldDefinition(
127                 name=key,
128                 default=Empty,
129                 parsed_type=parsed_type,
130                 default_factory=None,
131                 dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),
132                 unique_model_name=model_name,
133                 dto_for=None,
134             )
135         ]
136 
137     @handle_orm_descriptor.register(HybridExtensionType)
138     @classmethod
139     def _(
140         cls,
141         extension_type: HybridExtensionType,
142         key: str,
143         orm_descriptor: InspectionAttr,
144         model_type_hints: dict[str, ParsedType],
145         model_name: str,
146     ) -> list[FieldDefinition]:
147         if not isinstance(orm_descriptor, hybrid_property):
148             raise NotImplementedError(f"Unexpected descriptor type '{orm_descriptor}' for '{extension_type}'")
149 
150         getter_sig = ParsedSignature.from_fn(orm_descriptor.fget, {})
151 
152         field_defs = [
153             FieldDefinition(
154                 name=orm_descriptor.__name__,
155                 default=Empty,
156                 parsed_type=getter_sig.return_type,
157                 default_factory=None,
158                 dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.READ_ONLY)),
159                 unique_model_name=model_name,
160                 dto_for="return",
161             )
162         ]
163 
164         if orm_descriptor.fset is not None:
165             setter_sig = ParsedSignature.from_fn(orm_descriptor.fset, {})
166             field_defs.append(
167                 FieldDefinition(
168                     name=orm_descriptor.__name__,
169                     default=Empty,
170                     parsed_type=next(iter(setter_sig.parameters.values())).parsed_type,
171                     default_factory=None,
172                     dto_field=orm_descriptor.info.get(DTO_FIELD_META_KEY, DTOField(mark=Mark.WRITE_ONLY)),
173                     unique_model_name=model_name,
174                     dto_for="data",
175                 )
176             )
177 
178         return field_defs
179 
180     @classmethod
181     def generate_field_definitions(cls, model_type: type[DeclarativeBase]) -> Generator[FieldDefinition, None, None]:
182         if (mapper := inspect(model_type)) is None:  # pragma: no cover
183             raise RuntimeError("Unexpected `None` value for mapper.")
184 
185         # includes SQLAlchemy names and other mapped class names in the forward reference resolution namespace
186         namespace = {**SQLA_NS, **{m.class_.__name__: m.class_ for m in mapper.registry.mappers if m is not mapper}}
187         model_type_hints = get_model_type_hints(model_type, namespace=namespace)
188         model_name = get_fully_qualified_class_name(model_type)
189 
190         # the same hybrid property descriptor can be included in `all_orm_descriptors` multiple times, once
191         # for each method name it is bound to. We only need to see it once, so track views of it here.
192         seen_hybrid_descriptors: set[hybrid_property] = set()
193         for key, orm_descriptor in mapper.all_orm_descriptors.items():
194             if isinstance(orm_descriptor, hybrid_property):
195                 if orm_descriptor in seen_hybrid_descriptors:
196                     continue
197                 seen_hybrid_descriptors.add(orm_descriptor)
198 
199             yield from cls.handle_orm_descriptor(
200                 orm_descriptor.extension_type, key, orm_descriptor, model_type_hints, model_name
201             )
202 
203     @classmethod
204     def detect_nested_field(cls, parsed_type: ParsedType) -> bool:
205         return parsed_type.is_subclass_of(DeclarativeBase)
206 
207 
208 def _detect_defaults(elem: ElementType) -> tuple[Any, Any]:
209     default: Any = Empty
210     default_factory: Any = None  # pyright:ignore
211     if sqla_default := getattr(elem, "default", None):
212         if sqla_default.is_scalar:
213             default = sqla_default.arg
214         elif sqla_default.is_callable:
215 
216             def default_factory(d: Any = sqla_default) -> Any:
217                 return d.arg({})
218 
219         else:
220             raise ValueError("Unexpected default type")
221     else:
222         if (
223             isinstance(elem, RelationshipProperty)
224             and detect_nullable_relationship(elem)
225             or getattr(elem, "nullable", False)
226         ):
227             default = None
228 
229     return default, default_factory
230 
231 
232 def parse_type_from_element(elem: ElementType) -> ParsedType:
233     """Parses a type from a SQLAlchemy element.
234 
235     Args:
236         elem: The SQLAlchemy element to parse.
237 
238     Returns:
239         ParsedType: The parsed type.
240 
241     Raises:
242         ImproperlyConfiguredException: If the type cannot be parsed.
243     """
244 
245     if isinstance(elem, Column):
246         if elem.nullable:
247             return ParsedType(Optional[elem.type.python_type])
248         return ParsedType(elem.type.python_type)
249 
250     if isinstance(elem, RelationshipProperty):
251         if elem.direction in (RelationshipDirection.ONETOMANY, RelationshipDirection.MANYTOMANY):
252             collection_type = ParsedType(elem.collection_class or list)
253             return ParsedType(collection_type.safe_generic_origin[elem.mapper.class_])
254 
255         if detect_nullable_relationship(elem):
256             return ParsedType(Optional[elem.mapper.class_])
257 
258         return ParsedType(elem.mapper.class_)
259 
260     raise ImproperlyConfiguredException(
261         f"Unable to parse type from element '{elem}'. Consider adding a type hint.",
262     )
263 
264 
265 def detect_nullable_relationship(elem: RelationshipProperty) -> bool:
266     """Detects if a relationship is nullable.
267 
268     This attempts to decide if we should allow a ``None`` default value for a relationship by looking at the
269     foreign key fields. If all foreign key fields are nullable, then we allow a ``None`` default value.
270 
271     Args:
272         elem: The relationship to check.
273 
274     Returns:
275         bool: ``True`` if the relationship is nullable, ``False`` otherwise.
276     """
277     return elem.direction == RelationshipDirection.MANYTOONE and all(c.nullable for c in elem.local_columns)
278
```
--- 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
@@ -216,6 +216,11 @@
             def default_factory(d: Any = sqla_default) -> Any:
                 return d.arg({})
 
+        elif sqla_default.is_sequence:
+            # SQLAlchemy sequences represent server side defaults
+            # so we cannot infer a reasonable default value for
+            # them on the client side
+            pass
         else:
             raise ValueError("Unexpected default type")
     else:

{"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@@ -216,6 +216,11 @@\n             def default_factory(d: Any = sqla_default) -> Any:\n                 return d.arg({})\n \n+        elif sqla_default.is_sequence:\n+            # SQLAlchemy sequences represent server side defaults\n+            # so we cannot infer a reasonable default value for\n+            # them on the client side\n+            pass\n         else:\n             raise ValueError(\"Unexpected default type\")\n     else:\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, Optional, 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    RelationshipDirection,\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.typing import ParsedType\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__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:\n            parsed_type = parse_type_from_element(elem)\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 (\n            isinstance(elem, RelationshipProperty)\n            and detect_nullable_relationship(elem)\n            or getattr(elem, \"nullable\", False)\n        ):\n            default = None\n\n    return default, default_factory\n\n\ndef parse_type_from_element(elem: ElementType) -> ParsedType:\n    \"\"\"Parses a type from a SQLAlchemy element.\n\n    Args:\n        elem: The SQLAlchemy element to parse.\n\n    Returns:\n        ParsedType: The parsed type.\n\n    Raises:\n        ImproperlyConfiguredException: If the type cannot be parsed.\n    \"\"\"\n\n    if isinstance(elem, Column):\n        if elem.nullable:\n            return ParsedType(Optional[elem.type.python_type])\n        return ParsedType(elem.type.python_type)\n\n    if isinstance(elem, RelationshipProperty):\n        if elem.direction in (RelationshipDirection.ONETOMANY, RelationshipDirection.MANYTOMANY):\n            collection_type = ParsedType(elem.collection_class or list)\n            return ParsedType(collection_type.safe_generic_origin[elem.mapper.class_])\n\n        if detect_nullable_relationship(elem):\n            return ParsedType(Optional[elem.mapper.class_])\n\n        return ParsedType(elem.mapper.class_)\n\n    raise ImproperlyConfiguredException(\n        f\"Unable to parse type from element '{elem}'. Consider adding a type hint.\",\n    )\n\n\ndef detect_nullable_relationship(elem: RelationshipProperty) -> bool:\n    \"\"\"Detects if a relationship is nullable.\n\n    This attempts to decide if we should allow a ``None`` default value for a relationship by looking at the\n    foreign key fields. If all foreign key fields are nullable, then we allow a ``None`` default value.\n\n    Args:\n        elem: The relationship to check.\n\n    Returns:\n        bool: ``True`` if the relationship is nullable, ``False`` otherwise.\n    \"\"\"\n    return elem.direction == RelationshipDirection.MANYTOONE and all(c.nullable for c in elem.local_columns)\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, Optional, 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    RelationshipDirection,\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.typing import ParsedType\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__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:\n            parsed_type = parse_type_from_element(elem)\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        elif sqla_default.is_sequence:\n            # SQLAlchemy sequences represent server side defaults\n            # so we cannot infer a reasonable default value for\n            # them on the client side\n            pass\n        else:\n            raise ValueError(\"Unexpected default type\")\n    else:\n        if (\n            isinstance(elem, RelationshipProperty)\n            and detect_nullable_relationship(elem)\n            or getattr(elem, \"nullable\", False)\n        ):\n            default = None\n\n    return default, default_factory\n\n\ndef parse_type_from_element(elem: ElementType) -> ParsedType:\n    \"\"\"Parses a type from a SQLAlchemy element.\n\n    Args:\n        elem: The SQLAlchemy element to parse.\n\n    Returns:\n        ParsedType: The parsed type.\n\n    Raises:\n        ImproperlyConfiguredException: If the type cannot be parsed.\n    \"\"\"\n\n    if isinstance(elem, Column):\n        if elem.nullable:\n            return ParsedType(Optional[elem.type.python_type])\n        return ParsedType(elem.type.python_type)\n\n    if isinstance(elem, RelationshipProperty):\n        if elem.direction in (RelationshipDirection.ONETOMANY, RelationshipDirection.MANYTOMANY):\n            collection_type = ParsedType(elem.collection_class or list)\n            return ParsedType(collection_type.safe_generic_origin[elem.mapper.class_])\n\n        if detect_nullable_relationship(elem):\n            return ParsedType(Optional[elem.mapper.class_])\n\n        return ParsedType(elem.mapper.class_)\n\n    raise ImproperlyConfiguredException(\n        f\"Unable to parse type from element '{elem}'. Consider adding a type hint.\",\n    )\n\n\ndef detect_nullable_relationship(elem: RelationshipProperty) -> bool:\n    \"\"\"Detects if a relationship is nullable.\n\n    This attempts to decide if we should allow a ``None`` default value for a relationship by looking at the\n    foreign key fields. If all foreign key fields are nullable, then we allow a ``None`` default value.\n\n    Args:\n        elem: The relationship to check.\n\n    Returns:\n        bool: ``True`` if the relationship is nullable, ``False`` otherwise.\n    \"\"\"\n    return elem.direction == RelationshipDirection.MANYTOONE and all(c.nullable for c in elem.local_columns)\n", "path": "litestar/contrib/sqlalchemy/dto.py"}]}