scim2-sqlalchemy 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scim2-sqlalchemy
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Painless SCIM integration for SQLAlchemy
5
5
  Keywords: scim,scim2,provisioning,sqlalchemy,rfc7643,rfc7644
6
6
  Author: Éloi Rivard
@@ -18,8 +18,8 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
18
18
  Classifier: Environment :: Web Environment
19
19
  Classifier: Programming Language :: Python
20
20
  Classifier: Operating System :: OS Independent
21
- Requires-Dist: scim2-models>=0.12.2
22
- Requires-Dist: scim2-server>=0.8.8
21
+ Requires-Dist: scim2-models>=0.12.7
22
+ Requires-Dist: scim2-server>=0.8.9
23
23
  Requires-Dist: sqlalchemy>=2.0.41
24
24
  Requires-Dist: sqlalchemy[asyncio]>=2.0.41 ; extra == 'asyncio'
25
25
  Requires-Python: >=3.11
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-sqlalchemy"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Painless SCIM integration for SQLAlchemy"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -32,8 +32,8 @@ classifiers = [
32
32
  ]
33
33
  requires-python = ">=3.11"
34
34
  dependencies = [
35
- "scim2-models>=0.12.2",
36
- "scim2-server>=0.8.8",
35
+ "scim2-models>=0.12.7",
36
+ "scim2-server>=0.8.9",
37
37
  "sqlalchemy>=2.0.41",
38
38
  ]
39
39
 
