From 85ae13ef4c37e856dee2940c4aa3efd26a0c8aaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89loi=20Rivard?= Date: Fri, 27 Nov 2026 10:06:25 +0100 Subject: [PATCH] feat: build the storages on the mapping core of scim2-server The declaration, the checks, the filters, the sorts, the reading of the records and the checks of the writes now come from scim2_server.mapping, which scim2-django shares. Some error and warning messages change. The storages gain what scim2-django already had: Entry stores an entry in columns of the resource record, meta.created and meta.lastModified are optional, and without a version counter meta.version is a hash of the resource, keyed with the new version_key. --- doc/changelog.rst | 23 + doc/how-to/map-a-data-model.rst | 9 +- doc/reference/mapping.rst | 2 + pyproject.toml | 4 +- src/scim2_sqlalchemy/__init__.py | 2 + src/scim2_sqlalchemy/conversion.py | 262 +------ src/scim2_sqlalchemy/mapping.py | 1127 +++++++++------------------- src/scim2_sqlalchemy/query.py | 404 +++------- src/scim2_sqlalchemy/storage.py | 218 +++--- tests/conftest.py | 13 +- tests/plain.py | 114 +++ tests/test_contract.py | 36 + tests/test_many_values.py | 2 +- tests/test_mapping.py | 68 +- tests/test_parity.py | 134 ++++ tests/test_storage.py | 4 +- uv.lock | 10 +- 17 files changed, 981 insertions(+), 1451 deletions(-) create mode 100644 tests/plain.py create mode 100644 tests/test_parity.py diff --git a/doc/changelog.rst b/doc/changelog.rst index 6875b81..d29ab3f 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,29 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- :class:`~scim2_sqlalchemy.Entry` stores a multi-valued attribute holding one entry at most, such + as a work email, in columns of the resource record. +- ``meta.created`` and ``meta.lastModified`` are optional: without them, the resources have no such + date. +- The ``version`` of a :class:`~scim2_sqlalchemy.ResourceMapping` is optional. Without it, + ``meta.version`` is a hash of the resource, keyed with the new ``version_key`` of the storages. + +Changed +^^^^^^^ +- Needs scim2-server 0.9.0 or later. +- The storages are built on the mapping core of scim2-server, :mod:`scim2_server.mapping`, which + scim2-django shares. Some error and warning messages of the mappings change. +- :meth:`~scim2_sqlalchemy.ResourceMapping.schemas` publishes an attribute that is never returned + with the mutability of its schema, rather than ``writeOnly``. A hidden sub-attribute of an + immutable attribute keeps its own mutability. +- A :class:`~scim2_sqlalchemy.Link` refuses a relationship to another class than the record of + the mapping it links to. + [0.3.0] - 2026-11-26 -------------------- diff --git a/doc/how-to/map-a-data-model.rst b/doc/how-to/map-a-data-model.rst index be1bd8b..991a46a 100644 --- a/doc/how-to/map-a-data-model.rst +++ b/doc/how-to/map-a-data-model.rst @@ -14,13 +14,14 @@ Prepare the SQLAlchemy model Give each SQLAlchemy model the columns the storage needs: -- a primary key, mapped to ``id``; +- a primary key, mapped to ``id``. A :class:`~scim2_sqlalchemy.ResourceMapping` without it + raises a :class:`ValueError`; - a creation date and a modification date, mapped to ``meta.created`` and - ``meta.lastModified``; + ``meta.lastModified``. Without them, the resources have no such date; - an integer :ref:`version counter `, declared as the - ``version_id_col`` of the mapper, and passed as the ``version`` of the mapping. + ``version_id_col`` of the mapper, and passed as the ``version`` of the mapping. Without it, + ``meta.version`` is a hash of the resource, keyed with the ``version_key`` of the storage. -A :class:`~scim2_sqlalchemy.ResourceMapping` without one of them raises a :class:`ValueError`. The project model of the intranet has these columns: .. literalinclude:: ../_examples/intranet/projects.py diff --git a/doc/reference/mapping.rst b/doc/reference/mapping.rst index 57d3e1e..f6728a3 100644 --- a/doc/reference/mapping.rst +++ b/doc/reference/mapping.rst @@ -13,6 +13,8 @@ generating them from the resource types. .. autoclass:: scim2_sqlalchemy.Many +.. autoclass:: scim2_sqlalchemy.Entry + .. autoclass:: scim2_sqlalchemy.Link .. autofunction:: scim2_sqlalchemy.generate_mappings diff --git a/pyproject.toml b/pyproject.toml index 7026912..0ad021c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ authors = [ requires-python = ">=3.11" dependencies = [ "scim2-models>=0.12.7", - "scim2-server>=0.8.9", + "scim2-server>=0.9.0", "sqlalchemy>=2.0.41", ] @@ -54,7 +54,7 @@ dev = [ "pytest-cov>=7.1.0", "pytest-postgresql>=9.1.0", "scim2-client>=0.14.0", - "scim2-server[testing]>=0.8.9", + "scim2-server[testing]>=0.9.0", "scim2-tester[testing]>=0.6.2", "tox-uv>=1.36.0", "werkzeug>=3.1.8", diff --git a/src/scim2_sqlalchemy/__init__.py b/src/scim2_sqlalchemy/__init__.py index 7aeea3c..722ea81 100644 --- a/src/scim2_sqlalchemy/__init__.py +++ b/src/scim2_sqlalchemy/__init__.py @@ -1,5 +1,6 @@ from .generation import generate_mappings from .mapping import Attribute +from .mapping import Entry from .mapping import Hashed from .mapping import Link from .mapping import Many @@ -10,6 +11,7 @@ __all__ = [ "AsyncSqlAlchemyStorage", "Attribute", + "Entry", "Hashed", "Many", "Link", diff --git a/src/scim2_sqlalchemy/conversion.py b/src/scim2_sqlalchemy/conversion.py index a743b40..0a166d5 100644 --- a/src/scim2_sqlalchemy/conversion.py +++ b/src/scim2_sqlalchemy/conversion.py @@ -1,37 +1,15 @@ -import base64 import datetime from collections.abc import Iterable from collections.abc import Mapping from enum import Enum -from inspect import isclass from typing import Any -from pydantic import BaseModel -from scim2_models import AttributeBinding -from scim2_models import InvalidValueException -from scim2_models import Meta -from scim2_models import Mutability -from scim2_models import MutabilityException -from scim2_models import Path from scim2_models import Resource +from scim2_server.mapping import conversion as core +from scim2_server.mapping.descriptors import Collection from .mapping import ResourceMapping from .mapping import _Collection -from .mapping import _Column -from .mapping import _Storage - - -def _as_scim(value: Any) -> Any: - """Return a value read from the database in the form SCIM holds it. - - A date without a time zone is taken as UTC, since SQLite drops the zone. - Binary values are encoded in base64, the form the models decode them from. - """ - if isinstance(value, datetime.datetime) and value.tzinfo is None: - return value.replace(tzinfo=datetime.UTC) - if isinstance(value, bytes): - return base64.b64encode(value).decode() - return value def _as_stored(value: Any) -> Any: @@ -43,28 +21,14 @@ def _as_stored(value: Any) -> Any: return value -def _read(column: _Column, record: Any) -> Any: - """Return the SCIM value of a column of a record.""" - value = getattr(record, column.key) - if value is None: - return None - if isinstance(value, Enum) and column.enumeration is not None: - return column.stored_string(column.enumeration, value) - return _as_scim(value) - - -def _version(mapping: ResourceMapping, record: Any) -> str: - """Return the weak ETag of the version of a record.""" - return f'W/"{getattr(record, mapping._version.key)}"' - - def _to_scim( mapping: ResourceMapping, record: Any, resource_type: str, model: type[Resource[Any]], endpoints: Mapping[str, str], - collections: Iterable[_Collection], + collections: Iterable[Collection], + version_key: bytes | None, ) -> Resource[Any]: """Build the resource a record stores, as an instance of model. @@ -76,80 +40,16 @@ def _to_scim( by name: a link to one of them gets a $ref relative to the SCIM root, when model declares it, which the server makes absolute (RFC 7643 §2.3.7). """ - resource = model() - special = (mapping._id, mapping._created, mapping._last_modified) - for column in mapping._columns.values(): - if column in special: - continue - value = _read(column, record) - if value is not None: - Path[model](column.binding.urn).set(resource, value) # type: ignore[valid-type] - - read: dict[str, tuple[bool, list[dict[str, Any]]]] = {} - for collection in collections: - endpoint = None - if Path[model](f"{collection.binding.urn}.$ref").resolve() is not None: # type: ignore[valid-type] - endpoint = endpoints.get(collection.resource_type) # type: ignore[arg-type] - _, entries = read.setdefault(collection.binding.urn, (collection.single, [])) - for related in _related(collection, record): - entry = _read_entry(collection, related, endpoint) - if entry is not None: - entries.append(entry) - for urn, (single, entries) in read.items(): - if entries: - Path[model](urn).set(resource, entries[0] if single else entries) # type: ignore[valid-type] - - resource.id = str(_read(mapping._id, record)) - resource.meta = Meta( - resource_type=resource_type, - created=_read(mapping._created, record), - last_modified=_read(mapping._last_modified, record), - version=_version(mapping, record), + return core.to_scim( + mapping, record, resource_type, model, endpoints, collections, version_key ) - return model.model_validate(resource.model_dump()) - - -def _related(collection: _Collection, record: Any) -> list[Any]: - """Return the records a collection of a record holds, as a list even for a single one.""" - related = getattr(record, collection.relationship.key) - if collection.single: - return [] if related is None else [related] - return list(related) - - -def _entries(collection: _Collection, resource: Resource[Any]) -> list[Any]: - """Return the entries a resource holds for a collection, as a list even for a single one.""" - value = Path(collection.binding.urn).get(resource, strict=False) - if collection.single: - return [] if value is None else [value] - return list(value or []) - - -def _read_entry(collection: _Collection, entry: Any, endpoint: str | None) -> Any: - """Return the values of an entry, by sub-attribute name, or the value of an entry of a simple collection. - - A link gets a $ref when the endpoint of the resources it links to is known. - """ - if collection.simple: - return _read(collection.columns[None], entry) - values = {} - for sub_field_name, column in collection.columns.items(): - value = _read(column, entry) - if value is not None and sub_field_name == "value" and not collection.owned: - value = str(value) - if endpoint is not None: - values["$ref"] = f"{endpoint}/{value}" - values[column.binding.urn.rsplit(".", 1)[-1]] = value - if collection.link_type is not None: - values["type"] = collection.link_type - return values def _from_scim( mapping: ResourceMapping, resource: Resource[Any], record: Any, - links: dict[_Collection, list[Any]], + links: dict[Collection, list[Any]], creating: bool, ) -> None: """Write a resource into a record. @@ -160,30 +60,22 @@ def _from_scim( that the column keeps its default. links holds the records each Link of the resource links to. """ - for column in mapping._columns.values(): - if not column.writable: - continue - value = Path(column.binding.urn).get(resource, strict=False) - if value is None and creating: - continue - stored = None if value is None else _as_stored(value) - if not creating and stored == getattr(record, column.key): - continue - setattr(record, column.key, stored) + for column, value in core.write_plan(mapping, resource, record, creating): + setattr(record, column.key, None if value is None else _as_stored(value)) for collection in mapping._all_collections(): if not collection.writable: continue if collection.owned: value = [ - _write_entry(collection, entry) - for entry in _entries(collection, resource) + _write_entry(collection, entry) # type: ignore[arg-type] + for entry in core.entries(collection, resource) ] elif collection.single: value = next(iter(links[collection]), None) else: value = links[collection] - setattr(record, collection.relationship.key, value) + setattr(record, collection.relation.key, value) def _write_entry(collection: _Collection, entry: Any) -> Any: @@ -197,133 +89,3 @@ def _write_entry(collection: _Collection, entry: Any) -> Any: if value is not None: setattr(record, column.key, _as_stored(value)) return record - - -def _link_entries( - mapping: ResourceMapping, resource: Resource[Any] -) -> list[tuple[list[_Collection], list[Any]]]: - """Return the entries of each written attribute of a resource linking to other resources, with the collections of its Links. - - A link is stored by its value, so an entry without one, such as an entry - with a $ref only, raises InvalidValueException rather than being lost. - """ - links = [] - for collections in mapping._collections.values(): - collection = collections[0] - if collection.owned or not collection.writable: - continue - entries = _entries(collection, resource) - if any(entry.value is None for entry in entries): - raise InvalidValueException( - detail=f"'{collection.binding.urn}' holds an entry without value" - ) - links.append((collections, entries)) - return links - - -def _check_storable( - mapping: ResourceMapping, - resource: Resource[Any], - stored: Resource[Any] | None, -) -> None: - """Refuse a change of a resource that the mapping cannot store. - - Each attribute of the resource is compared with the stored resource, None - for a new one. A value equal to the stored one changes nothing, so a - resource read and sent back is accepted. A missing value changes nothing - either, except for a stored value whose column cannot hold none: removing it - raises MutabilityException. A new resource needs a value for each column - that cannot hold none and has no default. The read-only attributes of the - model of the resource are skipped, as RFC 7644 §3.5.1 has them ignored, and - so are the derived ones. - """ - _check_entries(mapping, resource) - model = type(resource) - for path in Path[model].iter_paths(): # type: ignore[valid-type] - binding = path.resolve() - if binding is None: - continue - target = binding.target_type - if isclass(target) and issubclass(target, BaseModel): - continue - if Mutability.read_only in ( - binding.model.get_field_annotation(binding.field_name, Mutability), - binding.get_annotation(Mutability), - ): - continue - storage = mapping._storage(binding.urn) - value = _comparable(path.get(resource, strict=False)) - current = None - if stored is not None: - current = _comparable(Path(binding.urn).get(stored, strict=False)) - if storage == _Storage.written: - _check_enumerated(mapping, binding, value) - if value is None and stored is None and mapping._required(binding.urn): - raise InvalidValueException( - detail=f"'{binding.urn}' is required on this server" - ) - if ( - value is None - and current is not None - and not mapping._nullable(binding.urn) - ): - raise MutabilityException( - attribute=binding.urn, - detail=f"'{binding.urn}' cannot be removed on this server", - ) - continue - if storage in (_Storage.derived, _Storage.ref, _Storage.link_type) or value in ( - None, - current, - ): - continue - if storage == _Storage.read_only: - raise MutabilityException( - attribute=binding.urn, - mutability="readOnly", - detail=f"'{binding.urn}' is read-only on this server", - ) - raise InvalidValueException( - detail=f"'{binding.urn}' is not stored by this server" - ) - - -def _check_entries(mapping: ResourceMapping, resource: Resource[Any]) -> None: - """Refuse an entry without a value that its column needs, rather than failing in the database.""" - for collection in mapping._all_collections(): - if not collection.owned or collection.simple or not collection.writable: - continue - required = [column for column in collection.columns.values() if column.required] - for entry in _entries(collection, resource): - for column in required: - if getattr(entry, column.binding.target_field_name, None) is None: - raise InvalidValueException( - detail=f"'{column.binding.urn}' is required on this server" - ) - - -def _check_enumerated( - mapping: ResourceMapping, binding: AttributeBinding, value: Any -) -> None: - """Refuse a string that an Enum column does not store, rather than failing in the database.""" - _, column = mapping._lookup(binding)[0] - if column is None or column.enumeration is None: - return - stored = column.enumeration.enums - for item in value if isinstance(value, list) else [value]: - if item is not None and item not in stored: - raise InvalidValueException( - detail=f"'{binding.urn}' cannot hold {item!r} on this server" - ) - - -def _comparable(value: Any) -> Any: - """Return a value in a form two resources compare in. - - A list of missing values, as a path through the entries of a multi-valued - attribute gives, is no value. - """ - if isinstance(value, list): - values = [_as_stored(item) for item in value] - return None if all(item is None for item in values) else values - return _as_stored(value) diff --git a/src/scim2_sqlalchemy/mapping.py b/src/scim2_sqlalchemy/mapping.py index 1a4127f..1865a03 100644 --- a/src/scim2_sqlalchemy/mapping.py +++ b/src/scim2_sqlalchemy/mapping.py @@ -1,25 +1,23 @@ +import base64 +import datetime import warnings from collections.abc import Callable from collections.abc import Iterable -from collections.abc import Iterator from collections.abc import Mapping from dataclasses import dataclass -from dataclasses import field from enum import Enum -from inspect import isclass from typing import Any -from pydantic import BaseModel -from scim2_models import Attribute as SchemaAttribute from scim2_models import AttributeBinding from scim2_models import Mutability -from scim2_models import Path -from scim2_models import Required from scim2_models import Resource -from scim2_models import ResponseParameters -from scim2_models import Returned from scim2_models import Schema -from scim2_models import Uniqueness +from scim2_server import mapping as core +from scim2_server.mapping import MappingProblem +from scim2_server.mapping.declaration import key +from scim2_server.mapping.declaration import mutabilities +from scim2_server.mapping.declaration import never_returned +from scim2_server.mapping.mapping import Problems from sqlalchemy import Column from sqlalchemy import ColumnElement from sqlalchemy import Dialect @@ -29,7 +27,6 @@ from sqlalchemy import cast from sqlalchemy import func from sqlalchemy import inspect -from sqlalchemy import literal from sqlalchemy.dialects import mysql from sqlalchemy.ext.compiler import compiles from sqlalchemy.ext.hybrid import hybrid_property @@ -61,23 +58,6 @@ """The start and the length of each group of digits of a UUID, without its hyphens.""" -class _Storage(Enum): - """How a mapping stores an attribute. - - A derived attribute is read from another resource, such as the display of - a member, so writing it changes nothing. A ref is the $ref of a link, - built from its value: clients may send it, and writing it changes nothing - either. A link type is the type a Link gives its entries: clients may send - it, and the storage checks it against the linked resource. - """ - - written = "written" - read_only = "read only" - derived = "derived" - ref = "ref" - link_type = "link type" - - class _UuidText(FunctionElement[str]): """The text of a UUID column, in the form with hyphens that SCIM holds.""" @@ -132,18 +112,6 @@ def _needs_value(column: Column[Any]) -> bool: ) -def _conceals(binding: AttributeBinding) -> bool: - """Whether clients never read an attribute back: its schema, or the one of the attribute holding it, makes it writeOnly or never returns it.""" - model, field_name = binding.model, binding.field_name - return Mutability.write_only in ( - model.get_field_annotation(field_name, Mutability), - binding.get_annotation(Mutability), - ) or Returned.never in ( - model.get_field_annotation(field_name, Returned), - binding.get_annotation(Returned), - ) - - def _python_type(expression: Any) -> type | None: """Return the Python type of the values of an expression, or None if its type tells none. @@ -161,35 +129,49 @@ def _holds_text(expression: Any) -> bool: return _python_type(expression) in (str, None) -def _key(binding: AttributeBinding) -> tuple[type[BaseModel], str, str | None]: - """Return what identifies an attribute, whatever the case or the form of its path.""" - return (binding.model, binding.field_name, binding.sub_field_name) +def _as_scim(value: Any) -> Any: + """Return a value read from the database in the form SCIM holds it. + A date without a time zone is taken as UTC, since SQLite drops the zone. + Binary values are encoded in base64, the form the models decode them from. + """ + if isinstance(value, datetime.datetime) and value.tzinfo is None: + return value.replace(tzinfo=datetime.UTC) + if isinstance(value, bytes): + return base64.b64encode(value).decode() + return value + + +def _as_key(column: "_Column", value: Any) -> Any: + """Return an identifier in the type of its column, or None when it cannot have that type.""" + python_type = _python_type(column.expression) + if python_type is None: + return value + try: + key = python_type(value) + except (TypeError, ValueError): + return None + if isinstance(key, int) and key not in _INTEGERS: + return None + return key -def _overlap( - key: tuple[type[BaseModel], str, str | None], - other: tuple[type[BaseModel], str, str | None], -) -> bool: - """Tell whether two attributes are the same, or one holds the other.""" - return key == other or (key[:2] == other[:2] and None in (key[2], other[2])) +def _writes(descriptor: Any, mapped: Any) -> bool: + """Tell whether the storage can write a value: a hybrid property needs a setter, and a computed column is never written.""" + if isinstance(descriptor, hybrid_property) and descriptor.fset is None: + return False + return getattr(mapped, "computed", None) is None -class Attribute: - """A column holding a SCIM attribute, whose writing can be turned off. - To store a value in another form, map the attribute to a - :class:`~sqlalchemy.ext.hybrid.hybrid_property` that converts it, in Python - and in SQL. +def _column_name(column: Column[Any]) -> str: + """Return the name of a column of a table, as the warnings give it.""" + return f"{column.table.name}.{column.name}" - :param expression: The column, or the - :class:`~sqlalchemy.ext.hybrid.hybrid_property`, holding the value. - :param writable: Whether the storage writes the attribute. When - :data:`False`, the attribute is read-only. - """ - def __init__(self, expression: Any, *, writable: bool = True) -> None: - self.expression = expression - self.writable = writable +def _sql_writable(binding: AttributeBinding) -> bool: + """Tell whether the schema lets clients write an attribute.""" + mutability = binding.model.get_field_annotation(binding.field_name, Mutability) + return bool(mutability != Mutability.read_only) class Hashed(TypeDecorator[str]): @@ -226,7 +208,29 @@ def process_bind_param(self, value: str | None, dialect: Dialect) -> str | None: return None if value is None else self.hash_value(value) -class Many: +class Attribute(core.Attribute): + """A column holding a SCIM attribute, whose writing can be turned off. + + To store a value in another form, map the attribute to a + :class:`~sqlalchemy.ext.hybrid.hybrid_property` that converts it, in Python + and in SQL. + + :param expression: The column, or the + :class:`~sqlalchemy.ext.hybrid.hybrid_property`, holding the value. + :param writable: Whether the storage writes the attribute. When + :data:`False`, the attribute is read-only. + """ + + def __init__(self, expression: Any, *, writable: bool = True) -> None: + super().__init__(expression, writable=writable) + + @property + def expression(self) -> Any: + """The column, or the hybrid property, holding the value.""" + return self.target + + +class Many(core.Many): """The entries of a multi-valued attribute, stored in a child table. The entries belong to the resource: writing the resource replaces them. @@ -251,11 +255,35 @@ class Many: """ def __init__(self, relationship: Any, attributes: Mapping[str, Any] | Any) -> None: - self.relationship = relationship - self.attributes = attributes + super().__init__(relationship, attributes) + + @property + def relationship(self) -> Any: + """The relationship from the resource record to the entry records.""" + return self.relation + + +class Entry(core.Entry): + """A multi-valued complex attribute holding one entry at most, stored in columns of the resource record. + + Such as the email address of a user, in its ``email`` column. The + resource holds an entry when one of the columns has a value, so the + columns accept ``NULL``: a write removing the entry empties them. A write + with several entries is refused. + + :param attributes: The columns of the resource record holding the + sub-attributes, by sub-attribute name, such as + ``{"value": UserRecord.email}``. A value may be an :class:`Attribute`. + :param type: The ``type`` sub-attribute of the entry, such as + ``"work"``. A client may send it, and a write with another type is + refused. Without it, the storage does not store ``type``. + :param primary: The ``primary`` sub-attribute of the entry. A client may + send any value, as the lone entry is the primary one, and reads this + one back. Without it, the storage does not store ``primary``. + """ -class Link: +class Link(core.Link): """A complex attribute linking to other resources. A multi-valued attribute, such as the ``members`` of a group, maps to a @@ -291,56 +319,22 @@ class Link: def __init__( self, relationship: Any, resource_type: str, *, type: str | None = None ) -> None: - self.relationship = relationship - self.resource_type = resource_type - self.type = type - - -@dataclass(eq=False) -class _Column: - """A SCIM attribute stored in a column or a hybrid property. - - textual tells whether filters compare the column as text, as they do for - an integer identifier. concealed tells whether clients never read the - value back, and immutable whether the schema keeps it from changing. - """ - - binding: AttributeBinding - expression: ColumnElement[Any] - key: str - writable: bool - textual: bool = False - concealed: bool = False - immutable: bool = False + super().__init__(relationship, resource_type, type=type) @property - def is_string(self) -> bool: - """Whether the attribute is a SCIM string.""" - target = self.binding.target_type - return ( - target is not None - and SchemaAttribute.Type.from_python(target) == SchemaAttribute.Type.string - ) + def relationship(self) -> Any: + """The relationship from the resource record to the records of the linked resources.""" + return self.relation - @property - def casefolded(self) -> bool: - """Whether the values compare without their case.""" - return self.is_string and not self.binding.case_exact - @property - def nullable(self) -> bool: - """Whether the column can hold no value. A hybrid or a column property is taken as nullable.""" - column = _table_column(self.expression) - return column is None or bool(column.nullable) +@dataclass(eq=False) +class _Column(core.Column): + """A SCIM attribute stored in a column or a hybrid property.""" - @property - def required(self) -> bool: - """Whether a new record needs a value: the column holds no null, has no default, and the database does not number it.""" - column = _table_column(self.expression) - return column is not None and _needs_value(column) + expression: ColumnElement[Any] = None # type: ignore[assignment] @property - def enumeration(self) -> SqlEnum | None: + def enum_type(self) -> SqlEnum | None: """The type of the column when it is an Enum, which stores strings.""" sql_type = self.expression.type return sql_type if isinstance(sql_type, SqlEnum) else None @@ -355,7 +349,7 @@ def compared(self) -> ColumnElement[Any]: """ if ( self.textual - or self.enumeration is not None + or self.enum_type is not None or _uuid_type(self.expression.type) is not None ): return self.text @@ -378,94 +372,61 @@ def stored_string(enumeration: SqlEnum, member: Enum) -> str: @dataclass(eq=False) -class _Collection: +class _Collection(core.Collection): """A multi-valued attribute, or a complex one, stored in related records. - The entries of an owned collection belong to the resource. The others are - links to the resources of another mapping, the target. A single collection - holds one entry at most, such as the manager of a user. A simple - collection holds the values of a multi-valued simple attribute, in the - column it keeps under None. - - link_type is the type a Link gives its entries, and type_column the - constant filters compare it as. + relation is the relationship from the resource record to the entries. """ - binding: AttributeBinding - relationship: InstrumentedAttribute[Any] - columns: dict[str | None, _Column] = field(default_factory=dict) - resource_type: str | None = None - target: "ResourceMapping | None" = None - link_type: str | None = None - type_column: _Column | None = None + @property + def relationship(self) -> InstrumentedAttribute[Any]: + """The relationship holding the entries.""" + relationship: InstrumentedAttribute[Any] = self.relation + return relationship @property - def owned(self) -> bool: - """Whether the entries belong to the resource, rather than link to other resources.""" - return self.resource_type is None + def relationship_property(self) -> RelationshipProperty[Any]: + """The property of the relationship holding the entries.""" + relationship: RelationshipProperty[Any] = self.relationship.property + return relationship @property def entry_class(self) -> type[Any]: """The SQLAlchemy model of the entries.""" return self.relationship_property.mapper.class_ - @property - def relationship_property(self) -> RelationshipProperty[Any]: - """The relationship holding the entries.""" - return self.relationship.property # type: ignore[return-value] - - @property - def single(self) -> bool: - """Whether the collection holds one entry at most.""" - return not self.binding.is_multivalued - - @property - def simple(self) -> bool: - """Whether the collection holds the values of a multi-valued simple attribute.""" - return None in self.columns - - def column(self, sub_field_name: str | None) -> _Column | None: - """Return the column of a sub-attribute, or of the values of a simple collection named alone. - - A complex collection named alone has no column. - """ - if sub_field_name == "type" and self.type_column is not None: - return self.type_column - return self.columns.get(sub_field_name) - def exists(self, condition: Any = None) -> ColumnElement[bool]: """Return the condition that an entry exists, and matches condition when given.""" method = self.relationship.has if self.single else self.relationship.any - return method() if condition is None else method(condition) - - @property - def writable(self) -> bool: - """Whether writing the resource writes these entries.""" - if self.owned and not any(column.writable for column in self.columns.values()): - return False - mutability = self.binding.model.get_field_annotation( - self.binding.field_name, Mutability + exists: ColumnElement[bool] = ( + method() if condition is None else method(condition) ) - return bool(mutability != Mutability.read_only) + return exists -class ResourceMapping: +class ResourceMapping(core.ResourceMapping): """How the resources of a SCIM model are stored in the records of a SQLAlchemy model. - The paths are checked against the SCIM model when the mapping is created, - so a mistake raises at import time rather than at the first request. + The paths and the columns are checked when the mapping is created, so a + mistake raises at import time rather than at the first request. :param model: The SCIM model of the resources, such as ``User[EnterpriseUser]``. :param record: The SQLAlchemy model of the records. :param attributes: The attributes, by SCIM path. A value is a column, a - :class:`~sqlalchemy.ext.hybrid.hybrid_property`, an :class:`Attribute`, a :class:`Many`, a - :class:`Link`, or a list of :class:`Link`. ``id``, ``meta.created`` and ``meta.lastModified`` - are required. + :class:`~sqlalchemy.ext.hybrid.hybrid_property`, an + :class:`Attribute`, a :class:`Many`, an :class:`Entry`, a + :class:`Link`, or a list of :class:`Link`. ``id`` is required. + ``meta.created`` and ``meta.lastModified`` are filled by the storage: + without them, the resources have no such date. :param version: The ``version_id_col`` of the mapper of ``record``, which gives ``meta.version`` (:ref:`sqlalchemy:mapper_version_counter`). It only changes when the record changes, not when a linked record - does: adding a member to a group leaves the version of the user as it is. + does: adding a member to a group leaves the version of the user as it + is. Without it, ``meta.version`` is a hash of the whole resource, + which the storage computes with its ``version_key``. The storage then + reads every collection of a resource, even those a response leaves + out, such as the members of a group. :raises ValueError: When a path is not valid for the model, when a value does not fit the attribute of its path, or when ``id`` is mapped to a column that can hold ``NULL``. Also when clients could neither @@ -477,7 +438,10 @@ class ResourceMapping: never writes. """ - _REQUIRED = ("id", "meta.created", "meta.lastModified") + version: Any + _id: _Column + _created: _Column | None + _last_modified: _Column | None def __init__( self, @@ -485,647 +449,278 @@ def __init__( record: type[Any], attributes: Mapping[str, Any], *, - version: Any, + version: Any = None, ) -> None: - self.model = model - self.record = record - self._columns: dict[tuple[type[BaseModel], str, str | None], _Column] = {} - self._collections: dict[tuple[type[BaseModel], str], list[_Collection]] = {} - - declared: dict[tuple[type[BaseModel], str, str | None], str] = {} - for path, value in attributes.items(): - binding = self._resolve(path) - key = _key(binding) - for other, other_path in declared.items(): - if _overlap(key, other): - raise ValueError( - f"{other_path!r} and {path!r} map the same attribute" - ) - declared[key] = path - self._add(path, binding, value) - for required in self._REQUIRED: - if _key(self._resolve(required)) not in declared: - raise ValueError(f"The mapping of {model.__name__} needs {required!r}") - - mapper: Mapper[Any] = inspect(record) - columns = getattr(getattr(version, "property", None), "columns", [None]) - if mapper.version_id_col is None or mapper.version_id_col is not columns[0]: - raise ValueError( - f"The version of {model.__name__} must be the version_id_col " - f"of the mapper of {record.__name__}" - ) - self._version: InstrumentedAttribute[Any] = version - self._id = self._column("id") - column = _table_column(self._id.expression) - if column is not None and column.nullable: - raise ValueError( - "'id' is mapped to a column that can hold no value, " - "but each resource needs one" - ) - self._id.textual = not _holds_text(self._id.expression) - self._created = self._column("meta.created") - self._last_modified = self._column("meta.lastModified") - self._warn_unwritten() - - def _always_held(self, binding: AttributeBinding) -> bool: - """Tell whether the schema makes every resource hold an attribute, and the extension holding it.""" - if Required.true not in ( - binding.model.get_field_annotation(binding.field_name, Required), - binding.get_annotation(Required), - ): - return False - if binding.model not in self.model.get_extension_models().values(): - return True - required = self.model.get_field_annotation(binding.model.__name__, Required) - return bool(required == Required.true) - - def _warn_unwritten(self) -> None: - """Warn about the columns of the record that need a value the storage never writes.""" - written: list[Any] = [ - _table_column(mapped.expression) - for mapped in self._columns.values() - if mapped.writable or mapped in (self._created, self._last_modified) - ] - mapper: Mapper[Any] = inspect(self.record) - # The setter of a property may write any column its expression reads. - for mapped in self._columns.values(): - descriptor = mapper.all_orm_descriptors.get(mapped.key) - # The storage sets the dates itself, read-only as they are. - dated = mapped in (self._created, self._last_modified) - if (mapped.writable or dated) and isinstance(descriptor, hybrid_property): - written += [ - element.table.columns.get(element.key) - for element in iterate(mapped.expression.__clause_element__()) - if isinstance(element, Column) - ] - for collection in self._all_collections(): - if collection.single and not collection.owned and collection.writable: - written += collection.relationship_property.local_columns - # SQLAlchemy fills the version, the discriminator of the classes, and - # the key each joined table shares with the table it inherits from. - written += [mapper.version_id_col, mapper.polymorphic_on] - for ancestor in mapper.iterate_to_root(): - if ancestor.inherits is not None: - written += [ - column - for column in ancestor.local_table.primary_key - if column.foreign_keys - ] - for column in mapper.columns: - if ( - not isinstance(column, Column) - or not _needs_value(column) - or any(column is other for other in written) - ): - continue - warnings.warn( - f"The column {column.table.name}.{column.name} needs a value, " - f"but the mapping of {self.model.__name__} never writes it: " - "map it, or give it a default", - stacklevel=3, - ) + super().__init__(model, record, attributes, version=version) + problems = self._resolve() + errors = [problem.message for problem in problems if problem.level == "error"] + if errors: + raise ValueError("\n".join(errors)) + for problem in problems: + warnings.warn(problem.message, stacklevel=2) def schemas(self) -> list[Schema]: """Return the schemas of the resources, restricted to what the mapping stores. They hold the mapped attributes only. An attribute the mapping reads - but never writes is ``readOnly``, and an attribute it writes but never - reads is ``writeOnly``. An attribute whose column cannot be ``NULL`` - and has no default is ``required``, unless it is write-only. A column - with a default that cannot be ``NULL`` leaves its attribute optional, - but its value cannot be removed. Publish them, rather than the - schemas of :attr:`model`, so that clients know what the server stores: - build the provider of the server with + but never writes is ``readOnly``. An attribute whose column cannot be + ``NULL`` and has no default is ``required``, unless clients never read + it back. A column with a default that cannot be ``NULL`` leaves its + attribute optional, but its value cannot be removed. Publish them, + rather than the schemas of :attr:`model`, so that clients know what + the server stores: build the provider of the server with :meth:`ScimProvider.from_discovery `, and pass it to the storage. :returns: The schema of the resource, then the schemas of its extensions. """ - models: list[Any] = [self.model, *self.model.get_extension_models().values()] - return [self._restrict(model.to_schema()) for model in models] - - def _restrict(self, schema: Schema) -> Schema: - """Return a schema with the attributes the mapping stores only.""" - attributes = [] - for attribute in schema.attributes or []: - restricted = self._restrict_attribute( - f"{schema.id}:{attribute.name}", attribute - ) - if restricted is not None: - attributes.append(restricted) - return schema.model_copy(update={"attributes": attributes}) - - def _restrict_attribute(self, urn: str, attribute: Any) -> Any: - """Return an attribute of a schema as the mapping stores it, or None when it stores nothing of it.""" - if attribute.sub_attributes: - sub_attributes = [ - restricted - for sub_attribute in attribute.sub_attributes - if ( - restricted := self._restrict_attribute( - f"{urn}.{sub_attribute.name}", sub_attribute - ) - ) - is not None - ] - if not sub_attributes: - return None - written = any( - sub_attribute.mutability != Mutability.read_only - for sub_attribute in sub_attributes - ) - required = attribute.required - if any( - self._always_needs(f"{urn}.{sub_attribute.name}", entries=False) - for sub_attribute in sub_attributes - ): - required = Required.true - mutability = attribute.mutability if written else Mutability.read_only - returned = attribute.returned - if all(sub.returned == Returned.never for sub in sub_attributes): - returned = Returned.never - required = Required.false - if mutability == Mutability.read_write: - mutability = Mutability.write_only - return attribute.model_copy( - update={ - "sub_attributes": sub_attributes, - "mutability": mutability, - "required": required, - "returned": returned, - } - ) - - storage = self._storage(urn) - if storage is None: - return None - columns = self._columns_of(urn, entries=True) - if storage == _Storage.written and any(c.concealed for c in columns): - mutability = Mutability.write_only - if any(c.immutable for c in columns): - mutability = Mutability.immutable - return attribute.model_copy( - update={ - "mutability": mutability, - "returned": Returned.never, - "required": Required.false, - } - ) - if self._always_needs(urn): - return attribute.model_copy(update={"required": Required.true}) - if storage in (_Storage.written, _Storage.link_type): - return attribute - if storage == _Storage.ref: - linked = self._linked_resource_types(urn) - return attribute.model_copy(update={"reference_types": linked}) - return attribute.model_copy(update={"mutability": Mutability.read_only}) - - def _storage(self, urn: str) -> _Storage | None: - """Return how the mapping stores the attribute of a URN, or None when it does not store it.""" - key = urn.lower() - for column in self._columns.values(): - if column.binding.urn.lower() == key: - return _Storage.written if column.writable else _Storage.read_only - for collection in self._all_collections(): - if not collection.owned: - head = collection.binding.urn.lower() - if key == f"{head}.value": - return _Storage.written - if key in (f"{head}.display", f"{head}.displayname"): - return _Storage.derived - if key == f"{head}.$ref": - return _Storage.ref - if key == f"{head}.type" and collection.link_type is not None: - return _Storage.link_type - continue - for column in collection.columns.values(): - if column.binding.urn.lower() == key: - return _Storage.written if column.writable else _Storage.read_only - return None - - def _columns_of(self, urn: str, *, entries: bool) -> list[_Column]: - """Return the columns of an attribute, with the columns of the entries when entries is True.""" - key = urn.lower() - columns = list(self._columns.values()) - if entries: - columns += [ - column - for collection in self._all_collections() - if collection.owned and not collection.simple - for column in collection.columns.values() - ] - return [column for column in columns if column.binding.urn.lower() == key] - - def _nullable(self, urn: str) -> bool: - """Tell whether the column of an attribute can hold no value, True for an attribute without column.""" - return all(c.nullable for c in self._columns_of(urn, entries=False)) - - def _required(self, urn: str) -> bool: - """Tell whether a new record needs a value for the column of an attribute.""" - return any(c.required for c in self._columns_of(urn, entries=False)) - - def _always_needs(self, urn: str, *, entries: bool = True) -> bool: - """Tell whether a resource, or an entry when entries is True, always needs a value for an attribute. - - This holds for a column that needs a value, that the storage writes, and - that clients read back. A concealed value is kept when a replacement - leaves it out, so a replacement does not need it. - """ - return any( - column.required and column.writable and not column.concealed - for column in self._columns_of(urn, entries=entries) - ) - - def _linked_resource_types(self, urn: str) -> list[str]: - """Return the resource types the Links of an attribute link to, from the URN of its $ref.""" - head = urn.lower().removesuffix(".$ref") - return [ - collection.resource_type - for collection in self._all_collections() - if collection.binding.urn.lower() == head - and collection.resource_type is not None - ] - - def _all_collections(self) -> Iterator[_Collection]: - """Yield the collections of every attribute, each Link of an attribute being a collection.""" - for collections in self._collections.values(): - yield from collections - - def _column(self, path: str) -> _Column: - """Return the column of the attribute at a path.""" - return self._columns[_key(self._resolve(path))] - - def _lookup( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column | None]]: - """Return each collection holding an attribute, if any, with the column of the attribute in it. - - An attribute outside collections gives one pair, without collection. - An attribute linking to several resource types gives a pair for each - of its Links. The column is None for an attribute stored nowhere, and - for a collection named alone, such as emails. - """ - collections = self._collections.get((binding.model, binding.field_name)) - if collections is None: - return [(None, self._columns.get(_key(binding)))] - return [ - (collection, collection.column(binding.sub_field_name)) - for collection in collections - ] - - def _sub_columns(self, binding: AttributeBinding) -> list[_Column]: - """Return the mapped sub-attributes of a complex attribute holding a single value.""" - return [ - column - for (model, field_name, sub_field_name), column in self._columns.items() - if model is binding.model - and field_name == binding.field_name - and sub_field_name is not None - ] - - def _string_columns(self) -> Iterator[_Column]: - """Yield the columns holding strings, those of the collections included.""" - for column in self._columns.values(): - if column.is_string: - yield column - for collection in self._all_collections(): - for column in collection.columns.values(): - if column.is_string: - yield column - if collection.type_column is not None: - yield collection.type_column - - def _unique_columns(self) -> Iterator[_Column]: - """Yield the columns whose values no two resources share, except those clients never read back.""" - for column in self._columns.values(): - if not column.concealed and column.binding.get_annotation(Uniqueness) in ( - Uniqueness.server, - Uniqueness.global_, - ): - yield column - - def _returned_collections( - self, parameters: ResponseParameters[Any] | None = None - ) -> list[_Collection]: - """Return the collections a response keeps, all of them without parameters.""" - collections = list(self._all_collections()) - if parameters is None: - return collections - paths = Path[self.model].iter_paths( # type: ignore[name-defined] - include_subattributes=False, - attributes=parameters.attributes, - excluded_attributes=parameters.excluded_attributes, - ) - bindings = (path.resolve() for path in paths) - kept = {binding.urn for binding in bindings if binding is not None} - return [ - collection for collection in collections if collection.binding.urn in kept - ] + return super().schemas() def _loader_options( - self, collections: Iterable[_Collection] + self, collections: Iterable[core.Collection] ) -> list[strategy_options._AbstractLoad]: """Return the options loading collections along with the records. Loading them up front is what lets an asynchronous session read them. """ return [ - strategy_options.selectinload(collection.relationship) + strategy_options.selectinload(collection.relation) for collection in collections ] - def _targets( - self, mappings: Mapping[str, "ResourceMapping"] - ) -> list[tuple[_Collection, "ResourceMapping"]]: - """Return each Link with the mapping of the resources it links to. + def _is_target(self, value: Any) -> bool: + return isinstance(getattr(value, "key", None), str) and hasattr(value, "class_") - Several storages may share a mapping, as long as they link it to the - same mappings. - """ - return [ - (collection, self._target(collection, mappings)) - for collection in self._all_collections() - if not collection.owned - ] + def _value_writable(self, value: Any) -> bool: + expression = value.target if isinstance(value, core.Attribute) else value + mapper: Mapper[Any] = inspect(expression.class_) + descriptor = mapper.all_orm_descriptors[expression.key] + mapped = mapper.columns.get(expression.key) + return super()._value_writable(value) and _writes(descriptor, mapped) - def _bind(self, links: list[tuple[_Collection, "ResourceMapping"]]) -> None: - """Bind each Link to the mapping :meth:`_targets` returned for it.""" - for collection, target in links: - collection.target = target - collection.columns = {} - head = collection.binding.urn - concealed = _conceals(collection.binding) - for binding, column in ( - (self._resolve(f"{head}.value"), target._id), - ( - self._find(f"{head}.display") or self._find(f"{head}.displayName"), - target._display(), - ), - ): - if binding is None or column is None: - continue - collection.columns[binding.sub_field_name] = _Column( - binding, - column.expression, - column.key, - False, - column.textual, - concealed=concealed or _conceals(binding), - ) - - def _target( - self, collection: _Collection, mappings: Mapping[str, "ResourceMapping"] - ) -> "ResourceMapping": - """Return the mapping a Link links to, refusing one that does not fit it.""" - target = mappings.get(collection.resource_type) # type: ignore[arg-type] - if target is None: + def _check_declared( + self, + path: str, + binding: AttributeBinding, + value: Any, + holder: core.Many | core.Entry | None, + ) -> None: + """Refuse a Hashed column that clients would read, or that would be immutable.""" + expression = value.target if isinstance(value, core.Attribute) else value + if not isinstance(getattr(expression, "type", None), Hashed): + return + concealed = never_returned(binding) or Mutability.write_only in mutabilities( + binding + ) + if not concealed: raise ValueError( - f"No mapping for the resource type {collection.resource_type!r}" + f"{path!r} stores a hash, which clients would read: map it to an " + "attribute that the schema makes writeOnly or never returns" ) - if collection.target is not None and collection.target is not target: + if _immutable(binding): raise ValueError( - f"{collection.binding.urn!r} already links to another mapping " - f"of {collection.resource_type!r}: a mapping serves storages " - "sharing the same mappings" + f"{path!r} is immutable, so a client sending its value again " + "must match the stored one, which a hash never does" ) - return target - - def _display(self) -> _Column | None: - """Return the column a link to these resources displays.""" - for path in ("displayName", "userName"): - binding = self._find(path) - if binding is None: - continue - ((_, column),) = self._lookup(binding) - if column is not None and not column.concealed: - return column - return None - def _find(self, path: str) -> AttributeBinding | None: - """Return the attribute at a path, or None if the model has none there.""" - return Path[self.model](path).resolve() # type: ignore[name-defined] - - def _resolve(self, path: str) -> AttributeBinding: - """Return the attribute at a path, refusing a path the model does not know.""" - binding = self._find(path) - if binding is None: - raise ValueError(f"{path!r} is not an attribute of {self.model.__name__}") - return binding - - def _add(self, path: str, binding: AttributeBinding, value: Any) -> None: - """Check the mapping of the attribute at a path, and keep its column or its collections.""" - target = binding.target_type - is_complex = isclass(target) and issubclass(target, BaseModel) - - key = (binding.model, binding.field_name) - if isinstance(value, Many): - self._collections[key] = [self._many(path, binding, value)] - return - if isinstance(value, Link): - value = [value] - if isinstance(value, list) and all(isinstance(item, Link) for item in value): - if not is_complex or binding.sub_field_name is not None: - raise ValueError( - f"{path!r} is not a complex attribute of {self.model.__name__}" - ) - self._collections[key] = self._links(path, binding, value) - return + def _build_column( + self, + path: str, + binding: AttributeBinding, + value: Any, + owner: core.Collection | None, + ) -> Problems: + """Build the column of an attribute, and decide whether it is written. - if binding.is_multivalued or is_complex: - raise ValueError( - f"{path!r} holds several values or sub-attributes: map it with Many " - "or Link, or map its sub-attributes" + A read-only attribute, a hybrid property without a setter, or a + computed column, is never written. + """ + expression = value.target if isinstance(value, core.Attribute) else value + writable = Mutability.read_only not in mutabilities( + binding + ) and self._value_writable(value) + column = _Column( + binding, + expression.key, + writable, + expression=expression, + ) + is_id = owner is None and key(binding) == key(self._resolve_path("id")) + python_type = _python_type(expression) + if ( + column.is_string + and column.enum_type is None + and python_type is not None + and not issubclass(python_type, (str, bytes)) + and not is_id + ): + yield MappingProblem( + "error", + "not-text", + f"{path!r} holds strings, but its column holds " + f"{python_type.__name__} values: map it to a property whose " + "expression casts the column to a string", ) - self._columns[_key(binding)] = self._build_column(path, binding, value) + return None - def _collection( - self, path: str, binding: AttributeBinding, relationship: Any - ) -> _Collection: + table_column = _table_column(expression) + column.nullable = table_column is None or bool(table_column.nullable) + column.needs_value = table_column is not None and _needs_value(table_column) + if column.enum_type is not None: + column.enumeration = list(column.enum_type.enums) + if owner is None and table_column is not None: + column.stores = _column_name(table_column) + if is_id: + column.textual = not _holds_text(expression) + column.keyed = column.textual + return column + + def _build_collection( + self, + path: str, + binding: AttributeBinding, + declaration: core.Many | core.Link, + ) -> Problems: """Build the collection of a relationship, holding as many records as the attribute holds entries.""" - collection = _Collection(binding, relationship) - if collection.relationship_property.uselist == collection.single: - raise ValueError( + collection = _Collection(binding, declaration.relation) + relationship = collection.relationship_property + if relationship.uselist == collection.single: + yield MappingProblem( + "error", + "relation-kind", f"{path!r} holds {'one entry' if collection.single else 'several entries'}, " - f"but its relationship holds {'several' if collection.single else 'one'}" + f"but its relationship holds {'several' if collection.single else 'one'}", ) - return collection + return None + + if isinstance(declaration, core.Many): + if not relationship.cascade.delete_orphan: + yield MappingProblem( + "error", + "relation-kind", + f"The relationship of {path!r} needs the delete-orphan cascade", + ) + return None + return collection - def _many(self, path: str, binding: AttributeBinding, many: Many) -> _Collection: - """Build the collection of a Many, with the columns of its entries, or the column of its values.""" - target = binding.target_type - is_complex = isclass(target) and issubclass(target, BaseModel) - simple = not isinstance(many.attributes, Mapping) + writable = _sql_writable(binding) if ( - binding.sub_field_name is not None - or not binding.is_multivalued - or is_complex == simple + relationship.direction is ONETOMANY + and writable + and any(not column.nullable for column in relationship.remote_side) ): - kind = "simple" if simple else "complex" - raise ValueError( - f"{path!r} is not a multi-valued {kind} attribute of " - f"{self.model.__name__}" - ) - collection = self._collection(path, binding, many.relationship) - if not collection.relationship_property.cascade.delete_orphan: - raise ValueError( - f"The relationship of {path!r} needs the delete-orphan cascade" - ) - paths: dict[str | None, str] = {} - if simple: - collection.columns[None] = self._build_column( - path, binding, many.attributes + yield MappingProblem( + "error", + "relation-kind", + f"Removing a link of {path!r} writes NULL in the foreign key " + "of the linked record, so it must accept NULL", ) - for sub_path, expression in ({} if simple else many.attributes).items(): - sub_binding = self._resolve(f"{path}.{sub_path}") - if sub_binding.sub_field_name in paths: - raise ValueError( - f"{paths[sub_binding.sub_field_name]!r} and " - f"'{path}.{sub_path}' map the same attribute" - ) - paths[sub_binding.sub_field_name] = f"{path}.{sub_path}" - collection.columns[sub_binding.sub_field_name] = self._build_column( - f"{path}.{sub_path}", sub_binding, expression + return None + + if relationship.direction is MANYTOONE and writable: + collection.nullable = all( + column.nullable for column in relationship.local_columns ) + return collection - columns = collection.columns.values() - if any(column.concealed for column in columns): - raise ValueError( - f"Writing {path!r} replaces its entries, so they cannot hold " - "write-only values, nor values clients never read back" + def _check_record(self) -> Problems: + """Refuse an identifier column that can hold NULL, and a version that is not the version counter of the mapper.""" + column = _table_column(self._id.expression) + if column is not None and column.nullable: + yield MappingProblem( + "error", + "id", + "'id' is mapped to a column that can hold no value, " + "but each resource needs one", ) - if len({column.writable for column in columns}) > 1: - raise ValueError( - f"Writing {path!r} replaces its entries, " - "so its sub-attributes are either all written or all read-only" + if self.version is None: + return + mapper: Mapper[Any] = inspect(self.record) + columns = getattr(getattr(self.version, "property", None), "columns", [None]) + if mapper.version_id_col is None or mapper.version_id_col is not columns[0]: + yield MappingProblem( + "error", + "version", + f"The version of {self.model.__name__} must be the version_id_col " + f"of the mapper of {self.record.__name__}", + ) + return + if self._last_modified is None and mapper.version_id_generator is False: + yield MappingProblem( + "error", + "version", + f"The mapping of {self.model.__name__} has no 'meta.lastModified', " + "so the storage counts the writes in its version, which the " + "database cannot generate", ) - return collection - def _links( - self, path: str, binding: AttributeBinding, links: list[Link] - ) -> list[_Collection]: - """Build the collections of the Links of an attribute, one per resource type. + def _fields_needing_value(self) -> Iterable[str]: + """Return the columns of the record that need a value the storage never writes by itself. - The type of the entries is compared, in filters, as a constant of each - Link. + The setter of a property may write any column its expression reads. + SQLAlchemy fills the version, the discriminator of the classes, and + the key each joined table shares with the table it inherits from. """ - resource_types = [link.resource_type for link in links] - if not links or len(set(resource_types)) != len(resource_types): - raise ValueError( - f"{path!r} needs one Link per resource type, and at least one" - ) - if not binding.is_multivalued and len(links) > 1: - raise ValueError(f"{path!r} holds one value, so it is mapped to one Link") - typed = {link.type is not None for link in links} - if len(typed) > 1: - raise ValueError(f"Either every Link of {path!r} has a type, or none") - type_binding = self._find(f"{path}.type") - if typed == {True} and type_binding is None: - raise ValueError(f"{path!r} has no type sub-attribute") - - collections = [] - for link in links: - collection = self._collection(path, binding, link.relationship) - collection.resource_type = link.resource_type - relationship = collection.relationship_property - if ( - relationship.direction is MANYTOONE - and collection.writable - and not self._always_held(binding) - and any(not column.nullable for column in relationship.local_columns) - ): - raise ValueError( - f"{path!r} can be removed, so the foreign key of its " - "relationship must accept NULL" - ) - if ( - relationship.direction is ONETOMANY - and collection.writable - and any(not column.nullable for column in relationship.remote_side) + dates = (self._created, self._last_modified) + written: list[Any] = [] + mapper: Mapper[Any] = inspect(self.record) + for mapped in self._columns.values(): + descriptor = mapper.all_orm_descriptors.get(mapped.key) + if (mapped.writable or mapped in dates) and isinstance( + descriptor, hybrid_property ): - raise ValueError( - f"Removing a link of {path!r} writes NULL in the foreign key " - "of the linked record, so it must accept NULL" - ) - if link.type is not None: - collection.link_type = link.type - collection.type_column = _Column( - type_binding, # type: ignore[arg-type] - literal(link.type), - "type", - False, - concealed=_conceals(binding) or _conceals(type_binding), # type: ignore[arg-type] - ) - collections.append(collection) - return collections + written += [ + element.table.columns.get(element.key) + for element in iterate(mapped.expression.__clause_element__()) # type: ignore[attr-defined] + if isinstance(element, Column) + ] + for collection in self._all_collections(): + if collection.single and not collection.owned and collection.writable: + written += collection.relationship_property.local_columns # type: ignore[attr-defined] + written += [mapper.version_id_col, mapper.polymorphic_on] + for ancestor in mapper.iterate_to_root(): + if ancestor.inherits is not None: + written += [ + column + for column in ancestor.local_table.primary_key + if column.foreign_keys + ] + return [ + _column_name(column) + for column in mapper.columns + if isinstance(column, Column) + and _needs_value(column) + and not any(column is other for other in written) + ] - def _build_column( - self, path: str, binding: AttributeBinding, value: Any - ) -> _Column: - """Build the column of an attribute, and decide whether it is written. + def _links_to(self, collection: core.Collection, target: Any) -> bool: + return bool(collection.entry_class is target.record) # type: ignore[attr-defined] - A read-only attribute, a hybrid property without a setter, or a - computed column, is never written. - """ - if binding.sub_field_name is not None and binding.target_is_multivalued: - raise ValueError( - f"{path!r} holds several values in a complex attribute, " - "which the storage cannot map" - ) - attribute = value if isinstance(value, Attribute) else Attribute(value) - expression = attribute.expression - key = getattr(expression, "key", None) - if not isinstance(key, str): - raise ValueError( - f"{path!r} must be mapped to a column or a hybrid property" - ) - writable = attribute.writable - descriptor = inspect(expression.class_).all_orm_descriptors[key] - mutabilities = { - binding.model.get_field_annotation(binding.field_name, Mutability), - binding.get_annotation(Mutability), - } - mapped = inspect(expression.class_).columns.get(key) - if ( - Mutability.read_only in mutabilities - or (isinstance(descriptor, hybrid_property) and descriptor.fset is None) - or getattr(mapped, "computed", None) is not None - ): - writable = False - concealed = _conceals(binding) - if concealed and not writable: - raise ValueError( - f"{path!r} would be neither read nor written by clients: check " - "its writable flag, the setter of its property, its column, and " - "the mutability and the returned of its schema, or leave it out" - ) - hashed = isinstance(getattr(expression, "type", None), Hashed) - if hashed and not concealed: - raise ValueError( - f"{path!r} stores a hash, which clients would read: map it to an " - "attribute that the schema makes writeOnly or never returns" - ) - immutable = Mutability.immutable in mutabilities and ( - Mutability.write_only not in mutabilities - ) - if hashed and immutable: - raise ValueError( - f"{path!r} is immutable, so a client sending its value again " - "must match the stored one, which a hash never does" - ) - column = _Column( - binding, expression, key, writable, concealed=concealed, immutable=immutable - ) - python_type = _python_type(expression) - if ( - column.is_string - and column.enumeration is None - and python_type is not None - and not issubclass(python_type, (str, bytes)) - and _key(binding) != _key(self._resolve("id")) - ): - raise ValueError( - f"{path!r} holds strings, but its column holds " - f"{python_type.__name__} values: map it to a property whose " - "expression casts the column to a string" - ) - return column + def _read(self, column: core.Column, record: Any) -> Any: + """Return the SCIM value of a column of a record.""" + value = getattr(record, column.key) + if value is None: + return None + enum_type = column.enum_type # type: ignore[attr-defined] + if isinstance(value, Enum) and enum_type is not None: + return column.stored_string(enum_type, value) # type: ignore[attr-defined] + return _as_scim(value) + + def _related(self, collection: core.Collection, record: Any) -> list[Any]: + """Return the records a collection of a record holds, as a list even for a single one.""" + related = getattr(record, collection.relation.key) + if collection.single: + return [] if related is None else [related] + return list(related) + + def _counter(self, record: Any) -> Any: + return getattr(record, self.version.key) + + def _holds_id(self, record: Any, value: str) -> bool: + return bool(getattr(record, self._id.key) == _as_key(self._id, value)) + + +def _immutable(binding: AttributeBinding) -> bool: + """Tell whether the schema keeps a value clients read from changing.""" + found = mutabilities(binding) + return Mutability.immutable in found and Mutability.write_only not in found diff --git a/src/scim2_sqlalchemy/query.py b/src/scim2_sqlalchemy/query.py index 19f4500..424cbcc 100644 --- a/src/scim2_sqlalchemy/query.py +++ b/src/scim2_sqlalchemy/query.py @@ -1,27 +1,23 @@ import decimal import operator from collections.abc import Callable +from collections.abc import Iterable from typing import Any from typing import TypeVarTuple +from typing import cast as cast_type -from scim2_models import AttributeBinding from scim2_models import InvalidCursorException -from scim2_models import InvalidFilterException from scim2_models import InvalidPathException from scim2_models import ResponseParameters -from scim2_models import ScimFilter from scim2_models import SearchRequest -from scim2_models.path import AttrPath from scim2_models.path import CompareOperator -from scim2_models.path import Comparison -from scim2_models.path import FilterVisitor -from scim2_models.path import LogicalExpr -from scim2_models.path import LogicalOperator -from scim2_models.path import Not -from scim2_models.path import Present -from scim2_models.path import ValuePath -from scim2_models.path import coerce_value from scim2_server.keyset import Position +from scim2_server.mapping import Collection +from scim2_server.mapping import Column +from scim2_server.mapping.filters import compare +from scim2_server.mapping.filters import entry_present +from scim2_server.mapping.filters import sort_target +from scim2_server.mapping.filters import where from sqlalchemy import BigInteger from sqlalchemy import ColumnElement from sqlalchemy import Double @@ -30,6 +26,7 @@ from sqlalchemy import Select from sqlalchemy import and_ from sqlalchemy import bindparam +from sqlalchemy import case from sqlalchemy import cast from sqlalchemy import false from sqlalchemy import func @@ -56,6 +53,7 @@ from .mapping import _INTEGERS from .mapping import _MARIADB from .mapping import ResourceMapping +from .mapping import _as_key from .mapping import _Collection from .mapping import _Column from .mapping import _python_type @@ -103,20 +101,6 @@ def _compile_typed_null_mariadb( return "NULL" -def _as_key(column: _Column, value: Any) -> Any: - """Return an identifier in the type of its column, or None when it cannot have that type.""" - python_type = _python_type(column.expression) - if python_type is None: - return value - try: - key = python_type(value) - except (TypeError, ValueError): - return None - if isinstance(key, int) and key not in _INTEGERS: - return None - return key - - def _bound(column: _Column, value: Any) -> Any: """Return a value ready to compare with a column. @@ -143,8 +127,6 @@ def _out_of_range( expression: ColumnElement[Any], op: CompareOperator, value: int ) -> ColumnElement[bool]: """Compare an integer column with an integer no database can store.""" - if op == CompareOperator.ne: - return true() above = value > 0 if (op in (CompareOperator.gt, CompareOperator.ge) and not above) or ( op in (CompareOperator.lt, CompareOperator.le) and above @@ -165,255 +147,97 @@ def _exact_key(column: _Column, value: str) -> Any: return key -def _unmapped(binding: AttributeBinding) -> InvalidFilterException: - """Return the error of a filter on an attribute the mapping does not let filters read.""" - return InvalidFilterException(detail=f"Cannot filter on '{binding.urn}'") - - -class _FilterTranslator(FilterVisitor[ColumnElement[bool]]): - """Turn a SCIM filter into a condition on the records of a mapping. +class _Predicates: + """The conditions of the mapping core, as SQLAlchemy expressions. - The condition keeps the records whose resources ScimFilter.match keeps. Every condition is true or false, never NULL, so that the negation of a - comparison with a missing value holds. - - scope is the collection that a value selection, such as - emails[type eq "work"], applies its filter to. + comparison with a missing value holds. The conditions on the entries of a + collection compare the columns of the entry class, which the relationship + correlates with the record. """ - def __init__( - self, - mapping: ResourceMapping, - scim_filter: ScimFilter[Any], - comparator: _Comparator, - scope: tuple[AttrPath, _Collection] | None = None, - ) -> None: - self.mapping = mapping - self.filter = scim_filter + def __init__(self, comparator: _Comparator) -> None: self.comparator = comparator - self.scope = scope - def _resolve( - self, - attr_path: AttrPath, - resolve: Callable[..., AttributeBinding | None], - ) -> AttributeBinding | None: - """Bind the attribute path of a comparison or of a presence test. - - Within a value selection of a simple attribute, such as - tags[value eq "x"], value is the entry itself, and any other attribute - matches nothing, as ScimFilter.match has it. - """ - if self.scope is None: - return resolve(attr_path, strict=False) - scope_path, scope = self.scope - if scope.simple: - own = attr_path.attr.lower() == "value" and not attr_path.sub_attr - return scope.binding if own else None - return resolve( - AttrPath(scope_path.attr, attr_path.attr, scope_path.uri), strict=False - ) + def true(self) -> ColumnElement[bool]: + return true() - def _lookup( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column | None]]: - """Return the collections holding an attribute, with its column in each, as the mapping does. + def false(self) -> ColumnElement[bool]: + return false() - Within a value selection, only the collection of the selection holds - the attribute. - """ - pairs = self.mapping._lookup(binding) - if self.scope is None: - return pairs - _, scope = self.scope - return [ - (collection, column) for collection, column in pairs if collection is scope - ] + def any(self, conditions: Iterable[ColumnElement[bool]]) -> ColumnElement[bool]: + return or_(false(), *conditions) - def _targets( - self, binding: AttributeBinding - ) -> list[tuple[_Collection | None, _Column]]: - """Return the collections holding an attribute with its column in each, refusing an attribute that one of them does not let filters read.""" - pairs = self._lookup(binding) - if any(column is None or column.concealed for _, column in pairs): - raise _unmapped(binding) - return pairs # type: ignore[return-value] - - def _in_collection( - self, collection: _Collection | None, condition: ColumnElement[bool] - ) -> ColumnElement[bool]: - """Apply a condition to the entries of a collection, or to the record itself outside of any collection. + def all(self, conditions: Iterable[ColumnElement[bool]]) -> ColumnElement[bool]: + return and_(true(), *conditions) - Within a value selection, the condition already applies to the entries. - """ - if collection is None or self.scope is not None: - return condition - return collection.exists(condition) - - def visit_comparison(self, node: Comparison) -> ColumnElement[bool]: - """Keep the records with a value matching the comparison, in any collection holding the attribute.""" - binding = self._resolve(node.attr_path, self.filter.resolve_comparison) - if binding is None: - return false() - targets = self._targets(binding) - value = coerce_value(binding, node.value, node.op) - - # 'emails ne "x"' holds when no email is "x", while - # 'emails[value ne "x"]' holds when one email is not "x". - if ( - node.op == CompareOperator.ne - and targets[0][0] is not None - and self.scope is None - ): - return not_( - or_( - *( - collection.exists( # type: ignore[union-attr] - _compare(self.comparator, column, CompareOperator.eq, value) - ) - for collection, column in targets - ) - ) - ) - return or_( - *( - self._in_collection( - collection, _compare(self.comparator, column, node.op, value) - ) - for collection, column in targets - ) - ) + def negate(self, condition: ColumnElement[bool]) -> ColumnElement[bool]: + return not_(condition) - def visit_present(self, node: Present) -> ColumnElement[bool]: - """Keep the records with a value for the attribute. + def is_null(self, column: Column) -> ColumnElement[bool]: + return _sa(column).compared.is_(None) - A complex attribute is present when one of its sub-attributes is. - """ - binding = self._resolve(node.attr_path, self.filter.resolve) - if binding is None: - return false() - pairs = self._lookup(binding) - in_collection = pairs[0][0] is not None - if in_collection and binding.sub_field_name is None and pairs[0][1] is None: - return or_(*(collection.exists() for collection, _ in pairs)) # type: ignore[union-attr] - if all(column is not None and not column.concealed for _, column in pairs): - return or_( - *( - self._in_collection(collection, _present(column)) # type: ignore[arg-type] - for collection, column in pairs - ) - ) - - sub_columns = [ - column - for column in self.mapping._sub_columns(binding) - if not column.concealed - ] - if in_collection or not sub_columns: - raise _unmapped(binding) - return or_(*(_present(column) for column in sub_columns)) - - def visit_not(self, node: Not) -> ColumnElement[bool]: - """Keep the records the inner filter does not keep.""" - return not_(self.visit(node.expr)) - - def visit_logical_expr(self, node: LogicalExpr) -> ColumnElement[bool]: - """Combine the conditions of the terms with AND or OR.""" - combine = and_ if node.op == LogicalOperator.and_ else or_ - return combine(*(self.visit(term) for term in node.terms)) - - def visit_value_path(self, node: ValuePath) -> ColumnElement[bool]: - """Keep the records with an entry of the attribute matching the inner filter.""" - binding = self.filter.resolve(node.attr_path, strict=False) - if binding is None: - return false() - collections = [ - collection - for collection, _ in self.mapping._lookup(binding) - if collection is not None - ] - if not collections: - raise _unmapped(binding) - return or_( - *( - collection.exists( - _FilterTranslator( - self.mapping, - self.filter, - self.comparator, - (node.attr_path, collection), - ).visit(node.val_filter) - ) - for collection in collections - ) - ) + def is_empty(self, column: Column) -> ColumnElement[bool]: + return _sa(column).compared == "" + def compare( + self, column: Column, op: CompareOperator, value: Any + ) -> ColumnElement[bool]: + """Compare a column that does not hold strings. -def _present(column: _Column) -> ColumnElement[bool]: - """Per RFC 7644 §3.4.2.2, an empty string is no value.""" - expression = column.compared - if column.is_string: - return and_(expression.is_not(None), expression != "") - return expression.is_not(None) + An integer no database stores is above or below every value. A + boolean is compared with a column of integers as 0 or 1, since + PostgreSQL has no operator between an integer and a boolean. + """ + column = _sa(column) + expression = column.compared + value = _as_stored(value) + if isinstance(value, int) and _python_type(column.expression) is int: + if value not in _INTEGERS: + return _out_of_range(expression, op, value) + value = _bound(column, int(value)) + return _ORDERINGS[op](expression, value) # type: ignore[no-any-return] + def compare_text( + self, column: Column, op: CompareOperator, value: str + ) -> ColumnElement[bool]: + """Compare a string column in the form the policy compares it under. -def _compare( - comparator: _Comparator, column: _Column, op: CompareOperator, value: Any -) -> ColumnElement[bool]: - """Compare a column with a value, strings in the form the policy compares them under. + A stored value the comparison key refuses is compared as no value, so + that the comparison is false rather than NULL. + """ + column = _sa(column) + left = self.comparator.column(column) + if op in _SUBSTRINGS: + condition = self.comparator.substring(op, column, value) + else: + condition = _ORDERINGS[op](left, self.comparator.operand(column, value)) + return and_(left.is_not(None), condition) - A string the policy cannot prepare is equal to no other value, so only ne - holds against it. - """ - expression = column.compared - value = _as_stored(value) - if value is None: - if op == CompareOperator.eq: - return expression.is_(None) - if op == CompareOperator.ne: - return expression.is_not(None) - return false() + def compare_key(self, column: Column, value: Any) -> ColumnElement[bool] | None: + """Compare an identifier in its own type. - if column.textual and op in (CompareOperator.eq, CompareOperator.ne): - # The identifier is compared in its own type, so that the database - # uses its index, and does not depend on how it writes a UUID as text. + The database then uses its index, and the result does not depend on + how the database writes a UUID as text. + """ + column = _sa(column) key = _exact_key(column, value) if key is None: - return true() if op == CompareOperator.ne else false() - if op == CompareOperator.ne: - return or_( - column.expression.is_(None), column.expression != _bound(column, key) - ) - return and_( - column.expression.is_not(None), column.expression == _bound(column, key) - ) + return None + return column.expression == _bound(column, key) # type: ignore[no-any-return] - if not column.is_string: - if isinstance(value, int) and _python_type(column.expression) is int: - if value not in _INTEGERS: - return _out_of_range(expression, op, value) - # A boolean is compared with a column of integers as 0 or 1, since - # PostgreSQL has no operator between an integer and a boolean. - value = _bound(column, int(value)) - if op == CompareOperator.ne: - return or_(expression.is_(None), expression != value) - if op in _SUBSTRINGS: - return false() - return and_(expression.is_not(None), _ORDERINGS[op](expression, value)) + def exists( + self, + collection: Collection, + build: Callable[[Any], ColumnElement[bool]] | None = None, + ) -> ColumnElement[bool]: + condition = None if build is None else build(self) + return collection.exists(condition) # type: ignore[attr-defined,no-any-return] - try: - column.binding.comparable(value, comparator.policy) - except ValueError: - return true() if op == CompareOperator.ne else false() - left = comparator.column(column) - if op == CompareOperator.ne: - return or_(left.is_(None), left != comparator.operand(column, value)) - if op in _SUBSTRINGS: - condition = comparator.substring(op, column, value) - else: - condition = _ORDERINGS[op](left, comparator.operand(column, value)) - return and_(left.is_not(None), condition) +def _sa(column: Column) -> _Column: + """Return a column built by the SQLAlchemy mapping.""" + return column # type: ignore[return-value] def _sort_key( @@ -424,29 +248,35 @@ def _sort_key( """Return the expression the records of a mapping sort on. Return None when the search has no sortBy, or when the model of the - mapping does not declare its attribute. + mapping does not declare its attribute. A constant of an Entry sorts as + its value when the entry exists, and as no value otherwise. """ - binding = search_request.sort_binding(mapping.model) - if binding is None: + target = sort_target(mapping, search_request) + if target is None: return None - collection, column = mapping._lookup(binding)[0] - if ( - column is None - or column.concealed - or (collection is not None and not collection.owned) - ): - raise InvalidPathException( - path=str(search_request.sort_by), - detail=f"Cannot sort on '{binding.urn}'", - ) - expression: Any = column.expression + collection, column = target + if column.is_constant: + return _constant_key(mapping, column, comparator) + expression: Any = _sa(column).expression if column.is_string: - expression = comparator.column(column) + expression = comparator.column(_sa(column)) if collection is not None: - expression = _first_entry(collection, expression) + expression = _first_entry(collection, expression) # type: ignore[arg-type] return expression +def _constant_key( + mapping: ResourceMapping, column: Column, comparator: _Comparator +) -> Any: + """Return the sort key of a constant of an Entry: its comparison key when the entry exists, and no value otherwise.""" + entry = mapping._entry_of(column) + present = entry_present(_Predicates(comparator), entry) # type: ignore[arg-type] + constant = column.constant + if column.is_string: + constant = column.binding.comparable(constant, comparator.policy) + return case((present, literal(constant)), else_=null()) + + def _first_entry(collection: _Collection, expression: Any) -> Any: """Return the value of the primary entry of a collection, or else of its first one.""" relationship = collection.relationship_property @@ -454,7 +284,7 @@ def _first_entry(collection: _Collection, expression: Any) -> Any: order: list[Any] = [] primary = collection.columns.get("primary") if primary is not None: - order.append(_Sorted(primary.expression, ascending=False, last=True)) + order.append(_Sorted(_sa(primary).expression, ascending=False, last=True)) order.extend(relationship.order_by or entry_mapper.primary_key) return ( select(expression) @@ -471,10 +301,10 @@ def _where( comparator: _Comparator, ) -> ColumnElement[bool]: """Return the condition keeping the records matching the filter of a search, or every record without filter.""" - if search_request.filter is None: - return true() - scim_filter = ScimFilter[mapping.model](str(search_request.filter)) # type: ignore[name-defined] - return _FilterTranslator(mapping, scim_filter, comparator).visit(scim_filter.ast) + condition: ColumnElement[bool] = where( + mapping, search_request, _Predicates(comparator), comparator.policy + ) + return condition def _cursor_page( @@ -621,40 +451,50 @@ def _load_statement( mapping: ResourceMapping, resource_id: str | None, parameters: ResponseParameters[Any] | None = None, + locked: bool = False, ) -> Select[Any] | None: """Return the statement loading a record, or None when no record can have this identifier. - Only the collections the response keeps are loaded, all of them without parameters. + Only the collections the response keeps are loaded, all of them without + parameters. A locked record stays locked until the end of the + transaction, on the databases that lock rows. """ key = _as_key(mapping._id, resource_id) if key is None: return None - return ( + statement = ( select(mapping.record) .where(mapping._id.expression == _bound(mapping._id, key)) .options(*mapping._loader_options(mapping._returned_collections(parameters))) ) + return statement.with_for_update() if locked else statement def _taken_statement( mapping: ResourceMapping, - column: _Column, + column: Column, value: Any, resource_id: str | None, comparator: _Comparator, ) -> Select[Any]: """Return the statement finding another record holding a unique value.""" - condition = _compare(comparator, column, CompareOperator.eq, value) + condition = compare( + mapping, + _Predicates(comparator), + comparator.policy, + column, + CompareOperator.eq, + value, + ) key = None if resource_id is None else _as_key(mapping._id, resource_id) if key is not None: condition = and_(condition, mapping._id.expression != _bound(mapping._id, key)) return select(mapping._id.expression).where(condition).limit(1) -def _links_statement(collection: _Collection, ids: list[str]) -> Select[Any]: +def _links_statement(collection: Collection, ids: list[str]) -> Select[Any]: """Return the statement loading the records a Link links to.""" - target = collection.target - assert target is not None + target = cast_type(ResourceMapping, collection.target) keys = [ key for key in (_as_key(target._id, value) for value in ids) if key is not None ] diff --git a/src/scim2_sqlalchemy/storage.py b/src/scim2_sqlalchemy/storage.py index 57fe639..ec3c777 100644 --- a/src/scim2_sqlalchemy/storage.py +++ b/src/scim2_sqlalchemy/storage.py @@ -12,7 +12,6 @@ from typing import Any from scim2_models import ConflictException -from scim2_models import InvalidValueException from scim2_models import NotFoundException from scim2_models import Path from scim2_models import PreconditionFailedException @@ -27,27 +26,29 @@ from scim2_server.keyset import Position from scim2_server.keyset import keyset_page from scim2_server.keyset import page_rows +from scim2_server.mapping import Collection +from scim2_server.mapping.conversion import assign_links +from scim2_server.mapping.conversion import check_storable +from scim2_server.mapping.conversion import comparable +from scim2_server.mapping.conversion import dates +from scim2_server.mapping.conversion import link_entries from scim2_server.storage import AsyncScimStorage from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage from sqlalchemy import Dialect from sqlalchemy import Select +from sqlalchemy import inspect from sqlalchemy.exc import DBAPIError from sqlalchemy.orm import Session from sqlalchemy.orm.exc import StaleDataError from .comparison import _Comparator from .comparison import _comparator -from .conversion import _check_storable -from .conversion import _comparable from .conversion import _from_scim -from .conversion import _link_entries from .conversion import _to_scim -from .conversion import _version from .mapping import ResourceMapping -from .mapping import _Collection +from .mapping import _as_key from .mapping import _Column -from .query import _as_key from .query import _links_statement from .query import _load_statement from .query import _records_statement @@ -80,12 +81,6 @@ def _expire( session.expire(record) -def _holds_id(collection: _Collection, record: Any, value: str) -> bool: - """Tell whether a record a Link links to has an identifier.""" - target_id = collection.target._id # type: ignore[union-attr] - return bool(getattr(record, target_id.key) == _as_key(target_id, value)) - - def _has_text_id(id_column: _Column, record: Any, value: str | None) -> bool: """Tell whether a record found by a string identifier has exactly this identifier. @@ -191,9 +186,11 @@ def __init__( self, mappings: Mapping[str, ResourceMapping], provider: ScimProvider | None, + version_key: bytes | None, ) -> None: self.mappings = dict(mappings) self.provider = provider + self.version_key = version_key self._policy = provider.policy if provider else ScimPolicy() self._comparators: dict[str, _Comparator] = {} self._endpoints = { @@ -205,6 +202,12 @@ def __init__( raise ValueError( f"No mapping for the resource type {resource_type.name!r}" ) + for name, mapping in self.mappings.items(): + if mapping.version is None and not version_key: + raise ValueError( + f"The mapping of {name!r} has no version, so the storage " + "needs a version_key to hash the resources" + ) links = [mapping._targets(self.mappings) for mapping in self.mappings.values()] for mapping, targets in zip(self.mappings.values(), links, strict=True): mapping._bind(targets) @@ -301,6 +304,7 @@ def _to_scim( model, self._endpoints, collections, + self.version_key, ) def _check_storable( @@ -310,7 +314,7 @@ def _check_storable( stored: Resource[Any] | None, ) -> None: """Refuse a change the mapping cannot store. stored is the stored resource, None for a new one.""" - _check_storable(self._mapping(resource_type), resource, stored) + check_storable(self._mapping(resource_type), resource, stored) @staticmethod def _not_found( @@ -321,15 +325,28 @@ def _not_found( detail=f"{resource_type.name} {resource_id!r} not found" ) - @staticmethod def _check_version( - mapping: ResourceMapping, record: Any, expected_version: str | None + self, + resource_type: ResourceType, + record: Any, + expected_version: str | None, + stored: Resource[Any] | None = None, ) -> None: - """Refuse to change a record whose version is not the expected one.""" - if ( - expected_version is not None - and _version(mapping, record) != expected_version - ): + """Refuse to change a record whose version is not the expected one. + + A version counter is read from the record. A hash is the one of the + stored resource, built from the record when not given, all of its + collections loaded. + """ + if expected_version is None: + return + mapping = self._mapping(resource_type) + if mapping.version is not None: + version = f'W/"{mapping._counter(record)}"' + else: + stored = stored or self._to_scim(resource_type, record) + version = stored.meta.version # type: ignore[union-attr,assignment] + if version != expected_version: raise PreconditionFailedException def _comparator(self, dialect: Dialect) -> _Comparator: @@ -357,69 +374,15 @@ def _unique_statements( """ resource_id = None if stored is None else resource.id for column in mapping._unique_columns(): - if not column.writable: - continue path = Path(column.binding.urn) value = path.get(resource, strict=False) if value is None or ( stored is not None - and _comparable(value) == _comparable(path.get(stored, strict=False)) + and comparable(value) == comparable(path.get(stored, strict=False)) ): continue yield _taken_statement(mapping, column, value, resource_id, comparator) - def _assign_links( - self, found: list[tuple[_Collection, list[Any]]], entries: list[Any] - ) -> dict[_Collection, list[Any]]: - """Give each entry of an attribute the record it links to, in the collection of the first Link holding that record. - - found holds the records each Link of the attribute holds among the - values of the entries. An entry with a type links to a Link giving - the same type. - """ - links: dict[_Collection, list[Any]] = { - collection: [] for collection, _ in found - } - urn = found[0][0].binding.urn - for entry in entries: - matches = [ - (collection, record) - for collection, records in found - for record in records - if _holds_id(collection, record, entry.value) - ] - if not matches: - raise InvalidValueException( - detail=f"'{urn}' links to an unknown resource" - ) - entry_type = getattr(entry, "type", None) - if entry_type is not None: - matches = [ - (collection, record) - for collection, record in matches - if self._same_type(collection, entry_type) - ] - if not matches: - raise InvalidValueException( - detail=f"'{urn}' links to {entry.value!r}, which is not " - f"of type {entry_type!r}" - ) - collection, record = matches[0] - if record not in links[collection]: - links[collection].append(record) - return links - - def _same_type(self, collection: _Collection, value: str) -> bool: - """Tell whether a type is the one a Link gives, compared as filters compare it.""" - binding = collection.type_column.binding # type: ignore[union-attr] - try: - return bool( - binding.comparable(value, self._policy) - == binding.comparable(collection.link_type, self._policy) - ) - except ValueError: - return False - def _new_record(self, resource_type: ResourceType, resource: Resource[Any]) -> Any: """Build an empty record for a new resource, with its dates. @@ -428,9 +391,8 @@ def _new_record(self, resource_type: ResourceType, resource: Resource[Any]) -> A """ mapping = self._mapping(resource_type) record = mapping.record() - now = _utcnow() - setattr(record, mapping._created.key, now) - setattr(record, mapping._last_modified.key, now) + for column, now in dates(mapping, _utcnow(), creating=True): + setattr(record, column.key, now) return record def _write_record( @@ -438,15 +400,21 @@ def _write_record( mapping: ResourceMapping, resource: Resource[Any], record: Any, - links: dict[_Collection, list[Any]], + links: dict[Collection, list[Any]], ) -> None: """Write a resource in its record, and date the write. - The date changes the row even when only links change, such as the - members of a group, so that the version changes too. + The date updates the record even when only links change, such as the + members of a group, so that its version counter changes too. Without + date, the storage counts the write in the version itself. """ _from_scim(mapping, resource, record, links, creating=False) - setattr(record, mapping._last_modified.key, _utcnow()) + for column, now in dates(mapping, _utcnow(), creating=False): + setattr(record, column.key, now) + if mapping.version is not None and mapping._last_modified is None: + version = mapping.version.key + generate = inspect(mapping.record).version_id_generator + setattr(record, version, generate(getattr(record, version))) class SqlAlchemyStorage(_StorageBase, ScimStorage): @@ -471,7 +439,14 @@ class SqlAlchemyStorage(_StorageBase, ScimStorage): endpoints of its resource types. Strings are compared with the :attr:`~scim2_models.ScimPolicy.comparison_key` of its policy. Each of its resource types needs a mapping. - :raises ValueError: When a resource type has no mapping. + :param version_key: The key of the hash giving the version of the + resources whose mapping has no version. Keep it secret, as the hash + covers the values clients never read, such as a password hash. The + hash covers the links too, so renaming a member changes the version + of its groups. A write on such a resource locks its row until the end + of the transaction. + :raises ValueError: When a resource type has no mapping, or when a + mapping has no version and no key is given. """ supports_cursors = True @@ -481,8 +456,10 @@ def __init__( mappings: Mapping[str, ResourceMapping], session: Callable[[], Session], provider: ScimProvider | None = None, + *, + version_key: bytes | None = None, ) -> None: - super().__init__(mappings, provider) + super().__init__(mappings, provider, version_key) self.session = session @contextmanager @@ -569,9 +546,9 @@ def update( ) -> Resource[Any]: """Replace a resource, and return it as stored.""" mapping = self._mapping(resource_type) - record = self._load(resource_type, resource.id) - self._check_version(mapping, record, expected_version) + record = self._load(resource_type, resource.id, locked=True) stored = self._to_scim(resource_type, record) + self._check_version(resource_type, record, expected_version, stored) self._check_storable(resource_type, resource, stored) self._check_uniqueness(mapping, resource, stored) links = self._links(mapping, resource) @@ -586,9 +563,8 @@ def delete( expected_version: str | None = None, ) -> None: """Delete a resource.""" - mapping = self._mapping(resource_type) - record = self._load(resource_type, resource_id) - self._check_version(mapping, record, expected_version) + record = self._load(resource_type, resource_id, locked=True) + self._check_version(resource_type, record, expected_version) self._flush(lambda: self.session().delete(record)) def _load( @@ -596,10 +572,18 @@ def _load( resource_type: ResourceType, resource_id: str | None, parameters: ResponseParameters[Any] | None = None, + locked: bool = False, ) -> Any: - """Load a record, with the collections the response keeps.""" + """Load a record, with the collections the response keeps. + + A record locked for a write whose version is a hash stays locked until + the end of the transaction, so that two writes cannot both pass the + check of the same version. + """ mapping = self._mapping(resource_type) - statement = _load_statement(mapping, resource_id, parameters) + statement = _load_statement( + mapping, resource_id, parameters, locked and mapping.version is None + ) _expire(self.session(), mapping, resource_id) record = None if statement is None else self.session().scalar(statement) if record is None or not _has_text_id(mapping._id, record, resource_id): @@ -628,10 +612,10 @@ def _ready_comparator(self, session: Session) -> _Comparator: def _links( self, mapping: ResourceMapping, resource: Resource[Any] - ) -> dict[_Collection, list[Any]]: + ) -> dict[Collection, list[Any]]: """Return the records each Link of a resource links to, refusing a value that links to nothing.""" - links: dict[_Collection, list[Any]] = {} - for collections, entries in _link_entries(mapping, resource): + links: dict[Collection, list[Any]] = {} + for collections, entries in link_entries(mapping, resource): ids = [entry.value for entry in entries] found = [ ( @@ -642,7 +626,7 @@ def _links( ) for collection in collections ] - links |= self._assign_links(found, entries) + links |= assign_links(found, entries, self._policy) return links def _flush(self, change: Callable[[], None]) -> None: @@ -682,7 +666,14 @@ class AsyncSqlAlchemyStorage(_StorageBase, AsyncScimStorage): Strings are compared with the :attr:`~scim2_models.ScimPolicy.comparison_key` of its policy. Each of its resource types needs a mapping. - :raises ValueError: When a resource type has no mapping. + :param version_key: The key of the hash giving the version of the + resources whose mapping has no version. Keep it secret, as the hash + covers the values clients never read, such as a password hash. The + hash covers the links too, so renaming a member changes the version + of its groups. A write on such a resource locks its row until the end + of the transaction. + :raises ValueError: When a resource type has no mapping, or when a + mapping has no version and no key is given. """ supports_cursors = True @@ -692,8 +683,10 @@ def __init__( mappings: Mapping[str, ResourceMapping], session: Callable[[], "AsyncSession"], provider: ScimProvider | None = None, + *, + version_key: bytes | None = None, ) -> None: - super().__init__(mappings, provider) + super().__init__(mappings, provider, version_key) self.session = session @asynccontextmanager @@ -777,9 +770,9 @@ async def update( ) -> Resource[Any]: """Replace a resource, and return it as stored.""" mapping = self._mapping(resource_type) - record = await self._load(resource_type, resource.id) - self._check_version(mapping, record, expected_version) + record = await self._load(resource_type, resource.id, locked=True) stored = self._to_scim(resource_type, record) + self._check_version(resource_type, record, expected_version, stored) self._check_storable(resource_type, resource, stored) await self._check_uniqueness(mapping, resource, stored) links = await self._links(mapping, resource) @@ -798,9 +791,8 @@ async def delete( expected_version: str | None = None, ) -> None: """Delete a resource.""" - mapping = self._mapping(resource_type) - record = await self._load(resource_type, resource_id) - self._check_version(mapping, record, expected_version) + record = await self._load(resource_type, resource_id, locked=True) + self._check_version(resource_type, record, expected_version) async def change() -> None: await self.session().delete(record) @@ -812,10 +804,18 @@ async def _load( resource_type: ResourceType, resource_id: str | None, parameters: ResponseParameters[Any] | None = None, + locked: bool = False, ) -> Any: - """Load a record, with the collections the response keeps.""" + """Load a record, with the collections the response keeps. + + A record locked for a write whose version is a hash stays locked until + the end of the transaction, so that two writes cannot both pass the + check of the same version. + """ mapping = self._mapping(resource_type) - statement = _load_statement(mapping, resource_id, parameters) + statement = _load_statement( + mapping, resource_id, parameters, locked and mapping.version is None + ) _expire(self.session(), mapping, resource_id) record = None if statement is None else await self.session().scalar(statement) if record is None or not _has_text_id(mapping._id, record, resource_id): @@ -845,17 +845,17 @@ async def _ready_comparator(self, session: "AsyncSession") -> _Comparator: async def _links( self, mapping: ResourceMapping, resource: Resource[Any] - ) -> dict[_Collection, list[Any]]: + ) -> dict[Collection, list[Any]]: """Return the records each Link of a resource links to, refusing a value that links to nothing.""" - links: dict[_Collection, list[Any]] = {} - for collections, entries in _link_entries(mapping, resource): + links: dict[Collection, list[Any]] = {} + for collections, entries in link_entries(mapping, resource): ids = [entry.value for entry in entries] found = [] for collection in collections: statement = _links_statement(collection, ids) records = (await self.session().scalars(statement)).all() found.append((collection, list(records))) - links |= self._assign_links(found, entries) + links |= assign_links(found, entries, self._policy) return links async def _flush(self, change: Callable[[], Awaitable[None]]) -> None: diff --git a/tests/conftest.py b/tests/conftest.py index b52f1a1..557b8d7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,6 +23,7 @@ from .models import MAPPINGS from .models import USERS from .models import Base +from .plain import PLAIN_MAPPINGS # noqa: F401 The tables of the plain records are created with the others. DATABASES = ( ["sqlite"] @@ -118,9 +119,11 @@ def sync_storage_factory(session): The mixins come before the storage class, to override its methods. """ - def factory(mappings=MAPPINGS, mixins=(), provider=None): + def factory(mappings=MAPPINGS, mixins=(), provider=None, version_key=None): storage_class = type("Storage", (*mixins, SqlAlchemyStorage), {}) - return storage_class(mappings, lambda: session, provider=provider) + return storage_class( + mappings, lambda: session, provider=provider, version_key=version_key + ) return factory @@ -133,9 +136,11 @@ def async_storage_factory(database_url): enforce_foreign_keys(engine.sync_engine) session = AsyncSession(engine) - def factory(mappings=MAPPINGS, mixins=(), provider=None): + def factory(mappings=MAPPINGS, mixins=(), provider=None, version_key=None): storage_class = type("Storage", (*mixins, AsyncSqlAlchemyStorage), {}) - storage = storage_class(mappings, lambda: session, provider=provider) + storage = storage_class( + mappings, lambda: session, provider=provider, version_key=version_key + ) return BlockingStorage(storage, runner) yield factory diff --git a/tests/plain.py b/tests/plain.py new file mode 100644 index 0000000..f44f19a --- /dev/null +++ b/tests/plain.py @@ -0,0 +1,114 @@ +"""Records without dates, whose resources get the hash of their values as version, and an Entry for the work email.""" + +from scim2_models import EnterpriseUser +from scim2_models import Group +from scim2_models import User +from sqlalchemy import Column +from sqlalchemy import ForeignKey +from sqlalchemy import Table +from sqlalchemy.orm import Mapped +from sqlalchemy.orm import mapped_column +from sqlalchemy.orm import relationship + +from scim2_sqlalchemy import Entry +from scim2_sqlalchemy import Link +from scim2_sqlalchemy import ResourceMapping + +from .models import ENTERPRISE +from .models import Base + +plain_membership = Table( + "plain_membership", + Base.metadata, + Column( + "group_id", ForeignKey("plain_groups.id", ondelete="CASCADE"), primary_key=True + ), + Column( + "user_id", ForeignKey("plain_users.id", ondelete="CASCADE"), primary_key=True + ), +) + + +class PlainUserRecord(Base): + __tablename__ = "plain_users" + + id: Mapped[int] = mapped_column(primary_key=True) + user_name: Mapped[str] = mapped_column(unique=True) + display_name: Mapped[str | None] + title: Mapped[str | None] + nick_name: Mapped[str | None] + given_name: Mapped[str | None] + family_name: Mapped[str | None] + active: Mapped[bool | None] + password: Mapped[str | None] + email: Mapped[str | None] + employee_number: Mapped[str | None] + + groups: Mapped[list["PlainGroupRecord"]] = relationship( + secondary=plain_membership, back_populates="members" + ) + + +class PlainGroupRecord(Base): + __tablename__ = "plain_groups" + + id: Mapped[int] = mapped_column(primary_key=True) + display_name: Mapped[str | None] + version: Mapped[int] = mapped_column() + + members: Mapped[list[PlainUserRecord]] = relationship( + secondary=plain_membership, back_populates="groups" + ) + + __mapper_args__ = {"version_id_col": version} + + +class GeneratedVersionRecord(Base): + """A record whose version the database generates.""" + + __tablename__ = "generated_versions" + + id: Mapped[int] = mapped_column(primary_key=True) + display_name: Mapped[str | None] + version: Mapped[int] = mapped_column(server_default="1") + + __mapper_args__ = {"version_id_col": version, "version_id_generator": False} + + +def plain_users_mapping(): + return ResourceMapping( + User[EnterpriseUser], + PlainUserRecord, + { + "id": PlainUserRecord.id, + "userName": PlainUserRecord.user_name, + "displayName": PlainUserRecord.display_name, + "title": PlainUserRecord.title, + "nickName": PlainUserRecord.nick_name, + "name.givenName": PlainUserRecord.given_name, + "name.familyName": PlainUserRecord.family_name, + "active": PlainUserRecord.active, + "password": PlainUserRecord.password, + "emails": Entry( + {"value": PlainUserRecord.email}, type="work", primary=True + ), + "groups": Link(PlainUserRecord.groups, "Group", type="direct"), + f"{ENTERPRISE}:employeeNumber": PlainUserRecord.employee_number, + }, + ) + + +def plain_groups_mapping(version=None): + return ResourceMapping( + Group, + PlainGroupRecord, + { + "id": PlainGroupRecord.id, + "displayName": PlainGroupRecord.display_name, + "members": Link(PlainGroupRecord.members, "User", type="User"), + }, + version=version, + ) + + +PLAIN_MAPPINGS = {"User": plain_users_mapping(), "Group": plain_groups_mapping()} diff --git a/tests/test_contract.py b/tests/test_contract.py index 0c3a93d..80a6c82 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -2,6 +2,8 @@ from scim2_server.testing import AsyncScimStorageContract from scim2_server.testing import ScimStorageContract +from .plain import PLAIN_MAPPINGS + class TestSqlAlchemyStorage(ScimStorageContract): @pytest.fixture @@ -13,3 +15,37 @@ class TestAsyncSqlAlchemyStorage(AsyncScimStorageContract): @pytest.fixture def storage(self, async_storage_factory): return async_storage_factory() + + +def one_work_email(user): + emails = user.get("emails") + if not emails: + return user + + return user | {"emails": [{"value": emails[-1]["value"], "type": "work"}]} + + +class TestSqlAlchemyStorageWithHashes(ScimStorageContract): + """Resources without dates nor version counter, whose emails are a work email held by the user record.""" + + stores_created = False + stores_last_modified = False + + def search_users(self): + return [one_work_email(user) for user in super().search_users()] + + @pytest.fixture + def storage(self, sync_storage_factory): + return sync_storage_factory(PLAIN_MAPPINGS, version_key=b"secret") + + +class TestAsyncSqlAlchemyStorageWithHashes(AsyncScimStorageContract): + stores_created = False + stores_last_modified = False + + def search_users(self): + return [one_work_email(user) for user in super().search_users()] + + @pytest.fixture + def storage(self, async_storage_factory): + return async_storage_factory(PLAIN_MAPPINGS, version_key=b"secret") diff --git a/tests/test_many_values.py b/tests/test_many_values.py index be6ab33..159392c 100644 --- a/tests/test_many_values.py +++ b/tests/test_many_values.py @@ -267,7 +267,7 @@ class Secret(Extension): def test_write_only_values_are_refused(): """Writing the tags creates their records again, so a value read back in another form would be written as is.""" - with pytest.raises(ValueError, match="cannot hold write-only values"): + with pytest.raises(ValueError, match="cannot hold values hidden from clients"): ResourceMapping( User[Secret], TaggedUser, diff --git a/tests/test_mapping.py b/tests/test_mapping.py index 0d40166..1568c35 100644 --- a/tests/test_mapping.py +++ b/tests/test_mapping.py @@ -167,15 +167,26 @@ def person_mapping(**attributes): return ResourceMapping(User, Person, REQUIRED | attributes, version=Person.version) -@pytest.mark.parametrize("missing", ["id", "meta.created", "meta.lastModified"]) -def test_a_mapping_needs_the_identifier_and_the_dates(missing): - """The storage fills these attributes, so it needs a column for each.""" - attributes = {key: value for key, value in REQUIRED.items() if key != missing} +def test_a_mapping_needs_the_identifier(): + """The storage finds each resource by its identifier.""" + attributes = {key: value for key, value in REQUIRED.items() if key != "id"} - with pytest.raises(ValueError, match=missing): + with pytest.raises(ValueError, match="needs 'id'"): ResourceMapping(User, Person, attributes, version=Person.version) +@pytest.mark.parametrize("missing", ["meta.created", "meta.lastModified"]) +def test_a_mapping_without_dates_gives_resources_without_dates(missing): + """The storage fills the dates it has a column for, and warns about the date column it leaves empty.""" + attributes = {key: value for key, value in REQUIRED.items() if key != missing} + + with pytest.warns(UserWarning, match="needs a value, but the storage never"): + mapping = ResourceMapping(User, Person, attributes, version=Person.version) + + assert (mapping._created is None) == (missing == "meta.created") + assert (mapping._last_modified is None) == (missing == "meta.lastModified") + + def test_an_identifier_that_can_be_missing_is_refused(): """A resource without id could not be read back, nor placed between two cursor pages.""" with pytest.raises( @@ -202,13 +213,13 @@ def test_a_hash_holds_a_write_only_attribute_only(): ) def test_an_attribute_neither_read_nor_written_is_refused(path, value): """The storage would do nothing with it, yet publish it.""" - with pytest.raises(ValueError, match="neither read nor written"): + with pytest.raises(ValueError, match="Clients could neither read nor write"): users_mapping({path: value}) def test_a_link_that_can_be_removed_needs_a_foreign_key_accepting_null(): """Removing the manager would write NULL in a column that refuses it.""" - with pytest.raises(ValueError, match="foreign key of its relationship must"): + with pytest.raises(ValueError, match="its relation needs to hold null"): desk_mapping( User[EnterpriseUser], { @@ -220,7 +231,7 @@ def test_a_link_that_can_be_removed_needs_a_foreign_key_accepting_null(): def test_a_required_link_of_an_optional_extension_can_be_removed(): """A resource without the extension has no owner, so the foreign key must accept NULL.""" - with pytest.raises(ValueError, match="foreign key of its relationship must"): + with pytest.raises(ValueError, match="its relation needs to hold null"): desk_mapping( User[Owned], { @@ -273,8 +284,8 @@ def test_a_column_the_mapping_never_writes_warns(): ) assert [str(warning.message) for warning in caught] == [ - "The column desks.keeper_id needs a value, but the mapping of " - "User[Owned] never writes it: map it, or give it a default" + "The field 'desks.keeper_id' needs a value, but the storage never writes " + "it, so creating a resource fails: map it, or give it a default" ] @@ -285,7 +296,7 @@ def test_a_column_the_mapping_never_writes_warns(): ) def test_a_column_needing_a_value_warns_when_it_is_not_written(user_name): """Creating a user would fail in the database.""" - with pytest.warns(UserWarning, match="users.user_name needs a value"): + with pytest.warns(UserWarning, match="'users.user_name' needs a value"): users_mapping({"userName": user_name}) @@ -415,8 +426,8 @@ def test_a_column_property_writes_no_column(): leader_mapping(Leader.first_text) assert [str(warning.message).split(" needs")[0] for warning in caught] == [ - "The column members.first", - "The column members.last", + "The field 'members.first'", + "The field 'members.last'", ] @@ -465,7 +476,7 @@ class Secrets(Extension): ) def test_entries_the_schema_makes_write_only_are_refused(path, attributes): """A client never reads them back, so a write would lose them.""" - with pytest.raises(ValueError, match="cannot hold write-only values"): + with pytest.raises(ValueError, match="cannot hold values hidden from clients"): ResourceMapping( User[Secrets], UserRecord, @@ -549,7 +560,7 @@ def test_the_entries_of_a_many_cannot_hold_write_only_values(): emails = Many( UserRecord.emails, {"value": EmailRecord.value, "type": EmailRecord.type} ) - with pytest.raises(ValueError, match="cannot hold write-only values"): + with pytest.raises(ValueError, match="cannot hold values hidden from clients"): ResourceMapping( SecretUser, UserRecord, @@ -570,7 +581,9 @@ def test_the_entries_of_a_many_are_all_written_or_all_read_only(): "value": EmailRecord.value, "display": Attribute(EmailRecord.value, writable=False), } - with pytest.raises(ValueError, match="all written or all read-only"): + with pytest.raises( + ValueError, match="cannot hold a read-only value next to written ones" + ): users_mapping({"emails": Many(UserRecord.emails, emails)}) @@ -627,7 +640,7 @@ def test_many_needs_the_delete_orphan_cascade(): def test_an_attribute_is_mapped_to_a_column(): """A plain value cannot be read from a record.""" - with pytest.raises(ValueError, match="column or a hybrid property"): + with pytest.raises(ValueError, match="cannot be mapped to"): person_mapping(userName="user_name") @@ -819,7 +832,7 @@ def test_an_attribute_never_returned_is_concealed(): (token,) = hidden.attributes assert (token.mutability, token.returned, token.required) == ( - Mutability.write_only, + Mutability.read_write, Returned.never, Required.false, ) @@ -877,9 +890,13 @@ def test_an_immutable_attribute_never_returned_is_published_optional(path): (_, hidden) = hidden_mapping(path, UserRecord.user_name).schemas() (attribute,) = hidden.attributes - for published in (attribute, *(attribute.sub_attributes or [])): - assert (published.mutability, published.returned, published.required) == ( - Mutability.immutable, + assert (attribute.mutability, attribute.returned, attribute.required) == ( + Mutability.immutable, + Returned.never, + Required.false, + ) + for published in attribute.sub_attributes or []: + assert (published.returned, published.required) == ( Returned.never, Required.false, ) @@ -907,19 +924,18 @@ def test_a_value_clients_never_read_makes_no_complex_attribute_required(): assert mapping._column(f"{HIDDEN}:plate.serial").concealed -def test_a_write_only_value_of_an_immutable_attribute_can_change(): +def test_a_write_only_value_of_an_immutable_attribute_can_be_hashed(): """The schema makes the secret write-only, which wins over the immutable certificate.""" - column = hidden_mapping("cert.secret", UserRecord.title)._column( + column = hidden_mapping("cert.secret", UserRecord.pin_hash)._column( f"{HIDDEN}:cert.secret" ) assert column.concealed - assert not column.immutable def test_an_attribute_clients_never_read_nor_the_storage_writes_is_refused(): """A client could neither read the serial back nor change it.""" - with pytest.raises(ValueError, match="neither read nor written"): + with pytest.raises(ValueError, match="Clients could neither read nor write"): hidden_mapping("serial", Attribute(UserRecord.title, writable=False)) @@ -978,7 +994,7 @@ def test_a_computed_column_is_published_read_only(): def test_a_computed_column_cannot_hold_a_value_clients_never_read(): """A client could neither read the password back nor set it.""" - with pytest.raises(ValueError, match="neither read nor written"): + with pytest.raises(ValueError, match="Clients could neither read nor write"): person_mapping(password=Person.shout) diff --git a/tests/test_parity.py b/tests/test_parity.py new file mode 100644 index 0000000..1ee5f65 --- /dev/null +++ b/tests/test_parity.py @@ -0,0 +1,134 @@ +import pytest +from scim2_models import Group +from scim2_models import PreconditionFailedException +from scim2_models import SearchRequest + +from scim2_sqlalchemy import Attribute +from scim2_sqlalchemy import Link +from scim2_sqlalchemy import Many +from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import SqlAlchemyStorage + +from .plain import PLAIN_MAPPINGS +from .plain import GeneratedVersionRecord +from .plain import PlainUserRecord +from .plain import plain_groups_mapping +from .plain import plain_users_mapping + + +def test_a_mapping_without_version_needs_a_version_key(session): + with pytest.raises(ValueError, match="'User' has no version, so the storage needs"): + SqlAlchemyStorage(PLAIN_MAPPINGS, lambda: session) + + +def test_a_mapping_without_version_refuses_an_empty_version_key(session): + """An empty key would let anyone compute the version of hidden values.""" + with pytest.raises(ValueError, match="needs a version_key"): + SqlAlchemyStorage(PLAIN_MAPPINGS, lambda: session, version_key=b"") + + +def test_a_version_the_database_generates_needs_a_modification_date(): + """Without a date, the storage counts the writes of links in the version itself.""" + with pytest.raises(ValueError, match="which the database cannot generate"): + ResourceMapping( + Group, + GeneratedVersionRecord, + { + "id": GeneratedVersionRecord.id, + "displayName": GeneratedVersionRecord.display_name, + }, + version=GeneratedVersionRecord.version, + ) + + +def test_a_counter_changes_when_only_the_links_change( + storage_factory, user_type, group_type, provider +): + """Without a modification date, a write of the members alone still counts.""" + mappings = { + "User": plain_users_mapping(), + "Group": plain_groups_mapping(version=PLAIN_MAPPINGS["Group"].record.version), + } + storage = storage_factory(mappings, version_key=b"secret") + user_model = provider.model_for(user_type) + group_model = provider.model_for(group_type) + alice = storage.create(user_type, user_model(user_name="alice")) + group = storage.create(group_type, group_model(display_name="admins")) + + updated = storage.update( + group_type, + group_model(id=group.id, display_name="admins", members=[{"value": alice.id}]), + ) + + assert updated.meta.version != group.meta.version + assert updated.meta.version.startswith('W/"') + + +def test_a_hash_version_refuses_an_outdated_write(storage_factory, user_type, provider): + storage = storage_factory(PLAIN_MAPPINGS, version_key=b"secret") + user_model = provider.model_for(user_type) + alice = storage.create(user_type, user_model(user_name="alice")) + storage.update(user_type, user_model(id=alice.id, user_name="alice", title="Boss")) + + with pytest.raises(PreconditionFailedException): + storage.delete(user_type, alice.id, expected_version=alice.meta.version) + + +def test_an_entry_is_read_with_its_constants(storage_factory, user_type, provider): + storage = storage_factory(PLAIN_MAPPINGS, version_key=b"secret") + user_model = provider.model_for(user_type) + storage.create( + user_type, + user_model(user_name="alice", emails=[{"value": "alice@example.com"}]), + ) + + (alice,) = storage.search( + [user_type], SearchRequest(filter='emails[type eq "work"]') + ).resources + + assert [(e.value, e.type, e.primary) for e in alice.emails] == [ + ("alice@example.com", "work", True) + ] + + +@pytest.mark.parametrize("sort_order", ["ascending", "descending"]) +def test_a_sort_on_a_constant_orders_the_users_without_entry_apart( + storage_factory, user_type, provider, sort_order +): + """A constant sorts as the value of the entry, and as no value without entry.""" + storage = storage_factory(PLAIN_MAPPINGS, version_key=b"secret") + user_model = provider.model_for(user_type) + storage.create(user_type, user_model(user_name="alice")) + storage.create( + user_type, user_model(user_name="bob", emails=[{"value": "bob@example.com"}]) + ) + search_request = SearchRequest(sort_by="emails.primary", sort_order=sort_order) + everyone = storage.search([user_type], SearchRequest()).resources + + page = storage.search([user_type], search_request) + + assert [search_request.sort_value(r) for r in page.resources] == [ + search_request.sort_value(r) for r in search_request.sort(everyone) + ] + + +def test_the_declarations_keep_their_relationship_and_expression(): + attribute = Attribute(PlainUserRecord.title, writable=False) + many = Many(PlainUserRecord.groups, PlainUserRecord.title) + link = Link(PlainUserRecord.groups, "Group") + + assert attribute.expression is PlainUserRecord.title + assert many.relationship is PlainUserRecord.groups + assert link.relationship is PlainUserRecord.groups + + +def test_a_write_counts_once(storage, user_type, provider): + """The counter of a written record goes up by one, whatever changes.""" + user_model = provider.model_for(user_type) + alice = storage.create(user_type, user_model(user_name="alice")) + + updated = storage.update( + user_type, user_model(id=alice.id, user_name="alice", title="Boss") + ) + + assert (alice.meta.version, updated.meta.version) == ('W/"1"', 'W/"2"') diff --git a/tests/test_storage.py b/tests/test_storage.py index 2553068..2ef0d8e 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -822,7 +822,7 @@ def test_a_column_the_database_numbers_needs_no_value( def test_another_integrity_error_goes_through(storage_factory, user_type): """An integrity error unrelated to unique values is not a 409.""" - with pytest.warns(UserWarning, match="users.user_name needs a value"): + with pytest.warns(UserWarning, match="'users.user_name' needs a value"): users = users_mapping({"userName": None}) storage = storage_factory({"User": users, "Group": groups_mapping()}) @@ -1108,7 +1108,7 @@ def test_an_identifier_is_found_by_its_exact_text( ) ) session.flush() - with pytest.warns(UserWarning, match="users.user_name needs a value"): + with pytest.warns(UserWarning, match="'users.user_name' needs a value"): mapping = users_mapping( {"id": UserRecord.user_name, "userName": UserRecord.display_name} ) diff --git a/uv.lock b/uv.lock index 1fe47fb..9db3a9d 100644 --- a/uv.lock +++ b/uv.lock @@ -1435,14 +1435,14 @@ wheels = [ [[package]] name = "scim2-server" -version = "0.8.9" +version = "0.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "scim2-models" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/02/34/d308685d2c491e34812301d83dbd24730279f23dbda63421ce3347381a6f/scim2_server-0.8.9.tar.gz", hash = "sha256:21946681ab14746732ddc59201d0493c276d06d2c01902a5da1b6b4b4dccb41c", size = 73743, upload-time = "2026-11-26T10:59:57.398Z" } +sdist = { url = "https://files.pythonhosted.org/packages/83/1d/29fb908e3c6cf5278ebf184e42757a634ce799fef332dfd4f8b793c5b1bc/scim2_server-0.9.0.tar.gz", hash = "sha256:2f7f6c34a9483c4a96ff5f65978a89e0f2e759fdc12dc5c03b6f517330d5b012", size = 90228, upload-time = "2026-11-27T08:53:54.929Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2d/1d/175c71451ce2ee91b490dc23a988aec3ccc88cf7ef45aeb9965276e34282/scim2_server-0.8.9-py3-none-any.whl", hash = "sha256:f701de00f104f620145d2c6257fcd3e4410255e7c1a74ca2608071b431c76faa", size = 77812, upload-time = "2026-11-26T10:59:56.017Z" }, + { url = "https://files.pythonhosted.org/packages/57/e6/0303d934ffd1c5101454b6bc74cd3bcfd40c65cc6c12d960d0bb9218afda/scim2_server-0.9.0-py3-none-any.whl", hash = "sha256:fde186347764c941400c08eba6ae3d5022fbfe76aa83e63d14d54f8456e4148e", size = 97077, upload-time = "2026-11-27T08:53:53.534Z" }, ] [package.optional-dependencies] @@ -1496,7 +1496,7 @@ doc = [ [package.metadata] requires-dist = [ { name = "scim2-models", specifier = ">=0.12.7" }, - { name = "scim2-server", specifier = ">=0.8.9" }, + { name = "scim2-server", specifier = ">=0.9.0" }, { name = "sqlalchemy", specifier = ">=2.0.41" }, { name = "sqlalchemy", extras = ["asyncio"], marker = "extra == 'asyncio'", specifier = ">=2.0.41" }, ] @@ -1515,7 +1515,7 @@ dev = [ { name = "pytest-mysql", specifier = ">=5.0.1" }, { name = "pytest-postgresql", specifier = ">=9.1.0" }, { name = "scim2-client", specifier = ">=0.14.0" }, - { name = "scim2-server", extras = ["testing"], specifier = ">=0.8.9" }, + { name = "scim2-server", extras = ["testing"], specifier = ">=0.9.0" }, { name = "scim2-tester", extras = ["testing"], specifier = ">=0.6.2" }, { name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2.0.41" }, { name = "tox-uv", specifier = ">=1.36.0" },