scim2-sqlalchemy 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,772 @@
1
+ from collections.abc import Callable
2
+ from collections.abc import Iterable
3
+ from collections.abc import Iterator
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass
6
+ from dataclasses import field
7
+ from enum import Enum
8
+ from inspect import isclass
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel
12
+ from scim2_models import Attribute as SchemaAttribute
13
+ from scim2_models import AttributeBinding
14
+ from scim2_models import Mutability
15
+ from scim2_models import Path
16
+ from scim2_models import Resource
17
+ from scim2_models import ResponseParameters
18
+ from scim2_models import Schema
19
+ from scim2_models import Uniqueness
20
+ from sqlalchemy import ColumnElement
21
+ from sqlalchemy import Dialect
22
+ from sqlalchemy import Enum as SqlEnum
23
+ from sqlalchemy import String
24
+ from sqlalchemy import cast
25
+ from sqlalchemy import inspect
26
+ from sqlalchemy import literal
27
+ from sqlalchemy.ext.hybrid import hybrid_property
28
+ from sqlalchemy.orm import InstrumentedAttribute
29
+ from sqlalchemy.orm import Mapper
30
+ from sqlalchemy.orm import RelationshipProperty
31
+ from sqlalchemy.orm import strategy_options
32
+ from sqlalchemy.types import TypeDecorator
33
+
34
+
35
+ class _Storage(Enum):
36
+ """How a mapping stores an attribute.
37
+
38
+ A derived attribute is read from another resource, such as the display of
39
+ a member, so writing it changes nothing. A ref is the $ref of a link,
40
+ built from its value: clients may send it, and writing it changes nothing
41
+ either. A link type is the type a Link gives its entries: clients may send
42
+ it, and the storage checks it against the linked resource.
43
+ """
44
+
45
+ written = "written"
46
+ read_only = "read only"
47
+ derived = "derived"
48
+ ref = "ref"
49
+ link_type = "link type"
50
+
51
+
52
+ def _python_type(expression: Any) -> type | None:
53
+ """Return the Python type of the values of an expression, or None if its type tells none.
54
+
55
+ SQLAlchemy 2.0 raises NotImplementedError for such a type, and 2.1 returns object.
56
+ """
57
+ try:
58
+ python_type: type = expression.type.python_type
59
+ except NotImplementedError:
60
+ return None
61
+ return None if python_type is object else python_type
62
+
63
+
64
+ def _holds_text(expression: Any) -> bool:
65
+ """Whether an expression holds strings. A type that tells no Python type is taken as text."""
66
+ return _python_type(expression) in (str, None)
67
+
68
+
69
+ class Attribute:
70
+ """A column holding a SCIM attribute that the storage only reads, or only writes.
71
+
72
+ To store a value in another form, map the attribute to a
73
+ :class:`~sqlalchemy.ext.hybrid.hybrid_property` that converts it, in Python
74
+ and in SQL.
75
+
76
+ :param expression: The column, or the
77
+ :class:`~sqlalchemy.ext.hybrid.hybrid_property`, holding the value.
78
+ :param readable: Whether the storage reads the attribute. When
79
+ :data:`False`, the attribute is write-only, such as a password: the
80
+ storage never returns it, nor filters or sorts on it.
81
+ :param writable: Whether the storage writes the attribute. When
82
+ :data:`False`, the attribute is read-only.
83
+ """
84
+
85
+ def __init__(
86
+ self, expression: Any, *, readable: bool = True, writable: bool = True
87
+ ) -> None:
88
+ self.expression = expression
89
+ self.readable = readable
90
+ self.writable = writable
91
+
92
+
93
+ class Hashed(TypeDecorator[str]):
94
+ """A column type storing the hash of a string, such as a password.
95
+
96
+ The column stores what the hash function returns for the value written.
97
+ Map it with ``readable=False``, since the storage cannot read a hash back.
98
+
99
+ :param hash_value: The function hashing a value.
100
+ :param length: The length of the column.
101
+ """
102
+
103
+ impl = String
104
+ cache_ok = True
105
+
106
+ def __init__(
107
+ self, hash_value: Callable[[str], str], length: int | None = None
108
+ ) -> None:
109
+ super().__init__(length)
110
+ self.hash_value = hash_value
111
+
112
+ def process_bind_param(self, value: str | None, dialect: Dialect) -> str | None:
113
+ """Hash the value before it is sent to the database."""
114
+ return None if value is None else self.hash_value(value)
115
+
116
+
117
+ class Many:
118
+ """The entries of a multi-valued attribute, stored in a child table.
119
+
120
+ The entries belong to the resource: writing the resource replaces them.
121
+ The relationship needs ``cascade="all, delete-orphan"``
122
+ (:ref:`sqlalchemy:cascade_delete_orphan`). Its ``order_by`` gives the
123
+ order of the entries. Without it, the order is the one the database
124
+ returns. A sort uses the ``primary`` entry, or else the first one.
125
+
126
+ The entries of a multi-valued simple attribute, such as a list of strings,
127
+ are the values of one column of the child table. The storage keeps their
128
+ order and their duplicates.
129
+
130
+ :param relationship: The :func:`~sqlalchemy.orm.relationship` from the
131
+ resource record to the entry records.
132
+ :param attributes: The columns of the entry records, by sub-attribute name,
133
+ such as ``"value"`` or ``"type"``. For a simple attribute, the column
134
+ holding the values.
135
+ """
136
+
137
+ def __init__(self, relationship: Any, attributes: Mapping[str, Any] | Any) -> None:
138
+ self.relationship = relationship
139
+ self.attributes = attributes
140
+
141
+
142
+ class Link:
143
+ """A complex attribute linking to other resources.
144
+
145
+ A multi-valued attribute, such as the ``members`` of a group, maps to a
146
+ relationship holding several records. A single-valued one, such as the
147
+ ``manager`` of an enterprise user, maps to a relationship holding one
148
+ record.
149
+
150
+ ``value`` is the ``id`` of the linked resource. Its display name, the
151
+ ``display`` or ``displayName`` sub-attribute, is the ``displayName`` of the
152
+ linked resource when its mapping has one, or else its ``userName``.
153
+ Writing the resource changes the links, and never creates nor deletes the
154
+ linked resources.
155
+
156
+ A Link links to the resources of one resource type. An attribute linking
157
+ to several resource types, such as the ``members`` of a group holding users
158
+ and groups, maps to a list of Links, one per resource type. The entries are
159
+ read in the order of the list.
160
+
161
+ :param relationship: The :func:`~sqlalchemy.orm.relationship` from the
162
+ resource record to the records of the linked resources.
163
+ :param resource_type: The name of the resource type of the linked
164
+ resources, as the storage knows it.
165
+ :param type: The ``type`` sub-attribute of the entries, such as ``"User"``
166
+ for the members of a group, or ``"direct"`` for the groups of a user.
167
+ A client may send it, and a write with another value is refused.
168
+ Without it, the storage does not store ``type``.
169
+ """
170
+
171
+ def __init__(
172
+ self, relationship: Any, resource_type: str, *, type: str | None = None
173
+ ) -> None:
174
+ self.relationship = relationship
175
+ self.resource_type = resource_type
176
+ self.type = type
177
+
178
+
179
+ @dataclass(eq=False)
180
+ class _Column:
181
+ """A SCIM attribute stored in a column or a hybrid property.
182
+
183
+ textual tells whether filters compare the column as text, as they do for
184
+ an integer identifier.
185
+ """
186
+
187
+ binding: AttributeBinding
188
+ expression: ColumnElement[Any]
189
+ key: str
190
+ readable: bool
191
+ writable: bool
192
+ textual: bool = False
193
+
194
+ @property
195
+ def is_string(self) -> bool:
196
+ """Whether the attribute is a SCIM string."""
197
+ target = self.binding.target_type
198
+ return (
199
+ target is not None
200
+ and SchemaAttribute.Type.from_python(target) == SchemaAttribute.Type.string
201
+ )
202
+
203
+ @property
204
+ def casefolded(self) -> bool:
205
+ """Whether the values compare without their case."""
206
+ return self.is_string and not self.binding.case_exact
207
+
208
+ @property
209
+ def nullable(self) -> bool:
210
+ """Whether the column can hold no value. A hybrid property is taken as nullable."""
211
+ columns = getattr(getattr(self.expression, "property", None), "columns", None)
212
+ return columns is None or bool(columns[0].nullable)
213
+
214
+ @property
215
+ def enumeration(self) -> SqlEnum | None:
216
+ """The type of the column when it is an Enum, which stores strings."""
217
+ sql_type = self.expression.type
218
+ return sql_type if isinstance(sql_type, SqlEnum) else None
219
+
220
+ @property
221
+ def compared(self) -> ColumnElement[Any]:
222
+ """The expression filters and sorts compare.
223
+
224
+ An Enum column is compared as text. PostgreSQL applies no string
225
+ function to its native enumerations, and sorts them in the order of
226
+ their declaration.
227
+ """
228
+ if self.textual or self.enumeration is not None:
229
+ return cast(self.expression, String)
230
+ return self.expression
231
+
232
+ @staticmethod
233
+ def stored_string(enumeration: SqlEnum, member: Enum) -> str:
234
+ """Return the string an Enum column stores for a member: its name, or its value with values_callable."""
235
+ strings: dict[Enum, str] = dict(
236
+ zip(type(member), enumeration.enums, strict=False)
237
+ )
238
+ return strings[member]
239
+
240
+
241
+ @dataclass(eq=False)
242
+ class _Collection:
243
+ """A multi-valued attribute, or a complex one, stored in related records.
244
+
245
+ The entries of an owned collection belong to the resource. The others are
246
+ links to the resources of another mapping, the target. A single collection
247
+ holds one entry at most, such as the manager of a user. A simple
248
+ collection holds the values of a multi-valued simple attribute, in the
249
+ column it keeps under None.
250
+
251
+ link_type is the type a Link gives its entries, and type_column the
252
+ constant filters compare it as.
253
+ """
254
+
255
+ binding: AttributeBinding
256
+ relationship: InstrumentedAttribute[Any]
257
+ columns: dict[str | None, _Column] = field(default_factory=dict)
258
+ resource_type: str | None = None
259
+ target: "ResourceMapping | None" = None
260
+ link_type: str | None = None
261
+ type_column: _Column | None = None
262
+
263
+ @property
264
+ def owned(self) -> bool:
265
+ """Whether the entries belong to the resource, rather than link to other resources."""
266
+ return self.resource_type is None
267
+
268
+ @property
269
+ def entry_class(self) -> type[Any]:
270
+ """The SQLAlchemy model of the entries."""
271
+ return self.relationship_property.mapper.class_
272
+
273
+ @property
274
+ def relationship_property(self) -> RelationshipProperty[Any]:
275
+ """The relationship holding the entries."""
276
+ return self.relationship.property # type: ignore[return-value]
277
+
278
+ @property
279
+ def single(self) -> bool:
280
+ """Whether the collection holds one entry at most."""
281
+ return not self.binding.is_multivalued
282
+
283
+ @property
284
+ def simple(self) -> bool:
285
+ """Whether the collection holds the values of a multi-valued simple attribute."""
286
+ return None in self.columns
287
+
288
+ def column(self, sub_field_name: str | None) -> _Column | None:
289
+ """Return the column of a sub-attribute, or of the values of a simple collection named alone.
290
+
291
+ A complex collection named alone has no column.
292
+ """
293
+ if sub_field_name == "type" and self.type_column is not None:
294
+ return self.type_column
295
+ return self.columns.get(sub_field_name)
296
+
297
+ def exists(self, condition: Any = None) -> ColumnElement[bool]:
298
+ """Return the condition that an entry exists, and matches condition when given."""
299
+ method = self.relationship.has if self.single else self.relationship.any
300
+ return method() if condition is None else method(condition)
301
+
302
+ @property
303
+ def writable(self) -> bool:
304
+ """Whether writing the resource writes these entries."""
305
+ if self.simple and not self.columns[None].writable:
306
+ return False
307
+ mutability = self.binding.model.get_field_annotation(
308
+ self.binding.field_name, Mutability
309
+ )
310
+ return bool(mutability != Mutability.read_only)
311
+
312
+
313
+ class ResourceMapping:
314
+ """How the resources of a SCIM model are stored in the records of a SQLAlchemy model.
315
+
316
+ The paths are checked against the SCIM model when the mapping is created,
317
+ so a mistake raises at import time rather than at the first request.
318
+
319
+ :param model: The SCIM model of the resources, such as
320
+ ``User[EnterpriseUser]``.
321
+ :param record: The SQLAlchemy model of the records.
322
+ :param attributes: The attributes, by SCIM path. A value is a column, a
323
+ :class:`~sqlalchemy.ext.hybrid.hybrid_property`, an :class:`Attribute`, a :class:`Many`, a
324
+ :class:`Link`, or a list of :class:`Link`. ``id``, ``meta.created`` and ``meta.lastModified``
325
+ are required.
326
+ :param version: The ``version_id_col`` of the mapper of ``record``, which
327
+ gives ``meta.version`` (:ref:`sqlalchemy:mapper_version_counter`).
328
+ :raises ValueError: When a path is not valid for the model, or when a
329
+ value does not fit the attribute of its path.
330
+ """
331
+
332
+ _REQUIRED = ("id", "meta.created", "meta.lastModified")
333
+
334
+ def __init__(
335
+ self,
336
+ model: type[Resource[Any]],
337
+ record: type[Any],
338
+ attributes: Mapping[str, Any],
339
+ *,
340
+ version: Any,
341
+ ) -> None:
342
+ self.model = model
343
+ self.record = record
344
+ self._columns: dict[tuple[type[BaseModel], str, str | None], _Column] = {}
345
+ self._collections: dict[tuple[type[BaseModel], str], list[_Collection]] = {}
346
+
347
+ for required in self._REQUIRED:
348
+ if required not in attributes:
349
+ raise ValueError(f"The mapping of {model.__name__} needs {required!r}")
350
+ for path, value in attributes.items():
351
+ self._add(path, value)
352
+
353
+ mapper: Mapper[Any] = inspect(record)
354
+ columns = getattr(getattr(version, "property", None), "columns", [None])
355
+ if mapper.version_id_col is None or mapper.version_id_col is not columns[0]:
356
+ raise ValueError(
357
+ f"The version of {model.__name__} must be the version_id_col "
358
+ f"of the mapper of {record.__name__}"
359
+ )
360
+ self._version: InstrumentedAttribute[Any] = version
361
+ self._id = self._column("id")
362
+ self._id.textual = not _holds_text(self._id.expression)
363
+ self._created = self._column("meta.created")
364
+ self._last_modified = self._column("meta.lastModified")
365
+
366
+ def schemas(self) -> list[Schema]:
367
+ """Return the schemas of the resources, restricted to what the mapping stores.
368
+
369
+ They hold the mapped attributes only, and an attribute the mapping
370
+ reads but never writes is ``readOnly``. Publish them, rather than the
371
+ schemas of :attr:`model`, so that clients know what the server stores:
372
+ build the provider of the server with
373
+ :meth:`ScimProvider.from_discovery <scim2_models.ScimProvider.from_discovery>`,
374
+ and pass it to the storage.
375
+
376
+ :returns: The schema of the resource, then the schemas of its extensions.
377
+ """
378
+ models: list[Any] = [self.model, *self.model.get_extension_models().values()]
379
+ return [self._restrict(model.to_schema()) for model in models]
380
+
381
+ def _restrict(self, schema: Schema) -> Schema:
382
+ """Return a schema with the attributes the mapping stores only."""
383
+ attributes = []
384
+ for attribute in schema.attributes or []:
385
+ restricted = self._restrict_attribute(
386
+ f"{schema.id}:{attribute.name}", attribute
387
+ )
388
+ if restricted is not None:
389
+ attributes.append(restricted)
390
+ return schema.model_copy(update={"attributes": attributes})
391
+
392
+ def _restrict_attribute(self, urn: str, attribute: Any) -> Any:
393
+ """Return an attribute of a schema as the mapping stores it, or None when it stores nothing of it."""
394
+ if attribute.sub_attributes:
395
+ sub_attributes = [
396
+ restricted
397
+ for sub_attribute in attribute.sub_attributes
398
+ if (
399
+ restricted := self._restrict_attribute(
400
+ f"{urn}.{sub_attribute.name}", sub_attribute
401
+ )
402
+ )
403
+ is not None
404
+ ]
405
+ if not sub_attributes:
406
+ return None
407
+ written = any(
408
+ sub_attribute.mutability != Mutability.read_only
409
+ for sub_attribute in sub_attributes
410
+ )
411
+ return attribute.model_copy(
412
+ update={
413
+ "sub_attributes": sub_attributes,
414
+ "mutability": attribute.mutability
415
+ if written
416
+ else Mutability.read_only,
417
+ }
418
+ )
419
+
420
+ storage = self._storage(urn)
421
+ if storage is None:
422
+ return None
423
+ if storage in (_Storage.written, _Storage.link_type):
424
+ return attribute
425
+ if storage == _Storage.ref:
426
+ linked = self._linked_resource_types(urn)
427
+ return attribute.model_copy(update={"reference_types": linked})
428
+ return attribute.model_copy(update={"mutability": Mutability.read_only})
429
+
430
+ def _storage(self, urn: str) -> _Storage | None:
431
+ """Return how the mapping stores the attribute of a URN, or None when it does not store it."""
432
+ key = urn.lower()
433
+ for column in self._columns.values():
434
+ if column.binding.urn.lower() == key:
435
+ return _Storage.written if column.writable else _Storage.read_only
436
+ for collection in self._all_collections():
437
+ if not collection.owned:
438
+ head = collection.binding.urn.lower()
439
+ if key == f"{head}.value":
440
+ return _Storage.written
441
+ if key in (f"{head}.display", f"{head}.displayname"):
442
+ return _Storage.derived
443
+ if key == f"{head}.$ref":
444
+ return _Storage.ref
445
+ if key == f"{head}.type" and collection.link_type is not None:
446
+ return _Storage.link_type
447
+ continue
448
+ for column in collection.columns.values():
449
+ if column.binding.urn.lower() == key:
450
+ return _Storage.written if column.writable else _Storage.read_only
451
+ return None
452
+
453
+ def _nullable(self, urn: str) -> bool:
454
+ """Tell whether the column of an attribute can hold no value, True for an attribute without column."""
455
+ key = urn.lower()
456
+ return all(
457
+ column.nullable
458
+ for column in self._columns.values()
459
+ if column.binding.urn.lower() == key
460
+ )
461
+
462
+ def _linked_resource_types(self, urn: str) -> list[str]:
463
+ """Return the resource types the Links of an attribute link to, from the URN of its $ref."""
464
+ head = urn.lower().removesuffix(".$ref")
465
+ return [
466
+ collection.resource_type
467
+ for collection in self._all_collections()
468
+ if collection.binding.urn.lower() == head
469
+ and collection.resource_type is not None
470
+ ]
471
+
472
+ def _all_collections(self) -> Iterator[_Collection]:
473
+ """Yield the collections of every attribute, each Link of an attribute being a collection."""
474
+ for collections in self._collections.values():
475
+ yield from collections
476
+
477
+ def _column(self, path: str) -> _Column:
478
+ """Return the column of the attribute at a path."""
479
+ binding = self._resolve(path)
480
+ return self._columns[
481
+ (binding.model, binding.field_name, binding.sub_field_name)
482
+ ]
483
+
484
+ def _lookup(
485
+ self, binding: AttributeBinding
486
+ ) -> list[tuple[_Collection | None, _Column | None]]:
487
+ """Return each collection holding an attribute, if any, with the column of the attribute in it.
488
+
489
+ An attribute outside collections gives one pair, without collection.
490
+ An attribute linking to several resource types gives a pair for each
491
+ of its Links. The column is None for an attribute stored nowhere, and
492
+ for a collection named alone, such as emails.
493
+ """
494
+ collections = self._collections.get((binding.model, binding.field_name))
495
+ if collections is None:
496
+ key = (binding.model, binding.field_name, binding.sub_field_name)
497
+ return [(None, self._columns.get(key))]
498
+ return [
499
+ (collection, collection.column(binding.sub_field_name))
500
+ for collection in collections
501
+ ]
502
+
503
+ def _sub_columns(self, binding: AttributeBinding) -> list[_Column]:
504
+ """Return the mapped sub-attributes of a complex attribute holding a single value."""
505
+ return [
506
+ column
507
+ for (model, field_name, sub_field_name), column in self._columns.items()
508
+ if model is binding.model
509
+ and field_name == binding.field_name
510
+ and sub_field_name is not None
511
+ ]
512
+
513
+ def _string_columns(self) -> Iterator[_Column]:
514
+ """Yield the columns holding strings, those of the collections included."""
515
+ for column in self._columns.values():
516
+ if column.is_string:
517
+ yield column
518
+ for collection in self._all_collections():
519
+ for column in collection.columns.values():
520
+ if column.is_string:
521
+ yield column
522
+ if collection.type_column is not None:
523
+ yield collection.type_column
524
+
525
+ def _unique_columns(self) -> Iterator[_Column]:
526
+ """Yield the readable columns whose values no two resources share."""
527
+ for column in self._columns.values():
528
+ if column.readable and column.binding.get_annotation(Uniqueness) in (
529
+ Uniqueness.server,
530
+ Uniqueness.global_,
531
+ ):
532
+ yield column
533
+
534
+ def _returned_collections(
535
+ self, parameters: ResponseParameters[Any] | None = None
536
+ ) -> list[_Collection]:
537
+ """Return the collections a response keeps, all of them without parameters."""
538
+ collections = list(self._all_collections())
539
+ if parameters is None:
540
+ return collections
541
+ paths = Path[self.model].iter_paths( # type: ignore[name-defined]
542
+ include_subattributes=False,
543
+ attributes=parameters.attributes,
544
+ excluded_attributes=parameters.excluded_attributes,
545
+ )
546
+ bindings = (path.resolve() for path in paths)
547
+ kept = {binding.urn for binding in bindings if binding is not None}
548
+ return [
549
+ collection for collection in collections if collection.binding.urn in kept
550
+ ]
551
+
552
+ def _loader_options(
553
+ self, collections: Iterable[_Collection]
554
+ ) -> list[strategy_options._AbstractLoad]:
555
+ """Return the options loading collections along with the records.
556
+
557
+ Loading them up front is what lets an asynchronous session read them.
558
+ """
559
+ return [
560
+ strategy_options.selectinload(collection.relationship)
561
+ for collection in collections
562
+ ]
563
+
564
+ def _bind(self, mappings: Mapping[str, "ResourceMapping"]) -> None:
565
+ """Bind each Link to the mapping of the resources it links to.
566
+
567
+ Several storages may share a mapping, as long as they link it to the
568
+ same mappings.
569
+ """
570
+ for collection in self._all_collections():
571
+ if collection.owned:
572
+ continue
573
+ target = mappings.get(collection.resource_type) # type: ignore[arg-type]
574
+ if target is None:
575
+ raise ValueError(
576
+ f"No mapping for the resource type {collection.resource_type!r}"
577
+ )
578
+ if collection.target is not None and collection.target is not target:
579
+ raise ValueError(
580
+ f"{collection.binding.urn!r} already links to another mapping "
581
+ f"of {collection.resource_type!r}: a mapping serves storages "
582
+ "sharing the same mappings"
583
+ )
584
+ collection.target = target
585
+ collection.columns = {}
586
+ head = collection.binding.urn
587
+ for binding, column in (
588
+ (self._resolve(f"{head}.value"), target._id),
589
+ (
590
+ self._find(f"{head}.display") or self._find(f"{head}.displayName"),
591
+ target._display(),
592
+ ),
593
+ ):
594
+ if binding is None or column is None:
595
+ continue
596
+ collection.columns[binding.sub_field_name] = _Column(
597
+ binding,
598
+ column.expression,
599
+ column.key,
600
+ column.readable,
601
+ False,
602
+ column.textual,
603
+ )
604
+
605
+ def _display(self) -> _Column | None:
606
+ """Return the column a link to these resources displays."""
607
+ for path in ("displayName", "userName"):
608
+ binding = self._find(path)
609
+ if binding is None:
610
+ continue
611
+ ((_, column),) = self._lookup(binding)
612
+ if column is not None and column.readable:
613
+ return column
614
+ return None
615
+
616
+ def _find(self, path: str) -> AttributeBinding | None:
617
+ """Return the attribute at a path, or None if the model has none there."""
618
+ return Path[self.model](path).resolve() # type: ignore[name-defined]
619
+
620
+ def _resolve(self, path: str) -> AttributeBinding:
621
+ """Return the attribute at a path, refusing a path the model does not know."""
622
+ binding = self._find(path)
623
+ if binding is None:
624
+ raise ValueError(f"{path!r} is not an attribute of {self.model.__name__}")
625
+ return binding
626
+
627
+ def _add(self, path: str, value: Any) -> None:
628
+ """Check the mapping of the attribute at a path, and keep its column or its collections."""
629
+ binding = self._resolve(path)
630
+ target = binding.target_type
631
+ is_complex = isclass(target) and issubclass(target, BaseModel)
632
+
633
+ key = (binding.model, binding.field_name)
634
+ if isinstance(value, Many):
635
+ self._collections[key] = [self._many(path, binding, value)]
636
+ return
637
+ if isinstance(value, Link):
638
+ value = [value]
639
+ if isinstance(value, list) and all(isinstance(item, Link) for item in value):
640
+ if not is_complex or binding.sub_field_name is not None:
641
+ raise ValueError(
642
+ f"{path!r} is not a complex attribute of {self.model.__name__}"
643
+ )
644
+ self._collections[key] = self._links(path, binding, value)
645
+ return
646
+
647
+ if binding.is_multivalued or is_complex:
648
+ raise ValueError(
649
+ f"{path!r} holds several values or sub-attributes: map it with Many "
650
+ "or Link, or map its sub-attributes"
651
+ )
652
+ self._columns[(binding.model, binding.field_name, binding.sub_field_name)] = (
653
+ self._build_column(path, binding, value)
654
+ )
655
+
656
+ def _collection(
657
+ self, path: str, binding: AttributeBinding, relationship: Any
658
+ ) -> _Collection:
659
+ """Build the collection of a relationship, holding as many records as the attribute holds entries."""
660
+ collection = _Collection(binding, relationship)
661
+ if collection.relationship_property.uselist == collection.single:
662
+ raise ValueError(
663
+ f"{path!r} holds {'one entry' if collection.single else 'several entries'}, "
664
+ f"but its relationship holds {'several' if collection.single else 'one'}"
665
+ )
666
+ return collection
667
+
668
+ def _many(self, path: str, binding: AttributeBinding, many: Many) -> _Collection:
669
+ """Build the collection of a Many, with the columns of its entries, or the column of its values."""
670
+ target = binding.target_type
671
+ is_complex = isclass(target) and issubclass(target, BaseModel)
672
+ simple = not isinstance(many.attributes, Mapping)
673
+ if (
674
+ binding.sub_field_name is not None
675
+ or not binding.is_multivalued
676
+ or is_complex == simple
677
+ ):
678
+ kind = "simple" if simple else "complex"
679
+ raise ValueError(
680
+ f"{path!r} is not a multi-valued {kind} attribute of "
681
+ f"{self.model.__name__}"
682
+ )
683
+ collection = self._collection(path, binding, many.relationship)
684
+ if not collection.relationship_property.cascade.delete_orphan:
685
+ raise ValueError(
686
+ f"The relationship of {path!r} needs the delete-orphan cascade"
687
+ )
688
+ if simple:
689
+ collection.columns[None] = self._build_column(
690
+ path, binding, many.attributes
691
+ )
692
+ return collection
693
+ for sub_path, expression in many.attributes.items():
694
+ sub_binding = self._resolve(f"{path}.{sub_path}")
695
+ collection.columns[sub_binding.sub_field_name] = self._build_column(
696
+ f"{path}.{sub_path}", sub_binding, expression
697
+ )
698
+ return collection
699
+
700
+ def _links(
701
+ self, path: str, binding: AttributeBinding, links: list[Link]
702
+ ) -> list[_Collection]:
703
+ """Build the collections of the Links of an attribute, one per resource type.
704
+
705
+ The type of the entries is compared, in filters, as a constant of each
706
+ Link.
707
+ """
708
+ resource_types = [link.resource_type for link in links]
709
+ if not links or len(set(resource_types)) != len(resource_types):
710
+ raise ValueError(
711
+ f"{path!r} needs one Link per resource type, and at least one"
712
+ )
713
+ typed = {link.type is not None for link in links}
714
+ if len(typed) > 1:
715
+ raise ValueError(f"Either every Link of {path!r} has a type, or none")
716
+ type_binding = self._find(f"{path}.type")
717
+ if typed == {True} and type_binding is None:
718
+ raise ValueError(f"{path!r} has no type sub-attribute")
719
+
720
+ collections = []
721
+ for link in links:
722
+ collection = self._collection(path, binding, link.relationship)
723
+ collection.resource_type = link.resource_type
724
+ if link.type is not None:
725
+ collection.link_type = link.type
726
+ collection.type_column = _Column(
727
+ type_binding, # type: ignore[arg-type]
728
+ literal(link.type),
729
+ "type",
730
+ True,
731
+ False,
732
+ )
733
+ collections.append(collection)
734
+ return collections
735
+
736
+ def _build_column(
737
+ self, path: str, binding: AttributeBinding, value: Any
738
+ ) -> _Column:
739
+ """Build the column of an attribute, and decide whether it is written.
740
+
741
+ A read-only attribute, or a hybrid property without a setter, is never
742
+ written.
743
+ """
744
+ if binding.sub_field_name is not None and binding.target_is_multivalued:
745
+ raise ValueError(
746
+ f"{path!r} holds several values in a complex attribute, "
747
+ "which the storage cannot map"
748
+ )
749
+ attribute = value if isinstance(value, Attribute) else Attribute(value)
750
+ expression = attribute.expression
751
+ key = getattr(expression, "key", None)
752
+ if not isinstance(key, str):
753
+ raise ValueError(
754
+ f"{path!r} must be mapped to a column or a hybrid property"
755
+ )
756
+ if attribute.readable and isinstance(getattr(expression, "type", None), Hashed):
757
+ raise ValueError(
758
+ f"{path!r} stores a hash, which the storage cannot read back: "
759
+ "map it with readable=False"
760
+ )
761
+
762
+ writable = attribute.writable
763
+ descriptor = inspect(expression.class_).all_orm_descriptors[key]
764
+ mutabilities = {
765
+ binding.model.get_field_annotation(binding.field_name, Mutability),
766
+ binding.get_annotation(Mutability),
767
+ }
768
+ if Mutability.read_only in mutabilities or (
769
+ isinstance(descriptor, hybrid_property) and descriptor.fset is None
770
+ ):
771
+ writable = False
772
+ return _Column(binding, expression, key, attribute.readable, writable)