@@ -60,7 +60,7 @@ dev = [
60
60
  "pytest-cov>=7.1.0",
61
61
  "pytest-postgresql>=9.1.0",
62
62
  "scim2-client>=0.14.0",
63
- "scim2-server[testing]>=0.8.8",
63
+ "scim2-server[testing]>=0.8.9",
64
64
  "scim2-tester[testing]>=0.6.2",
65
65
  "tox-uv>=1.36.0",
66
66
  "werkzeug>=3.1.8",
@@ -129,7 +129,10 @@ testpaths = [
129
129
  addopts = "--doctest-modules --doctest-glob='*.rst' --ignore=doc/conf.py"
130
130
  pythonpath = ["doc/_examples"]
131
131
  doctest_optionflags = "ALLOW_UNICODE ELLIPSIS NORMALIZE_WHITESPACE"
132
- filterwarnings = ["error::scim2_tester.testing.ScimDeviationWarning"]
132
+ filterwarnings = [
133
+ "error::scim2_tester.testing.ScimDeviationWarning",
134
+ "error:The column .* needs a value:UserWarning",
135
+ ]
133
136
 
134
137
  [tool.uv]
135
138
  exclude-newer = "14 days"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-sqlalchemy"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Painless SCIM integration for SQLAlchemy"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -28,8 +28,8 @@ authors = [
28
28
  ]
29
29
  requires-python = ">=3.11"
30
30
  dependencies = [
31
- "scim2-models>=0.12.2",
32
- "scim2-server>=0.8.8",
31
+ "scim2-models>=0.12.7",
32
+ "scim2-server>=0.8.9",
33
33
  "sqlalchemy>=2.0.41",
34
34
  ]
35
35
 
@@ -54,7 +54,7 @@ dev = [
54
54
  "pytest-cov>=7.1.0",
55
55
  "pytest-postgresql>=9.1.0",
56
56
  "scim2-client>=0.14.0",
57
- "scim2-server[testing]>=0.8.8",
57
+ "scim2-server[testing]>=0.8.9",
58
58
  "scim2-tester[testing]>=0.6.2",
59
59
  "tox-uv>=1.36.0",
60
60
  "werkzeug>=3.1.8",
@@ -117,7 +117,10 @@ testpaths = ["tests", "doc"]
117
117
  addopts = "--doctest-modules --doctest-glob='*.rst' --ignore=doc/conf.py"
118
118
  pythonpath = ["doc/_examples"]
119
119
  doctest_optionflags = "ALLOW_UNICODE ELLIPSIS NORMALIZE_WHITESPACE"
120
- filterwarnings = ["error::scim2_tester.testing.ScimDeviationWarning"]
120
+ filterwarnings = [
121
+ "error::scim2_tester.testing.ScimDeviationWarning",
122
+ "error:The column .* needs a value:UserWarning",
123
+ ]
121
124
 
122
125
  [tool.uv]
123
126
  exclude-newer = "14 days"
@@ -44,9 +44,9 @@ def _as_stored(value: Any) -> Any:
44
44
 
45
45
 
46
46
  def _read(column: _Column, record: Any) -> Any:
47
- """Return the SCIM value of a column of a record, or None if the column is not read."""
47
+ """Return the SCIM value of a column of a record."""
48
48
  value = getattr(record, column.key)
49
- if value is None or not column.readable:
49
+ if value is None:
50
50
  return None
51
51
  if isinstance(value, Enum) and column.enumeration is not None:
52
52
  return column.stored_string(column.enumeration, value)
@@ -154,19 +154,22 @@ def _from_scim(
154
154
  ) -> None:
155
155
  """Write a resource into a record.
156
156
 
157
- Read-only attributes are left as they are, and so is a write-only attribute
158
- the resource has no value for, since a resource never carries it back.
159
- When creating the record, a missing value is not written, so that the
160
- column keeps its default. links holds the records each Link of the
161
- resource links to.
157
+ Read-only attributes are left as they are. A value equal to the stored one
158
+ is not written again, so that a hash given back as it was read is not
159
+ hashed again. When creating the record, a missing value is not written, so
160
+ that the column keeps its default. links holds the records each Link of
161
+ the resource links to.
162
162
  """
163
163
  for column in mapping._columns.values():
164
164
  if not column.writable:
165
165
  continue
166
166
  value = Path(column.binding.urn).get(resource, strict=False)
167
- if value is None and (creating or not column.readable):
167
+ if value is None and creating:
168
168
  continue
169
- setattr(record, column.key, None if value is None else _as_stored(value))
169
+ stored = None if value is None else _as_stored(value)
170
+ if not creating and stored == getattr(record, column.key):
171
+ continue
172
+ setattr(record, column.key, stored)
170
173
 
171
174
  for collection in mapping._all_collections():
172
175
  if not collection.writable:
@@ -12,6 +12,7 @@ from scim2_models import Mutability
12
12
  from scim2_models import Path
13
13
  from scim2_models import Required
14
14
  from scim2_models import ResourceType
15
+ from scim2_models import Returned
15
16
  from scim2_models import ScimProvider
16
17
  from scim2_models import Uniqueness
17
18
  from sqlalchemy import Boolean
@@ -33,7 +34,6 @@ from sqlalchemy.types import TypeEngine
33
34
 
34
35
  from .mapping import _MARIADB
35
36
  from .mapping import _MARIADB_TEXT
36
- from .mapping import Attribute
37
37
  from .mapping import Link
38
38
  from .mapping import Many
39
39
  from .mapping import ResourceMapping
@@ -109,6 +109,14 @@ class _Forward:
109
109
  inverse_keys: dict[str, str]
110
110
 
111
111
 
112
+ def _hidden(attribute: Any) -> bool:
113
+ """Tell whether clients never read an attribute back."""
114
+ return bool(
115
+ attribute.mutability == Mutability.write_only
116
+ or attribute.returned == Returned.never
117
+ )
118
+
119
+
112
120
  class _Class:
113
121
  """The namespace of a record class being built, and the attributes of its mapping."""
114
122
 
@@ -209,10 +217,7 @@ class _Generator:
209
217
  continue
210
218
  if attribute.mutability == Mutability.read_only:
211
219
  continue
212
- if (
213
- attribute.multi_valued
214
- and attribute.mutability == Mutability.write_only
215
- ):
220
+ if attribute.multi_valued and _hidden(attribute):
216
221
  self.decisions[urn] = False
217
222
  continue
218
223
  if attribute.type != SchemaAttribute.Type.complex:
@@ -226,10 +231,7 @@ class _Generator:
226
231
  if (
227
232
  not sub.multi_valued
228
233
  and sub.mutability != Mutability.read_only
229
- and not (
230
- attribute.multi_valued
231
- and sub.mutability == Mutability.write_only
232
- )
234
+ and not (attribute.multi_valued and _hidden(sub))
233
235
  and self._ask_column(model, sub_urn, sub)
234
236
  ):
235
237
  clear.append(sub_urn)
@@ -467,10 +469,7 @@ class _Generator:
467
469
  ),
468
470
  path,
469
471
  )
470
- getter = self._getter(name, key)
471
- if attribute.mutability != Mutability.write_only:
472
- return getter
473
- return lambda: Attribute(getter(), readable=False)
472
+ return self._getter(name, key)
474
473
 
475
474
  @staticmethod
476
475
  def _type(attribute: Any, decision: bool | TypeEngine[Any]) -> TypeEngine[Any]:
@@ -1,3 +1,4 @@
1
+ import warnings
1
2
  from collections.abc import Callable
2
3
  from collections.abc import Iterable
3
4
  from collections.abc import Iterator
@@ -13,8 +14,10 @@ from scim2_models import Attribute as SchemaAttribute
13
14
  from scim2_models import AttributeBinding
14
15
  from scim2_models import Mutability
15
16
  from scim2_models import Path
17
+ from scim2_models import Required
16
18
  from scim2_models import Resource
17
19
  from scim2_models import ResponseParameters
20
+ from scim2_models import Returned
18
21
  from scim2_models import Schema
19
22
  from scim2_models import Uniqueness
20
23
  from sqlalchemy import Column
@@ -30,12 +33,15 @@ from sqlalchemy import literal
30
33
  from sqlalchemy.dialects import mysql
31
34
  from sqlalchemy.ext.compiler import compiles
32
35
  from sqlalchemy.ext.hybrid import hybrid_property
36
+ from sqlalchemy.orm import MANYTOONE
37
+ from sqlalchemy.orm import ONETOMANY
33
38
  from sqlalchemy.orm import InstrumentedAttribute
34
39
  from sqlalchemy.orm import Mapper
35
40
  from sqlalchemy.orm import RelationshipProperty
36
41
  from sqlalchemy.orm import strategy_options
37
42
  from sqlalchemy.sql.compiler import SQLCompiler
38
43
  from sqlalchemy.sql.functions import FunctionElement
44
+ from sqlalchemy.sql.visitors import iterate
39
45
  from sqlalchemy.types import TypeDecorator
40
46
  from sqlalchemy.types import TypeEngine
41
47
 
@@ -116,11 +122,25 @@ def _table_column(expression: Any) -> Column[Any] | None:
116
122
  return column if isinstance(column, Column) else None
117
123
 
118
124
 
119
- def _write_only(binding: AttributeBinding) -> bool:
120
- """Whether the schema makes an attribute write-only, itself or through its parent."""
125
+ def _needs_value(column: Column[Any]) -> bool:
126
+ """Whether a new row needs a value: the column holds no null, has no default, and the database does not number it."""
127
+ return (
128
+ not column.nullable
129
+ and column.default is None
130
+ and column.server_default is None
131
+ and column is not column.table.autoincrement_column
132
+ )
133
+
134
+
135
+ def _conceals(binding: AttributeBinding) -> bool:
136
+ """Whether clients never read an attribute back: its schema, or the one of the attribute holding it, makes it writeOnly or never returns it."""
137
+ model, field_name = binding.model, binding.field_name
121
138
  return Mutability.write_only in (
122
- binding.model.get_field_annotation(binding.field_name, Mutability),
139
+ model.get_field_annotation(field_name, Mutability),
123
140
  binding.get_annotation(Mutability),
141
+ ) or Returned.never in (
142
+ model.get_field_annotation(field_name, Returned),
143
+ binding.get_annotation(Returned),
124
144
  )
125
145
 
126
146
 
@@ -155,7 +175,7 @@ def _overlap(
155
175
 
156
176
 
157
177
  class Attribute:
158
- """A column holding a SCIM attribute that the storage only reads, or only writes.
178
+ """A column holding a SCIM attribute, whose writing can be turned off.
159
179
 
160
180
  To store a value in another form, map the attribute to a
161
181
  :class:`~sqlalchemy.ext.hybrid.hybrid_property` that converts it, in Python
@@ -163,18 +183,12 @@ class Attribute:
163
183
 
164
184
  :param expression: The column, or the
165
185
  :class:`~sqlalchemy.ext.hybrid.hybrid_property`, holding the value.
166
- :param readable: Whether the storage reads the attribute. When
167
- :data:`False`, the attribute is write-only, such as a password: the
168
- storage never returns it, nor filters or sorts on it.
169
186
  :param writable: Whether the storage writes the attribute. When
170
187
  :data:`False`, the attribute is read-only.
171
188
  """
172
189
 
173
- def __init__(
174
- self, expression: Any, *, readable: bool = True, writable: bool = True
175
- ) -> None:
190
+ def __init__(self, expression: Any, *, writable: bool = True) -> None:
176
191
  self.expression = expression
177
- self.readable = readable
178
192
  self.writable = writable
179
193
 
180
194
 
@@ -182,7 +196,10 @@ class Hashed(TypeDecorator[str]):
182
196
  """A column type storing the hash of a string, such as a password.
183
197
 
184
198
  The column stores what the hash function returns for the value written.
185
- Map it with ``readable=False``, since the storage cannot read a hash back.
199
+ Map it to an attribute that the schema makes ``writeOnly``, such as
200
+ ``password``, or never returns. The storage reads the hash back, and
201
+ clients never see it. A replacement without the value gives the hash back
202
+ to the storage, which keeps it as it is.
186
203
 
187
204
  :param hash_value: The function hashing a value.
188
205
  :param length: The length of the column. Without it, MariaDB stores a TEXT.
@@ -218,9 +235,9 @@ class Many:
218
235
  order of the entries. Without it, the order is the one the database
219
236
  returns. A sort uses the ``primary`` entry, or else the first one.
220
237
 
221
- Since writing replaces the entries, their columns are all readable: a
222
- client never sends back a write-only value, so a write would lose it.
223
- Their columns are also either all written or none.
238
+ Since writing replaces the entries, they cannot hold values that clients
239
+ never read back, such as write-only values. Their columns are also either
240
+ all written or none.
224
241
 
225
242
  The entries of a multi-valued simple attribute, such as a list of strings,
226
243
  are the values of one column of the child table. The storage keeps their
@@ -259,7 +276,10 @@ class Link:
259
276
  read in the order of the list.
260
277
 
261
278
  :param relationship: The :func:`~sqlalchemy.orm.relationship` from the
262
- resource record to the records of the linked resources.
279
+ resource record to the records of the linked resources. The foreign
280
+ key of a many-to-one relationship accepts ``NULL``, unless the schema
281
+ makes the attribute required, and the extension holding it too. The
282
+ foreign key of a one-to-many relationship always accepts ``NULL``.
263
283
  :param resource_type: The name of the resource type of the linked
264
284
  resources, as the storage knows it.
265
285
  :param type: The ``type`` sub-attribute of the entries, such as ``"User"``
@@ -281,15 +301,17 @@ class _Column:
281
301
  """A SCIM attribute stored in a column or a hybrid property.
282
302
 
283
303
  textual tells whether filters compare the column as text, as they do for
284
- an integer identifier.
304
+ an integer identifier. concealed tells whether clients never read the
305
+ value back, and immutable whether the schema keeps it from changing.
285
306
  """
286
307
 
287
308
  binding: AttributeBinding
288
309
  expression: ColumnElement[Any]
289
310
  key: str
290
- readable: bool
291
311
  writable: bool
292
312
  textual: bool = False
313
+ concealed: bool = False
314
+ immutable: bool = False
293
315
 
294
316
  @property
295
317
  def is_string(self) -> bool:
@@ -315,13 +337,7 @@ class _Column:
315
337
  def required(self) -> bool:
316
338
  """Whether a new record needs a value: the column holds no null, has no default, and the database does not number it."""
317
339
  column = _table_column(self.expression)
318
- return (
319
- column is not None
320
- and not column.nullable
321
- and column.default is None
322
- and column.server_default is None
323
- and column is not column.table.autoincrement_column
324
- )
340
+ return column is not None and _needs_value(column)
325
341
 
326
342
  @property
327
343
  def enumeration(self) -> SqlEnum | None:
@@ -452,7 +468,13 @@ class ResourceMapping:
452
468
  does: adding a member to a group leaves the version of the user as it is.
453
469
  :raises ValueError: When a path is not valid for the model, when a
454
470
  value does not fit the attribute of its path, or when ``id`` is mapped
455
- to a column that can hold ``NULL``.
471
+ to a column that can hold ``NULL``. Also when clients could neither
472
+ read nor write an attribute, when an attribute clients read, or an
473
+ immutable one, is mapped to a :class:`Hashed` column, or when removing
474
+ a :class:`Link` would write ``NULL`` in a foreign key that refuses it.
475
+
476
+ The mapping warns about a column that needs a value but that the storage
477
+ never writes.
456
478
  """
457
479
 
458
480
  _REQUIRED = ("id", "meta.created", "meta.lastModified")
@@ -503,12 +525,75 @@ class ResourceMapping:
503
525
  self._id.textual = not _holds_text(self._id.expression)
504
526
  self._created = self._column("meta.created")
505
527
  self._last_modified = self._column("meta.lastModified")
528
+ self._warn_unwritten()
529
+
530
+ def _always_held(self, binding: AttributeBinding) -> bool:
531
+ """Tell whether the schema makes every resource hold an attribute, and the extension holding it."""
532
+ if Required.true not in (
533
+ binding.model.get_field_annotation(binding.field_name, Required),
534
+ binding.get_annotation(Required),
535
+ ):
536
+ return False
537
+ if binding.model not in self.model.get_extension_models().values():
538
+ return True
539
+ required = self.model.get_field_annotation(binding.model.__name__, Required)
540
+ return bool(required == Required.true)
541
+
542
+ def _warn_unwritten(self) -> None:
543
+ """Warn about the columns of the record that need a value the storage never writes."""
544
+ written: list[Any] = [
545
+ _table_column(mapped.expression)
546
+ for mapped in self._columns.values()
547
+ if mapped.writable or mapped in (self._created, self._last_modified)
548
+ ]
549
+ mapper: Mapper[Any] = inspect(self.record)
550
+ # The setter of a property may write any column its expression reads.
551
+ for mapped in self._columns.values():
552
+ descriptor = mapper.all_orm_descriptors.get(mapped.key)
553
+ # The storage sets the dates itself, read-only as they are.
554
+ dated = mapped in (self._created, self._last_modified)
555
+ if (mapped.writable or dated) and isinstance(descriptor, hybrid_property):
556
+ written += [
557
+ element.table.columns.get(element.key)
558
+ for element in iterate(mapped.expression.__clause_element__())
559
+ if isinstance(element, Column)
560
+ ]
561
+ for collection in self._all_collections():
562
+ if collection.single and not collection.owned and collection.writable:
563
+ written += collection.relationship_property.local_columns
564
+ # SQLAlchemy fills the version, the discriminator of the classes, and
565
+ # the key each joined table shares with the table it inherits from.
566
+ written += [mapper.version_id_col, mapper.polymorphic_on]
567
+ for ancestor in mapper.iterate_to_root():
568
+ if ancestor.inherits is not None:
569
+ written += [
570
+ column
571
+ for column in ancestor.local_table.primary_key
572
+ if column.foreign_keys
573
+ ]
574
+ for column in mapper.columns:
575
+ if (
576
+ not isinstance(column, Column)
577
+ or not _needs_value(column)
578
+ or any(column is other for other in written)
579
+ ):
580
+ continue
581
+ warnings.warn(
582
+ f"The column {column.table.name}.{column.name} needs a value, "
583
+ f"but the mapping of {self.model.__name__} never writes it: "
584
+ "map it, or give it a default",
585
+ stacklevel=3,
586
+ )
506
587
 
507
588
  def schemas(self) -> list[Schema]:
508
589
  """Return the schemas of the resources, restricted to what the mapping stores.
509
590
 
510
- They hold the mapped attributes only, and an attribute the mapping
511
- reads but never writes is ``readOnly``. Publish them, rather than the
591
+ They hold the mapped attributes only. An attribute the mapping reads
592
+ but never writes is ``readOnly``, and an attribute it writes but never
593
+ reads is ``writeOnly``. An attribute whose column cannot be ``NULL``
594
+ and has no default is ``required``, unless it is write-only. A column
595
+ with a default that cannot be ``NULL`` leaves its attribute optional,
596
+ but its value cannot be removed. Publish them, rather than the
512
597
  schemas of :attr:`model`, so that clients know what the server stores:
513
598
  build the provider of the server with
514
599
  :meth:`ScimProvider.from_discovery <scim2_models.ScimProvider.from_discovery>`,
@@ -549,18 +634,45 @@ class ResourceMapping:
549
634
  sub_attribute.mutability != Mutability.read_only
550
635
  for sub_attribute in sub_attributes
551
636
  )
637
+ required = attribute.required
638
+ if any(
639
+ self._always_needs(f"{urn}.{sub_attribute.name}", entries=False)
640
+ for sub_attribute in sub_attributes
641
+ ):
642
+ required = Required.true
643
+ mutability = attribute.mutability if written else Mutability.read_only
644
+ returned = attribute.returned
645
+ if all(sub.returned == Returned.never for sub in sub_attributes):
646
+ returned = Returned.never
647
+ required = Required.false
648
+ if mutability == Mutability.read_write:
649
+ mutability = Mutability.write_only
552
650
  return attribute.model_copy(
553
651
  update={
554
652
  "sub_attributes": sub_attributes,
555
- "mutability": attribute.mutability
556
- if written
557
- else Mutability.read_only,
653
+ "mutability": mutability,
654
+ "required": required,
655
+ "returned": returned,
558
656
  }
559
657
  )
560
658
 
561
659
  storage = self._storage(urn)
562
660
  if storage is None:
563
661
  return None
662
+ columns = self._columns_of(urn, entries=True)
663
+ if storage == _Storage.written and any(c.concealed for c in columns):
664
+ mutability = Mutability.write_only
665
+ if any(c.immutable for c in columns):
666
+ mutability = Mutability.immutable
667
+ return attribute.model_copy(
668
+ update={
669
+ "mutability": mutability,
670
+ "returned": Returned.never,
671
+ "required": Required.false,
672
+ }
673
+ )
674
+ if self._always_needs(urn):
675
+ return attribute.model_copy(update={"required": Required.true})
564
676
  if storage in (_Storage.written, _Storage.link_type):
565
677
  return attribute
566
678
  if storage == _Storage.ref:
@@ -591,22 +703,37 @@ class ResourceMapping:
591
703
  return _Storage.written if column.writable else _Storage.read_only
592
704
  return None
593
705
 
706
+ def _columns_of(self, urn: str, *, entries: bool) -> list[_Column]:
707
+ """Return the columns of an attribute, with the columns of the entries when entries is True."""
708
+ key = urn.lower()
709
+ columns = list(self._columns.values())
710
+ if entries:
711
+ columns += [
712
+ column
713
+ for collection in self._all_collections()
714
+ if collection.owned and not collection.simple
715
+ for column in collection.columns.values()
716
+ ]
717
+ return [column for column in columns if column.binding.urn.lower() == key]
718
+
594
719
  def _nullable(self, urn: str) -> bool:
595
720
  """Tell whether the column of an attribute can hold no value, True for an attribute without column."""
596
- key = urn.lower()
597
- return all(
598
- column.nullable
599
- for column in self._columns.values()
600
- if column.binding.urn.lower() == key
601
- )
721
+ return all(c.nullable for c in self._columns_of(urn, entries=False))
602
722
 
603
723
  def _required(self, urn: str) -> bool:
604
724
  """Tell whether a new record needs a value for the column of an attribute."""
605
- key = urn.lower()
725
+ return any(c.required for c in self._columns_of(urn, entries=False))
726
+
727
+ def _always_needs(self, urn: str, *, entries: bool = True) -> bool:
728
+ """Tell whether a resource, or an entry when entries is True, always needs a value for an attribute.
729
+
730
+ This holds for a column that needs a value, that the storage writes, and
731
+ that clients read back. A concealed value is kept when a replacement
732
+ leaves it out, so a replacement does not need it.
733
+ """
606
734
  return any(
607
- column.required
608
- for column in self._columns.values()
609
- if column.binding.urn.lower() == key
735
+ column.required and column.writable and not column.concealed
736
+ for column in self._columns_of(urn, entries=entries)
610
737
  )
611
738
 
612
739
  def _linked_resource_types(self, urn: str) -> list[str]:
@@ -669,9 +796,9 @@ class ResourceMapping:
669
796
  yield collection.type_column
670
797
 
671
798
  def _unique_columns(self) -> Iterator[_Column]:
672
- """Yield the readable columns whose values no two resources share."""
799
+ """Yield the columns whose values no two resources share, except those clients never read back."""
673
800
  for column in self._columns.values():
674
- if column.readable and column.binding.get_annotation(Uniqueness) in (
801
+ if not column.concealed and column.binding.get_annotation(Uniqueness) in (
675
802
  Uniqueness.server,
676
803
  Uniqueness.global_,
677
804
  ):
@@ -727,6 +854,7 @@ class ResourceMapping:
727
854
  collection.target = target
728
855
  collection.columns = {}
729
856
  head = collection.binding.urn
857
+ concealed = _conceals(collection.binding)
730
858
  for binding, column in (
731
859
  (self._resolve(f"{head}.value"), target._id),
732
860
  (
@@ -740,9 +868,9 @@ class ResourceMapping:
740
868
  binding,
741
869
  column.expression,
742
870
  column.key,
743
- column.readable,
744
871
  False,
745
872
  column.textual,
873
+ concealed=concealed or _conceals(binding),
746
874
  )
747
875
 
748
876
  def _target(
@@ -769,7 +897,7 @@ class ResourceMapping:
769
897
  if binding is None:
770
898
  continue
771
899
  ((_, column),) = self._lookup(binding)
772
- if column is not None and column.readable:
900
+ if column is not None and not column.concealed:
773
901
  return column
774
902
  return None
775
903
 
@@ -860,12 +988,10 @@ class ResourceMapping:
860
988
  )
861
989
 
862
990
  columns = collection.columns.values()
863
- if not all(
864
- column.readable and not _write_only(column.binding) for column in columns
865
- ):
991
+ if any(column.concealed for column in columns):
866
992
  raise ValueError(
867
- f"Writing {path!r} replaces its entries, "
868
- "so they cannot hold write-only values"
993
+ f"Writing {path!r} replaces its entries, so they cannot hold "
994
+ "write-only values, nor values clients never read back"
869
995
  )
870
996
  if len({column.writable for column in columns}) > 1:
871
997
  raise ValueError(
@@ -900,14 +1026,34 @@ class ResourceMapping:
900
1026
  for link in links:
901
1027
  collection = self._collection(path, binding, link.relationship)
902
1028
  collection.resource_type = link.resource_type
1029
+ relationship = collection.relationship_property
1030
+ if (
1031
+ relationship.direction is MANYTOONE
1032
+ and collection.writable
1033
+ and not self._always_held(binding)
1034
+ and any(not column.nullable for column in relationship.local_columns)
1035
+ ):
1036
+ raise ValueError(
1037
+ f"{path!r} can be removed, so the foreign key of its "
1038
+ "relationship must accept NULL"
1039
+ )
1040
+ if (
1041
+ relationship.direction is ONETOMANY
1042
+ and collection.writable
1043
+ and any(not column.nullable for column in relationship.remote_side)
1044
+ ):
1045
+ raise ValueError(
1046
+ f"Removing a link of {path!r} writes NULL in the foreign key "
1047
+ "of the linked record, so it must accept NULL"
1048
+ )
903
1049
  if link.type is not None:
904
1050
  collection.link_type = link.type
905
1051
  collection.type_column = _Column(
906
1052
  type_binding, # type: ignore[arg-type]
907
1053
  literal(link.type),
908
1054
  "type",
909
- True,
910
1055
  False,
1056
+ concealed=_conceals(binding) or _conceals(type_binding), # type: ignore[arg-type]
911
1057
  )
912
1058
  collections.append(collection)
913
1059
  return collections
@@ -917,8 +1063,8 @@ class ResourceMapping:
917
1063
  ) -> _Column:
918
1064
  """Build the column of an attribute, and decide whether it is written.
919
1065
 
920
- A read-only attribute, or a hybrid property without a setter, is never
921
- written.
1066
+ A read-only attribute, a hybrid property without a setter, or a
1067
+ computed column, is never written.
922
1068
  """
923
1069
  if binding.sub_field_name is not None and binding.target_is_multivalued:
924
1070
  raise ValueError(
@@ -932,23 +1078,43 @@ class ResourceMapping:
932
1078
  raise ValueError(
933
1079
  f"{path!r} must be mapped to a column or a hybrid property"
934
1080
  )
935
- if attribute.readable and isinstance(getattr(expression, "type", None), Hashed):
936
- raise ValueError(
937
- f"{path!r} stores a hash, which the storage cannot read back: "
938
- "map it with readable=False"
939
- )
940
-
941
1081
  writable = attribute.writable
942
1082
  descriptor = inspect(expression.class_).all_orm_descriptors[key]
943
1083
  mutabilities = {
944
1084
  binding.model.get_field_annotation(binding.field_name, Mutability),
945
1085
  binding.get_annotation(Mutability),
946
1086
  }
947
- if Mutability.read_only in mutabilities or (
948
- isinstance(descriptor, hybrid_property) and descriptor.fset is None
1087
+ mapped = inspect(expression.class_).columns.get(key)
1088
+ if (
1089
+ Mutability.read_only in mutabilities
1090
+ or (isinstance(descriptor, hybrid_property) and descriptor.fset is None)
1091
+ or getattr(mapped, "computed", None) is not None
949
1092
  ):
950
1093
  writable = False
951
- column = _Column(binding, expression, key, attribute.readable, writable)
1094
+ concealed = _conceals(binding)
1095
+ if concealed and not writable:
1096
+ raise ValueError(
1097
+ f"{path!r} would be neither read nor written by clients: check "
1098
+ "its writable flag, the setter of its property, its column, and "
1099
+ "the mutability and the returned of its schema, or leave it out"
1100
+ )
1101
+ hashed = isinstance(getattr(expression, "type", None), Hashed)
1102
+ if hashed and not concealed:
1103
+ raise ValueError(
1104
+ f"{path!r} stores a hash, which clients would read: map it to an "
1105
+ "attribute that the schema makes writeOnly or never returns"
1106
+ )
1107
+ immutable = Mutability.immutable in mutabilities and (
1108
+ Mutability.write_only not in mutabilities
1109
+ )
1110
+ if hashed and immutable:
1111
+ raise ValueError(
1112
+ f"{path!r} is immutable, so a client sending its value again "
1113
+ "must match the stored one, which a hash never does"
1114
+ )
1115
+ column = _Column(
1116
+ binding, expression, key, writable, concealed=concealed, immutable=immutable
1117
+ )
952
1118
  python_type = _python_type(expression)
953
1119
  if (
954
1120
  column.is_string
@@ -235,7 +235,7 @@ class _FilterTranslator(FilterVisitor[ColumnElement[bool]]):
235
235
  ) -> list[tuple[_Collection | None, _Column]]:
236
236
  """Return the collections holding an attribute with its column in each, refusing an attribute that one of them does not let filters read."""
237
237
  pairs = self._lookup(binding)
238
- if any(column is None or not column.readable for _, column in pairs):
238
+ if any(column is None or column.concealed for _, column in pairs):
239
239
  raise _unmapped(binding)
240
240
  return pairs # type: ignore[return-value]
241
241
 
@@ -296,7 +296,7 @@ class _FilterTranslator(FilterVisitor[ColumnElement[bool]]):
296
296
  in_collection = pairs[0][0] is not None
297
297
  if in_collection and binding.sub_field_name is None and pairs[0][1] is None:
298
298
  return or_(*(collection.exists() for collection, _ in pairs)) # type: ignore[union-attr]
299
- if all(column is not None and column.readable for _, column in pairs):
299
+ if all(column is not None and not column.concealed for _, column in pairs):
300
300
  return or_(
301
301
  *(
302
302
  self._in_collection(collection, _present(column)) # type: ignore[arg-type]
@@ -305,7 +305,9 @@ class _FilterTranslator(FilterVisitor[ColumnElement[bool]]):
305
305
  )
306
306
 
307
307
  sub_columns = [
308
- column for column in self.mapping._sub_columns(binding) if column.readable
308
+ column
309
+ for column in self.mapping._sub_columns(binding)
310
+ if not column.concealed
309
311
  ]
310
312
  if in_collection or not sub_columns:
311
313
  raise _unmapped(binding)
@@ -430,7 +432,7 @@ def _sort_key(
430
432
  collection, column = mapping._lookup(binding)[0]
431
433
  if (
432
434
  column is None
433
- or not column.readable
435
+ or column.concealed
434
436
  or (collection is not None and not collection.owned)
435
437
  ):
436
438
  raise InvalidPathException(
@@ -11,6 +11,7 @@ from contextlib import contextmanager
11
11
  from typing import TYPE_CHECKING
12
12
  from typing import Any
13
13
 
14
+ from scim2_models import ConflictException
14
15
  from scim2_models import InvalidValueException
15
16
  from scim2_models import NotFoundException
16
17
  from scim2_models import Path
@@ -126,6 +127,17 @@ _UNIQUE_VIOLATIONS = {
126
127
  """The codes of a unique value already taken: the SQLSTATE of PostgreSQL, the
127
128
  name of the SQLite error, and the number of the MariaDB error."""
128
129
 
130
+ _FOREIGN_KEY_VIOLATIONS = {
131
+ "23503",
132
+ "SQLITE_CONSTRAINT_FOREIGNKEY",
133
+ 1216,
134
+ 1217,
135
+ 1451,
136
+ 1452,
137
+ }
138
+ """The codes of a foreign key the change breaks, such as a record still
139
+ referring to a deleted one, as _UNIQUE_VIOLATIONS gives them."""
140
+
129
141
  _CHANGED_MEANWHILE = 1020
130
142
  """The number of the MariaDB error on a record another transaction changed since it was read."""
131
143
 
@@ -153,7 +165,7 @@ def _error_code(error: BaseException | None) -> Any:
153
165
 
154
166
 
155
167
  def _translate(exception: DBAPIError) -> None:
156
- """Raise the SCIM error of a database error: 409 for a unique value taken, 412 for a record changed meanwhile.
168
+ """Raise the SCIM error of a database error: 409 for a unique value taken or a foreign key broken, 412 for a record changed meanwhile.
157
169
 
158
170
  MariaDB rolls back the whole transaction on a record changed meanwhile.
159
171
  Rolling back to the savepoint then fails, and its error holds the first
@@ -164,6 +176,10 @@ def _translate(exception: DBAPIError) -> None:
164
176
  code = _error_code(exception.__context__.orig)
165
177
  if code in _UNIQUE_VIOLATIONS:
166
178
  raise UniquenessException from exception
179
+ if code in _FOREIGN_KEY_VIOLATIONS:
180
+ raise ConflictException(
181
+ detail="Another record refers to this resource, or it refers to a missing one"
182
+ ) from exception
167
183
  if code == _CHANGED_MEANWHILE:
168
184
  raise PreconditionFailedException from exception
169
185
 
@@ -635,7 +651,9 @@ class SqlAlchemyStorage(_StorageBase, ScimStorage):
635
651
  A version changed in the meantime by another transaction raises a 412.
636
652
  A unique value taken in the meantime raises a 409, as does a value
637
653
  the unique constraint of the database refuses, such as a value that
638
- differs only by its accents under a collation ignoring them.
654
+ differs only by its accents under a collation ignoring them. A
655
+ foreign key the change breaks raises a 409 too, such as a record
656
+ outside SCIM still referring to a deleted resource.
639
657
  """
640
658
  session = self.session()
641
659
  try: