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