Coverage for fastapi_restly/schemas/_base.py: 95%
1021 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
1import contextlib
2import dataclasses
3import functools
4import inspect
5import math
6import re
7import sys
8import types
9import typing
10import weakref
11from collections.abc import Callable, Generator, Iterable, Iterator, Mapping
12from collections.abc import Sequence as _AbcSequence
13from collections.abc import Set as _AbcSet
14from datetime import datetime
15from enum import Enum
16from typing import (
17 TYPE_CHECKING,
18 Annotated,
19 Any,
20 ClassVar,
21 ForwardRef,
22 Generic,
23 Literal,
24 Union,
25 cast,
26 get_args,
27 get_origin,
28)
30import pydantic
31import sqlalchemy
32from pydantic.fields import Field, FieldInfo
33from sqlalchemy import inspect as sa_inspect
34from sqlalchemy import select
35from sqlalchemy.exc import NoResultFound
36from sqlalchemy.ext.asyncio.session import AsyncSession as SA_AsyncSession
37from sqlalchemy.orm.session import Session as SA_Session
38from sqlalchemy.sql import ClauseElement
39from typing_extensions import TypeAliasType, TypeVar, is_typeddict
41from .._columns import column_value
42from .._mapping import is_mapped_class, is_mapped_instance, is_to_many_relationship
43from .._pagination import _DEFAULT_PAGINATION, Envelope, Pagination
44from .._times import in_utc
45from ..clauses import apply_clauses
46from ..clauses._scopes import _default_scope
47from ..exc import NotFound, RestlyConfigurationError
49if sys.version_info >= (3, 14): 49 ↛ 50line 49 didn't jump to line 50 because the condition on line 49 was never true
50 import annotationlib
53class BaseSchema(pydantic.BaseModel):
54 """The base of a Restly schema: a Pydantic model with
55 ``from_attributes=True``, so it can read a SQLAlchemy object by its
56 attributes.
58 It also has ``ser_json_inf_nan="strings"``, so a response writes a NaN or
59 an infinity as the text ``"NaN"``, ``"Infinity"`` or ``"-Infinity"``.
60 JSON has no number for these values, and Pydantic's default writes
61 ``null``, which loses the value. A ``float`` field reads the text back.
62 This needs FastAPI 0.130 or later, with its default response class. A
63 Pydantic model of your own in a field follows its own setting.
65 It also checks where the ``ReadOnly``, ``WriteOnly`` and ``MustExist``
66 markers are placed. A marker deep inside the type of a field, such as
67 ``ReadOnly[int] | None``, would have no effect. So the class raises
68 :class:`~fastapi_restly.exc.RestlyConfigurationError` when Python defines
69 it. Put the marker around the whole type: ``ReadOnly[int | None]``.
70 """
72 model_config = pydantic.ConfigDict(from_attributes=True, ser_json_inf_nan="strings")
74 @classmethod
75 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
76 super().__pydantic_init_subclass__(**kwargs)
77 # Reject a ReadOnly/WriteOnly marker buried inside a union member, where
78 # it silently no-ops (see ``_reject_buried_markers``). This fires as the
79 # schema class is defined, so the mistake surfaces at import time. Views
80 # also re-check the schemas they use, to cover schemas that do not derive
81 # from ``BaseSchema``.
82 _reject_buried_markers(cls)
85class _Marker:
86 def __init__(self, name: str):
87 self.name = name
89 def __repr__(self):
90 return f"fr.{self.name}"
93readonly_marker = _Marker("ReadOnly")
94writeonly_marker = _Marker("WriteOnly")
96_T = TypeVar("_T")
98ReadOnly = Annotated[_T, readonly_marker, Field(json_schema_extra={"readOnly": True})]
99# ``exclude=True`` strips the field from serialization at the field level, so it
100# is dropped from every response -- recursively, including in nested schemas, and
101# from the OpenAPI response schema -- while staying a writable request input
102# (exclude does not affect validation). Prefer ``WriteOnly[Optional[T]]`` over
103# ``Optional[WriteOnly[T]]`` / ``WriteOnly[T] | None``: when the marker is only a
104# union member the exclude rides on the inner type and does NOT apply, so the
105# field would leak.
106WriteOnly = Annotated[
107 _T, writeonly_marker, Field(json_schema_extra={"writeOnly": True}, exclude=True)
108]
110#: A ``datetime`` field in UTC. It reads a time without an offset as UTC, and
111#: changes a time with an offset to the same time in UTC. So the object of
112#: the schema always has the time in UTC, and JSON shows it with ``Z``, such
113#: as ``2024-01-01T09:30:00Z``. See :ref:`utc-times`.
114UTCDatetime = Annotated[datetime, pydantic.AfterValidator(in_utc)]
117#: The classes of a type alias. ``type X = ...`` makes a
118#: ``typing.TypeAliasType``, and typing_extensions has a class of its own on
119#: some Python versions.
120_TYPE_ALIAS_TYPES: tuple[type, ...] = tuple(
121 {TypeAliasType, getattr(typing, "TypeAliasType", TypeAliasType)}
122)
125def _alias_value(annotation: Any, seen: set[Any] | None = None) -> Any:
126 """The type that a type alias stands for: ``int`` for
127 ``type UserId = int``, and ``list[int]`` for ``Many[int]`` with
128 ``type Many[T] = list[T]``. Any other annotation comes back unchanged.
130 ``seen`` collects the aliases that a check has expanded, each with its
131 arguments. An alias that comes back inside its own value, as in
132 ``type Json = list[Json] | str``, is not expanded again, so the check
133 ends. A check that follows a type into its arguments passes its ``seen``
134 on.
135 """
136 if seen is None:
137 seen = set()
138 while True:
139 origin = get_origin(annotation)
140 if type(origin) in _TYPE_ALIAS_TYPES:
141 alias, args = origin, get_args(annotation)
142 elif type(annotation) in _TYPE_ALIAS_TYPES:
143 alias, args = annotation, ()
144 else:
145 return annotation
146 key = _seen_key(alias, args)
147 if key in seen:
148 return annotation
149 seen.add(key)
150 try:
151 annotation = _alias_body(alias, args)
152 except NameError:
153 # A type statement is lazy, and may name a class that Python has
154 # not created yet. The view checks the schema again when it
155 # registers.
156 return annotation
159def _seen_key(alias: Any, args: tuple[Any, ...]) -> Any:
160 """``alias`` with its ``args``, as a key for the ``seen`` of
161 :func:`_alias_value`. An argument that cannot be hashed counts by its
162 identity."""
163 try:
164 hash(args)
165 except TypeError:
166 return (alias, tuple(id(arg) for arg in args))
167 return (alias, args)
170def _alias_body(alias: Any, args: tuple[Any, ...]) -> Any:
171 """The value of ``alias``, with ``args`` in place of its type parameters.
172 A parameter without an argument takes its default, if it has one."""
173 value = alias.__value__
174 replacements = dict(zip(alias.__type_params__, args))
175 for param in alias.__type_params__[len(args) :]:
176 if getattr(param, "has_default", lambda: False)(): 176 ↛ 175line 176 didn't jump to line 175 because the condition on line 176 was always true
177 replacements[param] = param.__default__
178 if not replacements:
179 return value
180 if isinstance(value, typing.TypeVar): 180 ↛ 181line 180 didn't jump to line 181 because the condition on line 180 was never true
181 return replacements.get(value, value)
182 # A generic Pydantic model keeps its parameters in its own metadata.
183 params = getattr(value, "__parameters__", ()) or getattr(
184 value, "__pydantic_generic_metadata__", {}
185 ).get("parameters", ())
186 if not params: 186 ↛ 187line 186 didn't jump to line 187 because the condition on line 186 was never true
187 return value
188 try:
189 return value[tuple(replacements.get(p, p) for p in params)]
190 except TypeError:
191 return value
194# A ReadOnly/WriteOnly marker only takes effect as the OUTER annotation of a
195# field: its ``Annotated`` metadata has to sit at the field's top level. Nested
196# anywhere inside the field's type -- a union member (``Optional[ReadOnly[T]]``,
197# ``WriteOnly[T] | None``) or a container element (``list[WriteOnly[T]]``) -- the
198# marker silently no-ops: ReadOnly fails to drop the field from create/update (it
199# stays writable) and WriteOnly fails to exclude it from responses (it leaks).
200# The guards below detect that misuse and reject it loudly.
201#
202# Coverage boundary: detection reads ``field_info.annotation``, so a marker
203# hidden behind an unresolved forward reference is not seen until the annotation
204# resolves (the view-registration backstop re-checks resolved schemas), and that
205# backstop only inspects a view's own read/create/update schemas -- not a custom
206# ``response_model=`` or a non-``BaseSchema`` nested model. Those narrow cases are
207# left uncovered by design.
208def _annotation_buries_marker(
209 annotation: Any, marker: _Marker, seen: set[Any] | None = None
210) -> bool:
211 """True if ``marker`` appears anywhere below the top level of ``annotation``
212 -- inside a union member, ``Annotated`` inner type, container arg, or type
213 alias. Pydantic does not apply the field settings of an ``Annotated``
214 inside a type alias either.
216 Only descends type arguments (``get_args``); it does not recurse into the
217 fields of a nested model, so a nested schema carrying its own top-level
218 marker is not flagged.
219 """
220 seen = set() if seen is None else set(seen)
221 annotation = _alias_value(annotation, seen)
222 if marker in getattr(annotation, "__metadata__", ()):
223 return True
224 return any(
225 _annotation_buries_marker(arg, marker, seen) for arg in get_args(annotation)
226 )
229def _find_buried_marker_fields(
230 model_cls: type[pydantic.BaseModel],
231) -> list[tuple[str, _Marker]]:
232 """Return ``(field_name, marker)`` for each field whose ReadOnly/WriteOnly
233 marker is nested inside the field's type instead of wrapping it, where it
234 does not take effect."""
235 buried: list[tuple[str, _Marker]] = []
236 for name, field_info in model_cls.model_fields.items():
237 top_level = getattr(field_info, "metadata", None) or ()
238 for marker in (readonly_marker, writeonly_marker):
239 if marker in top_level:
240 continue
241 if _annotation_buries_marker(field_info.annotation, marker):
242 buried.append((name, marker))
243 return buried
246def _reject_buried_markers(model_cls: type[pydantic.BaseModel]) -> None:
247 """Raise if any field nests a ReadOnly/WriteOnly/RefExists marker inside
248 its type, where the marker machinery cannot see it."""
249 for name, marker in _find_buried_marker_fields(model_cls):
250 raise RestlyConfigurationError(
251 f"{model_cls.__name__}.{name} nests the {marker.name} marker inside "
252 f"its type, such as Optional[{marker.name}[T]], "
253 f"{marker.name}[T] | None, list[{marker.name}[T]] or a type alias. "
254 f"The marker only takes effect as the outer annotation, so it is "
255 f"silently ignored here and {marker.name} is not applied. Wrap the "
256 f"whole field type instead, such as {marker.name}[Optional[T]], or "
257 f"move the marker out of the type alias."
258 )
259 _reject_buried_ref_exists(model_cls)
262#: The message for code that still uses the removed public ``RefExists``.
263_REF_EXISTS_REMOVED = (
264 "fr.RefExists was removed. Declare a reference as "
265 "fr.MustExist[<id type>, <Model>], such as fr.MustExist[int, Post]. It "
266 "finds the rows of the model's default_scope, under the rules of the "
267 "session. A tenant rule goes on the session. A rule for one caller or one "
268 "action goes in authorize."
269)
272class RefExists:
273 """Marker for an existence-checked scalar foreign key.
275 Built by ``MustExist[pk, Model]``. On write, Restly checks that each
276 marked id is a row of ``model`` and raises ``NotFound`` (404) on a miss.
277 The field stays a plain scalar: the marker only adds the check.
279 The check finds the rows of the model's ``default_scope``, under the
280 rules of the session, as ``IDRef`` and ``IDSchema`` do. A model without a
281 ``default_scope`` is checked by primary key alone.
282 """
284 def __init__(self, model: type[Any]) -> None:
285 self.model = model
287 def __repr__(self) -> str:
288 return f"RefExists({getattr(self.model, '__name__', self.model)})"
291def _annotation_contains_ref_exists(
292 annotation: Any, seen: set[Any] | None = None
293) -> bool:
294 seen = set() if seen is None else set(seen)
295 annotation = _alias_value(annotation, seen)
296 if any(isinstance(m, RefExists) for m in getattr(annotation, "__metadata__", ())):
297 return True
298 return any(
299 _annotation_contains_ref_exists(arg, seen) for arg in get_args(annotation)
300 )
303def _reject_buried_ref_exists(model_cls: type[pydantic.BaseModel]) -> None:
304 """Raise for a RefExists marker the check machinery cannot see.
306 The existence check reads the field's type, or the item type of a list
307 (``list[MustExist[int, T]]``), each also with ``| None``. A marker deeper
308 in the type, such as in ``dict[str, MustExist[int, T]]``, is invisible
309 there, so the field would validate and write with no check at all -- a
310 silent no-op of a check the schema explicitly asks for.
311 """
312 for name, field_info in model_cls.model_fields.items():
313 if not _annotation_contains_ref_exists(field_info.annotation):
314 continue
315 if _ref_exists_marker(field_info) is not None:
316 continue
317 if _listed_ref_exists_marker(field_info) is not None:
318 continue
319 raise RestlyConfigurationError(
320 f"{model_cls.__name__}.{name} buries a MustExist marker "
321 f"inside its type, such as in dict[str, MustExist[int, T]], where "
322 f"the existence check cannot see it, so the reference would go "
323 f"unchecked. Use MustExist as the type of the field, or as the "
324 f"item type of a list: list[MustExist[int, T]]."
325 )
328class TimestampsSchemaMixin(pydantic.BaseModel):
329 """Schema mixin that adds two fields: ``created_at`` and ``updated_at``.
331 It is the schema side of :class:`~fastapi_restly.models.TimestampsMixin`.
332 Both fields are ``ReadOnly[UTCDatetime]``, so the responses contain them,
333 in UTC, and the create and update bodies that Restly generates leave them
334 out. When a client sends them in a body, Restly ignores them. The fields
335 have no default, so the object that a response reads must have both
336 attributes.
338 The mixin adds nothing else, so combine it with :class:`IDSchema` or
339 :class:`BaseSchema`. Put it before the base class, so that ``id`` stays
340 the first field in the responses::
342 class UserSchema(fr.TimestampsSchemaMixin, fr.IDSchema):
343 name: str
345 A schema that Restly generates for a model with ``created_at`` and
346 ``updated_at`` columns uses this mixin.
347 """
349 #: When the row was created. It is ``ReadOnly``: the responses show it,
350 #: and the create and update bodies that Restly generates leave it out.
351 created_at: ReadOnly[UTCDatetime]
352 #: When the row last changed. It is ``ReadOnly``: the responses show it,
353 #: and the create and update bodies that Restly generates leave it out.
354 updated_at: ReadOnly[UTCDatetime]
357# Unbound: a mapped class need not subclass DeclarativeBase.
358SQLAlchemyModel = TypeVar("SQLAlchemyModel", default=Any)
359_IDREF_UNSET = object()
360_SCHEMA_RESOURCE_SUFFIXES = ("Schema", "Response")
363@functools.cache
364def _id_type_adapter(id_type: Any) -> pydantic.TypeAdapter[Any]:
365 return pydantic.TypeAdapter(id_type)
368def _schema_resource_name(model_cls: type[pydantic.BaseModel]) -> str:
369 """The resource part of a schema's class name: the name without a final
370 ``Schema`` or ``Response``. ``UserSchema`` and ``UserResponse`` both give
371 ``User``."""
372 name = model_cls.__name__
373 for suffix in _SCHEMA_RESOURCE_SUFFIXES:
374 if name.endswith(suffix) and len(name) > len(suffix):
375 return name[: -len(suffix)]
376 return name
379def _schema_role_name(model_cls: type[pydantic.BaseModel], role: str) -> str:
380 """The name of a class that Restly generates from a schema:
381 ``<Resource><Role>``, as in ``UserCreate``."""
382 return f"{_schema_resource_name(model_cls)}{role}"
385def _own_annotations(cls: type) -> dict[str, Any]:
386 """Return the annotations ``cls`` itself declares, without failing on them.
388 Under PEP 563 the values are strings. On 3.14 a name that is undefined at
389 runtime, such as a ``TYPE_CHECKING`` import, comes back as a ``ForwardRef``
390 where reading ``__annotations__`` would raise ``NameError``.
391 """
392 if sys.version_info >= (3, 14): 392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true
393 return annotationlib.get_annotations(
394 cls, format=annotationlib.Format.FORWARDREF
395 )
396 return inspect.get_annotations(cls)
399def _is_unresolved(annotation: Any) -> bool:
400 """Whether ``annotation`` still holds a string or ``ForwardRef`` anywhere."""
401 if isinstance(annotation, (str, ForwardRef)):
402 return True
403 origin = get_origin(annotation)
404 if origin is Literal: 404 ↛ 405line 404 didn't jump to line 405 because the condition on line 404 was never true
405 return False
406 args = get_args(annotation)
407 if origin is Annotated: 407 ↛ 409line 407 didn't jump to line 409 because the condition on line 407 was never true
408 # Metadata may be any object, strings included.
409 args = args[:1]
410 return any(_is_unresolved(arg) for arg in args)
413def _model_id_type(sql_model: type[Any]) -> Any:
414 """Return the Python type of ``sql_model``'s ``id`` primary key, or ``None``.
416 Reads the ``id`` annotation off the model's MRO (works before the mapper is
417 configured), then falls back to the SA mapper -- which also covers a PEP 563
418 / ``from __future__ import annotations`` model, whose ``id`` annotation is a
419 string the mapper resolves authoritatively. Shared by ``IDSchema``/``IDRef``
420 (via ``_get_sql_model_id_type``) and ``MustExist``.
421 """
422 for model_cls in sql_model.mro():
423 annotation = _own_annotations(model_cls).get("id")
424 if annotation is None:
425 continue
426 if get_origin(annotation) is not None:
427 args = get_args(annotation)
428 if args: 428 ↛ 430line 428 didn't jump to line 430 because the condition on line 428 was always true
429 annotation = args[0]
430 if _is_unresolved(annotation):
431 # Don't return a raw string; the mapper below resolves the real
432 # column type without eval'ing it.
433 break
434 return annotation
436 # Fallback: ask the SA mapper. `python_type` raises NotImplementedError for
437 # column types without a Python equivalent (e.g. some user types), and
438 # a class that is not mapped has no mapper to ask.
439 try:
440 return sa_inspect(sql_model, raiseerr=False).primary_key[0].type.python_type
441 except (AttributeError, NotImplementedError, IndexError):
442 return None
445class IDSchema(BaseSchema, Generic[SQLAlchemyModel]):
446 """The base of a view's main schema, which adds a read-only ``id``. As the
447 type of a field, ``IDSchema[Model]`` is a reference to a related row.
449 - As a BASE CLASS (``class UserSchema(IDSchema): ...``) it adds the resource's
450 own read-only ``id`` -- the common use.
451 - As a FIELD TYPE on a RELATIONSHIP-named field (``author: IDSchema[User]``)
452 the JSON value is ``{"id": N}`` (JSON-API / React-Admin); Restly resolves
453 the id to the related ORM object, so ``data.author`` is a wrapper (read
454 ``.id``). Use ``IDRef[User]`` for a flat id (``5``) instead.
456 For a scalar foreign-key COLUMN (``author_id``), use ``fr.MustExist[int, T]``
457 rather than ``IDSchema``/``IDRef``: it keeps the field a plain checked id
458 instead of turning a ``*_id`` field into an object wrapper.
459 """
461 # Keep this broad so relation-id payloads can target non-int primary keys.
462 #: The id of the row. In a view's main schema, it is ``ReadOnly``: the
463 #: responses show it, and the create and update bodies that Restly
464 #: generates leave it out. In a reference field, such as
465 #: ``author: fr.IDSchema[Author]``, the client sends it.
466 id: ReadOnly[Any]
468 @classmethod
469 def _get_sql_model_annotation(cls) -> type[Any] | None:
470 # `__pydantic_generic_metadata__` is set on parameterised subclasses;
471 # on the bare `IDSchema` class the "args" tuple may be missing or empty.
472 try:
473 sql_model = cls.__pydantic_generic_metadata__["args"][0]
474 except (KeyError, IndexError, TypeError):
475 return None
476 return sql_model if isinstance(sql_model, type) else None
478 @classmethod
479 def _get_sql_model_id_type(cls) -> Any:
480 sql_model = cls._get_sql_model_annotation()
481 if sql_model is None:
482 return None
483 return _model_id_type(sql_model)
485 @pydantic.field_validator("id", mode="before")
486 @classmethod
487 def _coerce_id_to_model_primary_key_type(cls, value: Any) -> Any:
488 id_type = cls._get_sql_model_id_type()
489 if id_type in (None, Any):
490 return value
491 return _id_type_adapter(id_type).validate_python(value)
493 @pydantic.model_validator(mode="before")
494 @classmethod
495 def _coerce_scalar(cls, v: Any) -> Any:
496 # A pure id reference (``IDSchema[Model]`` / ``IDRef[Model]``, whose only
497 # field is ``id``) accepts a bare scalar id or a related ORM row where the
498 # ``{"id": ...}`` mapping is expected, so the reference type is
499 # self-sufficient under plain ``from_attributes``: a scalar FK column read
500 # straight off the row in ``to_single_response``, a related row reached
501 # through a relationship, or a ``{"id": N}`` payload all validate without
502 # any view-layer pre-extraction. A subclass that adds fields (a nested
503 # response schema) is NOT a pure reference, so it validates normally and
504 # its row is never collapsed to just the id.
505 if set(cls.model_fields) != {"id"}:
506 return v
507 if isinstance(v, dict):
508 return v
509 if is_mapped_instance(v):
510 return {"id": getattr(v, "id")}
511 return {"id": v}
513 def get_sql_model_annotation(self) -> type[SQLAlchemyModel] | None:
514 """
515 Return the annotation on IDSchema when used as:
517 foo: IDSchema[Foo]
519 This property will return "Foo".
520 """
521 # The runtime introspection returns the bound type; cast through the
522 # generic parameter so callers see the concrete model class.
523 return self._get_sql_model_annotation() # type: ignore[return-value]
526class IDRef(IDSchema[SQLAlchemyModel], Generic[SQLAlchemyModel]):
527 """Flat-id reference to a related row, for a RELATIONSHIP-named field.
529 Use ``IDRef[T]`` when the field is named after a relationship
530 (``author: IDRef[User]``, ``products: list[IDRef[Product]]``), not after a
531 ``*_id`` column. The JSON value is the raw id (``5``); input also accepts
532 ``{"id": N}``. Restly resolves the id to the related ORM object, so
533 ``data.author`` is an ``IDRef`` wrapper (read ``.id``), not a plain scalar.
535 For a scalar foreign-key COLUMN (``author_id``, ``task_id``) use
536 ``fr.MustExist[int, T]`` instead -- it keeps the field a plain checked id
537 (``data.author_id == 1``), rather than making a ``*_id`` field an object
538 wrapper. For a nested ``{"id": N}`` value on a relationship, use ``IDSchema[T]``.
540 author: IDRef[User] # to-one relationship, flat id
541 products: list[IDRef[Product]] # serializes as [1, 2, 3]
543 Resolution applies the referenced model's ``default_scope``: a
544 reference to a row the scope hides raises ``NotFound``, as a missing row
545 does. A model without a ``default_scope`` resolves by primary key alone.
546 A session rule, such as a tenant rule added with
547 ``with_loader_criteria``, reaches the lookup too, except for an object
548 that is already in the session. A rule that is neither goes in
549 ``authorize``, where ``data.<field>.id`` is the requested id. See "Which
550 rows can a reference reach?" on the Relationships guide page.
551 """
553 def __init__(self, value: Any = _IDREF_UNSET, **data: Any) -> None:
554 if value is not _IDREF_UNSET:
555 if data: 555 ↛ 556line 555 didn't jump to line 556 because the condition on line 555 was never true
556 raise TypeError(
557 "IDRef accepts either a positional id or keyword fields"
558 )
559 data = value if isinstance(value, dict) else {"id": value}
560 super().__init__(**data)
562 @classmethod
563 def __get_pydantic_json_schema__(
564 cls, core_schema: Any, handler: pydantic.GetJsonSchemaHandler
565 ) -> dict[str, Any]:
566 id_type = cls._get_sql_model_id_type()
567 if id_type in (None, Any): 567 ↛ 568line 567 didn't jump to line 568 because the condition on line 567 was never true
568 return {}
569 return pydantic.TypeAdapter(id_type).json_schema(
570 mode=getattr(handler, "mode", "validation")
571 )
573 @pydantic.model_serializer
574 def _serialize_flat(self) -> Any:
575 return self.id if hasattr(self, "id") else self
578if TYPE_CHECKING:
579 _MustExistPK = TypeVar("_MustExistPK")
580 _MustExistModel = TypeVar("_MustExistModel")
582 # Static view: ``MustExist[pk, Model]`` reads as the pk scalar (the alias
583 # value is the first param), so a field stays a plain scalar --
584 # ``data.post_id`` is an ``int``, not a wrapper. The model is a runtime
585 # concern; the runtime ``MustExist`` is defined below.
586 MustExist = TypeAliasType(
587 "MustExist", _MustExistPK, type_params=(_MustExistPK, _MustExistModel)
588 )
589else:
591 class MustExist:
592 """Existence-checked scalar foreign key: ``MustExist[int, Post]``.
594 The first argument is the type of the id, the second the model of the
595 row. The field stays the id everywhere (JSON, column,
596 ``data.<field>``). On write, Restly checks that the row exists (404 on
597 a miss), among the rows of the model's ``default_scope``.
598 """
600 def __class_getitem__(cls, params: Any) -> Any:
601 if not isinstance(params, tuple) or len(params) != 2:
602 raise TypeError(
603 "MustExist takes the type of the id and the model of the "
604 "row: MustExist[int, Post]. Restly does not take the model "
605 "from the foreign key, because a schema can also write "
606 "another model, and then the check would use the wrong "
607 "table."
608 )
609 pk_type, model = params
610 if not isinstance(model, type):
611 raise TypeError(
612 f"MustExist[{getattr(pk_type, '__name__', pk_type)}, "
613 f"{model!r}]: the second argument must be the model class, "
614 "such as MustExist[int, Post]."
615 )
616 return Annotated[pk_type, RefExists(model)]
619def _unwrap_optional_annotation(annotation: Any) -> Any:
620 """Unwrap Optional[X] or X | None to X. Returns annotation unchanged otherwise."""
621 origin = get_origin(annotation)
622 if origin not in (types.UnionType, Union):
623 return annotation
625 non_none_args = [arg for arg in get_args(annotation) if arg is not type(None)]
626 if len(non_none_args) == 1:
627 return non_none_args[0]
628 return annotation
631def _unwrap_type(
632 annotation: Any, seen: set[Any] | None = None
633) -> tuple[Any, list[Any]]:
634 """Return ``annotation`` without its ``Optional``, ``Annotated`` and type
635 alias layers, and the metadata of each ``Annotated`` layer that it removed.
637 Pydantic moves the metadata of an outer ``Annotated`` to
638 ``field.metadata``, but it keeps an ``Annotated`` inside ``Optional`` or
639 inside a type alias. So ``Annotated[IDRef[User], Field(...)] | None``,
640 ``constr(...) | None`` and ``type AuthorId = MustExist[int, User]`` keep
641 their layers, and every check of a field's type must remove them.
642 ``seen`` is as in :func:`_alias_value`.
643 """
644 if seen is None:
645 seen = set()
646 metadata: list[Any] = []
647 while True:
648 unwrapped = _alias_value(_unwrap_optional_annotation(annotation), seen)
649 if get_origin(unwrapped) is Annotated:
650 unwrapped, *extra = get_args(unwrapped)
651 metadata.extend(extra)
652 if unwrapped is annotation:
653 return annotation, metadata
654 annotation = unwrapped
657def is_reference_annotation(annotation: Any) -> bool:
658 """True if ``annotation`` is an ``IDRef``/``IDSchema`` reference type.
660 The one check for a reference type, kept beside the types so callers
661 (views, query) don't inspect Pydantic generics themselves. Removes
662 ``Optional`` and ``Annotated`` first, then matches the bare types or a
663 parametrization whose generic origin is ``IDSchema``/``IDRef``
664 (``IDRef[Post]``, ``IDSchema[Post]``) -- not a user subclass that merely
665 inherits from them.
666 """
667 annotation, _ = _unwrap_type(annotation)
668 if annotation in (IDSchema, IDRef):
669 return True
670 if not inspect.isclass(annotation):
671 return False
672 try:
673 if not issubclass(annotation, IDSchema):
674 return False
675 except TypeError:
676 return False
677 metadata = getattr(annotation, "__pydantic_generic_metadata__", {})
678 return metadata.get("origin") in (IDSchema, IDRef)
681def is_reference_field(schema_cls: type[pydantic.BaseModel], field_name: str) -> bool:
682 """True if ``schema_cls``'s ``field_name`` is typed as an ``IDRef``/``IDSchema``."""
683 field_info = schema_cls.model_fields.get(field_name)
684 if field_info is None: 684 ↛ 685line 684 didn't jump to line 685 because the condition on line 684 was never true
685 return False
686 return is_reference_annotation(field_info.annotation)
689def reference_origin_and_target(annotation: Any) -> tuple[type, type | None] | None:
690 """For an ``IDRef``/``IDSchema`` field annotation (``Optional`` and
691 ``Annotated`` removed), return ``(origin, target)``: the
692 ``IDRef``/``IDSchema`` class and the referenced model (``None`` for a bare,
693 unparametrized reference), or ``None`` when the annotation is not a
694 reference type. Lets the scalar-named-reference
695 lint name both the type and its target in the ``MustExist`` hint.
696 """
697 annotation, _ = _unwrap_type(annotation)
698 if annotation in (IDSchema, IDRef): 698 ↛ 699line 698 didn't jump to line 699 because the condition on line 698 was never true
699 return (annotation, None)
700 if not inspect.isclass(annotation): 700 ↛ 701line 700 didn't jump to line 701 because the condition on line 700 was never true
701 return None
702 try:
703 if not issubclass(annotation, IDSchema):
704 return None
705 except TypeError:
706 return None
707 metadata = getattr(annotation, "__pydantic_generic_metadata__", {})
708 origin = metadata.get("origin")
709 if origin not in (IDSchema, IDRef): 709 ↛ 710line 709 didn't jump to line 710 because the condition on line 709 was never true
710 return None
711 args = metadata.get("args") or ()
712 target = args[0] if args and isinstance(args[0], type) else None
713 return (origin, target)
716_CHECKED_REFERENCES_KEY = "_fr_checked_references"
718#: The value in the record for a reference whose row was not loaded: the
719#: check of a ``MustExist`` field reads only the primary key.
720_NO_ROW: Any = object()
722#: The most ids in one ``IN`` list, below the parameter limits of the
723#: databases (SQLite allows 32766 in all, older versions 999).
724_IN_CHUNK = 500
727def _checked_references(
728 session: SA_Session | SA_AsyncSession,
729) -> dict[tuple[type[Any], Any], Any]:
730 """The references that the running write action has checked, as
731 ``{(model, id): row}``. Empty outside a write action."""
732 return session.info.get(_CHECKED_REFERENCES_KEY) or {}
735@contextlib.contextmanager
736def _remember_checked_references(
737 session: SA_Session | SA_AsyncSession, checked: dict[tuple[type[Any], Any], Any]
738) -> Iterator[None]:
739 """Keep ``checked`` on the session until the block ends.
741 The builders of :mod:`fastapi_restly.objects` read it, so a reference that
742 the write action checked is not queried again. An id that code changes
743 after the check is not in the record, so the builder checks it.
744 """
745 previous = session.info.get(_CHECKED_REFERENCES_KEY)
746 session.info[_CHECKED_REFERENCES_KEY] = checked
747 try:
748 yield
749 finally:
750 if previous is None:
751 session.info.pop(_CHECKED_REFERENCES_KEY, None)
752 else:
753 session.info[_CHECKED_REFERENCES_KEY] = previous
756def _recorded_rows(
757 checked: Mapping[tuple[type[Any], Any], Any], model: type[Any], ids: list[Any]
758) -> list[Any] | None:
759 """The rows that the write action loaded for ``ids``, or ``None`` when one
760 of them is not in the record."""
761 rows = [checked.get((model, id_), _NO_ROW) for id_ in ids]
762 return None if any(row is _NO_ROW for row in rows) else rows
765@dataclasses.dataclass(frozen=True)
766class _BodyReference:
767 """One reference in the data of a write action."""
769 #: Where the id is, such as ``post_id`` or ``lines[2].product_id``.
770 path: str
771 model: type[Any]
772 id: Any
773 #: An ``IDRef`` or ``IDSchema``: the builder needs the row itself.
774 row: bool
775 #: One id of a list of references, such as ``tags: list[IDRef[Tag]]``.
776 listed: bool = False
779def _body_references(data: Any) -> list[_BodyReference]:
780 """Every reference in ``data``, in the order of the fields.
782 ``data`` is a schema object, or a list, tuple or dict of them. The walk
783 goes into the fields that hold other schema objects, so a reference in
784 an order line is found too. It reads only the fields that were set, and
785 skips ``None``.
786 """
787 references: list[_BodyReference] = []
788 seen: set[int] = set()
789 if isinstance(data, pydantic.BaseModel):
790 _collect_model_references(data, "", references, seen)
791 elif isinstance(data, (list, tuple)):
792 for index, item in enumerate(data):
793 _collect_value_references(item, f"[{index}]", references, seen)
794 elif isinstance(data, dict):
795 for key, item in data.items():
796 _collect_value_references(item, f"{key}", references, seen)
797 return references
800#: The classes of the data whose ``MustExist`` markers are known to be
801#: where the check can see them.
802_MARKERS_CHECKED: "weakref.WeakSet[type[pydantic.BaseModel]]" = weakref.WeakSet()
805def _collect_model_references(
806 obj: pydantic.BaseModel, path: str, references: list[_BodyReference], seen: set[int]
807) -> None:
808 if id(obj) in seen: 808 ↛ 809line 808 didn't jump to line 809 because the condition on line 808 was never true
809 return
810 seen.add(id(obj))
811 cls = type(obj)
812 if cls not in _MARKERS_CHECKED:
813 # fr.BaseSchema raises this when the class is defined; a plain
814 # pydantic model only gets here
815 _reject_buried_ref_exists(cls)
816 _MARKERS_CHECKED.add(cls)
817 for name, field_info in type(obj).model_fields.items():
818 if name not in obj.model_fields_set:
819 continue
820 value = getattr(obj, name, None)
821 if value is None:
822 continue
823 public_name = _client_name(name, field_info)
824 here = f"{path}.{public_name}" if path else public_name
825 marker = _ref_exists_marker(field_info)
826 listed = _listed_ref_exists_marker(field_info) if marker is None else None
827 if marker is not None:
828 references.append(_BodyReference(here, marker.model, value, row=False))
829 elif listed is not None:
830 references.extend(
831 _BodyReference(here, listed.model, item, row=False, listed=True)
832 for item in value
833 if item is not None
834 )
835 else:
836 _collect_value_references(value, here, references, seen)
839def _reference_model(value: Any) -> type[Any] | None:
840 """The model that ``value`` refers to, when it is an ``IDRef`` or
841 ``IDSchema`` reference."""
842 if isinstance(value, IDSchema):
843 return value.get_sql_model_annotation()
844 return None
847def _collect_value_references(
848 value: Any, path: str, references: list[_BodyReference], seen: set[int]
849) -> None:
850 model = _reference_model(value)
851 if model is not None:
852 references.append(_BodyReference(path, model, value.id, row=True))
853 elif isinstance(value, pydantic.BaseModel):
854 _collect_model_references(value, path, references, seen)
855 elif isinstance(value, (list, tuple)):
856 for index, item in enumerate(value):
857 item_model = _reference_model(item)
858 if item_model is not None:
859 references.append(
860 _BodyReference(path, item_model, item.id, row=True, listed=True)
861 )
862 else:
863 _collect_value_references(item, f"{path}[{index}]", references, seen)
864 elif isinstance(value, dict):
865 for key, item in value.items():
866 _collect_value_references(item, f"{path}.{key}", references, seen)
869def _reference_lookups(
870 references: list[_BodyReference],
871) -> dict[type[Any], tuple[list[Any], bool]]:
872 """``{model: (ids, rows)}``: the ids of each model, without repeats, and
873 whether a reference to it needs the rows."""
874 lookups: dict[type[Any], tuple[dict[Any, None], bool]] = {}
875 for reference in references:
876 ids, rows = lookups.get(reference.model, ({}, False))
877 ids[reference.id] = None
878 lookups[reference.model] = (ids, rows or reference.row)
879 return {model: (list(ids), rows) for model, (ids, rows) in lookups.items()}
882def _key_name(model: type[Any]) -> str:
883 """The name of the primary key attribute of ``model``."""
884 mapper = sa_inspect(model)
885 return mapper.get_property_by_column(mapper.primary_key[0]).key
888def _reference_statements(
889 model: type[Any], ids: list[Any], rows: bool
890) -> Iterator[Any]:
891 """The statements that find the rows of ``model`` for ``ids``, in chunks.
893 The statements are ORM statements over the mapped attribute, so a rule of
894 the session (``with_loader_criteria``) reaches them too. An id that does
895 not fit the key column names no row, so it is left out: the database
896 would refuse it with an error, such as a number beyond an ``INTEGER``.
897 When no id fits, there is no statement.
898 """
899 pk = getattr(model, _key_name(model))
900 scope = _default_scope(model)
901 ids = [id_ for id_ in ids if _fits_key(model, id_)]
902 for start in range(0, len(ids), _IN_CHUNK):
903 stmt = select(model if rows else pk).where(
904 pk.in_(ids[start : start + _IN_CHUNK])
905 )
906 if scope is not None:
907 stmt = apply_clauses(stmt, scope)
908 yield stmt
911def _fits_key(model: type[Any], id_: Any) -> bool:
912 """Whether ``id_`` fits the primary key column of ``model``, by the rule
913 of ``column_value``. An id that does not fit names no row."""
914 column = sa_inspect(model).primary_key[0]
915 try:
916 column_value(column.type, id_)
917 except ValueError:
918 return False
919 return True
922def _found_references(
923 model: type[Any], ids: list[Any], rows: bool, key: str, results: Iterable[Any]
924) -> dict[tuple[type[Any], Any], Any]:
925 """``{(model, id): row}`` for what one statement found.
927 A row is keyed by the id that the client sent when the statement asked
928 for one id: the database matched it, and its key can differ in Python,
929 as with a case-insensitive key.
930 """
931 found = list(results)
932 if len(ids) == 1 and len(found) == 1:
933 return {(model, ids[0]): found[0] if rows else _NO_ROW}
934 if rows:
935 return {(model, getattr(row, key)): row for row in found}
936 return {(model, id_): _NO_ROW for id_ in found}
939def _raise_for_missing_references(
940 references: list[_BodyReference], found: Mapping[tuple[type[Any], Any], Any]
941) -> None:
942 """Raise ``NotFound`` for the first field that names a row that was not
943 found. A list of references names all its missing ids."""
944 missing: dict[str, dict[Any, None]] = {}
945 listed: set[str] = set()
946 for reference in references:
947 if (reference.model, reference.id) in found:
948 continue
949 missing.setdefault(reference.path, {})[reference.id] = None
950 if reference.listed:
951 listed.add(reference.path)
952 for path, ids in missing.items():
953 shown = _id_list(list(ids)) if path in listed else next(iter(ids))
954 raise NotFound(f"Id not found for {path}: {shown}")
957def _check_body_references(
958 session: SA_Session, data: Any
959) -> dict[tuple[type[Any], Any], Any]:
960 """Check every reference in ``data``, and return what was found as
961 ``{(model, id): row}``.
963 One query per referenced model (in chunks for a long list). A reference
964 to a row that the model's ``default_scope`` or the session hides is a
965 miss, and raises ``NotFound`` (404) with the field and the id.
966 """
967 references = _body_references(data)
968 found: dict[tuple[type[Any], Any], Any] = {}
969 # the query must not write an object that the code is still building
970 with session.no_autoflush:
971 for model, (ids, rows) in _reference_lookups(references).items():
972 key = _key_name(model)
973 for stmt in _reference_statements(model, ids, rows):
974 results = session.scalars(stmt).unique()
975 found.update(_found_references(model, ids, rows, key, results))
976 _raise_for_missing_references(references, found)
977 return found
980async def _async_check_body_references(
981 session: SA_AsyncSession, data: Any
982) -> dict[tuple[type[Any], Any], Any]:
983 """Async twin of :func:`_check_body_references`."""
984 references = _body_references(data)
985 found: dict[tuple[type[Any], Any], Any] = {}
986 with session.no_autoflush:
987 for model, (ids, rows) in _reference_lookups(references).items():
988 key = _key_name(model)
989 for stmt in _reference_statements(model, ids, rows):
990 results = (await session.scalars(stmt)).unique()
991 found.update(_found_references(model, ids, rows, key, results))
992 _raise_for_missing_references(references, found)
993 return found
996def _id_schema_fields(
997 schema_obj: pydantic.BaseModel, model_cls: type[Any] | None
998) -> Iterator[tuple[str, type[Any], list[Any], bool]]:
999 """``(field, model, ids, is_list)`` for each ``IDRef`` or ``IDSchema``
1000 field that the client sent. ``ids`` keeps the client's order, without
1001 repeats, so a repeated id cannot give a false 404.
1003 A tuple counts only when :func:`_is_reference_tuple` accepts it."""
1004 for field in schema_obj.model_fields_set:
1005 value = getattr(schema_obj, field, None)
1006 model = _reference_model(value)
1007 if model is not None:
1008 yield field, model, [value.id], False
1009 elif (
1010 isinstance(value, list) or _is_reference_tuple(schema_obj, field, model_cls)
1011 ) and any(isinstance(i, IDSchema) for i in value):
1012 # Assume all IdSchemas are for the same model
1013 model = value[0].get_sql_model_annotation()
1014 if model is not None: 1014 ↛ 1004line 1014 didn't jump to line 1004 because the condition on line 1014 was always true
1015 yield field, model, list(dict.fromkeys(i.id for i in value)), True
1018def _is_reference_tuple(
1019 schema_obj: pydantic.BaseModel, field: str, model_cls: type[Any] | None
1020) -> bool:
1021 """Whether ``field`` of ``schema_obj`` holds a tuple of references for a
1022 to-many relationship of ``model_cls``.
1024 The field's type decides, not its value: it must be a collection of
1025 references, such as ``tuple[IDRef[Tag], ...]``. Another tuple, such as
1026 ``tuple[IDRef[Author], int]`` or a tuple for a JSON column, is written as
1027 it is.
1028 """
1029 field_info = type(schema_obj).model_fields.get(field)
1030 if (
1031 model_cls is None
1032 or field_info is None
1033 or not isinstance(getattr(schema_obj, field, None), tuple)
1034 ):
1035 return False
1036 item = _collection_item_type(field_info.annotation)
1037 return (
1038 item is not None
1039 and is_reference_annotation(item)
1040 and is_to_many_relationship(model_cls, field)
1041 )
1044def _client_name(field_name: str, field_info: FieldInfo) -> str:
1045 """The name of a field as the client sends it in a body: its validation
1046 alias when that is a string, else its alias, else its name."""
1047 if isinstance(field_info.validation_alias, str):
1048 return field_info.validation_alias
1049 return field_info.alias or field_name
1052def _public_name(schema_obj: pydantic.BaseModel, field: str) -> str:
1053 """The name of ``field`` of ``schema_obj`` as the client sends it."""
1054 return _client_name(field, type(schema_obj).model_fields[field])
1057def _id_list(ids: list[Any]) -> str:
1058 """Ids for an error text, as the client wrote them, such as ``[7, 9]``."""
1059 return "[" + ", ".join(map(str, ids)) + "]"
1062def _id_schema_rows(
1063 label: str, ids: list[Any], found: list[Any], key: str, is_list: bool
1064) -> Any:
1065 """The resolved value of a field, from the rows that were ``found``.
1066 Raises ``NotFound`` for an id that has no row, with the field's public
1067 name, ``label``."""
1068 if not is_list:
1069 if not found:
1070 raise NotFound(f"Id not found for {label}: {ids[0]}")
1071 return found[0]
1072 by_id = {getattr(row, key): row for row in found}
1073 missing = [id_ for id_ in ids if id_ not in by_id]
1074 if missing:
1075 raise NotFound(f"Id not found for {label}: {_id_list(missing)}")
1076 return [by_id[id_] for id_ in ids]
1079async def _async_resolve_ids_to_sqlalchemy_objects(
1080 session: SA_AsyncSession,
1081 schema_obj: pydantic.BaseModel,
1082 model_cls: type[Any] | None = None,
1083) -> dict[str, Any]:
1084 """Async twin of :func:`_resolve_ids_to_sqlalchemy_objects`."""
1085 checked = _checked_references(session)
1086 resolved: dict[str, Any] = {}
1087 for field, model, ids, is_list in _id_schema_fields(schema_obj, model_cls):
1088 rows = _recorded_rows(checked, model, ids)
1089 if rows is not None:
1090 resolved[field] = rows if is_list else rows[0]
1091 continue
1092 if not is_list and _default_scope(model) is None:
1093 # unscoped: keep get_one, which serves identity-map hits
1094 try:
1095 if not _fits_key(model, ids[0]):
1096 raise NoResultFound
1097 resolved[field] = await session.get_one(model, ids[0])
1098 except NoResultFound as e:
1099 label = _public_name(schema_obj, field)
1100 raise NotFound(f"Id not found for {label}: {ids[0]}") from e
1101 continue
1102 found: list[Any] = []
1103 for stmt in _reference_statements(model, ids, rows=True):
1104 found.extend((await session.scalars(stmt)).unique())
1105 label = _public_name(schema_obj, field)
1106 key = _key_name(model)
1107 resolved[field] = _id_schema_rows(label, ids, found, key, is_list)
1108 return resolved
1111def _resolve_ids_to_sqlalchemy_objects(
1112 session: SA_Session,
1113 schema_obj: pydantic.BaseModel,
1114 model_cls: type[Any] | None = None,
1115) -> dict[str, Any]:
1116 """Resolve the ``IDRef`` and ``IDSchema`` fields of ``schema_obj`` to rows.
1118 Returns ``{field_name: row_or_rows}`` for the fields that refer to a
1119 model. ``schema_obj`` itself is left unchanged, so it keeps the validated
1120 request values (``IDRef[T]``, not ORM rows). ``model_cls`` is the model
1121 that ``schema_obj`` is written to. A tuple of references resolves only
1122 for a to-many relationship of it, so without ``model_cls`` no tuple
1123 resolves.
1125 The lookup applies the referenced model's ``default_scope``, so a
1126 reference to a row that the scope hides is ``NotFound``, as a missing row
1127 is. A model without a ``default_scope`` resolves by primary key alone.
1128 Inside a write action, a reference that the action already checked is
1129 taken from its record, without a query.
1130 """
1131 checked = _checked_references(session)
1132 resolved: dict[str, Any] = {}
1133 for field, model, ids, is_list in _id_schema_fields(schema_obj, model_cls):
1134 rows = _recorded_rows(checked, model, ids)
1135 if rows is not None:
1136 resolved[field] = rows if is_list else rows[0]
1137 continue
1138 if not is_list and _default_scope(model) is None:
1139 # unscoped: keep get_one, which serves identity-map hits
1140 try:
1141 if not _fits_key(model, ids[0]):
1142 raise NoResultFound
1143 resolved[field] = session.get_one(model, ids[0])
1144 except NoResultFound as e:
1145 label = _public_name(schema_obj, field)
1146 raise NotFound(f"Id not found for {label}: {ids[0]}") from e
1147 continue
1148 found: list[Any] = []
1149 for stmt in _reference_statements(model, ids, rows=True):
1150 found.extend(session.scalars(stmt).unique())
1151 label = _public_name(schema_obj, field)
1152 key = _key_name(model)
1153 resolved[field] = _id_schema_rows(label, ids, found, key, is_list)
1154 return resolved
1157def _ref_exists_marker(field_info: FieldInfo) -> RefExists | None:
1158 """Return the ``RefExists`` marker on a field, or ``None``.
1160 Found at the field's top level (``MustExist[pk, M]``), or recovered from
1161 the union member for an optional field (``MustExist[pk, M] | None``),
1162 where Pydantic keeps the marker on the inner annotation rather than
1163 ``field_info.metadata`` -- so an optional checked FK is checked like the
1164 plain form (parity with ``Optional[IDRef]``).
1165 """
1166 _, metadata = _unwrap_type(field_info.annotation)
1167 for m in (*field_info.metadata, *metadata):
1168 if isinstance(m, RefExists):
1169 return m
1170 return None
1173#: The collections of a to-many field of rows, as in ``Sequence[PostSchema]``
1174#: or ``list[IDRef[Tag]]``. A set cannot hold them: Pydantic models are not
1175#: hashable.
1176_ROW_COLLECTIONS = (list, tuple, _AbcSequence)
1177#: The collections of a list of ids, as in ``list[MustExist[int, Tag]]``.
1178_ID_COLLECTIONS = (*_ROW_COLLECTIONS, set, frozenset, _AbcSet)
1181def _collection_item_type(
1182 annotation: Any,
1183 seen: set[Any] | None = None,
1184 collections: tuple[type, ...] = _ROW_COLLECTIONS,
1185) -> Any:
1186 """The item type of a list-like ``annotation``, or ``None``.
1188 The ``collections`` count, by default a list and a ``Sequence``, and a
1189 tuple only in its form with one item type, ``tuple[X, ...]``. ``str``
1190 does not count. The ``Optional``, ``Annotated`` and type alias layers
1191 around the collection are removed first. ``seen`` is as in
1192 :func:`_alias_value`.
1193 """
1194 annotation, _ = _unwrap_type(annotation, seen)
1195 origin = get_origin(annotation)
1196 if origin not in collections:
1197 return None
1198 args = get_args(annotation)
1199 if origin is tuple and not (len(args) == 2 and args[1] is Ellipsis):
1200 return None
1201 return args[0] if args else None
1204def _listed_ref_exists_marker(field_info: FieldInfo) -> RefExists | None:
1205 """Return the ``RefExists`` marker of the items of a list field, such as
1206 ``list[MustExist[int, Tag]]``, or ``None``.
1208 The field may allow ``None``, and so may each item. A tuple counts only
1209 in its form with one item type, ``tuple[MustExist[int, Tag], ...]``.
1210 """
1211 item = _collection_item_type(field_info.annotation, collections=_ID_COLLECTIONS)
1212 if item is None:
1213 return None
1214 _, metadata = _unwrap_type(item)
1215 for m in metadata:
1216 if isinstance(m, RefExists): 1216 ↛ 1215line 1216 didn't jump to line 1215 because the condition on line 1216 was always true
1217 return m
1218 return None
1221def _ref_exists_fields(
1222 schema_obj: pydantic.BaseModel,
1223) -> dict[type[Any], list[tuple[str, Any, bool]]]:
1224 """``{model: [(label, id, listed), ...]}`` for the ``MustExist``
1225 fields that the client sent with a value other than ``None``. ``label`` is
1226 the name that the client sends. A list of ids gives one entry for each
1227 id, with ``listed`` set."""
1228 by_target: dict[type[Any], list[tuple[str, Any, bool]]] = {}
1229 model_fields = type(schema_obj).model_fields
1230 for field_name in schema_obj.model_fields_set:
1231 field_info = model_fields.get(field_name)
1232 if field_info is None: 1232 ↛ 1233line 1232 didn't jump to line 1233 because the condition on line 1232 was never true
1233 continue
1234 value = getattr(schema_obj, field_name, None)
1235 if value is None:
1236 continue
1237 label = _client_name(field_name, field_info)
1238 marker = _ref_exists_marker(field_info)
1239 if marker is not None:
1240 by_target.setdefault(marker.model, []).append((label, value, False))
1241 continue
1242 listed = _listed_ref_exists_marker(field_info)
1243 if listed is not None:
1244 by_target.setdefault(listed.model, []).extend(
1245 (label, item, True) for item in value if item is not None
1246 )
1247 return by_target
1250def _unchecked_ref_exists_fields(
1251 session: SA_Session | SA_AsyncSession, schema_obj: pydantic.BaseModel
1252) -> dict[type[Any], list[tuple[str, Any, bool]]]:
1253 """:func:`_ref_exists_fields` without the ids that the running write
1254 action has checked."""
1255 checked = _checked_references(session)
1256 unchecked: dict[type[Any], list[tuple[str, Any, bool]]] = {}
1257 for model, items in _ref_exists_fields(schema_obj).items():
1258 items = [item for item in items if (model, item[1]) not in checked]
1259 if items:
1260 unchecked[model] = items
1261 return unchecked
1264def _raise_for_missing_refs(
1265 items: list[tuple[str, Any, bool]], found: set[Any]
1266) -> None:
1267 """Raise ``NotFound`` for the first field with an id that was not found.
1268 A list of ids names all its missing ids."""
1269 missing: dict[str, dict[Any, None]] = {}
1270 listed: set[str] = set()
1271 for field_name, value, is_listed in items:
1272 if value in found:
1273 continue
1274 missing.setdefault(field_name, {})[value] = None
1275 if is_listed:
1276 listed.add(field_name)
1277 for field_name, ids in missing.items():
1278 shown = _id_list(list(ids)) if field_name in listed else next(iter(ids))
1279 raise NotFound(f"Id not found for {field_name}: {shown}")
1282def _check_ref_exists(session: SA_Session, schema_obj: pydantic.BaseModel) -> None:
1283 """Check that every ``MustExist`` id of ``schema_obj`` exists (sync).
1285 One ``SELECT pk WHERE pk IN (...)`` per referenced model (no N+1); raises
1286 ``NotFound`` (404) naming the field and id on a miss. The model's
1287 ``default_scope`` applies, so a row the scope hides is a miss. Inside a
1288 write action, an id that the action already checked is not queried again.
1289 """
1290 for model, items in _unchecked_ref_exists_fields(session, schema_obj).items():
1291 ids = list(dict.fromkeys(value for _, value, _ in items))
1292 found: set[Any] = set()
1293 for stmt in _reference_statements(model, ids, rows=False):
1294 found.update(session.scalars(stmt))
1295 _raise_for_missing_refs(items, found)
1298async def _async_check_ref_exists(
1299 session: SA_AsyncSession, schema_obj: pydantic.BaseModel
1300) -> None:
1301 """Async twin of :func:`_check_ref_exists`."""
1302 for model, items in _unchecked_ref_exists_fields(session, schema_obj).items():
1303 ids = list(dict.fromkeys(value for _, value, _ in items))
1304 found: set[Any] = set()
1305 for stmt in _reference_statements(model, ids, rows=False):
1306 found.update(await session.scalars(stmt))
1307 _raise_for_missing_refs(items, found)
1310def get_read_only_fields(model_cls: type[pydantic.BaseModel]) -> list[str]:
1311 """Get all fields from a model annotated as ReadOnly[]"""
1312 read_only_fields: list[str] = []
1313 # Get read-only fields from Annotated metadata
1314 for field_name, field_info in model_cls.model_fields.items():
1315 metadata = getattr(field_info, "metadata", None)
1316 if metadata and readonly_marker in metadata:
1317 read_only_fields.append(field_name)
1318 return read_only_fields
1321#: Pydantic's secret types. A response shows their value masked, and a write
1322#: stores the secret.
1323_SECRET_TYPES: tuple[type, ...] = (
1324 pydantic.SecretStr,
1325 pydantic.SecretBytes,
1326 pydantic.Secret,
1327)
1330#: Dumps a value by its own type, as ``model_dump(mode="json")`` dumps a
1331#: field of type ``Any``. A float such as ``nan`` stays a float, as in a field
1332#: of type ``float``, so that ``_with_non_finite_as_text`` finds it.
1333_ANY_VALUE = pydantic.TypeAdapter(
1334 Any, config=pydantic.ConfigDict(ser_json_inf_nan="constants")
1335)
1337#: The types of the values in a JSON document that need no check.
1338_JSON_SCALAR_TYPES = frozenset({str, int, float, bool, type(None)})
1341def _json_data(
1342 value: Any, column: str, adapter: pydantic.TypeAdapter[Any] = _ANY_VALUE
1343) -> Any:
1344 """``value`` as a ``JSON`` column takes it: dumped as Pydantic dumps a
1345 value of type ``Any`` in JSON mode. A model becomes what
1346 ``model_dump(mode="json", round_trip=True)`` gives, also a model in a dict
1347 or a list. A ``datetime``, a ``UUID`` or a ``Decimal``
1348 becomes text, and a set becomes a list. The dump goes by the type of each
1349 value, so a serializer on the field itself, such as a
1350 ``PlainSerializer``, does not run. A serializer in a nested model does.
1352 The dump is one that Restly reads back. The keys are the names of the
1353 fields, not the aliases, also for a model with
1354 ``serialize_by_alias=True``: a response reads the document of a column by
1355 the names, as it reads the columns. A computed field is left out, because
1356 a model with ``extra="forbid"`` refuses it. A ``Json[T]`` field stays
1357 text, as its validation reads it.
1359 A field typed as a nested model validates to a model, and a field typed
1360 ``list[datetime]`` to datetimes. A ``JSON`` column binds through
1361 ``json.dumps``, which cannot take them. A write and a filter dump the value
1362 the same way, so they agree. SQLAlchemy's ``JSON.NULL`` and an SQL
1363 expression, such as ``null()``, go to the column as they are.
1365 :param column: The column, such as ``Shop.address``, for the message of
1366 an error.
1367 :param adapter: The type to dump by, such as the type of a
1368 ``PydanticJSON`` column in a query, so that the query dumps a value
1369 as the write does. A part that does not fit the type, such as a part
1370 of a document, is dumped by its own type.
1371 :raises RestlyConfigurationError: the value holds something that a dump
1372 leaves out or masks, such as a secret.
1373 """
1374 if value is sqlalchemy.JSON.NULL or isinstance(value, ClauseElement):
1375 return value
1376 _reject_excluded_json_fields(value, column)
1377 return _with_non_finite_as_text(
1378 adapter.dump_python(
1379 value, mode="json", round_trip=True, by_alias=False, warnings=False
1380 )
1381 )
1384def _with_non_finite_as_text(data: Any) -> Any:
1385 """``data``, JSON data from a dump, with each NaN or infinity as the text
1386 ``"NaN"``, ``"Infinity"`` or ``"-Infinity"``.
1388 JSON has no number for them, so PostgreSQL and MySQL refuse them in a
1389 ``JSON`` column. PostgreSQL's ``to_jsonb()`` writes this text, and so does
1390 Pydantic's ``dump_json()`` with ``ser_json_inf_nan="strings"``. A
1391 ``float`` field reads the text back as a number in lax mode. The dump
1392 itself cannot write the text: Pydantic applies ``ser_json_inf_nan`` to a
1393 field of type ``float`` only in ``dump_json()``.
1395 ``data`` comes back as it is when it holds no such float, which is the
1396 common case. Otherwise the containers are copied, not changed.
1397 """
1398 pending = [data]
1399 while pending:
1400 item = pending.pop()
1401 kind = type(item)
1402 if kind is float:
1403 if not math.isfinite(item):
1404 return _replace_non_finite(data)
1405 elif kind is list:
1406 pending.extend(item)
1407 elif kind is dict:
1408 pending.extend(item.values())
1409 return data
1412def _replace_non_finite(data: Any) -> Any:
1413 kind = type(data)
1414 if kind is float and not math.isfinite(data):
1415 if math.isnan(data):
1416 return "NaN"
1417 return "Infinity" if data > 0 else "-Infinity"
1418 if kind is list:
1419 return [_replace_non_finite(item) for item in data]
1420 if kind is dict:
1421 return {key: _replace_non_finite(item) for key, item in data.items()}
1422 return data
1425def _secret_error(column: str, where: str) -> RestlyConfigurationError:
1426 return RestlyConfigurationError(
1427 f"{column}: {where} is a secret, such as a SecretStr. A JSON dump masks "
1428 "a secret, so the column would store '**********'. Leave the secret out "
1429 "of the document, or write a SQLAlchemy TypeDecorator that stores it."
1430 )
1433def _excluded_error(column: str, where: str) -> RestlyConfigurationError:
1434 return RestlyConfigurationError(
1435 f"{column}: {where} is left out of the dump, as a WriteOnly or "
1436 "Field(exclude=True) field is. So the column would not store its value. "
1437 "Remove the exclusion, or write a SQLAlchemy TypeDecorator that stores it."
1438 )
1441def _excluded_if_error(column: str, where: str) -> RestlyConfigurationError:
1442 return RestlyConfigurationError(
1443 f"{column}: {where} has exclude_if, so a JSON dump can leave it out. Then "
1444 "the column would not store its value. Remove exclude_if, or write a "
1445 "SQLAlchemy TypeDecorator that stores the field."
1446 )
1449def _read_only_error(column: str, where: str) -> RestlyConfigurationError:
1450 return RestlyConfigurationError(
1451 f"{column}: {where} is ReadOnly. But a request writes the whole "
1452 "document, so it would replace the value that the server set. Keep such "
1453 "a value in a column of its own, or use a model without ReadOnly for "
1454 "the document."
1455 )
1458def _read_only(model: type[pydantic.BaseModel], field: FieldInfo) -> bool:
1459 """Whether ``field`` of ``model`` is ``ReadOnly``, also as in
1460 ``ReadOnly[int] | None``. The ``id`` of a reference, such as
1461 ``IDRef[User]``, is a value that the client sends, so it does not count."""
1462 if is_reference_annotation(model):
1463 return False
1464 _, metadata = _unwrap_type(field.annotation)
1465 return readonly_marker in field.metadata or readonly_marker in metadata
1468def _dataclass_error(column: str, where: str) -> RestlyConfigurationError:
1469 return RestlyConfigurationError(
1470 f"{column}: {where} is a dataclass. Restly cannot check a dataclass for "
1471 "secrets and excluded fields before the dump. Use a Pydantic model."
1472 )
1475def _iterator_error(column: str, where: str) -> RestlyConfigurationError:
1476 return RestlyConfigurationError(
1477 f"{column}: {where} is an iterator, which can be read only once. Use a list."
1478 )
1481#: A field that a JSON dump leaves out or masks, or that a write would
1482#: replace, and the function that makes its error.
1483_Unstorable = tuple[str, Callable[[str, str], RestlyConfigurationError]]
1485#: For each model class, its first such field, or None. A write checks each
1486#: model in the document, so the fields of a class are checked only once.
1487_UNSTORABLE_FIELDS: weakref.WeakKeyDictionary[type, _Unstorable | None] = (
1488 weakref.WeakKeyDictionary()
1489)
1492def _unstorable_field(model: type[pydantic.BaseModel]) -> _Unstorable | None:
1493 """The first field of ``model`` that a JSON dump leaves out or masks, or
1494 that is ``ReadOnly``, and the function that makes its error."""
1495 try:
1496 return _UNSTORABLE_FIELDS[model]
1497 except KeyError:
1498 pass
1499 found: _Unstorable | None = None
1500 for name, field in model.model_fields.items():
1501 if field.exclude:
1502 found = (name, _excluded_error)
1503 elif _excluded_if(field):
1504 found = (name, _excluded_if_error)
1505 # A secret field, also one without a value yet: the first write of
1506 # such a document fails, not the first with a secret.
1507 elif _hides_value(field):
1508 found = (name, _secret_error)
1509 elif _read_only(model, field):
1510 found = (name, _read_only_error)
1511 if found:
1512 break
1513 _UNSTORABLE_FIELDS[model] = found
1514 return found
1517def _reject_excluded_json_fields(value: Any, column: str) -> None:
1518 """Reject exclusions, secrets, ``ReadOnly`` fields, and document values
1519 that cannot be inspected safely. A JSON dump leaves out an excluded field
1520 and masks a secret, so the column would not get the value. A request
1521 writes the whole document, so it would replace a ``ReadOnly`` value.
1523 :param column: The column, or the type of a ``PydanticJSON`` column, for
1524 the message of an error.
1525 """
1526 pending = [value]
1527 seen: set[int] = set()
1528 while pending:
1529 item = pending.pop()
1530 kind = type(item)
1531 # Most of a document is plain JSON data, as a request body gives it.
1532 # Check it by its exact type first: this is much faster.
1533 if kind in _JSON_SCALAR_TYPES:
1534 continue
1535 if kind is dict or kind is list:
1536 if id(item) not in seen: 1536 ↛ 1541line 1536 didn't jump to line 1541 because the condition on line 1536 was always true
1537 seen.add(id(item))
1538 pending.extend(item)
1539 if kind is dict:
1540 pending.extend(item.values())
1541 continue
1542 if dataclasses.is_dataclass(item):
1543 raise _dataclass_error(column, f"the {kind.__name__} in the document")
1544 if isinstance(item, Iterator):
1545 raise _iterator_error(column, "a value in the document")
1546 if isinstance(item, _SECRET_TYPES):
1547 raise _secret_error(column, "a value in the document")
1548 if isinstance(item, str | bytes | bytearray) or not isinstance(
1549 item, (pydantic.BaseModel, Mapping, _AbcSequence, _AbcSet, Enum)
1550 ):
1551 continue
1552 if id(item) in seen: 1552 ↛ 1553line 1552 didn't jump to line 1553 because the condition on line 1552 was never true
1553 continue
1554 seen.add(id(item))
1555 if isinstance(item, pydantic.BaseModel):
1556 unstorable = _unstorable_field(kind)
1557 if unstorable is not None:
1558 name, error = unstorable
1559 raise error(column, f"{kind.__name__}.{name}")
1560 pending.extend(getattr(item, name, None) for name in kind.model_fields)
1561 if item.model_extra:
1562 pending.extend(item.model_extra.values())
1563 elif isinstance(item, Mapping): 1563 ↛ 1564line 1563 didn't jump to line 1564 because the condition on line 1563 was never true
1564 pending.extend(item.keys())
1565 pending.extend(item.values())
1566 elif isinstance(item, Enum):
1567 pending.append(item.value)
1568 else:
1569 pending.extend(item)
1572#: Pydantic validates a field of these types to an iterator, which can be
1573#: read only once.
1574_ITERATOR_TYPES = (Iterable, Iterator, Generator)
1577def _reject_excluded_json_type(type_: Any, column: str) -> None:
1578 """Reject a document type with a part that a JSON dump leaves out or
1579 masks, or that is ``ReadOnly``, as :func:`_reject_excluded_json_fields`
1580 rejects such a value. The type tells it when the column is defined,
1581 before the first write. A part of type ``Any`` can still hold such a
1582 value, so each write checks too.
1584 :param column: The type of the column, such as
1585 ``PydanticJSON(Address)``, for the message of an error.
1586 :raises RestlyConfigurationError: ``type_`` has a secret, an excluded
1587 field, a ``ReadOnly`` part, a dataclass or an iterator in it.
1588 """
1589 seen_aliases: set[Any] = set()
1590 seen_classes: set[Any] = set()
1591 # A ReadOnly around the whole type is not a part of the document.
1592 root, _ = _unwrap_type(type_, seen_aliases)
1593 # Each part, the field or the type it is in, and whether the part is
1594 # inside that field or type, as P is in list[P].
1595 pending: list[tuple[Any, str, bool]] = [(root, _type_label(type_), False)]
1596 while pending:
1597 annotation, where, inside = pending.pop()
1598 part, metadata = _unwrap_type(annotation, seen_aliases)
1599 origin = get_origin(part) or part
1600 found = f"{_type_label(part)} in {where}" if inside else where
1601 if readonly_marker in metadata:
1602 raise _read_only_error(column, found)
1603 if not isinstance(origin, type):
1604 # A union, a Literal or a value in a Literal.
1605 pending.extend((arg, where, True) for arg in get_args(part))
1606 continue
1607 if issubclass(origin, _SECRET_TYPES):
1608 raise _secret_error(column, found)
1609 if dataclasses.is_dataclass(origin):
1610 raise _dataclass_error(column, found)
1611 if origin in _ITERATOR_TYPES:
1612 raise RestlyConfigurationError(
1613 f"{column}: Pydantic validates {found} to an iterator, which can "
1614 "be read only once. Use list."
1615 )
1616 if issubclass(origin, pydantic.BaseModel):
1617 if origin in seen_classes:
1618 continue
1619 seen_classes.add(origin)
1620 for name, field in origin.model_fields.items():
1621 field_where = f"{origin.__name__}.{name}"
1622 if field.exclude is True:
1623 raise _excluded_error(column, field_where)
1624 if _excluded_if(field):
1625 raise _excluded_if_error(column, field_where)
1626 if _read_only(origin, field):
1627 raise _read_only_error(column, field_where)
1628 pending.append((field.annotation, field_where, False))
1629 continue
1630 if is_typeddict(origin) or (
1631 issubclass(origin, tuple) and hasattr(origin, "_fields")
1632 ):
1633 # A TypedDict or a NamedTuple: check its fields, and below, the
1634 # arguments of a generic one, as SecretStr in Pair[SecretStr].
1635 if part in seen_classes: 1635 ↛ 1636line 1635 didn't jump to line 1636 because the condition on line 1635 was never true
1636 continue
1637 seen_classes.add(part)
1638 try:
1639 hints = typing.get_type_hints(origin, include_extras=True)
1640 except NameError:
1641 # A forward reference that does not resolve yet. Each write
1642 # checks the value.
1643 hints = {}
1644 for name, hint in hints.items():
1645 hint_where = f"{origin.__name__}.{name}"
1646 if is_typeddict(origin):
1647 # A dump leaves out an excluded key of a TypedDict, as
1648 # it leaves out such a field of a model. A NamedTuple
1649 # keeps it.
1650 field = FieldInfo.from_annotation(hint)
1651 if field.exclude is True:
1652 raise _excluded_error(column, hint_where)
1653 if _excluded_if(field):
1654 raise _excluded_if_error(column, hint_where)
1655 if readonly_marker in field.metadata:
1656 raise _read_only_error(column, hint_where)
1657 pending.append((hint, hint_where, False))
1658 pending.extend((arg, where, True) for arg in get_args(part))
1661def _excluded_if(field: FieldInfo) -> bool:
1662 """Whether a dump can leave out ``field``, by its ``exclude_if``.
1663 Pydantic has ``exclude_if`` from version 2.12."""
1664 return getattr(field, "exclude_if", None) is not None
1667def _type_label(type_: Any) -> str:
1668 """``type_`` as a message shows it: ``Address``, or ``dict[str, Address]``,
1669 without the names of modules. Text in quotes, as in a ``Literal``, stays
1670 as it is."""
1671 if isinstance(type_, type) and not get_args(type_):
1672 return type_.__name__
1673 return re.sub(
1674 r"'[^']*'|\"[^\"]*\"|\b(?:[A-Za-z_]\w*\.)+([A-Za-z_]\w*)",
1675 lambda match: match.group(1) or match.group(0),
1676 repr(type_),
1677 )
1680def _hides_value(field: FieldInfo) -> bool:
1681 """Whether a response never shows the value of ``field``.
1683 A WriteOnly field, or one with ``exclude=True``, never goes out. A field
1684 of one of Pydantic's secret types goes out masked, also in a union such
1685 as ``SecretStr | int``. A filter or a sort on such a field would let a
1686 client find out the value.
1687 """
1688 if field.exclude is True:
1689 return True
1690 return _holds_secret(field.annotation, set())
1693def _holds_secret(annotation: Any, seen: set[Any]) -> bool:
1694 """Whether ``annotation`` is one of Pydantic's secret types, or a union
1695 with one. ``seen`` is as in :func:`_alias_value`."""
1696 annotation, _ = _unwrap_type(annotation, seen)
1697 if get_origin(annotation) in (types.UnionType, Union):
1698 return any(_holds_secret(arg, seen) for arg in get_args(annotation))
1699 origin = get_origin(annotation) or annotation
1700 return isinstance(origin, type) and issubclass(origin, _SECRET_TYPES)
1703def is_readonly_field(
1704 model: pydantic.BaseModel | type[pydantic.BaseModel], field_name: str
1705) -> bool:
1706 """Check if a specific field is marked as readonly."""
1707 if isinstance(model, pydantic.BaseModel):
1708 model = model.__class__
1709 field_info = model.model_fields.get(field_name)
1710 return _is_readonly(field_info)
1713def _is_readonly(field_info: FieldInfo | None) -> bool:
1714 if field_info is None:
1715 return False
1716 metadata = getattr(field_info, "metadata", None)
1717 if not metadata:
1718 return False
1719 return readonly_marker in metadata
1722def _is_writeonly(field_info: FieldInfo | None) -> bool:
1723 if field_info is None:
1724 return False
1725 metadata = getattr(field_info, "metadata", None)
1726 if not metadata:
1727 return False
1728 return writeonly_marker in metadata
1731def get_write_only_fields(model_cls: type[pydantic.BaseModel]) -> list[str]:
1732 """Get all fields from a model annotated as WriteOnly[]"""
1733 write_only_fields: list[str] = []
1734 # Get write-only fields from Annotated metadata
1735 for field_name, field_info in model_cls.model_fields.items():
1736 if _is_writeonly(field_info):
1737 write_only_fields.append(field_name)
1738 return write_only_fields
1741def is_writeonly_field(
1742 model_cls: pydantic.BaseModel | type[pydantic.BaseModel], field_name: str
1743) -> bool:
1744 """Check if a specific field is marked as writeonly."""
1745 if isinstance(model_cls, pydantic.BaseModel):
1746 model_cls = model_cls.__class__
1747 field_info = model_cls.model_fields.get(field_name)
1748 return _is_writeonly(field_info)
1751def create_model_without_read_only_fields(
1752 model_cls: type[pydantic.BaseModel], *, omit: Iterable[str] = ()
1753) -> type[pydantic.BaseModel]:
1754 """
1755 Create a subclass of the given pydantic model class with a new name.
1756 Read-only fields are removed, and so are the fields named in ``omit``.
1757 """
1758 new_model_name = _schema_role_name(model_cls, "Create")
1759 new_doc = (model_cls.__doc__ or "") + "\nRead-only fields have been removed."
1761 # Create a subclass that mixes in OmitReadOnlyMixin
1762 new_model_cls = type(
1763 new_model_name,
1764 (OmitReadOnlyMixin, model_cls),
1765 {
1766 "__module__": model_cls.__module__,
1767 "__doc__": new_doc,
1768 "__restly_omit_fields__": frozenset(omit),
1769 },
1770 )
1772 return new_model_cls
1775class OmitReadOnlyMixin(pydantic.BaseModel):
1776 """
1777 Mixin for pydantic models that removes all fields marked as ReadOnly.
1779 Implementation note: this mutates ``cls.model_fields`` in place and then
1780 calls ``model_rebuild(force=True)`` to regenerate the validator/serializer.
1781 Pydantic v2 does not officially document mutation of ``model_fields`` as
1782 a supported customisation hook, but this approach has been stable since
1783 pydantic 2.0 and works on the pinned minimum (``pydantic>=2.11.7``). The
1784 regression test ``tests/test_pydantic_model_fields_mutation.py`` exercises
1785 this contract on the currently-installed pydantic.
1787 Building the class with ``pydantic.create_model(...)`` over the kept
1788 fields was tried first, and it is harder: validators, config, generics
1789 and serializers do not carry over the way inheritance carries them. Only
1790 revisit that if pydantic stops allowing this mutation.
1791 """
1793 @classmethod
1794 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
1795 super().__pydantic_init_subclass__(**kwargs)
1797 # Only this class's own omit: a subclass may declare such a field again.
1798 omit = cls.__dict__.get("__restly_omit_fields__", ())
1799 _drop_fields(
1800 cls,
1801 _brought_back_fields(cls)
1802 | {
1803 name
1804 for name, field_info in cls.model_fields.items()
1805 if _is_readonly(field_info) or name in omit
1806 },
1807 )
1809 cls.model_rebuild(force=True)
1812class _OmitWriteOnlyMixin(pydantic.BaseModel):
1813 """Mixin for the response schema: removes the WriteOnly fields."""
1815 #: The names and aliases of the removed WriteOnly fields.
1816 __restly_writeonly_keys__: ClassVar[frozenset[str]] = frozenset()
1818 @classmethod
1819 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
1820 super().__pydantic_init_subclass__(**kwargs)
1822 writeonly_fields = {
1823 name: field_info
1824 for name, field_info in cls.model_fields.items()
1825 if _is_writeonly(field_info)
1826 }
1827 new_keys = frozenset(
1828 key
1829 for name, field_info in writeonly_fields.items()
1830 for key in _input_keys(name, field_info)
1831 )
1832 removed = _brought_back_fields(cls) | set(writeonly_fields)
1833 _drop_fields(cls, removed)
1834 # A field that this class declares again goes out, so its keys stay.
1835 declared_again = frozenset(
1836 key
1837 for name, field_info in cls.model_fields.items()
1838 if name in cls.__restly_dropped_fields__
1839 for key in _input_keys(name, field_info)
1840 )
1841 cls.__restly_writeonly_keys__ = (
1842 cls.__restly_writeonly_keys__ - declared_again
1843 ) | new_keys
1845 if removed:
1846 # A forward reference that is not defined yet does not fail here:
1847 # pydantic builds the class again when it is first used.
1848 cls.model_rebuild(force=True, raise_errors=False)
1850 # "before", not "wrap": pydantic does not pass ``by_name`` through a wrap
1851 # validator to the nested models.
1852 @pydantic.model_validator(mode="before")
1853 @classmethod
1854 def _drop_writeonly_keys(cls, value: Any) -> Any:
1855 """Drop WriteOnly keys from a dict. With ``extra="allow"`` they would
1856 otherwise go out as extra fields."""
1857 keys = cls.__restly_writeonly_keys__
1858 if keys and isinstance(value, Mapping):
1859 return {key: item for key, item in value.items() if key not in keys}
1860 return value
1863def _input_keys(name: str, field_info: FieldInfo) -> set[str]:
1864 """The keys under which a field can be in a dict: its name and aliases."""
1865 keys = {name}
1866 if field_info.alias is not None:
1867 keys.add(field_info.alias)
1868 validation_alias = field_info.validation_alias
1869 if isinstance(validation_alias, str):
1870 keys.add(validation_alias)
1871 elif isinstance(validation_alias, pydantic.AliasChoices): 1871 ↛ 1872line 1871 didn't jump to line 1872 because the condition on line 1871 was never true
1872 keys.update(
1873 choice for choice in validation_alias.choices if isinstance(choice, str)
1874 )
1875 return keys
1878def _drop_fields(cls: type[pydantic.BaseModel], names: set[str]) -> None:
1879 """Remove the fields ``names`` from ``cls``, and remember them for its
1880 subclasses: see :func:`_brought_back_fields`."""
1881 for name in names:
1882 del cls.model_fields[name]
1883 _skip_field_checks(cls, names)
1884 cls.__restly_dropped_fields__ = _dropped_fields(cls) | names # type: ignore[attr-defined]
1887def _dropped_fields(cls: type) -> frozenset[str]:
1888 """The fields that ``cls`` and each of its parents dropped."""
1889 return frozenset().union(
1890 *(vars(klass).get("__restly_dropped_fields__", ()) for klass in cls.__mro__)
1891 )
1894def _brought_back_fields(cls: type[pydantic.BaseModel]) -> set[str]:
1895 """The fields that a parent dropped and that pydantic built again for ``cls``.
1897 Pydantic collects the fields of a class from the annotations of all its
1898 parents. A field that is no longer in the fields of the parent, it builds
1899 again from the annotation, without its ``ReadOnly`` or ``WriteOnly`` marker
1900 and its default. So a ``ReadOnly`` field would become writable in a subclass
1901 of the update schema.
1903 A field that ``cls`` declares itself, or that another parent has, is a real
1904 field and stays.
1905 """
1906 dropped = _dropped_fields(cls)
1907 if not dropped:
1908 return set()
1909 own = _own_annotations(cls)
1910 in_parents = {
1911 name
1912 for base in cls.__bases__
1913 for name in getattr(base, "__pydantic_fields__", ())
1914 }
1915 return {
1916 name
1917 for name in dropped
1918 if name in cls.model_fields and name not in own and name not in in_parents
1919 }
1922def _skip_field_checks(cls: type[pydantic.BaseModel], removed: set[str]) -> None:
1923 """Let validators and serializers of the removed fields stay on ``cls``.
1925 Pydantic checks that each field validator and serializer names a field of
1926 the class. A ``@field_validator("password")`` on the main schema would
1927 then fail the response schema, which has no ``password``, and a
1928 ``@field_validator("slug")`` on a ``ReadOnly`` slug would fail the create
1929 and update schemas. Without the check, pydantic does not use it there.
1930 """
1931 decorators = cls.__pydantic_decorators__
1932 for group in (
1933 decorators.validators,
1934 decorators.field_validators,
1935 decorators.field_serializers,
1936 ):
1937 for name, decorator in list(group.items()):
1938 if removed.intersection(decorator.info.fields):
1939 info = dataclasses.replace(decorator.info, check_fields=False)
1940 group[name] = dataclasses.replace(decorator, info=info) # type: ignore[assignment]
1943def _as_response(cls: type[pydantic.BaseModel], value: Any) -> Any:
1944 """An instance of another model as an instance of the response schema
1945 ``cls``. Fields that ``cls`` does not have stay behind, also on a route
1946 without a response model, such as the list of a react-admin view.
1948 Restly copies the values of an instance of a subclass of ``cls``, and of
1949 an instance of the main schema for a response schema that
1950 :func:`derive_response_schema` built. It does not validate them again:
1951 they are already valid, and a validator that changes a value would
1952 change it twice.
1954 Any other model is validated into ``cls`` from its attributes. A response
1955 schema that a view sets itself can have other fields and types, so Restly
1956 cannot copy into it.
1958 A value that is not a model comes back as it is. So does an ORM object,
1959 also a SQLModel table row, which is a model too: the view serializes it
1960 as an ORM object.
1961 """
1962 if type(value) is cls or not isinstance(value, pydantic.BaseModel):
1963 return value
1964 if is_mapped_instance(value): 1964 ↛ 1965line 1964 didn't jump to line 1965 because the condition on line 1964 was never true
1965 return value
1966 schema = cls.__dict__.get("__restly_response_of__")
1967 if not isinstance(value, cls) and (schema is None or not isinstance(value, schema)):
1968 return _response_adapter(cls).validate_python(
1969 value, from_attributes=True, by_alias=False, by_name=True
1970 )
1971 fields = cls.model_fields
1972 values = {name: item for name, item in value.__dict__.items() if name in fields}
1973 writeonly_keys = getattr(cls, "__restly_writeonly_keys__", frozenset())
1974 extra = {
1975 key: item
1976 for key, item in (value.__pydantic_extra__ or {}).items()
1977 if key not in writeonly_keys
1978 }
1979 copy = cls.model_construct(
1980 _fields_set=value.model_fields_set & fields.keys(), **extra, **values
1981 )
1982 if value.__pydantic_private__ is not None: 1982 ↛ 1983line 1982 didn't jump to line 1983 because the condition on line 1982 was never true
1983 object.__setattr__(
1984 copy, "__pydantic_private__", dict(value.__pydantic_private__)
1985 )
1986 return copy
1989@functools.cache
1990def _response_adapter(
1991 response_schema: type[pydantic.BaseModel],
1992) -> pydantic.TypeAdapter[pydantic.BaseModel]:
1993 """Validates into a response schema. Through an adapter, not
1994 ``model_validate``: a schema may narrow that classmethod's signature
1995 (SQLModel drops ``by_alias`` and ``by_name``)."""
1996 return pydantic.TypeAdapter(response_schema)
1999_SchemaT = TypeVar("_SchemaT", bound=pydantic.BaseModel)
2002def _reject_table_class(
2003 schema: type[pydantic.BaseModel], where: str, fix: str | None = None
2004) -> None:
2005 """A SQLModel table class cannot be the main schema or a write schema.
2007 Its ``__init__`` does not validate, and a subclass keeps ``table=True``. In
2008 a subclass, Pydantic also takes the column attribute of the parent as the
2009 default of each field, so OpenAPI shows no required fields. SQLModel says
2010 not to inherit from a table class, so Restly does not build a class from
2011 one.
2013 ``fix`` says what to do instead, for a caller that knows a better way than
2014 the default advice.
2016 :raises RestlyConfigurationError: ``schema`` is a table class, or a
2017 subclass of one.
2018 """
2019 if _is_table_subclass(schema): 2019 ↛ 2020line 2019 didn't jump to line 2020 because the condition on line 2019 was never true
2020 _reject_table_subclass(schema, where)
2021 if schema.model_config.get("table") is True: 2021 ↛ 2022line 2021 didn't jump to line 2022 because the condition on line 2021 was never true
2022 raise RestlyConfigurationError(
2023 f"{where} is {schema.__name__}, a SQLModel table class. A table class "
2024 "does not validate its input. A class that Restly builds from it shows "
2025 "no required fields in OpenAPI. "
2026 + (
2027 fix
2028 or "Pass a class without `table=True`, such as the one from "
2029 f"`fr.schemas.derive_schema({schema.__name__})`."
2030 )
2031 )
2034def _reject_table_subclass(annotation: Any, where: str) -> None:
2035 """A schema of a view cannot be, or hold, a subclass of a SQLModel table class.
2037 The table class itself can go out as a response, but a subclass shows no
2038 required fields in OpenAPI, also with ``table=False``. It has no mapper, so
2039 ``derive_schema`` cannot take it either.
2041 :raises RestlyConfigurationError: the type ``annotation`` is such a class,
2042 or holds one at any depth.
2043 """
2044 found = _class_in_type(annotation, _is_table_subclass)
2045 if found is not None: 2045 ↛ 2046line 2045 didn't jump to line 2046 because the condition on line 2045 was never true
2046 raise RestlyConfigurationError(
2047 f"{where} {'is' if found is annotation else 'holds'} {found.__name__}, "
2048 "a subclass of a SQLModel table class. It shows no required fields in "
2049 "OpenAPI. Use a class that does not inherit from the table class: a "
2050 "schema that you write. SQLModel says to inherit from a data model, not "
2051 "from a table class."
2052 )
2055def _is_table_class(cls: type) -> bool:
2056 """Whether ``cls`` is a SQLModel table class, or inherits from one."""
2057 return any(
2058 getattr(base, "model_config", {}).get("table") is True for base in cls.__mro__
2059 )
2062def _is_table_subclass(cls: type) -> bool:
2063 """Whether ``cls`` inherits from a SQLModel table class, and has no table."""
2064 return _is_table_class(cls) and not is_mapped_class(cls)
2067def _class_in_type(
2068 annotation: Any,
2069 matches: Callable[[type], bool],
2070 *,
2071 writable_only: bool = False,
2072 seen: set[Any] | None = None,
2073) -> type | None:
2074 """The first Pydantic class for which ``matches`` is true in the type
2075 ``annotation``, or ``None``.
2077 This follows a type into its arguments, and a Pydantic class into its
2078 fields. With ``writable_only``, it leaves out each ``ReadOnly`` field, as
2079 such a field takes no input. ``seen`` is as in :func:`_alias_value`, and
2080 also holds the classes that the check has followed.
2081 """
2082 seen = set() if seen is None else seen
2083 annotation, _ = _unwrap_type(annotation, seen)
2084 if inspect.isclass(annotation) and issubclass(annotation, pydantic.BaseModel):
2085 if annotation in seen:
2086 return None
2087 seen.add(annotation)
2088 if matches(annotation): 2088 ↛ 2089line 2088 didn't jump to line 2089 because the condition on line 2088 was never true
2089 return annotation
2090 arguments = [
2091 field.annotation
2092 for field in annotation.model_fields.values()
2093 if not (writable_only and _is_readonly(field))
2094 ]
2095 else:
2096 arguments = list(get_args(annotation))
2097 for argument in arguments:
2098 found = _class_in_type(
2099 argument, matches, writable_only=writable_only, seen=seen
2100 )
2101 if found is not None: 2101 ↛ 2102line 2101 didn't jump to line 2102 because the condition on line 2101 was never true
2102 return found
2103 return None
2106def _reject_writable_table_class(schema: type[pydantic.BaseModel], where: str) -> None:
2107 """A client must not write a row through a field of a write schema.
2109 A SQLModel table class does not validate its input, also as the type of a
2110 field, and the model takes the object as it is. So the request body would
2111 create a row, with any id and any column.
2113 :raises RestlyConfigurationError: a field that a client can write holds a
2114 table class.
2115 """
2116 for name, field in schema.model_fields.items():
2117 if _is_readonly(field):
2118 continue
2119 table = _class_in_type(field.annotation, _is_table_class, writable_only=True)
2120 if table is not None: 2120 ↛ 2121line 2120 didn't jump to line 2121 because the condition on line 2120 was never true
2121 raise RestlyConfigurationError(
2122 f"{where} has the field {name}, which holds {table.__name__}, a "
2123 "SQLModel table class. A table class does not validate its input. "
2124 "So a client can write a row through this field, with any id and "
2125 "any column. To let a client choose a row, send its id with "
2126 "`fr.MustExist`, `fr.IDRef` or `fr.IDSchema`. To show the row in "
2127 "responses, mark the field `fr.ReadOnly`."
2128 )
2131def derive_response_schema(schema: type[_SchemaT]) -> type[_SchemaT]:
2132 """Build the response schema from a view's main schema: the schema without its
2133 ``WriteOnly`` fields, named ``<Resource>Response``.
2135 A view without its own
2136 :attr:`~fastapi_restly.views.BaseRestView.response_schema` gets this
2137 class. Restly builds it also when the schema has no ``WriteOnly`` fields,
2138 so OpenAPI shows ``UserResponse`` and not the main schema.
2140 The class is a subclass of ``schema``. Each call with the same schema
2141 returns the same class, so a custom route can name the class that the
2142 view uses::
2144 UserResponse = fr.schemas.derive_response_schema(UserSchema)
2147 class UserView(fr.AsyncRestView):
2148 schema = UserSchema
2150 @fr.get("/me", response_model=UserResponse)
2151 async def me(self): ...
2153 :param schema: The main schema.
2154 :returns: The response schema.
2155 :raises RestlyConfigurationError: ``schema`` is a SQLModel table class.
2156 """
2157 _reject_table_class(schema, "The schema of derive_response_schema")
2158 return cast(type[_SchemaT], _derive_response_schema(schema))
2161@functools.cache
2162def _derive_response_schema(
2163 schema: type[pydantic.BaseModel],
2164) -> type[pydantic.BaseModel]:
2165 """Cached, so a view, a custom route and every request use the same
2166 class. :func:`_as_response` turns an instance of the schema into an
2167 instance of this class."""
2168 cls = type(
2169 _schema_role_name(schema, "Response"),
2170 (_OmitWriteOnlyMixin, schema),
2171 {
2172 "__module__": schema.__module__,
2173 "__doc__": schema.__doc__,
2174 "__restly_response_of__": schema,
2175 },
2176 )
2177 # A recursive schema refers to itself by name, like list["NodeSchema"].
2178 # Pydantic finds a class's own name, but not the name of a parent class
2179 # that was defined in a function. So the response schema gets that name.
2180 namespace = {**(schema.__pydantic_parent_namespace__ or {})}
2181 namespace[schema.__name__] = schema
2182 cls.model_rebuild(force=True, raise_errors=False, _types_namespace=namespace)
2183 return cls
2186def derive_create_schema(schema: type[_SchemaT], model: type[Any]) -> type[_SchemaT]:
2187 """Build the create schema from a view's main schema: the schema without its
2188 ``ReadOnly`` fields, named ``<Resource>Create``.
2190 A view without its own
2191 :attr:`~fastapi_restly.views.BaseRestView.create_schema` gets this class.
2192 The class is a subclass of ``schema``. Each call with the same arguments
2193 returns the same class, so a custom route can name the class that the view
2194 uses::
2196 UserCreate = fr.schemas.derive_create_schema(UserSchema, User)
2198 :param schema: The main schema.
2199 :param model: The view's model. The class also leaves out a primary key that
2200 the server generates, as a view does.
2201 :returns: The create schema.
2202 :raises RestlyConfigurationError: ``schema`` is a SQLModel table class.
2203 """
2204 _reject_table_class(schema, "The schema of derive_create_schema")
2205 return cast(type[_SchemaT], _derive_create_schema(schema, model))
2208@functools.cache
2209def _derive_create_schema(
2210 schema: type[pydantic.BaseModel], model: type[Any]
2211) -> type[pydantic.BaseModel]:
2212 return create_model_without_read_only_fields(
2213 schema, omit=_generated_primary_key_fields(model)
2214 )
2217def derive_update_schema(schema: type[_SchemaT], model: type[Any]) -> type[_SchemaT]:
2218 """Build the update schema from a view's main schema: the schema without its
2219 ``ReadOnly`` fields, with each other field optional, named
2220 ``<Resource>Update``.
2222 A view without its own
2223 :attr:`~fastapi_restly.views.BaseRestView.update_schema` gets this class.
2224 The class is a subclass of ``schema``. Each call with the same arguments
2225 returns the same class, so a custom route can name the class that the view
2226 uses.
2228 ``schema`` can be a class of your own, such as the create schema of a view that
2229 sets ``create_schema``, so that ``PATCH`` follows that body::
2231 class UserCreate(fr.BaseSchema):
2232 name: str
2235 class UserView(fr.AsyncRestView):
2236 create_schema = UserCreate
2237 update_schema = fr.schemas.derive_update_schema(UserCreate, User)
2239 :param schema: The main schema, or another class to start from.
2240 :param model: The view's model. The class also leaves out a primary key that
2241 the server generates, as a view does.
2242 :returns: The update schema.
2243 :raises RestlyConfigurationError: ``schema`` is a SQLModel table class.
2244 """
2245 _reject_table_class(schema, "The schema of derive_update_schema")
2246 return cast(type[_SchemaT], _derive_update_schema(schema, model))
2249@functools.cache
2250def _derive_update_schema(
2251 schema: type[pydantic.BaseModel], model: type[Any]
2252) -> type[pydantic.BaseModel]:
2253 return create_model_with_optional_fields(
2254 schema, omit=_generated_primary_key_fields(model)
2255 )
2258def _generated_primary_key_fields(model_cls: type[Any]) -> frozenset[str]:
2259 """The primary key attributes the server generates, never the client.
2261 A derived create or update schema leaves these out even when the schema
2262 does not mark them ReadOnly. Generated means an autoincrement column, a
2263 column default, or a dataclass field outside ``__init__``. A key without
2264 any of these is a natural key, and the client supplies it.
2265 """
2266 mapper = sa_inspect(model_cls)
2267 autoincrement = getattr(mapper.local_table, "autoincrement_column", None)
2268 not_in_init = (
2269 {f.name for f in dataclasses.fields(model_cls) if not f.init}
2270 if dataclasses.is_dataclass(model_cls)
2271 else set()
2272 )
2273 generated = set()
2274 for column in mapper.primary_key:
2275 key = mapper.get_property_by_column(column).key
2276 if (
2277 column is autoincrement
2278 or column.default is not None
2279 or column.server_default is not None
2280 or key in not_in_init
2281 ):
2282 generated.add(key)
2283 return frozenset(generated)
2286def derive_list_response_schema(
2287 response_schema: type[pydantic.BaseModel],
2288 *,
2289 pagination: Pagination | None = _DEFAULT_PAGINATION,
2290) -> type[pydantic.BaseModel]:
2291 """Build the list response schema of a view: the envelope of its
2292 pagination, filled with its response schema, named
2293 ``<Resource>ListResponse``.
2295 This is what a view's ``list_response_schema`` is unless it sets another
2296 class. On a react-admin view it is a plain list. A route on a router, or
2297 outside the view, can name it, so OpenAPI shows one type for both routes::
2299 UserResponse = fr.schemas.derive_response_schema(UserSchema)
2300 UserListResponse = fr.schemas.derive_list_response_schema(
2301 UserResponse, pagination=AppView.pagination
2302 )
2305 class UserView(AppView):
2306 schema = UserSchema
2308 @fr.get("/inactive", response_model=UserListResponse)
2309 async def inactive(self, list_params): ...
2311 Each call with the same response schema and envelope returns the same
2312 class. Only the envelope of the pagination matters: two paginations with
2313 the same envelope give the same class.
2315 :param response_schema: The view's response schema, such as the one from
2316 :func:`derive_response_schema`.
2317 :param pagination: The view's pagination. ``None`` is a view without
2318 pagination, as on the view. The default is the default pagination.
2319 :returns: The list response schema.
2320 """
2321 envelope = Envelope if pagination is None else pagination.envelope
2322 return _named_list_envelope(envelope, response_schema)
2325@functools.cache
2326def _named_list_envelope(
2327 envelope: type[pydantic.BaseModel], response_schema: type[pydantic.BaseModel]
2328) -> type[pydantic.BaseModel]:
2329 """Cached, so the route and every request use the same class, and two
2330 views with the same response schema and envelope share it.
2332 It is a subclass, so OpenAPI shows ``UserListResponse`` and not
2333 ``NumberedEnvelope_UserResponse_``.
2334 """
2335 filled: Any = envelope[response_schema] # type: ignore[index]
2336 return type(
2337 _schema_role_name(response_schema, "ListResponse"),
2338 (filled,),
2339 {
2340 "__module__": response_schema.__module__,
2341 # For the warning about two classes with one name.
2342 "__restly_list_response_of__": (envelope, response_schema),
2343 },
2344 )
2347def rebase_with_model_config(
2348 base: tuple[type, ...], model_cls: type[pydantic.BaseModel]
2349) -> type[pydantic.BaseModel]:
2350 def class_body(ns: dict[str, Any]) -> None:
2351 ns["model_config"] = model_cls.model_config.copy()
2353 return types.new_class(
2354 f"{model_cls.__name__}ModelConfig", base, exec_body=class_body
2355 )
2358def create_model_with_optional_fields(
2359 model_cls: type[pydantic.BaseModel], *, omit: Iterable[str] = ()
2360) -> type[pydantic.BaseModel]:
2361 """
2362 Create a subclass of the given pydantic model class with a new name.
2363 Read-only fields and the fields named in ``omit`` are removed, and the
2364 client may leave out each writable field, which then defaults to None.
2365 Each field keeps its type, so ``null`` is valid only where the type
2366 allows it; see :class:`PatchMixin`.
2367 """
2368 new_model_name = _schema_role_name(model_cls, "Update")
2369 new_doc = (
2370 model_cls.__doc__ or ""
2371 ) + "\nRead-only fields have been removed and all fields are optional."
2373 # Create a subclass that mixes in both OmitReadOnlyMixin and PatchMixin
2374 new_model_cls = type(
2375 new_model_name,
2376 (PatchMixin, OmitReadOnlyMixin, model_cls),
2377 {
2378 "__module__": model_cls.__module__,
2379 "__doc__": new_doc,
2380 "__restly_omit_fields__": frozenset(omit),
2381 },
2382 )
2384 return new_model_cls
2387class PatchMixin(pydantic.BaseModel):
2388 """
2389 A mixin for pydantic classes that lets the client leave out every field,
2390 for the body of ``PATCH``.
2392 Each field keeps its type, so ``null`` is valid only where the type
2393 allows ``None``, as in the body of ``POST``. A field that the client
2394 leaves out gets the default ``None``. Pydantic does not validate it, and
2395 Restly writes only the fields in ``model_fields_set``, so the default is
2396 never written. The defaults of the schema are **replaced** by ``None``.
2398 Implementation note: like :class:`OmitReadOnlyMixin` this mutates
2399 ``cls.model_fields`` (``FieldInfo.default`` and ``validate_default``) and
2400 then calls ``model_rebuild(force=True)``. This relies on pydantic v2
2401 keeping ``FieldInfo`` mutable; verified on the pinned
2402 ``pydantic>=2.11.7`` minimum and exercised by
2403 ``tests/test_pydantic_model_fields_mutation.py``.
2404 """
2406 @classmethod
2407 def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
2408 super().__pydantic_init_subclass__(**kwargs)
2410 for field in cls.model_fields.values():
2411 field.default = None
2412 # A field cannot have both. FastAPI builds the field again from
2413 # its attributes for OpenAPI, which raises with both.
2414 field.default_factory = None
2415 # Also when the class sets ``validate_default=True``: the default
2416 # is not a value of the field's type.
2417 field.validate_default = False
2419 # The rebuild validates the default again for a field with a
2420 # ``@validator(..., always=True)``.
2421 validators = cls.__pydantic_decorators__.validators
2422 for name, decorator in list(validators.items()):
2423 if decorator.info.always: 2423 ↛ 2422line 2423 didn't jump to line 2422 because the condition on line 2423 was always true
2424 info = dataclasses.replace(decorator.info, always=False)
2425 validators[name] = dataclasses.replace(decorator, info=info) # type: ignore[assignment]
2427 cls.model_rebuild(force=True)
2430def getattrs(obj: Any, *attrs: str, default: Any = None) -> Any:
2431 """
2432 Try access a chain of attributes and return the default if any of the attrs is not defined.
2433 """
2434 for attr in attrs:
2435 if not hasattr(obj, attr):
2436 return default
2437 obj = getattr(obj, attr)
2438 return obj
2441def set_schema_title(schema_cls: type[pydantic.BaseModel]) -> None:
2442 """Set the title of a schema class to its name.
2443 This is used to make the schema title match the model name in the OpenAPI schema.
2444 """
2445 schema_cls.model_config["title"] = schema_cls.__name__
2448def get_writable_inputs(schema_obj: pydantic.BaseModel) -> dict[str, Any]:
2449 """
2450 Return a dictionary of field_name: value pairs for writable input fields.
2452 Filters out:
2453 - ReadOnly fields
2454 - fields not provided with input (using Pydantic model_fields_set)
2456 :param schema_obj: The schema object to extract writable fields from. Its
2457 own schema decides which fields are ``ReadOnly``.
2458 :returns: Dictionary mapping field names to their values, for writable
2459 input fields only.
2460 """
2461 schema_cls = type(schema_obj)
2462 updated_fields: dict[str, Any] = {}
2463 for field_name, value in schema_obj:
2464 if field_name not in schema_obj.model_fields_set:
2465 continue
2466 # Skip readonly fields
2467 if is_readonly_field(schema_cls, field_name):
2468 continue
2469 updated_fields[field_name] = value
2471 return updated_fields