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,727 @@
1
+ import hashlib
2
+ import re
3
+ import uuid
4
+ from collections.abc import Callable
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from scim2_models import Attribute as SchemaAttribute
10
+ from scim2_models import AttributeBinding
11
+ from scim2_models import Mutability
12
+ from scim2_models import Path
13
+ from scim2_models import Required
14
+ from scim2_models import ResourceType
15
+ from scim2_models import ScimProvider
16
+ from scim2_models import Uniqueness
17
+ from sqlalchemy import Boolean
18
+ from sqlalchemy import Column
19
+ from sqlalchemy import DateTime
20
+ from sqlalchemy import Float
21
+ from sqlalchemy import ForeignKey
22
+ from sqlalchemy import Integer
23
+ from sqlalchemy import LargeBinary
24
+ from sqlalchemy import MetaData
25
+ from sqlalchemy import String
26
+ from sqlalchemy import Table
27
+ from sqlalchemy import Uuid
28
+ from sqlalchemy.orm import DeclarativeBase
29
+ from sqlalchemy.orm import mapped_column
30
+ from sqlalchemy.orm import relationship
31
+ from sqlalchemy.types import TypeEngine
32
+
33
+ from .mapping import Attribute
34
+ from .mapping import Link
35
+ from .mapping import Many
36
+ from .mapping import ResourceMapping
37
+
38
+ _GROUPS = "urn:ietf:params:scim:schemas:core:2.0:User:groups"
39
+ _MEMBERS = "urn:ietf:params:scim:schemas:core:2.0:Group:members"
40
+
41
+ _MAX_NAME_LENGTH = 63
42
+ """The longest identifier PostgreSQL keeps."""
43
+
44
+ _SQL_TYPES: dict[SchemaAttribute.Type, Callable[[], TypeEngine[Any]]] = {
45
+ SchemaAttribute.Type.string: String,
46
+ SchemaAttribute.Type.reference: String,
47
+ SchemaAttribute.Type.boolean: Boolean,
48
+ SchemaAttribute.Type.integer: Integer,
49
+ SchemaAttribute.Type.decimal: Float,
50
+ SchemaAttribute.Type.date_time: lambda: DateTime(timezone=True),
51
+ SchemaAttribute.Type.binary: LargeBinary,
52
+ }
53
+
54
+
55
+ def _snake(name: str) -> str:
56
+ """Return a name in snake case, such as user_name for userName."""
57
+ name = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)
58
+ return re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower()
59
+
60
+
61
+ def _fit(name: str) -> str:
62
+ """Shorten a name longer than PostgreSQL keeps, ending it with a hash of the full name."""
63
+ if len(name) <= _MAX_NAME_LENGTH:
64
+ return name
65
+ digest = hashlib.sha256(name.encode()).hexdigest()[:8]
66
+ return f"{name[: _MAX_NAME_LENGTH - 9]}_{digest}"
67
+
68
+
69
+ def _sub_attribute(attribute: Any, name: str) -> Any:
70
+ """Return the sub-attribute of an attribute by its name, or None."""
71
+ return next(
72
+ (sub for sub in attribute.sub_attributes or [] if sub.name == name), None
73
+ )
74
+
75
+
76
+ @dataclass
77
+ class _Schema:
78
+ """A schema of a resource type, with the prefixes of the paths and of the columns of its attributes."""
79
+
80
+ urn: str
81
+ attributes: list[Any]
82
+ path_prefix: str
83
+ column_prefix: str
84
+
85
+
86
+ @dataclass
87
+ class _Forward:
88
+ """An attribute linking to resources, with the association table of each multi-valued link."""
89
+
90
+ owner: str
91
+ attribute: Any
92
+ targets: list[str]
93
+ keys: dict[str, str]
94
+ tables: dict[str, Table]
95
+ inverse_keys: dict[str, str]
96
+
97
+
98
+ class _Class:
99
+ """The namespace of a record class being built, and the attributes of its mapping."""
100
+
101
+ def __init__(self, name: str, table: str) -> None:
102
+ self.name = name
103
+ self.namespace: dict[str, Any] = {"__tablename__": table}
104
+ self.attributes: list[tuple[str, Callable[[], Any]]] = []
105
+
106
+ def add(self, key: str, value: Any, path: str) -> None:
107
+ """Add a column or a relationship to the class, and refuse a name already used."""
108
+ if key in self.namespace:
109
+ raise ValueError(
110
+ f"{path!r} needs the name {key!r}, which {self.name!r} already uses"
111
+ )
112
+ self.namespace[key] = value
113
+
114
+
115
+ class _Generator:
116
+ """Build the tables, the record classes and the mappings of the resource types of a provider."""
117
+
118
+ def __init__(
119
+ self,
120
+ provider: ScimProvider,
121
+ metadata: MetaData,
122
+ prefix: str,
123
+ store: Callable[[AttributeBinding], bool | TypeEngine[Any]],
124
+ inverses: Mapping[str, str],
125
+ ) -> None:
126
+ self.provider = provider
127
+ self.metadata = metadata
128
+ self.prefix = prefix
129
+ self.store = store
130
+ self.inverses = inverses
131
+ self.decisions: dict[str, bool | TypeEngine[Any]] = {}
132
+ self.resource_types = {str(rt.name): rt for rt in provider.resource_types}
133
+ self.tables = {
134
+ name: _fit(prefix + _snake(rt.endpoint or name))
135
+ for name, rt in self.resource_types.items()
136
+ }
137
+ self.base: Any = type("Base", (DeclarativeBase,), {"metadata": metadata})
138
+ self.classes: dict[str, Any] = {}
139
+ self.schemas = {
140
+ name: self._schemas(rt) for name, rt in self.resource_types.items()
141
+ }
142
+ self.forwards: dict[str, _Forward] = {}
143
+ self.reverses: dict[str, _Forward] = {}
144
+
145
+ def _schemas(self, resource_type: ResourceType) -> list[_Schema]:
146
+ """Return the core schema and the extensions of a resource type."""
147
+ model: Any = self.provider.model_for(resource_type)
148
+ schemas = [_Schema(model.__schema__, model.to_schema().attributes, "", "")]
149
+ for urn, extension in model.get_extension_models().items():
150
+ schema = extension.to_schema()
151
+ schemas.append(
152
+ _Schema(
153
+ urn,
154
+ schema.attributes,
155
+ f"{urn}:",
156
+ f"{_snake(str(schema.name or extension.__name__))}_",
157
+ )
158
+ )
159
+ return schemas
160
+
161
+ def generate(self) -> dict[str, ResourceMapping]:
162
+ """Return the mappings of the resource types, by name."""
163
+ self._decide()
164
+ for name in self.resource_types:
165
+ self._find_forwards(name)
166
+ self._find_inverses()
167
+ built = {name: self._build(name) for name in self.resource_types}
168
+ for record_class in built.values():
169
+ self._make(record_class)
170
+ self.base.registry.configure()
171
+ return {
172
+ name: ResourceMapping(
173
+ self.provider.model_for(self.resource_types[name]), # type: ignore[arg-type]
174
+ self.classes[name],
175
+ {path: build() for path, build in record_class.attributes},
176
+ version=self.classes[name].meta_version,
177
+ )
178
+ for name, record_class in built.items()
179
+ }
180
+
181
+ def _decide(self) -> None:
182
+ """Ask store how to keep each attribute the tables could hold, and check the answers."""
183
+ clear = []
184
+ for name, schemas in self.schemas.items():
185
+ model = self.provider.model_for(self.resource_types[name])
186
+ for schema in schemas:
187
+ for attribute in schema.attributes:
188
+ urn = f"{schema.urn}:{attribute.name}"
189
+ if self._linked(attribute):
190
+ if (
191
+ attribute.mutability != Mutability.read_only
192
+ or urn in self.inverses
193
+ ):
194
+ self._ask(model, urn, column=False)
195
+ continue
196
+ if attribute.mutability == Mutability.read_only:
197
+ continue
198
+ if attribute.type != SchemaAttribute.Type.complex:
199
+ if self._ask_column(model, urn, attribute):
200
+ clear.append(urn)
201
+ continue
202
+ if not self._ask(model, urn, column=False):
203
+ continue
204
+ for sub in attribute.sub_attributes or []:
205
+ sub_urn = f"{urn}.{sub.name}"
206
+ if (
207
+ not sub.multi_valued
208
+ and sub.mutability != Mutability.read_only
209
+ and self._ask_column(model, sub_urn, sub)
210
+ ):
211
+ clear.append(sub_urn)
212
+ if clear:
213
+ raise ValueError(
214
+ f"{', '.join(repr(urn) for urn in clear)} are write-only: store "
215
+ "them with a column type that hashes them, such as Hashed, or "
216
+ "not at all"
217
+ )
218
+
219
+ def _ask_column(self, model: Any, urn: str, attribute: Any) -> bool:
220
+ """Ask store how to keep an attribute held by a column, and tell whether it is a write-only string kept in clear text."""
221
+ if attribute.mutability == Mutability.write_only and not self._hashed(
222
+ attribute
223
+ ):
224
+ return False
225
+ decision = self._ask(model, urn, column=True)
226
+ return self._hashed(attribute) and decision is True
227
+
228
+ def _ask(self, model: Any, urn: str, *, column: bool) -> bool | TypeEngine[Any]:
229
+ """Ask store how to keep an attribute, and refuse a column type for an attribute without its own column."""
230
+ decision = self.store(Path(urn).resolve(model)) # type: ignore[arg-type]
231
+ if not column and not isinstance(decision, bool):
232
+ raise ValueError(
233
+ f"{urn!r} has no column of its own: store it or not, without a "
234
+ "column type"
235
+ )
236
+ self.decisions[urn] = decision
237
+ return decision
238
+
239
+ @staticmethod
240
+ def _hashed(attribute: Any) -> bool:
241
+ """Tell whether an attribute is a single write-only string, whose hash can be stored."""
242
+ return bool(
243
+ attribute.mutability == Mutability.write_only
244
+ and attribute.type == SchemaAttribute.Type.string
245
+ and not attribute.multi_valued
246
+ )
247
+
248
+ def _linked(self, attribute: Any) -> list[str]:
249
+ """Return the served resource types an attribute links to, through the referenceTypes of its $ref."""
250
+ if attribute.type != SchemaAttribute.Type.complex:
251
+ return []
252
+ ref = _sub_attribute(attribute, "$ref")
253
+ if ref is None:
254
+ return []
255
+ return [name for name in ref.reference_types or [] if name in self.tables]
256
+
257
+ def _find_forwards(self, owner: str) -> None:
258
+ """Find the attributes of a resource type that link to resources, and add their association tables."""
259
+ for schema in self.schemas[owner]:
260
+ for attribute in schema.attributes:
261
+ targets = self._linked(attribute)
262
+ urn = f"{schema.urn}:{attribute.name}"
263
+ if (
264
+ not targets
265
+ or attribute.mutability == Mutability.read_only
266
+ or self.decisions[urn] is False
267
+ ):
268
+ continue
269
+ base = _snake(schema.column_prefix + attribute.name)
270
+ keys = {
271
+ target: _fit(
272
+ base if len(targets) == 1 else f"{base}_{_snake(target)}"
273
+ )
274
+ for target in targets
275
+ }
276
+ tables = {}
277
+ if attribute.multi_valued:
278
+ for target in targets:
279
+ tables[target] = Table(
280
+ _fit(
281
+ f"{self.tables[owner]}_{base}_"
282
+ f"{self.tables[target].removeprefix(self.prefix)}"
283
+ ),
284
+ self.metadata,
285
+ Column(
286
+ "resource_id",
287
+ Uuid,
288
+ ForeignKey(
289
+ f"{self.tables[owner]}.id", ondelete="CASCADE"
290
+ ),
291
+ primary_key=True,
292
+ ),
293
+ Column(
294
+ "linked_id",
295
+ Uuid,
296
+ ForeignKey(
297
+ f"{self.tables[target]}.id", ondelete="CASCADE"
298
+ ),
299
+ primary_key=True,
300
+ ),
301
+ )
302
+ self.forwards[urn] = _Forward(
303
+ owner, attribute, targets, keys, tables, {}
304
+ )
305
+
306
+ def _find_inverses(self) -> None:
307
+ """Pair each inverse attribute with the Link of the attribute it reverses, that links to its own resource type."""
308
+ for reverse, forward_urn in self.inverses.items():
309
+ forward = self.forwards.get(forward_urn)
310
+ if forward is None or self.decisions.get(reverse) is False:
311
+ continue
312
+ urn, _, name = reverse.rpartition(":")
313
+ for owner, schemas in self.schemas.items():
314
+ for schema in schemas:
315
+ attribute = next(
316
+ (a for a in schema.attributes if a.name == name), None
317
+ )
318
+ if (
319
+ schema.urn != urn
320
+ or attribute is None
321
+ or not attribute.multi_valued
322
+ or owner not in forward.tables
323
+ or forward.owner not in self._linked(attribute)
324
+ ):
325
+ continue
326
+ forward.inverse_keys[owner] = _snake(
327
+ schema.column_prefix + attribute.name
328
+ )
329
+ self.reverses[reverse] = forward
330
+
331
+ def _build(self, name: str) -> _Class:
332
+ """Return the class of a resource type, with its columns and relationships, and the attributes of its mapping."""
333
+ record_class = _Class(name, self.tables[name])
334
+ version = mapped_column(Integer, nullable=False)
335
+ for key, value, path in [
336
+ ("id", mapped_column(Uuid, primary_key=True, default=uuid.uuid4), "id"),
337
+ ("external_id", mapped_column(String), "externalId"),
338
+ (
339
+ "meta_created",
340
+ mapped_column(DateTime(timezone=True), nullable=False),
341
+ "meta.created",
342
+ ),
343
+ (
344
+ "meta_last_modified",
345
+ mapped_column(DateTime(timezone=True), nullable=False),
346
+ "meta.lastModified",
347
+ ),
348
+ ("meta_version", version, "meta.version"),
349
+ ]:
350
+ record_class.add(key, value, path)
351
+ if key != "meta_version":
352
+ record_class.attributes.append((path, self._getter(name, key)))
353
+ record_class.namespace["__mapper_args__"] = {"version_id_col": version}
354
+
355
+ for schema in self.schemas[name]:
356
+ for attribute in schema.attributes:
357
+ path = f"{schema.path_prefix}{attribute.name}"
358
+ key = _snake(schema.column_prefix + attribute.name)
359
+ attribute_urn = f"{schema.urn}:{attribute.name}"
360
+ if self.decisions.get(attribute_urn) is False:
361
+ continue
362
+ if attribute_urn in self.forwards:
363
+ self._link(name, record_class, path, self.forwards[attribute_urn])
364
+ elif attribute_urn in self.reverses:
365
+ self._reverse(
366
+ name,
367
+ record_class,
368
+ path,
369
+ attribute,
370
+ key,
371
+ self.reverses[attribute_urn],
372
+ )
373
+ elif attribute.mutability == Mutability.read_only:
374
+ continue
375
+ elif attribute.type == SchemaAttribute.Type.complex:
376
+ self._complex(
377
+ name, record_class, path, attribute, key, attribute_urn
378
+ )
379
+ elif attribute.multi_valued:
380
+ self._values(
381
+ name, record_class, path, attribute, key, attribute_urn
382
+ )
383
+ else:
384
+ required = schema.path_prefix == "" and (
385
+ attribute.required == Required.true
386
+ )
387
+ mapped = self._column(
388
+ name,
389
+ record_class,
390
+ path,
391
+ attribute,
392
+ key,
393
+ attribute_urn,
394
+ nullable=not required,
395
+ unique=attribute.uniqueness
396
+ in (Uniqueness.server, Uniqueness.global_),
397
+ )
398
+ if mapped is not None:
399
+ record_class.attributes.append((path, mapped))
400
+ return record_class
401
+
402
+ def _make(self, record_class: _Class) -> None:
403
+ """Create the record class from its namespace."""
404
+ self.classes[record_class.name] = type(
405
+ record_class.name, (self.base,), record_class.namespace
406
+ )
407
+
408
+ def _getter(self, name: str, key: str) -> Callable[[], Any]:
409
+ """Return a function reading an attribute of a record class once it is created."""
410
+ return lambda: getattr(self.classes[name], key)
411
+
412
+ def _class(self, name: str) -> Callable[[], Any]:
413
+ """Return a function reading a record class once it is created."""
414
+ return lambda: self.classes[name]
415
+
416
+ def _join(self, name: str, column: Any) -> Callable[[], Any]:
417
+ """Return the condition joining the records of a resource type to a column of an association table."""
418
+ return lambda: self.classes[name].id == column
419
+
420
+ def _column(
421
+ self,
422
+ name: str,
423
+ record_class: _Class,
424
+ path: str,
425
+ attribute: Any,
426
+ key: str,
427
+ urn: str,
428
+ *,
429
+ nullable: bool = True,
430
+ unique: bool = False,
431
+ ) -> Callable[[], Any] | None:
432
+ """Add the column of a simple attribute, and return what maps it, or None when it is not stored."""
433
+ decision = self.decisions.get(urn, False)
434
+ if decision is False:
435
+ return None
436
+ key = _fit(key)
437
+ record_class.add(
438
+ key,
439
+ mapped_column(
440
+ self._type(attribute, decision),
441
+ nullable=nullable,
442
+ unique=unique or None,
443
+ ),
444
+ path,
445
+ )
446
+ getter = self._getter(name, key)
447
+ if attribute.mutability != Mutability.write_only:
448
+ return getter
449
+ return lambda: Attribute(getter(), readable=False)
450
+
451
+ @staticmethod
452
+ def _type(attribute: Any, decision: bool | TypeEngine[Any]) -> TypeEngine[Any]:
453
+ """Return the column type store gave, or the type matching the attribute."""
454
+ if isinstance(decision, TypeEngine):
455
+ return decision
456
+ return _SQL_TYPES[attribute.type]()
457
+
458
+ def _complex(
459
+ self,
460
+ name: str,
461
+ record_class: _Class,
462
+ path: str,
463
+ attribute: Any,
464
+ key: str,
465
+ urn: str,
466
+ ) -> None:
467
+ """Add the columns of the sub-attributes of a single-valued complex attribute, or its child table if it is multi-valued."""
468
+ if attribute.multi_valued:
469
+ self._entries(name, record_class, path, attribute, key, urn)
470
+ return
471
+ for sub in attribute.sub_attributes or []:
472
+ if sub.multi_valued or sub.mutability == Mutability.read_only:
473
+ continue
474
+ sub_path = f"{path}.{sub.name}"
475
+ mapped = self._column(
476
+ name,
477
+ record_class,
478
+ sub_path,
479
+ sub,
480
+ f"{key}_{_snake(sub.name)}",
481
+ f"{urn}.{sub.name}",
482
+ )
483
+ if mapped is not None:
484
+ record_class.attributes.append((sub_path, mapped))
485
+
486
+ def _child(
487
+ self, name: str, record_class: _Class, path: str, key: str
488
+ ) -> tuple[_Class, str]:
489
+ """Start the class of the child table of an attribute, and add the relationship to it."""
490
+ key = _fit(key)
491
+ child_name = _fit(f"{self.tables[name]}_{key}")
492
+ child = _Class(child_name, child_name)
493
+ child.add("id", mapped_column(Integer, primary_key=True), path)
494
+ child.add(
495
+ "resource_id",
496
+ mapped_column(
497
+ Uuid,
498
+ ForeignKey(f"{self.tables[name]}.id", ondelete="CASCADE"),
499
+ nullable=False,
500
+ ),
501
+ path,
502
+ )
503
+ record_class.add(
504
+ key,
505
+ relationship(
506
+ self._class(child_name),
507
+ cascade="all, delete-orphan",
508
+ order_by=self._getter(child_name, "id"),
509
+ ),
510
+ path,
511
+ )
512
+ return child, key
513
+
514
+ def _entries(
515
+ self,
516
+ name: str,
517
+ record_class: _Class,
518
+ path: str,
519
+ attribute: Any,
520
+ key: str,
521
+ urn: str,
522
+ ) -> None:
523
+ """Add the child table of a multi-valued complex attribute, with a column for each stored sub-attribute."""
524
+ child, key = self._child(name, record_class, path, key)
525
+ columns = {}
526
+ for sub in attribute.sub_attributes or []:
527
+ if sub.multi_valued or sub.mutability == Mutability.read_only:
528
+ continue
529
+ mapped = self._column(
530
+ child.name,
531
+ child,
532
+ f"{path}.{sub.name}",
533
+ sub,
534
+ _snake(sub.name),
535
+ f"{urn}.{sub.name}",
536
+ )
537
+ if mapped is not None:
538
+ columns[sub.name] = mapped
539
+ if not columns:
540
+ del record_class.namespace[key]
541
+ return
542
+ self._make(child)
543
+ getter = self._getter(name, key)
544
+ record_class.attributes.append(
545
+ (
546
+ path,
547
+ lambda: Many(
548
+ getter(), {sub: mapped() for sub, mapped in columns.items()}
549
+ ),
550
+ )
551
+ )
552
+
553
+ def _values(
554
+ self,
555
+ name: str,
556
+ record_class: _Class,
557
+ path: str,
558
+ attribute: Any,
559
+ key: str,
560
+ urn: str,
561
+ ) -> None:
562
+ """Add the child table of a multi-valued simple attribute, with a value column."""
563
+ if attribute.mutability == Mutability.write_only:
564
+ return
565
+ child, key = self._child(name, record_class, path, key)
566
+ child.add(
567
+ "value",
568
+ mapped_column(self._type(attribute, self.decisions[urn]), nullable=False),
569
+ path,
570
+ )
571
+ self._make(child)
572
+ getter = self._getter(name, key)
573
+ value = self._getter(child.name, "value")
574
+ record_class.attributes.append((path, lambda: Many(getter(), value())))
575
+
576
+ def _link(
577
+ self, name: str, record_class: _Class, path: str, forward: _Forward
578
+ ) -> None:
579
+ """Add a relationship for each resource type an attribute links to: an association table for a multi-valued attribute, a foreign key otherwise."""
580
+ attribute = forward.attribute
581
+ type_values = (_sub_attribute(attribute, "type") or attribute).canonical_values
582
+ typed = bool(type_values) and all(
583
+ target in type_values for target in forward.targets
584
+ )
585
+ links = []
586
+ for target in forward.targets:
587
+ key = forward.keys[target]
588
+ if attribute.multi_valued:
589
+ table = forward.tables[target]
590
+ value = relationship(
591
+ self._class(target),
592
+ secondary=table,
593
+ primaryjoin=self._join(name, table.c.resource_id),
594
+ secondaryjoin=self._join(target, table.c.linked_id),
595
+ back_populates=forward.inverse_keys.get(target),
596
+ )
597
+ else:
598
+ column_key = _fit(f"{key}_id")
599
+ record_class.add(
600
+ column_key,
601
+ mapped_column(
602
+ Uuid,
603
+ ForeignKey(f"{self.tables[target]}.id", ondelete="SET NULL"),
604
+ ),
605
+ path,
606
+ )
607
+ # A resource linking to a resource of its own type, such as a
608
+ # user managed by another user, may form a cycle, which the
609
+ # unit of work only stores with a second UPDATE.
610
+ value = relationship(
611
+ self._class(target),
612
+ foreign_keys=self._getter(name, column_key),
613
+ remote_side=self._getter(target, "id") if target == name else (),
614
+ post_update=target == name,
615
+ )
616
+ record_class.add(key, value, path)
617
+ links.append((self._getter(name, key), target))
618
+ record_class.attributes.append(
619
+ (
620
+ path,
621
+ lambda: [
622
+ Link(getter(), target, type=target if typed else None)
623
+ for getter, target in links
624
+ ],
625
+ )
626
+ )
627
+
628
+ def _reverse(
629
+ self,
630
+ name: str,
631
+ record_class: _Class,
632
+ path: str,
633
+ attribute: Any,
634
+ key: str,
635
+ forward: _Forward,
636
+ ) -> None:
637
+ """Add the relationship of an inverse attribute, which reads the association table of the attribute it reverses."""
638
+ table = forward.tables[name]
639
+ record_class.add(
640
+ key,
641
+ relationship(
642
+ self._class(forward.owner),
643
+ secondary=table,
644
+ primaryjoin=self._join(name, table.c.linked_id),
645
+ secondaryjoin=self._join(forward.owner, table.c.resource_id),
646
+ back_populates=forward.keys[name],
647
+ ),
648
+ path,
649
+ )
650
+ type_values = (_sub_attribute(attribute, "type") or attribute).canonical_values
651
+ link_type = "direct" if "direct" in (type_values or []) else None
652
+ getter = self._getter(name, key)
653
+ record_class.attributes.append(
654
+ (path, lambda: Link(getter(), forward.owner, type=link_type))
655
+ )
656
+
657
+
658
+ def _store_all(binding: AttributeBinding) -> bool:
659
+ """Store each attribute with the column type matching it."""
660
+ return True
661
+
662
+
663
+ def generate_mappings(
664
+ provider: ScimProvider,
665
+ metadata: MetaData,
666
+ *,
667
+ prefix: str = "",
668
+ store: Callable[[AttributeBinding], bool | TypeEngine[Any]] = _store_all,
669
+ inverses: Mapping[str, str] | None = None,
670
+ ) -> dict[str, ResourceMapping]:
671
+ """Generate the tables and the mappings that store the resources of a provider.
672
+
673
+ Each resource type gets a table named after its endpoint, such as
674
+ ``users``. A simple attribute gets a column, a complex attribute holding a
675
+ single value gets a column for each sub-attribute, and an extension gets
676
+ columns prefixed by the name of its schema. A multi-valued attribute gets a
677
+ child table, mapped with :class:`~scim2_sqlalchemy.Many`. A complex
678
+ attribute whose ``$ref`` links to served resource types gets a
679
+ :class:`~scim2_sqlalchemy.Link` for each of them.
680
+
681
+ A read-only attribute is not stored, except an inverse: it reads the links
682
+ of the attribute it reverses, such as ``groups`` of a user, which reads the
683
+ ``members`` of the groups. A multi-valued sub-attribute is not stored
684
+ either, nor a write-only attribute other than a single string. A column
685
+ holds ``NOT NULL`` for a required attribute of the core schema, and
686
+ ``UNIQUE`` for an attribute unique on the server. The table and column
687
+ names longer than 63 characters are shortened.
688
+
689
+ ``store`` decides how each attribute is kept. It receives the
690
+ :class:`~scim2_models.AttributeBinding` of the attribute, and returns:
691
+
692
+ - :data:`True`, to store the attribute with the column type matching it;
693
+ - :data:`False`, not to store it: the published schemas leave it out;
694
+ - a column type, such as :class:`~scim2_sqlalchemy.Hashed`, to store it
695
+ in a column of this type. Only an attribute with a column of its own
696
+ takes one: a simple attribute, a sub-attribute, or the values of a
697
+ multi-valued simple attribute.
698
+
699
+ A write-only string, such as a password, is never stored in clear text:
700
+ ``store`` gives it a column type that hashes it, or does not store it.
701
+
702
+ Pass the mappings to the storage, and create the tables with
703
+ :meth:`MetaData.create_all <sqlalchemy.schema.MetaData.create_all>` or a
704
+ migration tool.
705
+
706
+ :param provider: The provider of the server, which gives the resource types
707
+ and their models.
708
+ :param metadata: The :class:`~sqlalchemy.schema.MetaData` the tables are
709
+ added to.
710
+ :param prefix: A prefix of the names of the tables.
711
+ :param store: The function deciding how each attribute is kept. By
712
+ default, every attribute is stored with the column type matching it.
713
+ :param inverses: The read-only attributes reading the links of another
714
+ attribute, by URN, in addition to ``groups`` of a user reversing
715
+ ``members`` of a group.
716
+ :returns: The mappings, by resource type name.
717
+ :raises ValueError: When ``store`` keeps a write-only string in clear
718
+ text, when it gives a column type to an attribute without a column of
719
+ its own, or when two attributes need the same column name.
720
+ """
721
+ return _Generator(
722
+ provider,
723
+ metadata,
724
+ prefix,
725
+ store,
726
+ {_GROUPS: _MEMBERS, **(inverses or {})},
727
+ ).generate()