Coverage for fastapi_restly/schemas/_generator.py: 95%
206 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-09 21:47 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-09 21:47 +0000
1"""
2Schema generation utilities for auto-generating Pydantic schemas from SQLAlchemy models.
3"""
5import dataclasses
6import enum
7import functools
8import inspect
9import sys
10import types
11from collections.abc import Collection
12from datetime import date, datetime, time, timedelta
13from decimal import Decimal
14from typing import Any, ForwardRef, Union, get_args, get_origin
15from uuid import UUID
17import pydantic
18from pydantic import Field
19from sqlalchemy import Column
20from sqlalchemy import inspect as sa_inspect
21from sqlalchemy.orm import (
22 ColumnProperty,
23 LoaderCallableStatus,
24 Mapped,
25 RelationshipProperty,
26)
28from .._mapping import is_mapped_class
29from ..models._pydantic_json import PydanticJSON
30from ._base import (
31 BaseSchema,
32 IDSchema,
33 ReadOnly,
34 TimestampsSchemaMixin,
35 UTCDatetime,
36 _is_unresolved,
37 _own_annotations,
38)
41def get_sqlalchemy_field_type(field: Any) -> Any:
42 """
43 Extract the Python type from a SQLAlchemy Mapped field.
45 :param field: A SQLAlchemy Mapped field.
46 :returns: The Python type annotation.
47 """
48 # Get the type annotation from the Mapped field
49 if hasattr(field, "type"):
50 return field.type
51 elif hasattr(field, "__origin__"):
52 return field.__origin__
53 else:
54 # Fallback to Any if we can't determine the type
55 return Any
58def is_relationship_field(field: Any) -> bool:
59 """
60 Check if a field is a SQLAlchemy relationship.
62 :param field: A SQLAlchemy Mapped field.
63 :returns: True if the field is a relationship, False otherwise.
64 """
65 if isinstance(field, RelationshipProperty):
66 return True
67 return isinstance(getattr(field, "property", None), RelationshipProperty)
70def get_relationship_target_model(field: Any) -> type[Any] | None:
71 """
72 Get the target model class for a relationship field.
74 :param field: A SQLAlchemy relationship field.
75 :returns: The target model class, or None if not found.
76 """
77 if not is_relationship_field(field):
78 return None
80 # Try to get the target from the relationship property
81 relationship = field
82 if not isinstance(relationship, RelationshipProperty):
83 relationship = getattr(field, "property", None)
85 if (
86 relationship is not None
87 and hasattr(relationship, "mapper")
88 and hasattr(relationship.mapper, "class_")
89 ):
90 return relationship.mapper.class_
92 # Try to get from the type annotation
93 if hasattr(field, "type"): 93 ↛ 103line 93 didn't jump to line 103 because the condition on line 93 was always true
94 target_type = field.type
95 if hasattr(target_type, "__origin__") and target_type.__origin__ is list:
96 # Handle list[Model] case
97 args = get_args(target_type)
98 if args: 98 ↛ 103line 98 didn't jump to line 103 because the condition on line 98 was always true
99 return args[0]
100 elif is_mapped_class(target_type): 100 ↛ 103line 100 didn't jump to line 103 because the condition on line 100 was always true
101 return target_type
103 return None
106def _resolve_annotation(owner: type, annotation: Any) -> Any:
107 """Evaluate a string annotation against ``owner``'s module, or return None."""
108 if isinstance(annotation, ForwardRef): 108 ↛ 109line 108 didn't jump to line 109 because the condition on line 108 was never true
109 annotation = annotation.__forward_arg__
110 if isinstance(annotation, str):
111 module = sys.modules.get(owner.__module__)
112 # Module names win over class attributes, as in typing.get_type_hints:
113 # a column named ``date`` must not shadow the ``date`` type.
114 try:
115 annotation = eval(
116 annotation, dict(vars(owner)), dict(vars(module)) if module else {}
117 )
118 except Exception:
119 return None
120 return annotation
123def _model_annotations(model_cls: type, keys: Collection[str]) -> dict[str, Any]:
124 """Map each annotated name in ``keys`` to its inner type, or None if unresolvable.
126 ``Mapped[X]`` gives ``X``; a plain annotation (SQLModel) is kept as is.
127 The class nearest ``model_cls`` on the MRO wins.
128 """
129 annotations: dict[str, Any] = {}
130 for cls in model_cls.mro():
131 for name, annotation in _own_annotations(cls).items():
132 if name in annotations or name not in keys:
133 continue
134 annotation = _resolve_annotation(cls, annotation)
135 if get_origin(annotation) is Mapped:
136 args = get_args(annotation)
137 annotation = _resolve_annotation(cls, args[0]) if args else None
138 if annotation is not None and _is_unresolved(annotation):
139 annotation = None
140 annotations[name] = annotation
141 return annotations
144# SQLAlchemy 2.1 puts this placeholder in the dataclass field of each
145# mapped_column default, and keeps the real default on the Column.
146_DONT_SET = getattr(LoaderCallableStatus, "DONT_SET", None)
149@functools.cache
150def _required_init_params(model_cls: type) -> frozenset[str]:
151 """The keyword parameters of ``model_cls(...)`` that have no default.
153 Reads the signature of ``__init__``, so it also sees a hand-written
154 ``__init__`` and a dataclass ``InitVar``, which ``dataclasses.fields()``
155 leaves out. The default constructor of a declarative model requires
156 nothing. The signature of the class itself would not do: on a SQLModel
157 table it is Pydantic's validation signature, but ``__init__`` takes
158 keyword arguments without validating them.
159 """
160 try:
161 signature = inspect.signature(model_cls.__init__)
162 except (TypeError, ValueError):
163 return frozenset()
164 parameters = list(signature.parameters.values())[1:] # without self
165 keyword = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)
166 return frozenset(
167 p.name
168 for p in parameters
169 if p.kind in keyword and p.default is inspect.Parameter.empty
170 )
173def _split_optional(annotation: Any) -> tuple[Any, bool]:
174 """Return ``(type, is_optional)`` with ``None`` removed from a union. The
175 other members stay: ``Cat | Dog | None`` gives ``Cat | Dog``."""
176 if isinstance(annotation, types.UnionType) or get_origin(annotation) is Union:
177 union_args = get_args(annotation)
178 if type(None) in union_args:
179 non_none_types = tuple(arg for arg in union_args if arg is not type(None))
180 if not non_none_types: 180 ↛ 181line 180 didn't jump to line 181 because the condition on line 180 was never true
181 return annotation, True
182 if len(non_none_types) == 1:
183 return non_none_types[0], True
184 return Union[non_none_types], True # noqa: UP007
185 return annotation, False
188def get_model_fields(model_cls: type[Any]) -> dict[str, Any]:
189 """
190 Extract field information from a SQLAlchemy model.
192 The mapper decides which attributes exist; annotations only refine a
193 column's type. Fields follow annotation order, then the mapper's order.
195 :param model_cls: A SQLAlchemy model class.
196 :returns: Dictionary mapping field names to their types and metadata.
197 :raises TypeError: If a column's Python type can be read from neither its
198 annotation nor its column type.
199 """
200 fields: dict[str, Any] = {}
202 mapper = sa_inspect(model_cls)
203 props = {prop.key: prop for prop in mapper.attrs}
204 annotations = _model_annotations(model_cls, props.keys())
205 dc_fields = (
206 {f.name: f for f in dataclasses.fields(model_cls)}
207 if dataclasses.is_dataclass(model_cls)
208 else {}
209 )
210 not_in_init = {name for name, f in dc_fields.items() if not f.init}
211 required_params = _required_init_params(model_cls)
212 names = list(annotations)
213 names += [name for name in props if name not in annotations]
215 for name in names:
216 if name.startswith("_"): 216 ↛ 217line 216 didn't jump to line 217 because the condition on line 216 was never true
217 continue
218 prop = props[name]
220 if isinstance(prop, RelationshipProperty):
221 target_model = prop.mapper.class_
222 # Listed so a caller can tell a relationship from a column.
223 # derive_schema leaves relationships out.
224 fields[name] = {
225 "type": list[target_model] if prop.uselist else target_model,
226 "is_relationship": True,
227 "target_model": target_model,
228 "is_optional": True,
229 "is_nullable": True,
230 "is_read_only": False,
231 "default": None,
232 }
233 continue
235 if not isinstance(prop, ColumnProperty): 235 ↛ 237line 235 didn't jump to line 237 because the condition on line 235 was never true
236 # Synonyms and composites are views of attributes listed already.
237 continue
239 column = prop.columns[0]
240 annotation = annotations.get(name)
241 if annotation is not None:
242 field_type, is_nullable = _split_optional(annotation)
243 else:
244 try:
245 if isinstance(column.type, PydanticJSON):
246 # The whole type, as dict[str, Address], not only dict.
247 field_type, _ = _split_optional(column.type.type_)
248 else:
249 field_type = column.type.python_type
250 except NotImplementedError:
251 field_type = object
252 if field_type is object:
253 raise TypeError(
254 f"Cannot determine the Python type of "
255 f"{model_cls.__name__}.{name} for an auto-generated schema: "
256 f"it has no annotation that resolves at runtime, and its "
257 f"column type {column.type!r} has no concrete python_type. Annotate "
258 f"it as Mapped[...] or set schema= on the view."
259 ) from None
260 is_nullable = bool(getattr(column, "nullable", False))
262 if isinstance(column, Column):
263 # As in SQLAlchemy, mapped_column(nullable=...) wins over the
264 # annotation. The field allows None only when the column does.
265 is_nullable = bool(column.nullable)
266 default = None
267 column_default = getattr(column, "default", None)
268 server_default = getattr(column, "server_default", None)
269 if column_default is not None or server_default is not None:
270 default = column_default or server_default
272 # A column_property over an expression cannot be written. The model
273 # or the server sets a column outside the constructor.
274 is_read_only = not isinstance(column, Column) or name in not_in_init
275 if is_read_only:
276 # Only a response has the field, and the row has a value.
277 is_optional = is_nullable
278 else:
279 # The create schema follows the constructor: the client may leave
280 # out a field that the constructor may leave out, when the model
281 # then still gives the column a value. A None default gives a
282 # NOT NULL column no value.
283 dc_field = dc_fields.get(name)
284 ctor_default = dataclasses.MISSING if dc_field is None else dc_field.default
285 init_default = dc_field is not None and (
286 dc_field.default_factory is not dataclasses.MISSING
287 or all(
288 ctor_default is not v
289 for v in (dataclasses.MISSING, None, _DONT_SET)
290 )
291 )
292 # On SQLAlchemy 2.0 the constructor's None goes into the INSERT. A
293 # type that stores None, such as JSON, then skips the column default.
294 none_is_stored = ctor_default is None and getattr(
295 column.type, "should_evaluate_none", False
296 )
297 is_optional = is_nullable or (
298 name not in required_params
299 and ((default is not None and not none_is_stored) or init_default)
300 )
302 fields[name] = {
303 "type": field_type,
304 "is_relationship": False,
305 "target_model": None,
306 "is_optional": is_optional,
307 "is_nullable": is_nullable,
308 "is_read_only": is_read_only,
309 "default": default,
310 }
312 return fields
315def derive_schema(model: type[Any], *, name: str | None = None) -> type[BaseSchema]:
316 """
317 Generate a Pydantic schema from a SQLAlchemy model.
319 This is the same schema that a view generates when it has no ``schema``:
320 one field per column, and no relationship fields. A foreign key column,
321 such as ``author_id``, is an ordinary field unless it has ``init=False``.
322 These fields are marked ``ReadOnly``: ``id``, ``created_at`` and
323 ``updated_at``, a ``column_property`` over a SQL expression, and a column
324 that the constructor does not take (``init=False``).
326 A time column gets a field of type :data:`UTCDatetime`, which holds the
327 time in UTC.
329 A field allows ``None`` only when its column is nullable. The create schema
330 follows the constructor: the client may leave out a field when its
331 column is nullable, or when the constructor does not require it and the
332 model then still gives the column a value. That value comes from the
333 column (``insert_default``, ``server_default``) or from the constructor
334 (a ``default`` other than ``None``, or a ``default_factory``). Such a
335 field has the default ``None``, which Pydantic does not validate. Restly
336 does not pass it to the constructor, so the model's default applies.
338 :param model: The SQLAlchemy model class.
339 :param name: Name for the generated schema class. Defaults to the
340 model name followed by ``Schema``, as in ``UserSchema``.
341 :returns: A Pydantic schema class.
342 """
343 if name is None:
344 name = f"{model.__name__}Schema"
346 # Get field information from the model
347 model_fields = get_model_fields(model)
349 # Determine base classes - start with the most specific ones
350 bases: list[type] = []
352 # Check if model has timestamp fields (inherits from TimestampsMixin)
353 has_timestamps = "created_at" in model_fields and "updated_at" in model_fields
354 if has_timestamps:
355 bases.append(TimestampsSchemaMixin)
357 # Check if model has an id field (as from IDMixin)
358 has_id = "id" in model_fields
359 if has_id:
360 bases.append(IDSchema)
362 # Always include BaseSchema as the base
363 bases.append(BaseSchema)
365 # Create field definitions for the schema
366 field_definitions: dict[str, Any] = {}
367 read_only_fields: list[str] = []
369 for field_name, field_info in model_fields.items():
370 if field_info["is_relationship"]:
371 continue
373 if (
374 field_name in ["id", "created_at", "updated_at"]
375 or field_info["is_read_only"]
376 ):
377 read_only_fields.append(field_name)
379 pydantic_type = convert_sqlalchemy_type_to_pydantic(
380 field_info["type"], field_info["is_nullable"]
381 )
383 # A field that the client may leave out gets the default None. Pydantic
384 # does not validate it, so a field typed ``int`` keeps rejecting
385 # ``null``. The SQLAlchemy default is not JSON-serializable, and the
386 # model applies it when the client leaves the field out.
387 if field_info["is_optional"]:
388 field_definitions[field_name] = (pydantic_type, Field(default=None))
389 else:
390 field_definitions[field_name] = (pydantic_type, ...)
392 # Apply ReadOnly annotation to read-only fields
393 for field_name in read_only_fields:
394 if field_name in field_definitions: 394 ↛ 393line 394 didn't jump to line 393 because the condition on line 394 was always true
395 original_type, field_info = field_definitions[field_name]
396 # Apply ReadOnly annotation to the type
397 field_definitions[field_name] = (ReadOnly[original_type], field_info)
399 # Create the schema class using pydantic.create_model
400 # The model's module, so OpenAPI's long names for this class point to
401 # the project and not to Restly.
402 schema_cls = pydantic.create_model( # type: ignore[call-overload]
403 name,
404 __doc__=f"Auto-generated schema for {model.__name__}",
405 __base__=tuple(bases),
406 __module__=model.__module__,
407 **field_definitions,
408 )
410 return schema_cls
413def convert_sqlalchemy_type_to_pydantic(
414 sqlalchemy_type: Any, is_optional: bool = False
415) -> Any:
416 """
417 Convert a SQLAlchemy type to a Pydantic-compatible type.
419 :param sqlalchemy_type: The SQLAlchemy type.
420 :param is_optional: Whether the field is optional.
421 :returns: A Pydantic-compatible type.
422 """
423 type_name = getattr(sqlalchemy_type, "__name__", str(sqlalchemy_type))
425 if sqlalchemy_type is Any:
426 pydantic_type = Any
427 elif sqlalchemy_type is datetime:
428 pydantic_type = UTCDatetime
429 elif sqlalchemy_type in (
430 str,
431 int,
432 float,
433 bool,
434 dict,
435 list,
436 date,
437 time,
438 timedelta,
439 UUID,
440 Decimal,
441 ):
442 pydantic_type = sqlalchemy_type
443 elif isinstance(sqlalchemy_type, type) and issubclass(sqlalchemy_type, enum.Enum):
444 pydantic_type = sqlalchemy_type
445 elif isinstance(sqlalchemy_type, type) and issubclass(
446 sqlalchemy_type, pydantic.BaseModel
447 ):
448 # The document in a JSON column, as in dict[str, Address].
449 pydantic_type = sqlalchemy_type
450 elif is_mapped_class(sqlalchemy_type):
451 # Relationship targets are replaced with nested schemas later.
452 pydantic_type = sqlalchemy_type
453 elif getattr(sqlalchemy_type, "__origin__", None) is not None or isinstance(
454 sqlalchemy_type, types.UnionType
455 ):
456 # Preserve parameterized container types like dict[str, Any] or
457 # list[int], and a union such as Cat | Dog.
458 pydantic_type = sqlalchemy_type
459 elif type_name in {"Text", "String"}:
460 pydantic_type = str
461 elif type_name in {"Integer"}:
462 pydantic_type = int
463 elif type_name in {"Float"}:
464 pydantic_type = float
465 elif type_name in {"Boolean"}:
466 pydantic_type = bool
467 elif type_name in {"DateTime"}:
468 pydantic_type = UTCDatetime
469 elif type_name in {"Date"}:
470 pydantic_type = date
471 elif type_name in {"Time"}:
472 pydantic_type = time
473 elif type_name in {"Interval"}:
474 pydantic_type = timedelta
475 else:
476 raise TypeError(
477 f"Unsupported field type for auto-generated schema: {sqlalchemy_type!r}"
478 )
480 # Handle optional types
481 if is_optional:
482 pydantic_type = pydantic_type | None
484 return pydantic_type