diff --git a/doc/_examples/intranet/models.py b/doc/_examples/intranet/models.py index 37dcb03..25eab83 100644 --- a/doc/_examples/intranet/models.py +++ b/doc/_examples/intranet/models.py @@ -1,4 +1,4 @@ -"""The tables of an intranet application, before it serves SCIM.""" +"""The tables of an intranet application, ready to serve SCIM.""" import datetime import hashlib @@ -6,6 +6,7 @@ import uuid from sqlalchemy import Column +from sqlalchemy import Computed from sqlalchemy import ForeignKey from sqlalchemy import Table from sqlalchemy import func @@ -15,6 +16,8 @@ from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship +from scim2_sqlalchemy import comparison_key + def hash_password(password): salt = os.urandom(16) @@ -41,7 +44,10 @@ class Account(Base): id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) external_id: Mapped[str | None] - login: Mapped[str] = mapped_column(unique=True) + login: Mapped[str] + login_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("login"), persisted=True), unique=True + ) first_name: Mapped[str | None] last_name: Mapped[str | None] active: Mapped[bool | None] = mapped_column(default=True) diff --git a/doc/_examples/intranet/projects.py b/doc/_examples/intranet/projects.py index 68d2c7a..c877310 100644 --- a/doc/_examples/intranet/projects.py +++ b/doc/_examples/intranet/projects.py @@ -18,6 +18,7 @@ from scim2_models import User from scim2_server.utils import load_default_service_provider_config from sqlalchemy import Column +from sqlalchemy import Computed from sqlalchemy import ForeignKey from sqlalchemy import Table from sqlalchemy.orm import Mapped @@ -28,6 +29,7 @@ from scim2_sqlalchemy import Many from scim2_sqlalchemy import ResourceMapping from scim2_sqlalchemy import SqlAlchemyStorage +from scim2_sqlalchemy import comparison_key from .models import Account from .models import Base @@ -68,7 +70,10 @@ class ProjectRecord(Base): __tablename__ = "projects" id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) - code: Mapped[str] = mapped_column(unique=True) + code: Mapped[str] + code_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("code"), persisted=True), unique=True + ) title: Mapped[str | None] created_at: Mapped[datetime.datetime] updated_at: Mapped[datetime.datetime] diff --git a/doc/changelog.rst b/doc/changelog.rst index fadeda5..5da9f2e 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,6 +1,27 @@ Changelog ========= +[Unreleased] +------------ + +Added +^^^^^ +- :func:`~scim2_sqlalchemy.comparison_key` gives the expression of a unique column for an + attribute that ignores the case, such as ``userName``. +- The storage warns with :exc:`~scim2_sqlalchemy.UniqueConstraintWarning` about a unique attribute + that no unique constraint covers. +- A 409 tells the attribute, but never the value. + +Changed +^^^^^^^ +- The database checks the unique values, so two concurrent writes cannot take the same value. + Give each unique attribute a unique constraint. Values and identifiers are no longer checked + across resource types. +- :func:`~scim2_sqlalchemy.generate_mappings` gives a unique constraint to each unique attribute. +- :meth:`~scim2_sqlalchemy.SqlAlchemyStorage.generate_id` can run for a resource that the + database then refuses. +- scim2-server 0.11.0 or later is required. + [0.5.0] - 2026-11-28 -------------------- diff --git a/doc/explanation.rst b/doc/explanation.rst index 930a870..87955e7 100644 --- a/doc/explanation.rst +++ b/doc/explanation.rst @@ -67,7 +67,7 @@ receives, or the default policy without a provider. It reproduces the comparison as the database allows: - SQLite runs Python functions. The storage gives each connection a SQL function that calls the key, - so filters, sorts and uniqueness checks compare exactly as in Python, whatever the comparison key. + so filters and sorts compare exactly as in Python, whatever the comparison key. The function runs once for each row, and no index serves it. The ``co``, ``sw`` and ``ew`` filters use ``instr()`` and ``substr()``, since the ``LIKE`` of SQLite ignores the case of ASCII letters, even for a ``caseExact`` attribute. @@ -85,7 +85,7 @@ as the database allows: the ``utf8mb4_uca1400_nopad_as_cs`` collation, the only one under which it lowers the recent letters. It differs from Python for the same letters as PostgreSQL. MariaDB has no ``normalize()``: only the value of a filter is normalized to NFC, so a stored string written in - another form, such as NFD, matches neither filters nor uniqueness checks. MariaDB has no index on + another form, such as NFD, matches no filter. MariaDB has no index on an expression either: an index that serves these filters is an index on a virtual generated column, with the same expression. The storage needs MariaDB 10.10, the first version with the ``uca1400`` collations, and refuses MySQL. With a comparison key other than the default one, the @@ -195,40 +195,64 @@ version of the group, but not the version of the user, whose ``groups`` change t user does not change the version of its groups either. A client may then get a 304 for a resource that changed. -Unique values are checked twice -------------------------------- - -Before a write, the storage searches for another record holding a unique value of the resource, -such as its ``userName``, and answers 409 when it finds one. The search follows the case rules of -the attribute, so ``BJensen`` clashes with ``bjensen``, which a plain unique constraint does not -catch. +The database checks the unique values +------------------------------------- + +The storage does not search for a unique value before a write. Two concurrent writes could both +pass the search and both store the same value. The database checks the unique values instead, +with a unique constraint, when the storage flushes the write. The storage answers 409 when the +constraint refuses a value. The detail of the 409 tells the attribute, such as +``Uniqueness conflict with attribute userName``, but never the value. It tells the attribute when +the constraint covers one column, and that column holds the attribute. A constraint that the +application adds for its own reasons gives a 409 without attribute. + +The constraint must refuse two values that the filters find equal. Otherwise a filter +``userName eq "bjensen"`` finds two users. A ``caseExact`` attribute needs a unique column. An +attribute that ignores the case, such as ``userName``, needs a unique column computed with +:func:`~scim2_sqlalchemy.comparison_key`. This function writes the expression that the filters +compare, so the column and the filters agree: + +- on PostgreSQL and MariaDB, they agree for every letter; +- on SQLite, the filters call the comparison key of the policy, but the computed column only + lowers the ASCII letters. ``Élise`` and ``élise`` are then two values for the constraint, and + one value for the filters. + +A value in NFD and the same value in NFC are one value for the filters on PostgreSQL and SQLite, +but two values for a unique column of a ``caseExact`` attribute, which compares the code points. +The same goes for the computed column on SQLite and MariaDB. + +A constraint stricter than the filters gives a 409 on values the filters tell apart. This happens +on MariaDB, whose default collations ignore the case and the accents: ``José`` clashes with +``Jose``. A ``caseExact`` column needs a binary collation, such as ``utf8mb4_nopad_bin``, so that +``Babs`` and ``babs`` remain two values. A unique value can be below an attribute, such as ``emails.value``. Each value of a multi-valued -attribute counts on its own, wherever the mapping stores it: in a column, in an -:class:`~scim2_sqlalchemy.Entry`, in the entries of a :class:`~scim2_sqlalchemy.Many`, or as the -target of a :class:`~scim2_sqlalchemy.Link`. A resource may hold the same value twice. Per -:rfc:`7643` erratum 8279, the search covers every resource type whose schema holds the attribute. -The schema cannot make unique a value that clients never read back: the mapping refuses it, as a -409 would tell that another resource holds the value. +attribute counts on its own, so the constraint goes where the mapping stores the value: on a +column of the record, on the column of an :class:`~scim2_sqlalchemy.Entry`, or on the column of the +entries of a :class:`~scim2_sqlalchemy.Many`. For a :class:`~scim2_sqlalchemy.Link`, the +constraint goes on the foreign key that links to the other record. The storage deletes the old +entries before it inserts the new ones, so a resource that keeps its value, or swaps two values, +gets no 409. scim2-server refuses a resource that holds the same unique value twice, with a 400, +before the storage writes it. + +A constraint covers one table. A value is then unique among the resources of one type. Per +:rfc:`7643` erratum 8279, a value would be unique among all the resource types whose schema holds +its attribute: the storage does not check it, unless these resource types share a table. The same +goes for the ``id``, which :rfc:`RFC 7643 §3.1 <7643#section-3.1>` makes unique across all the +resource types. The primary key only checks it in its table, so the identifiers need to be UUIDs, +or to come from a sequence that every table shares. + +The storage reads the constraints of each mapping when it is created, and warns with a +:exc:`~scim2_sqlalchemy.UniqueConstraintWarning` about a unique attribute that no constraint +covers. It reads the constraints that the SQLAlchemy models declare, not those of the database. A +migration that is not applied yet passes the check, and an index that a migration creates outside +the models gets the warning. Filter the warning in that case. -A unique constraint of the database remains the guard against two concurrent writes. When a flush -fails on a unique constraint, the storage answers 409. This also holds when the constraint is -stricter than the search: under a collation that ignores the accents, as the default ones of -MariaDB do, ``José`` clashes with ``Jose``. A flush that fails on a foreign key also gets a 409, -such as deleting a resource that a record outside SCIM still refers to. Any other +The schema cannot make unique a value that clients never read back: the mapping refuses it, as a +409 would tell that another resource holds the value. A flush that fails on a foreign key also +gets a 409, such as deleting a resource that a record outside SCIM still refers to. Any other :exc:`~sqlalchemy.exc.IntegrityError` goes through unchanged. -:func:`~scim2_sqlalchemy.generate_mappings` puts a unique constraint on the unique columns of the -records only. Two concurrent writes can then take the same value of an entry. An application can -add a unique index to the table of the entries. The storage deletes the old entries before it -inserts the new ones, so the index accepts a resource that keeps its value. The index also refuses -a value repeated in one resource, which SCIM allows. - -An update only checks the unique values it changes. Another application may have stored values -that clash under the case rules of SCIM, such as ``alice`` and ``Alice``. Each resource then -remains writable while it keeps its value. Writing ``ALICE`` keeps the value too, as -``userName`` is not ``caseExact``. - The application owns the transaction ------------------------------------ diff --git a/doc/how-to/compare-strings.rst b/doc/how-to/compare-strings.rst index e25dd33..35d97d4 100644 --- a/doc/how-to/compare-strings.rst +++ b/doc/how-to/compare-strings.rst @@ -39,7 +39,8 @@ with their plain form: - the superscripts and the subscripts: ``x²`` becomes ``x2``. The stored values keep their form: only the comparisons change. More values then compare equal. A -filter on ``BJENSEN`` finds the user ``bjensen``, and a second user named ``bjensen`` is refused: +filter on ``BJENSEN`` finds the user ``bjensen``. The unique constraint of ``userName`` does not +follow the comparison key, so a second user named ``bjensen`` is accepted: .. doctest:: :hide: @@ -63,7 +64,7 @@ filter on ``BJENSEN`` finds the user ``bjensen``, and a second use >>> response.json["totalResults"] 1 >>> client.post("/v2/Users", json={"userName": "bjensen"}).status_code - 409 + 201 .. doctest:: :hide: @@ -83,13 +84,14 @@ The comparisons happen in two places: - :doc:`scim2-models ` and :doc:`scim2-server ` compare in Python, with the comparison key itself. They do so for the path filters of PATCH requests, such as ``emails[value eq "…"]``, and to find the values a PATCH request adds or removes. -- The storage compares in SQL, for the filters and the sorts of searches, and for the uniqueness - checks. +- The storage compares in SQL, for the filters and the sorts of searches. +- The database compares in its unique constraints. A unique column computed with + :func:`~scim2_sqlalchemy.comparison_key` follows the default comparison key, never another one. Both give the same results only when the database follows the comparison key: -- On SQLite, the storage calls the comparison key for each row, and follows it exactly. No index - serves these filters. +- On SQLite, the storage calls the comparison key for each row, and follows it exactly in the + filters. No index serves these filters. - On PostgreSQL and MariaDB, the storage cannot call the comparison key. It compares the strings in the form of the default comparison key, and warns when the policy sets another one. With the comparison key of this guide, a search on ``BJENSEN`` finds nothing, and ``bjensen`` can be created next to diff --git a/doc/how-to/generate-the-tables.rst b/doc/how-to/generate-the-tables.rst index d2ece4c..a997419 100644 --- a/doc/how-to/generate-the-tables.rst +++ b/doc/how-to/generate-the-tables.rst @@ -105,6 +105,10 @@ the schemas, so the migration tool finds the same names from a run to the next: Pass ``prefix`` to start the name of every table with it, such as ``prefix="scim_"``, so that the tables of SCIM stay apart from the other tables of the database. +A unique attribute gets a unique constraint. A unique string that ignores the case, such as +``userName``, gets a second column computed with :func:`~scim2_sqlalchemy.comparison_key`, such +as ``user_name_key``, and the constraint goes on it. + On MariaDB, a string is stored in a ``TEXT`` column under the ``utf8mb4_nopad_bin`` collation, so that its unique constraint follows the code points, as the storage does. A date keeps its microseconds. diff --git a/doc/how-to/map-a-data-model.rst b/doc/how-to/map-a-data-model.rst index ae86217..e4e520c 100644 --- a/doc/how-to/map-a-data-model.rst +++ b/doc/how-to/map-a-data-model.rst @@ -68,6 +68,46 @@ writes, such as a column left out of the mapping or mapped as read-only. Creatin would then fail in the database. The setter of a property is taken to write the columns that its expression reads. +Declare the unique constraints +------------------------------ + +The database checks the attributes that the schema makes unique, such as ``userName``. Give each +of them a unique constraint in the model: + +- a ``caseExact`` attribute: ``unique=True`` on its column, or a + :class:`~sqlalchemy.schema.UniqueConstraint` or a unique :class:`~sqlalchemy.schema.Index` on + this column alone; +- an attribute that ignores the case: a second column, computed with + :func:`~scim2_sqlalchemy.comparison_key`, and ``unique=True``; +- a unique value of a :class:`~scim2_sqlalchemy.Many`: the same, on the column of the entries; +- a unique :class:`~scim2_sqlalchemy.Link`: ``unique=True`` on the foreign key that links to the + other record, in the association table or in the record. + +The ``code`` of a project ignores the case, so the project model computes ``code_key`` from it: + +.. literalinclude:: ../_examples/intranet/projects.py + :language: python + :start-at: code: Mapped[str] + :end-before: title: Mapped + +On MariaDB, give a ``caseExact`` column a binary collation, such as ``utf8mb4_nopad_bin``. The +default collations ignore the case, so their unique constraint refuses ``babs`` next to ``Babs``. + +The storage warns with a :exc:`~scim2_sqlalchemy.UniqueConstraintWarning` about a unique +attribute that no constraint of the model covers. It does not see an index that a migration +creates outside the models. In that case, filter the warning for this attribute: + +.. code-block:: python + + import warnings + from scim2_sqlalchemy import UniqueConstraintWarning + + warnings.filterwarnings( + "ignore", message=".*:Project:code,", category=UniqueConstraintWarning + ) + +For what each database compares, read :doc:`../explanation`. + Map an extension ---------------- diff --git a/doc/overview.rst b/doc/overview.rst index f9ee6f8..fe5cef1 100644 --- a/doc/overview.rst +++ b/doc/overview.rst @@ -30,11 +30,14 @@ account has a login, a name, a password hash, email addresses and teams: :language: python :pyobject: Account -The models need four things for SCIM: +The models need five things for SCIM: - a primary key unique across the accounts and the teams, here a UUID. Per :rfc:`RFC 7643 §3.1 <7643#section-3.1>`, two resources never share an ``id``, even of different types; +- a unique column computed from the login with :func:`~scim2_sqlalchemy.comparison_key`, here + ``login_key``. ``userName`` ignores the case, so the database refuses ``BJensen`` when + ``bjensen`` exists; - a column for the identifier the identity provider gives, here ``external_id``; - a creation date and a modification date, here ``created_at`` and ``updated_at``; - a :ref:`version counter `, declared as the diff --git a/doc/reference/errors.rst b/doc/reference/errors.rst index 0cf0c6f..44727f4 100644 --- a/doc/reference/errors.rst +++ b/doc/reference/errors.rst @@ -15,8 +15,8 @@ into error responses: - The stored version differs from ``expected_version``, or another transaction changed the record before the write. * - :class:`~scim2_models.UniquenessException` - - Another resource holds a unique value of the resource, such as its ``userName``, or a - unique constraint of the database refuses a value. + - A unique constraint of the database refuses a value, such as a ``userName`` that another + user holds. The detail tells the attribute when the constraint covers it alone. * - :class:`~scim2_models.InvalidValueException` - The resource holds a value no mapping stores, an entry of a :class:`~scim2_sqlalchemy.Link` without ``value``, a link to an unknown resource, or a diff --git a/doc/reference/mapping.rst b/doc/reference/mapping.rst index f6728a3..a445c62 100644 --- a/doc/reference/mapping.rst +++ b/doc/reference/mapping.rst @@ -1,8 +1,8 @@ Mapping ======= -The classes describing how SCIM resources are stored in SQLAlchemy models, and the function -generating them from the resource types. +The classes describing how SCIM resources are stored in SQLAlchemy models, the function +generating them from the resource types, and the expression of the unique columns. .. autoclass:: scim2_sqlalchemy.ResourceMapping :members: schemas @@ -18,3 +18,7 @@ generating them from the resource types. .. autoclass:: scim2_sqlalchemy.Link .. autofunction:: scim2_sqlalchemy.generate_mappings + +.. autofunction:: scim2_sqlalchemy.comparison_key + +.. autoexception:: scim2_sqlalchemy.UniqueConstraintWarning diff --git a/pyproject.toml b/pyproject.toml index be7e01f..2d908b4 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.10.0", + "scim2-server>=0.11.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.10.0", + "scim2-server[testing]>=0.11.0", "scim2-tester[testing]>=0.6.2", "tox-uv>=1.36.0", "werkzeug>=3.1.8", @@ -120,6 +120,7 @@ doctest_optionflags = "ALLOW_UNICODE ELLIPSIS NORMALIZE_WHITESPACE" filterwarnings = [ "error::scim2_tester.testing.ScimDeviationWarning", "error:The column .* needs a value:UserWarning", + "error:No unique constraint covers:UserWarning", ] [tool.uv] diff --git a/src/scim2_sqlalchemy/__init__.py b/src/scim2_sqlalchemy/__init__.py index 722ea81..200e133 100644 --- a/src/scim2_sqlalchemy/__init__.py +++ b/src/scim2_sqlalchemy/__init__.py @@ -1,3 +1,5 @@ +from .constraints import UniqueConstraintWarning +from .constraints import comparison_key from .generation import generate_mappings from .mapping import Attribute from .mapping import Entry @@ -17,5 +19,7 @@ "Link", "ResourceMapping", "SqlAlchemyStorage", + "UniqueConstraintWarning", + "comparison_key", "generate_mappings", ] diff --git a/src/scim2_sqlalchemy/comparison.py b/src/scim2_sqlalchemy/comparison.py index d419231..e5804f4 100644 --- a/src/scim2_sqlalchemy/comparison.py +++ b/src/scim2_sqlalchemy/comparison.py @@ -11,14 +11,12 @@ from scim2_models.path import CompareOperator from sqlalchemy import ColumnElement from sqlalchemy import Dialect -from sqlalchemy import FunctionElement from sqlalchemy import String from sqlalchemy import func from sqlalchemy import literal -from sqlalchemy import literal_column -from sqlalchemy.ext.compiler import compiles -from sqlalchemy.sql.compiler import SQLCompiler +from .constraints import _mariadb_form +from .constraints import _postgresql_form from .mapping import _MARIADB from .mapping import ResourceMapping from .mapping import _Column @@ -111,26 +109,7 @@ class _Normalizer(_Formed): def _form(self, column: _Column, expression: Any) -> ColumnElement[Any]: """Normalize a string expression to NFC, lowered if the column ignores the case, under the C collation.""" - normalized = func.normalize(expression, literal_column("NFC"), type_=String) - if column.casefolded: - normalized = func.normalize( - func.lower(normalized), literal_column("NFC"), type_=String - ) - return normalized.collate("C") - - -class _Utf8mb4(FunctionElement[str]): - """A string converted to utf8mb4, the character set of the MariaDB collations.""" - - type = String() - inherit_cache = True - - -@compiles(_Utf8mb4) -def _compile_utf8mb4(element: _Utf8mb4, compiler: SQLCompiler, **kw: Any) -> str: - """Write the conversion of a string to utf8mb4.""" - (expression,) = element.clauses - return f"CONVERT({compiler.process(expression, **kw)} USING utf8mb4)" + return _postgresql_form(expression, column.casefolded) class _CodePoints(_Formed): @@ -145,12 +124,7 @@ class _CodePoints(_Formed): def _form(self, column: _Column, expression: Any) -> ColumnElement[Any]: """Return a string expression in utf8mb4, lowered if the column ignores the case, under a binary collation.""" - converted: ColumnElement[Any] = _Utf8mb4(expression) - if column.casefolded: - converted = func.lower( - converted.collate("utf8mb4_uca1400_nopad_as_cs"), type_=String - ) - return converted.collate("utf8mb4_nopad_bin") + return _mariadb_form(expression, column.casefolded) class _KeyFunction(_Comparator): diff --git a/src/scim2_sqlalchemy/constraints.py b/src/scim2_sqlalchemy/constraints.py new file mode 100644 index 0000000..40d3a1f --- /dev/null +++ b/src/scim2_sqlalchemy/constraints.py @@ -0,0 +1,164 @@ +from typing import Any + +from sqlalchemy import Column +from sqlalchemy import ColumnElement +from sqlalchemy import FunctionElement +from sqlalchemy import String +from sqlalchemy import UniqueConstraint +from sqlalchemy import column as sql_column +from sqlalchemy import func +from sqlalchemy import literal_column +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.sql.compiler import SQLCompiler + + +class UniqueConstraintWarning(UserWarning): + """A unique attribute that no unique constraint of the database covers. + + The database checks the unique values, so the storage lets such an + attribute take a value that another resource holds. + """ + + +def _postgresql_form(expression: Any, casefolded: bool) -> ColumnElement[Any]: + """Return a string expression normalized to NFC, lowered if casefolded, under the C collation.""" + normalized = func.normalize(expression, literal_column("NFC"), type_=String) + if casefolded: + normalized = func.normalize( + func.lower(normalized), literal_column("NFC"), type_=String + ) + return normalized.collate("C") + + +class _Utf8mb4(FunctionElement[str]): + """A string converted to utf8mb4, the character set of the MariaDB collations.""" + + type = String() + inherit_cache = True + + +@compiles(_Utf8mb4) +def _compile_utf8mb4(element: _Utf8mb4, compiler: SQLCompiler, **kw: Any) -> str: + """Write the conversion of a string to utf8mb4.""" + (expression,) = element.clauses + return f"CONVERT({compiler.process(expression, **kw)} USING utf8mb4)" + + +def _mariadb_form(expression: Any, casefolded: bool) -> ColumnElement[Any]: + """Return a string expression in utf8mb4, lowered if casefolded, under a binary collation.""" + converted: ColumnElement[Any] = _Utf8mb4(expression) + if casefolded: + converted = func.lower( + converted.collate("utf8mb4_uca1400_nopad_as_cs"), type_=String + ) + return converted.collate("utf8mb4_nopad_bin") + + +class _ComparisonKey(FunctionElement[str]): + """The form in which the storage compares a string column that ignores the case.""" + + type = String() + inherit_cache = True + + @property + def source(self) -> str: + """Return the name of the column the key is computed from.""" + (column,) = self.clauses + return str(column.name) + + +@compiles(_ComparisonKey) +def _compile_key(element: _ComparisonKey, compiler: SQLCompiler, **kw: Any) -> str: + """Write the key with lower(), which only lowers ASCII letters on SQLite.""" + (column,) = element.clauses + return compiler.process(func.lower(column), **kw) + + +@compiles(_ComparisonKey, "postgresql") +def _compile_postgresql_key( + element: _ComparisonKey, compiler: SQLCompiler, **kw: Any +) -> str: + """Write the key as the PostgreSQL storage compares the strings.""" + (column,) = element.clauses + return compiler.process(_postgresql_form(column, True), **kw) + + +@compiles(_ComparisonKey, "mysql") +@compiles(_ComparisonKey, "mariadb") +def _compile_mariadb_key( + element: _ComparisonKey, compiler: SQLCompiler, **kw: Any +) -> str: + """Write the key as the MariaDB storage compares the strings.""" + (column,) = element.clauses + return compiler.process(_mariadb_form(column, True), **kw) + + +def comparison_key(column: str) -> ColumnElement[str]: + """Return the SQL expression of a column in the form the storage compares it, ignoring the case. + + A unique column computed from this expression refuses two values that the + filters of the storage find equal, such as ``bjensen`` and ``BJensen``. + Declare it for each unique attribute that ignores the case, such as + ``userName``: + + >>> from sqlalchemy import Computed + >>> from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + >>> from scim2_sqlalchemy import comparison_key + >>> class Base(DeclarativeBase): + ... pass + >>> class UserRecord(Base): + ... __tablename__ = "users" + ... id: Mapped[int] = mapped_column(primary_key=True) + ... user_name: Mapped[str] + ... user_name_key: Mapped[str | None] = mapped_column( + ... Computed(comparison_key("user_name"), persisted=True), unique=True + ... ) + + On MariaDB, give the column a binary collation, such as + ``utf8mb4_nopad_bin``: the default collations ignore the accents, and + refuse ``élise`` next to ``elise``. + + On SQLite, the expression only lowers the ASCII letters, while the filters + follow the comparison key of the policy: two values that differ by the + case of another letter, such as ``Élise`` and ``élise``, are both + accepted. + + :param column: The name of the column in its table. + """ + return _ComparisonKey(sql_column(column)) + + +def _unique_on(column: Column[Any]) -> bool: + """Tell whether a unique constraint of its table covers this column alone.""" + table = column.table + if column.unique or list(table.primary_key.columns) == [column]: + return True + constraints = [ + list(constraint.columns) + for constraint in table.constraints + if isinstance(constraint, UniqueConstraint) + ] + indexes = [list(index.expressions) for index in table.indexes if index.unique] + return [column] in constraints + indexes + + +def _key_columns(column: Column[Any]) -> list[Column[Any]]: + """Return the columns of its table computed from the comparison_key() of a column.""" + return [ + key + for key in column.table.columns + if key.computed is not None + and isinstance(key.computed.sqltext, _ComparisonKey) + and key.computed.sqltext.source == column.name + ] + + +def _constrained(column: Column[Any], casefolded: bool) -> bool: + """Tell whether a unique constraint refuses two values of a column that the storage finds equal. + + A column that ignores the case needs a unique column computed from its + comparison_key(). + """ + if not casefolded: + return _unique_on(column) + return any(_unique_on(key) for key in _key_columns(column)) diff --git a/src/scim2_sqlalchemy/generation.py b/src/scim2_sqlalchemy/generation.py index 444420d..fcf2082 100644 --- a/src/scim2_sqlalchemy/generation.py +++ b/src/scim2_sqlalchemy/generation.py @@ -17,6 +17,7 @@ from scim2_models import Uniqueness from sqlalchemy import Boolean from sqlalchemy import Column +from sqlalchemy import Computed from sqlalchemy import DateTime from sqlalchemy import Double from sqlalchemy import ForeignKey @@ -32,6 +33,7 @@ from sqlalchemy.orm import relationship from sqlalchemy.types import TypeEngine +from .constraints import comparison_key from .mapping import _MARIADB from .mapping import _MARIADB_TEXT from .mapping import Link @@ -418,8 +420,6 @@ def _build(self, name: str) -> _Class: key, attribute_urn, nullable=not required, - unique=attribute.uniqueness - in (Uniqueness.server, Uniqueness.global_), ) if mapped is not None: record_class.attributes.append((path, mapped)) @@ -453,23 +453,61 @@ def _column( urn: str, *, nullable: bool = True, - unique: bool = False, ) -> Callable[[], Any] | None: """Add the column of a simple attribute, and return what maps it, or None when it is not stored.""" decision = self.decisions.get(urn, False) if decision is False: return None key = _fit(key) + self._add_column( + record_class, + key, + self._type(attribute, decision), + attribute, + path, + nullable, + ) + return self._getter(name, key) + + @staticmethod + def _add_column( + record_class: _Class, + key: str, + sql_type: TypeEngine[Any], + attribute: Any, + path: str, + nullable: bool, + ) -> None: + """Add the column of an attribute, with the unique constraint the storage needs. + + A unique string ignoring the case gets a unique column computed from + its comparison key, as the storage compares its values. The key is a + string without length under a binary collation, whatever the type of + the attribute, so that it compares by code point and holds a value + that lowering makes longer. MariaDB refuses NOT NULL on a computed + column. + """ + unique = attribute.uniqueness in (Uniqueness.server, Uniqueness.global_) + casefolded = ( + attribute.type == SchemaAttribute.Type.string and not attribute.case_exact + ) record_class.add( key, mapped_column( - self._type(attribute, decision), - nullable=nullable, - unique=unique or None, + sql_type, nullable=nullable, unique=(unique and not casefolded) or None ), path, ) - return self._getter(name, key) + if unique and casefolded: + record_class.add( + _fit(f"{key}_key"), + mapped_column( + _string(), + Computed(comparison_key(key), persisted=True), + unique=True, + ), + path, + ) @staticmethod def _type(attribute: Any, decision: bool | TypeEngine[Any]) -> TypeEngine[Any]: @@ -584,11 +622,8 @@ def _values( ) -> None: """Add the child table of a multi-valued simple attribute, with a value column.""" child, key = self._child(name, record_class, path, key) - child.add( - "value", - mapped_column(self._type(attribute, self.decisions[urn]), nullable=False), - path, - ) + sql_type = self._type(attribute, self.decisions[urn]) + self._add_column(child, "value", sql_type, attribute, path, nullable=False) self._make(child) getter = self._getter(name, key) value = self._getter(child.name, "value") @@ -704,8 +739,10 @@ def generate_mappings( ``members`` of the groups. A multi-valued sub-attribute is not stored either, nor a write-only attribute other than a single string. A column holds ``NOT NULL`` for a required attribute of the core schema, and - ``UNIQUE`` for an attribute unique on the server. The table and column - names longer than 63 characters are shortened. + ``UNIQUE`` for an attribute unique on the server. A unique string that + ignores the case, such as ``userName``, gets a second column, computed + with :func:`~scim2_sqlalchemy.comparison_key` and ``UNIQUE``. The table + and column names longer than 63 characters are shortened. ``store`` decides how each attribute is kept. It receives the :class:`~scim2_models.AttributeBinding` of the attribute, and returns: diff --git a/src/scim2_sqlalchemy/mapping.py b/src/scim2_sqlalchemy/mapping.py index 25338ae..488eba4 100644 --- a/src/scim2_sqlalchemy/mapping.py +++ b/src/scim2_sqlalchemy/mapping.py @@ -23,6 +23,7 @@ from sqlalchemy import Dialect from sqlalchemy import Enum as SqlEnum from sqlalchemy import String +from sqlalchemy import Table from sqlalchemy import Uuid from sqlalchemy import cast from sqlalchemy import func @@ -42,6 +43,10 @@ from sqlalchemy.types import TypeDecorator from sqlalchemy.types import TypeEngine +from .constraints import UniqueConstraintWarning +from .constraints import _constrained +from .constraints import _key_columns + _MARIADB = ("mysql", "mariadb") """The names of the dialects connecting to MariaDB.""" @@ -102,6 +107,43 @@ def _table_column(expression: Any) -> Column[Any] | None: return column if isinstance(column, Column) else None +def _constrained_column(column: "_Column", collection: Any) -> bool: + """Tell whether a unique constraint covers a column, as the storage compares its values. + + The value of a Link is the identifier of a record, so the constraint + must cover the foreign key that links to it. A record holding the + foreign key to its owner has one owner. + """ + if collection is not None and not collection.owned: + relationship = collection.relationship_property + keys = _link_keys(relationship) + return relationship.direction is ONETOMANY or ( + len(keys) == 1 and _constrained(keys[0], casefolded=False) + ) + table_column = _table_column(column.expression) + return table_column is not None and _constrained(table_column, column.casefolded) + + +def _link_keys(relationship: RelationshipProperty[Any]) -> list[Any]: + """Return the foreign keys a link writes, none when the linked record holds the foreign key to its owner.""" + if relationship.direction is ONETOMANY: + return [] + if relationship.direction is MANYTOONE: + return list(relationship.local_columns) + pairs = relationship.secondary_synchronize_pairs or [] + return [column for _, column in pairs] + + +def _holding_columns(column: "_Column", collection: Any) -> list[Column[Any]]: + """Return the columns whose unique constraint refuses a value of an attribute.""" + if collection is not None and not collection.owned: + return _link_keys(collection.relationship_property) + table_column = _table_column(column.expression) + if table_column is None: + return [] + return [table_column, *_key_columns(table_column)] + + def _needs_value(column: Column[Any]) -> bool: """Whether a new row needs a value: the column holds no null, has no default, and the database does not number it.""" return ( @@ -458,6 +500,7 @@ def __init__( raise ValueError("\n".join(errors)) for problem in problems: warnings.warn(problem.message, stacklevel=2) + self._constraints_checked = False def schemas(self) -> list[Schema]: """Return the schemas of the resources, restricted to what the mapping stores. @@ -646,6 +689,57 @@ def _build_collection( ) return collection + def _check_constraints(self) -> None: + """Warn once about each unique attribute that no unique constraint covers, once its links are bound.""" + if self._constraints_checked: + return + self._constraints_checked = True + for urn in self._unconstrained_attributes(): + warnings.warn( + f"No unique constraint covers the unique attribute {urn}, " + "so two resources can hold the same value", + UniqueConstraintWarning, + stacklevel=4, + ) + + def _unique_fields(self) -> list[tuple[Any, Any]]: + """Return the columns of the unique attributes, with the collection holding each, or None.""" + unique = self.unique_attributes() + columns: list[tuple[Any, Any]] = [ + *((column, None) for column in self._columns.values()), + *( + (column, collection) + for collection in self._all_collections() + for column in collection.columns.values() + ), + ] + return [ + (column, collection) + for column, collection in columns + if column.binding.urn in unique + ] + + def _unconstrained_attributes(self) -> list[str]: + """Return the URN of the unique attributes that no unique constraint of the database covers.""" + return [ + column.binding.urn + for column, collection in self._unique_fields() + if not _constrained_column(column, collection) + ] + + def _unique_columns(self) -> dict[tuple[Table, str], AttributeBinding]: + """Return the unique attributes and the id, by the table and the name of a column whose unique constraint refuses their values.""" + return { + (key.table, key.name): column.binding + for column, collection in [(self._id, None), *self._unique_fields()] + for key in _holding_columns(column, collection) + } + + def _record_table(self) -> Table | None: + """Return the table holding the identifier, or None when a property gives it.""" + column = _table_column(self._id.expression) + return None if column is None else column.table + 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) diff --git a/src/scim2_sqlalchemy/query.py b/src/scim2_sqlalchemy/query.py index 791a64c..0e9c8c4 100644 --- a/src/scim2_sqlalchemy/query.py +++ b/src/scim2_sqlalchemy/query.py @@ -6,7 +6,6 @@ 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 InvalidPathException from scim2_models import ResponseParameters @@ -16,7 +15,6 @@ from scim2_server.mapping import Collection from scim2_server.mapping import Column from scim2_server.mapping.filters import entry_present -from scim2_server.mapping.filters import holds_any from scim2_server.mapping.filters import sort_target from scim2_server.mapping.filters import where from sqlalchemy import BigInteger @@ -471,51 +469,6 @@ def _load_statement( return statement.with_for_update() if locked else statement -def _id_taken_statement( - mapping: ResourceMapping, resource_id: str -) -> Select[Any] | None: - """Return the statement finding a record of a mapping with an identifier, or None when no record can have it.""" - key = _as_key(mapping._id, resource_id) - if key is None: - return None - condition = mapping._id.expression == _bound(mapping._id, key) - return select(mapping._id.expression).where(condition).limit(1) - - -def _taken_statement( - mapping: ResourceMapping, - binding: AttributeBinding, - values: list[Any], - comparator: _Comparator, - record: Any, -) -> Select[Any]: - """Return the statement finding a record of a mapping holding one of some unique values. - - record is the record an update writes, and None for a new resource. It is - left out, even when it is read through another mapping of its class. - """ - condition = holds_any( - mapping, _Predicates(comparator), comparator.policy, binding, values - ) - if record is not None: - condition = and_(condition, _other_than(mapping, record)) - return select(mapping._id.expression).where(condition).limit(1) - - -def _other_than(mapping: ResourceMapping, record: Any) -> ColumnElement[bool]: - """Return the condition that a record of a mapping is not the given one. - - Two classes share their records when their base classes map the same - table, such as two classes of a table, or of an inheritance. - """ - mapper: Mapper[Any] = inspect(mapping.record) - state = inspect(record) - if mapper.base_mapper.local_table is not state.mapper.base_mapper.local_table: - return true() - keys = zip(mapper.primary_key, state.identity, strict=True) - return not_(and_(*(column == key for column, key in keys))) - - def _links_statement(collection: Collection, ids: list[str]) -> Select[Any]: """Return the statement loading the records a Link links to.""" target = cast_type(ResourceMapping, collection.target) diff --git a/src/scim2_sqlalchemy/storage.py b/src/scim2_sqlalchemy/storage.py index f288738..91ef0cb 100644 --- a/src/scim2_sqlalchemy/storage.py +++ b/src/scim2_sqlalchemy/storage.py @@ -3,7 +3,6 @@ from collections.abc import Awaitable from collections.abc import Callable from collections.abc import Generator -from collections.abc import Iterator from collections.abc import Mapping from collections.abc import Sequence from contextlib import asynccontextmanager @@ -33,9 +32,9 @@ from scim2_server.storage import AsyncScimStorage from scim2_server.storage import ScimStorage from scim2_server.storage import SearchPage -from scim2_server.storage import unique_values +from scim2_server.storage import uniqueness_conflict from sqlalchemy import Dialect -from sqlalchemy import Select +from sqlalchemy import Table from sqlalchemy import inspect from sqlalchemy.exc import DBAPIError from sqlalchemy.orm import Session @@ -48,13 +47,11 @@ from .mapping import ResourceMapping from .mapping import _as_key from .mapping import _Column -from .query import _id_taken_statement from .query import _links_statement from .query import _load_statement from .query import _records_statement from .query import _root_statements from .query import _search_statements -from .query import _taken_statement if TYPE_CHECKING: from sqlalchemy.ext.asyncio import AsyncSession @@ -160,7 +157,7 @@ def _error_code(error: BaseException | None) -> Any: def _translate(exception: DBAPIError) -> None: - """Raise the SCIM error of a database error: 409 for a unique value taken or a foreign key broken, 412 for a record changed meanwhile. + """Raise the SCIM error of a database error: 409 for a foreign key broken, 412 for a record changed meanwhile. MariaDB rolls back the whole transaction on a record changed meanwhile. Rolling back to the savepoint then fails, and its error holds the first @@ -169,8 +166,6 @@ def _translate(exception: DBAPIError) -> None: code = _error_code(exception.orig) if code == _SAVEPOINT_GONE and isinstance(exception.__context__, DBAPIError): code = _error_code(exception.__context__.orig) - if code in _UNIQUE_VIOLATIONS: - raise UniquenessException from exception if code in _FOREIGN_KEY_VIOLATIONS: raise ConflictException( detail="Another record refers to this resource, or it refers to a missing one" @@ -179,6 +174,85 @@ def _translate(exception: DBAPIError) -> None: raise PreconditionFailedException from exception +def _violation(error: Any) -> tuple[str | None, str | None, list[str]]: + """Return the table, the constraint and the columns of a unique violation, as far as the database tells them. + + PostgreSQL tells the table and the constraint. MariaDB tells the + constraint at the end of its message, after the value, and MySQL + prefixes it with the table. SQLite tells the columns, or the index of an + expression. Another driver tells nothing the storage reads. + """ + diag = getattr(error, "diag", None) + if diag is not None: + return diag.table_name, diag.constraint_name, [] + message = str(error.args[-1]) + if isinstance(_error_code(error), int): + key = message.rpartition(" for key '")[2].removesuffix("'") + table, _, name = key.rpartition(".") + return table or None, name, [] + if getattr(error, "sqlite_errorname", None) is None: + return None, None, [] + failed = message.partition(": ")[2] + if failed.startswith("index '"): + return None, failed.removeprefix("index '").removesuffix("'"), [] + columns = [column.strip().partition(".") for column in failed.split(",")] + return columns[0][0], None, [column for _, _, column in columns] + + +def _constraint_columns(inspector: Any, table: Table, name: str) -> list[str]: + """Return the columns of a unique constraint, a unique index or the primary key of a table, by its name.""" + constraints = [ + *inspector.get_unique_constraints(table.name, schema=table.schema), + *( + index + for index in inspector.get_indexes(table.name, schema=table.schema) + if index["unique"] + ), + ] + for constraint in constraints: + if constraint["name"] == name: + return list(constraint["column_names"]) + primary = inspector.get_pk_constraint(table.name, schema=table.schema) + if name in (primary["name"], "PRIMARY"): + return list(primary["constrained_columns"]) + return [] + + +def _violated_columns( + connection: Any, error: Any, tables: list[Table], record: Table | None +) -> list[tuple[Table, str]]: + """Return the table and the name of each column of the constraint a unique violation breaks, or nothing when it is unclear. + + MariaDB names the constraint without its table, and two tables may have + a constraint of the same name, such as PRIMARY: the table of the record + comes first, as the database numbers the entries of the other tables. + """ + table_name, name, columns = _violation(error) + if columns: + return [ + (table, column) + for table in tables + if table.name == table_name + for column in columns + ] + if name is None: + return [] + inspector = inspect(connection) + matches = [ + (table, found) + for table in tables + if table_name in (None, table.name) + for found in [_constraint_columns(inspector, table, name)] + if found + ] + if len(matches) > 1: + matches = [(table, found) for table, found in matches if table is record] + if len(matches) != 1: + return [] + table, found = matches[0] + return [(table, column) for column in found] + + class _StorageBase: """What the synchronous and asynchronous storages share: everything but the queries.""" @@ -211,6 +285,17 @@ def __init__( 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) + for mapping in self.mappings.values(): + mapping._check_constraints() + + @staticmethod + def _conflict( + attributes: dict[tuple[Table, str], Any], columns: list[tuple[Table, str]] + ) -> UniquenessException: + """Return the 409 of a unique violation, telling the attribute when a single column of its constraint holds it.""" + if len(columns) == 1 and columns[0] in attributes: + return uniqueness_conflict(attributes[columns[0]]) + return UniquenessException() def _mapping(self, resource_type: ResourceType) -> ResourceMapping: """Return the mapping of a resource type.""" @@ -357,48 +442,6 @@ def _comparator(self, dialect: Dialect) -> _Comparator: ) return self._comparators[dialect.name] - def _unique_statements( - self, - resource: Resource[Any], - comparator: _Comparator, - stored: Resource[Any] | None, - record: Any, - ) -> Iterator[Select[Any]]: - """Yield the statements finding another record holding a unique value of the resource. - - Per RFC 7643 erratum 8279, a value is looked for in every mapping - storing its attribute, whatever their resource type. stored and record - are the resource an update changes and its record, and None for a new - one. A value the stored resource already holds is not checked: another - application may have stored a value that clashes with it, and the - record must remain writable. - """ - held = {} if stored is None else unique_values(stored, self._policy) - for urn, pairs in unique_values(resource, self._policy).items(): - kept = [comparable for _, comparable in held.get(urn, [])] - values = [ - value - for value, comparable in pairs - if comparable is not None and comparable not in kept - ] - if not values: - continue - for mapping in self.mappings.values(): - binding = mapping._unique_attributes().get(urn) - if binding is not None: - yield _taken_statement(mapping, binding, values, comparator, record) - - def _id_statements(self, resource_id: str) -> Iterator[Select[Any]]: - """Yield the statements finding a record of any mapping with an identifier. - - Per RFC 7643 §3.1, an identifier is unique across the resources of - every resource type. - """ - for mapping in self.mappings.values(): - statement = _id_taken_statement(mapping, resource_id) - if statement is not None: - yield statement - @staticmethod def _clear_entries(mapping: ResourceMapping, record: Any) -> bool: """Remove the entries a record owns before an update, and tell whether it had any. @@ -481,6 +524,11 @@ class SqlAlchemyStorage(_StorageBase, ScimStorage): of the transaction. :raises ValueError: When a resource type has no mapping, or when a mapping has no version and no key is given. + + The storage warns with a :exc:`~scim2_sqlalchemy.UniqueConstraintWarning` about each + unique attribute that no unique constraint of the models covers: the + database checks the unique values, so two resources could hold the same + value. """ supports_cursors = True @@ -527,9 +575,14 @@ def generate_id( ... return str(uuid.uuid5(USERS, resource.user_name)) The storage calls it once for each new resource, after checking the - resource, and does not call it for a resource it refuses. Per - :rfc:`7643#section-3.1`, an identifier is unique across all the resource - types: an identifier that another resource holds raises a 409. + resource. The database checks the unique values when the storage + writes the resource, after this method. So this method can run for a + resource that the database then refuses with a 409. + + An identifier that another resource of the same type holds raises a + 409. Per :rfc:`7643#section-3.1`, an identifier is unique across all the + resource types, but the storage does not check it: choose identifiers + that cannot clash, such as UUIDs. The storage stores the identifier in the type of its column, and the created resource has the identifier as the column gives it back. For @@ -598,18 +651,15 @@ def create( """Store a new resource, and return it as stored.""" mapping = self._mapping(resource_type) self._check_storable(resource_type, resource, None) - self._check_uniqueness(resource, None, None) links = self._links(mapping, resource) resource_id = self.generate_id(resource_type, resource) - if resource_id is not None: - self._check_id(resource_id) record = self._new_record(resource_type, resource_id) def change() -> None: self.session().add(record) _from_scim(mapping, resource, record, links, creating=True) - self._flush(change) + self._flush(mapping, change) return self.get(resource_type, str(getattr(record, mapping._id.key))) def update( @@ -625,7 +675,6 @@ def update( 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(resource, stored, record) links = self._links(mapping, resource) def change() -> None: @@ -633,7 +682,7 @@ def change() -> None: self.session().flush() self._write_record(mapping, resource, record, links) - self._flush(change) + self._flush(mapping, change) return self.get(resource_type, resource.id) # type: ignore[arg-type] def delete( @@ -646,7 +695,7 @@ def delete( """Delete a resource.""" record = self._load(resource_type, resource_id, locked=True) self._check_version(resource_type, record, expected_version) - self._flush(lambda: self.session().delete(record)) + self._flush(self._mapping(resource_type), lambda: self.session().delete(record)) def _load( self, @@ -671,23 +720,6 @@ def _load( raise self._not_found(resource_type, resource_id) return record - def _check_uniqueness( - self, resource: Resource[Any], stored: Resource[Any] | None, record: Any - ) -> None: - """Refuse a resource with a unique value another resource already has.""" - session = self.session() - comparator = self._ready_comparator(session) - statements = self._unique_statements(resource, comparator, stored, record) - for statement in statements: - if session.scalar(statement) is not None: - raise UniquenessException - - def _check_id(self, resource_id: str) -> None: - """Refuse an identifier another resource already has.""" - for statement in self._id_statements(resource_id): - if self.session().scalar(statement) is not None: - raise UniquenessException - def _ready_comparator(self, session: Session) -> _Comparator: """Return how the database of the session compares strings, ready to compare them.""" connection = session.connection() @@ -714,13 +746,12 @@ def _links( links |= assign_links(found, entries, self._policy) return links - def _flush(self, change: Callable[[], None]) -> None: - """Apply a change in a savepoint, and flush it. + def _flush(self, mapping: ResourceMapping, change: Callable[[], None]) -> None: + """Apply a change of a resource in a savepoint, and flush it. A version changed in the meantime by another transaction raises a 412. - A unique value taken in the meantime raises a 409, as does a value - the unique constraint of the database refuses, such as a value that - differs only by its accents under a collation ignoring them. A + A value that a unique constraint of the database refuses raises a + 409, which tells the attribute when the constraint covers it alone. A foreign key the change breaks raises a 409 too, such as a record outside SCIM still referring to a deleted resource. """ @@ -732,6 +763,16 @@ def _flush(self, change: Callable[[], None]) -> None: except StaleDataError as exception: raise PreconditionFailedException from exception except DBAPIError as exception: + if _error_code(exception.orig) in _UNIQUE_VIOLATIONS: + attributes = mapping._unique_columns() + tables = list(dict.fromkeys(table for table, _ in attributes)) + columns = _violated_columns( + session.connection(), + exception.orig, + tables, + mapping._record_table(), + ) + raise self._conflict(attributes, columns) from exception _translate(exception) raise @@ -789,7 +830,7 @@ async def generate_id( instance to create the account in another service and take its identifier. A write that fails afterwards, such as with a 409 from the database, does not undo what the method did: override - :meth:`create` to handle it. + :meth:`create` to undo it. """ return None @@ -848,18 +889,15 @@ async def create( """Store a new resource, and return it as stored.""" mapping = self._mapping(resource_type) self._check_storable(resource_type, resource, None) - await self._check_uniqueness(resource, None, None) links = await self._links(mapping, resource) resource_id = await self.generate_id(resource_type, resource) - if resource_id is not None: - await self._check_id(resource_id) record = self._new_record(resource_type, resource_id) async def change() -> None: self.session().add(record) _from_scim(mapping, resource, record, links, creating=True) - await self._flush(change) + await self._flush(mapping, change) return await self.get(resource_type, str(getattr(record, mapping._id.key))) async def update( @@ -875,7 +913,6 @@ async def update( 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(resource, stored, record) links = await self._links(mapping, resource) async def change() -> None: @@ -883,7 +920,7 @@ async def change() -> None: await self.session().flush() self._write_record(mapping, resource, record, links) - await self._flush(change) + await self._flush(mapping, change) return await self.get(resource_type, resource.id) # type: ignore[arg-type] async def delete( @@ -900,7 +937,7 @@ async def delete( async def change() -> None: await self.session().delete(record) - await self._flush(change) + await self._flush(self._mapping(resource_type), change) async def _load( self, @@ -925,23 +962,6 @@ async def _load( raise self._not_found(resource_type, resource_id) return record - async def _check_uniqueness( - self, resource: Resource[Any], stored: Resource[Any] | None, record: Any - ) -> None: - """Refuse a resource with a unique value another resource already has.""" - session = self.session() - comparator = await self._ready_comparator(session) - statements = self._unique_statements(resource, comparator, stored, record) - for statement in statements: - if await session.scalar(statement) is not None: - raise UniquenessException - - async def _check_id(self, resource_id: str) -> None: - """Refuse an identifier another resource already has.""" - for statement in self._id_statements(resource_id): - if await self.session().scalar(statement) is not None: - raise UniquenessException - async def _ready_comparator(self, session: "AsyncSession") -> _Comparator: """Return how the database of the session compares strings, ready to compare them.""" connection = await session.connection() @@ -965,8 +985,10 @@ async def _links( links |= assign_links(found, entries, self._policy) return links - async def _flush(self, change: Callable[[], Awaitable[None]]) -> None: - """Apply a change in a savepoint, and flush it, as the synchronous storage does.""" + async def _flush( + self, mapping: ResourceMapping, change: Callable[[], Awaitable[None]] + ) -> None: + """Apply a change of a resource in a savepoint, and flush it, as the synchronous storage does.""" session = self.session() try: async with session.begin_nested(): @@ -975,5 +997,13 @@ async def _flush(self, change: Callable[[], Awaitable[None]]) -> None: except StaleDataError as exception: raise PreconditionFailedException from exception except DBAPIError as exception: + if _error_code(exception.orig) in _UNIQUE_VIOLATIONS: + attributes = mapping._unique_columns() + tables = list(dict.fromkeys(table for table, _ in attributes)) + connection = await session.connection() + columns = await connection.run_sync( + _violated_columns, exception.orig, tables, mapping._record_table() + ) + raise self._conflict(attributes, columns) from exception _translate(exception) raise diff --git a/tests/mailboxes.py b/tests/mailboxes.py index 1857e5a..9dc9208 100644 --- a/tests/mailboxes.py +++ b/tests/mailboxes.py @@ -1,35 +1,39 @@ """Mailbox records for the storage contract. -Their unique values are sub-attributes and multi-valued attributes. +Their unique values are sub-attributes and multi-valued attributes, each +covered by a unique constraint. """ import datetime import uuid from scim2_server.testing import Mailbox +from sqlalchemy import Computed from sqlalchemy import ForeignKey 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 Many from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import comparison_key from .models import MAPPINGS from .models import Base class MailboxRecord(Base): - """A mailbox whose addresses and aliases are in child tables, with a column for its work address.""" + """A mailbox whose addresses and aliases are in child tables.""" __tablename__ = "mailboxes" id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) display_name: Mapped[str | None] owner: Mapped[str | None] + owner_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("owner"), persisted=True), unique=True + ) owner_display: Mapped[str | None] - work_address: Mapped[str | None] created: Mapped[datetime.datetime] last_modified: Mapped[datetime.datetime] version: Mapped[int] = mapped_column() @@ -52,6 +56,9 @@ class AddressRecord(Base): ForeignKey("mailboxes.id", ondelete="CASCADE") ) value: Mapped[str | None] + value_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("value"), persisted=True), unique=True + ) type: Mapped[str | None] @@ -62,72 +69,7 @@ class AliasRecord(Base): mailbox_id: Mapped[uuid.UUID] = mapped_column( ForeignKey("mailboxes.id", ondelete="CASCADE") ) - value: Mapped[str] - - -class MailboxView(Base): - """Another class of the mailbox table, without inheritance.""" - - __table__ = MailboxRecord.__table__ - __mapper_args__ = {"version_id_col": __table__.c.version} - - -class SharedMailboxRecord(Base): - """A mailbox holding a single address, in a column of its record.""" - - __tablename__ = "shared_mailboxes" - - id: Mapped[int] = mapped_column(primary_key=True) - display_name: Mapped[str | None] - address: Mapped[str | None] - address_type: Mapped[str | None] - owner: Mapped[str | None] - created: Mapped[datetime.datetime] - last_modified: Mapped[datetime.datetime] - version: Mapped[int] = mapped_column() - - aliases: Mapped[list["SharedAliasRecord"]] = relationship( - cascade="all, delete-orphan", order_by="SharedAliasRecord.id" - ) - - __mapper_args__ = {"version_id_col": version} - - -class SharedAliasRecord(Base): - __tablename__ = "shared_mailbox_aliases" - - id: Mapped[int] = mapped_column(primary_key=True) - mailbox_id: Mapped[int] = mapped_column( - ForeignKey("shared_mailboxes.id", ondelete="CASCADE") - ) - value: Mapped[str] - - -class GuardedMailboxRecord(Base): - """A mailbox whose application refuses an address held twice, with a unique index.""" - - __tablename__ = "guarded_mailboxes" - - id: Mapped[int] = mapped_column(primary_key=True) - display_name: Mapped[str | None] - version: Mapped[int] = mapped_column() - - addresses: Mapped[list["GuardedAddressRecord"]] = relationship( - cascade="all, delete-orphan", order_by="GuardedAddressRecord.id" - ) - - __mapper_args__ = {"version_id_col": version} - - -class GuardedAddressRecord(Base): - __tablename__ = "guarded_mailbox_addresses" - - id: Mapped[int] = mapped_column(primary_key=True) - mailbox_id: Mapped[int] = mapped_column( - ForeignKey("guarded_mailboxes.id", ondelete="CASCADE") - ) - value: Mapped[str | None] = mapped_column(unique=True) - type: Mapped[str | None] + value: Mapped[str] = mapped_column(unique=True) def mailboxes_mapping(changes=None): @@ -151,65 +93,5 @@ def mailboxes_mapping(changes=None): ) -def work_addresses_mapping(record): - """Return a mapping of the mailboxes of a class, reading their work address only.""" - return ResourceMapping( - Mailbox, - record, - { - "id": record.id, - "displayName": record.display_name, - "addresses": Entry({"value": record.work_address}, type="work"), - "meta.created": record.created, - "meta.lastModified": record.last_modified, - }, - version=record.version, - ) - - -def shared_mailboxes_mapping(): - return ResourceMapping( - Mailbox, - SharedMailboxRecord, - { - "id": SharedMailboxRecord.id, - "displayName": SharedMailboxRecord.display_name, - "addresses": Entry( - { - "value": SharedMailboxRecord.address, - "type": SharedMailboxRecord.address_type, - } - ), - "aliases": Many(SharedMailboxRecord.aliases, SharedAliasRecord.value), - "owner.value": SharedMailboxRecord.owner, - "meta.created": SharedMailboxRecord.created, - "meta.lastModified": SharedMailboxRecord.last_modified, - }, - version=SharedMailboxRecord.version, - ) - - -def guarded_mailboxes_mapping(): - return ResourceMapping( - Mailbox, - GuardedMailboxRecord, - { - "id": GuardedMailboxRecord.id, - "displayName": GuardedMailboxRecord.display_name, - "addresses": Many( - GuardedMailboxRecord.addresses, - { - "value": GuardedAddressRecord.value, - "type": GuardedAddressRecord.type, - }, - ), - }, - version=GuardedMailboxRecord.version, - ) - - -MAILBOX_MAPPINGS = MAPPINGS | { - "Mailbox": mailboxes_mapping(), - "SharedMailbox": shared_mailboxes_mapping(), -} +MAILBOX_MAPPINGS = MAPPINGS | {"Mailbox": mailboxes_mapping()} """The mappings of the storage contract, with the mailboxes of the tests of uniqueness.""" diff --git a/tests/models.py b/tests/models.py index 33db201..e299c64 100644 --- a/tests/models.py +++ b/tests/models.py @@ -8,6 +8,7 @@ from scim2_models import Group from scim2_models import User from sqlalchemy import Column +from sqlalchemy import Computed from sqlalchemy import DateTime from sqlalchemy import Double from sqlalchemy import ForeignKey @@ -29,6 +30,7 @@ from scim2_sqlalchemy import Link from scim2_sqlalchemy import Many from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import comparison_key ENTERPRISE = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" @@ -42,12 +44,18 @@ class Ranked(Extension): TYPES = { - str: String().with_variant(String(255), "mariadb"), + str: String().with_variant( + mysql.VARCHAR(255, charset="utf8mb4", collation="utf8mb4_nopad_bin"), "mariadb" + ), float: Double(), decimal.Decimal: Numeric().with_variant(Numeric(38, 10), "mariadb"), datetime.datetime: DateTime().with_variant(mysql.DATETIME(fsp=6), "mariadb"), } -"""The column types of the records, with the lengths and precisions MariaDB needs.""" +"""The column types of the records, with the lengths and precisions MariaDB needs. + +The strings differ by code point, so that a unique index tells apart the +values that differ by their case. +""" class Base(DeclarativeBase): @@ -88,6 +96,9 @@ class UserRecord(Base): id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) external_id: Mapped[str | None] user_name: Mapped[str] = mapped_column(unique=True) + user_name_key: Mapped[str] = mapped_column( + Computed(comparison_key("user_name"), persisted=True), unique=True + ) display_name: Mapped[str | None] title: Mapped[str | None] nick_name: Mapped[str | None] diff --git a/tests/plain.py b/tests/plain.py index f44f19a..19ff8a1 100644 --- a/tests/plain.py +++ b/tests/plain.py @@ -4,6 +4,7 @@ from scim2_models import Group from scim2_models import User from sqlalchemy import Column +from sqlalchemy import Computed from sqlalchemy import ForeignKey from sqlalchemy import Table from sqlalchemy.orm import Mapped @@ -13,6 +14,7 @@ from scim2_sqlalchemy import Entry from scim2_sqlalchemy import Link from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import comparison_key from .models import ENTERPRISE from .models import Base @@ -34,6 +36,9 @@ class PlainUserRecord(Base): id: Mapped[int] = mapped_column(primary_key=True) user_name: Mapped[str] = mapped_column(unique=True) + user_name_key: Mapped[str] = mapped_column( + Computed(comparison_key("user_name"), persisted=True), unique=True + ) display_name: Mapped[str | None] title: Mapped[str | None] nick_name: Mapped[str | None] diff --git a/tests/test_comparison.py b/tests/test_comparison.py index b212597..ddd62bd 100644 --- a/tests/test_comparison.py +++ b/tests/test_comparison.py @@ -68,14 +68,27 @@ def test_a_decomposed_value_matches_its_composed_form(storage, user_type, databa assert user_names(storage, user_type, filter='userName eq "José"') == ["Jose\u0301"] -def test_a_decomposed_value_is_taken(storage, user_type): - """The uniqueness check compares the values in NFC. On MariaDB, the unique constraint of the column catches it.""" +def test_a_decomposed_value_is_taken_on_postgresql(storage, user_type, database_url): + """The comparison key of PostgreSQL normalizes the values to NFC.""" + if not database_url.startswith("postgresql"): + pytest.skip("SQLite and MariaDB do not normalize the values in their index") storage.create(user_type, UserModel(user_name="José")) with pytest.raises(UniquenessException): storage.create(user_type, UserModel(user_name="Jose\u0301")) +def test_a_decomposed_value_is_new_for_the_index_of_sqlite_and_mariadb( + storage, user_type, database_url +): + """The filters find José in both forms, but the unique column holds each form as written.""" + if database_url.startswith("postgresql"): + pytest.skip("PostgreSQL normalizes the values in its index") + storage.create(user_type, UserModel(user_name="José")) + + storage.create(user_type, UserModel(user_name="Jose\u0301")) + + @pytest.mark.parametrize( ("filter", "expected"), [ @@ -151,8 +164,20 @@ def test_sqlite_compares_with_the_key_of_the_policy( storage.create(user_type, UserModel(user_name="Straße")) assert user_names(storage, user_type, filter='userName eq "STRASSE"') == ["Straße"] + + +def test_the_index_of_sqlite_only_lowers_ascii_letters( + storage, user_type, database_url +): + """The filters find Élise and élise equal, but lower() of SQLite keeps É.""" + if not database_url.startswith("sqlite"): + pytest.skip("PostgreSQL and MariaDB lower every letter") + storage.create(user_type, UserModel(user_name="Élise")) + + storage.create(user_type, UserModel(user_name="élise")) + with pytest.raises(UniquenessException): - storage.create(user_type, UserModel(user_name="strasse")) + storage.create(user_type, UserModel(user_name="éLISE")) @pytest.fixture @@ -287,17 +312,17 @@ def test_the_database_approaches_the_default_key(session, database_url, value): LINGUISTIC_COLLATIONS = { - "postgresql": 'ALTER TABLE users ALTER COLUMN user_name TYPE varchar COLLATE "und-x-icu"', - "mariadb": "ALTER TABLE users MODIFY user_name VARCHAR(255) NOT NULL COLLATE utf8mb4_uca1400_as_ci", + "postgresql": 'ALTER TABLE users ALTER COLUMN display_name TYPE varchar COLLATE "und-x-icu"', + "mariadb": "ALTER TABLE users MODIFY display_name VARCHAR(255) COLLATE utf8mb4_uca1400_as_ci", } -"""The statement giving the names of the users a collation that orders é before f.""" +"""The statement giving the display names of the users a collation that orders é before f.""" @pytest.mark.parametrize( ("parameters", "expected"), [ - ({"sort_by": "userName"}, ["e", "f", "é"]), - ({"filter": 'userName lt "f"'}, ["e"]), + ({"sort_by": "displayName"}, ["e", "f", "é"]), + ({"filter": 'displayName lt "f"'}, ["e"]), ], ) def test_the_database_orders_strings_by_code_point( @@ -309,7 +334,7 @@ def test_the_database_orders_strings_by_code_point( session.execute(text(LINGUISTIC_COLLATIONS[session.connection().dialect.name])) storage = sync_storage_factory() for name in ("é", "f", "e"): - storage.create(user_type, UserModel(user_name=name)) + storage.create(user_type, UserModel(user_name=name, display_name=name)) assert user_names(storage, user_type, **parameters) == expected diff --git a/tests/test_enum.py b/tests/test_enum.py index f79f513..99616b5 100644 --- a/tests/test_enum.py +++ b/tests/test_enum.py @@ -6,6 +6,7 @@ from scim2_models import InvalidValueException from scim2_models import SearchRequest from scim2_models import User +from sqlalchemy import Computed from sqlalchemy import Enum from sqlalchemy import ForeignKey from sqlalchemy import create_engine @@ -16,6 +17,7 @@ from scim2_sqlalchemy import Many from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import comparison_key from .models import TYPES @@ -36,7 +38,10 @@ class ColoredUser(Base): __tablename__ = "colored_users" id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) - user_name: Mapped[str] = mapped_column(unique=True) + user_name: Mapped[str] + user_name_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("user_name"), persisted=True), unique=True + ) title: Mapped[Color | None] = mapped_column(Enum(Color, name="title_color")) external_id: Mapped[Color | None] = mapped_column( Enum( diff --git a/tests/test_generate_id.py b/tests/test_generate_id.py index 73f65ec..24db6e3 100644 --- a/tests/test_generate_id.py +++ b/tests/test_generate_id.py @@ -6,7 +6,7 @@ from scim2_models import Group from scim2_models import UniquenessException from scim2_models import User -from scim2_server.testing import MAILBOX_TYPES +from scim2_server.testing import MAILBOX_TYPE from scim2_server.testing import Mailbox from .mailboxes import MAILBOX_MAPPINGS @@ -16,8 +16,6 @@ UserModel = User[EnterpriseUser] -MAILBOX_TYPE, _ = MAILBOX_TYPES - BJENSEN = uuid.UUID("2819c223-7f76-453a-919d-413861904646") @@ -99,7 +97,9 @@ def create_two_users_with_the_same_identifier(storage, chooser, user_type): chooser.ids = [str(BJENSEN), str(BJENSEN)] storage.create(user_type, UserModel(user_name="bjensen")) - with pytest.raises(UniquenessException): + with pytest.raises( + UniquenessException, match="^Uniqueness conflict with attribute id$" + ): storage.create(user_type, UserModel(user_name="babs")) @@ -119,14 +119,17 @@ def test_an_asynchronous_storage_refuses_a_taken_identifier( create_two_users_with_the_same_identifier(storage, storage.storage, user_type) -def test_an_identifier_is_unique_across_resource_types(sync_storage_factory, user_type): - """Per RFC 7643 §3.1, a mailbox cannot take the identifier of a user, though they are in different tables.""" +def test_an_identifier_is_not_checked_across_resource_types( + sync_storage_factory, user_type +): + """The users and the mailboxes are in different tables, and only the primary key of each table checks the identifiers.""" storage = sync_storage_factory(MAILBOX_MAPPINGS, mixins=[SyncChosenIds]) storage.ids = [str(BJENSEN), str(BJENSEN)] storage.create(user_type, UserModel(user_name="bjensen")) - with pytest.raises(UniquenessException): - storage.create(MAILBOX_TYPE, Mailbox(display_name="Babs")) + mailbox = storage.create(MAILBOX_TYPE, Mailbox(display_name="Babs")) + + assert mailbox.id == str(BJENSEN) def refuse_a_taken_user_name(storage, chooser, user_type): @@ -136,20 +139,20 @@ def refuse_a_taken_user_name(storage, chooser, user_type): with pytest.raises(UniquenessException): storage.create(user_type, UserModel(user_name="BJensen")) - assert chooser.calls == 1 + assert chooser.calls == 2 -def test_a_refused_resource_gets_no_identifier(sync_storage_factory, user_type): - """The storage checks the unique values first, so a refused user does not call generate_id.""" +def test_a_refused_resource_gets_an_identifier_first(sync_storage_factory, user_type): + """The database checks the unique values when the user is written, after generate_id.""" storage = sync_storage_factory(mixins=[SyncChosenIds]) refuse_a_taken_user_name(storage, storage, user_type) -def test_an_asynchronous_storage_chooses_no_identifier_for_a_refused_resource( +def test_an_asynchronous_storage_chooses_an_identifier_before_the_database_refuses( async_storage_factory, user_type ): - """A refused user does not call another service.""" + """The other service has created the account by then: create must undo it.""" storage = async_storage_factory(mixins=[AsyncChosenIds]) refuse_a_taken_user_name(storage, storage.storage, user_type) diff --git a/tests/test_generation.py b/tests/test_generation.py index 3b9369c..b37f320 100644 --- a/tests/test_generation.py +++ b/tests/test_generation.py @@ -4,6 +4,7 @@ from pydantic import Field from scim2_client.engines.wsgi import WSGISCIMClient from scim2_models import URN +from scim2_models import CaseExact from scim2_models import ComplexAttribute from scim2_models import EnterpriseUser from scim2_models import Extension @@ -15,6 +16,7 @@ from scim2_models import Returned from scim2_models import ScimProvider from scim2_models import Uniqueness +from scim2_models import UniquenessException from scim2_models import User from scim2_server.applications.wsgi import WSGIApplication from scim2_server.utils import load_default_provider @@ -243,7 +245,8 @@ def test_the_columns_follow_the_attributes(): generate_mappings(load_default_provider(), metadata, store=without_secrets) users = metadata.tables["users"].c - assert not users.user_name.nullable and users.user_name.unique + assert not users.user_name.nullable and not users.user_name.unique + assert users.user_name_key.unique and users.user_name_key.computed is not None assert users.name_given_name.nullable assert isinstance(users.active.type, Boolean) assert isinstance(users.meta_created.type, DateTime) @@ -612,3 +615,57 @@ def test_a_unique_value_hidden_from_clients_is_refused(): """A 409 on the code would tell that another vault holds it.""" with pytest.raises(ValueError, match="hidden from clients"): generate_mappings(ScimProvider(models=[Vault]), MetaData()) + + +class BadgeHolder(ComplexAttribute): + value: Annotated[str | None, Uniqueness.server] = None + + +class Badge(Resource): + """A resource type with unique values in its child tables.""" + + __schema__ = URN("urn:example:params:scim:schemas:core:2.0:Badge") + + serial: Annotated[str | None, Uniqueness.server, CaseExact.true] = None + codes: Annotated[list[str] | None, Uniqueness.server, CaseExact.true] = None + nicknames: Annotated[list[str] | None, Uniqueness.server] = None + holders: list[BadgeHolder] | None = None + + +def test_each_unique_attribute_gets_a_unique_constraint(): + """A case exact value gets a unique column, and a value ignoring the case a unique column computed from it.""" + metadata = MetaData() + mappings = generate_mappings(ScimProvider(models=[Badge]), metadata) + tables = metadata.tables + + assert tables["badges"].c.serial.unique + assert tables["badges_codes"].c.value.unique + assert not tables["badges_nicknames"].c.value.unique + assert tables["badges_nicknames"].c.value_key.unique + assert tables["badges_holders"].c.value_key.unique + assert mappings["Badge"]._unconstrained_attributes() == [] + + +def test_a_generated_storage_tells_the_attribute_of_a_taken_value(storage, user_type): + storage.create(user_type, User(user_name="bjensen")) + + with pytest.raises( + UniquenessException, match="^Uniqueness conflict with attribute userName$" + ): + storage.create(user_type, User(user_name="BJensen")) + + +def test_the_key_of_a_string_ignores_the_type_of_its_column(): + """A short column type would not hold a lowered value grown longer, and a collation ignoring the accents would refuse élise next to elise.""" + metadata = MetaData() + + def store(binding): + if binding.urn.endswith(":userName"): + return String(12) + return without_secrets(binding) + + generate_mappings(load_default_provider(), metadata, store=store) + users = metadata.tables["users"].c + + assert users.user_name.type.length == 12 + assert users.user_name_key.type.length is None diff --git a/tests/test_many_values.py b/tests/test_many_values.py index 159392c..4ffb96e 100644 --- a/tests/test_many_values.py +++ b/tests/test_many_values.py @@ -11,6 +11,7 @@ from scim2_models import Required from scim2_models import SearchRequest from scim2_models import User +from sqlalchemy import Computed from sqlalchemy import ForeignKey from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase @@ -22,6 +23,7 @@ from scim2_sqlalchemy import Attribute from scim2_sqlalchemy import Many from scim2_sqlalchemy import ResourceMapping +from scim2_sqlalchemy import comparison_key from .models import TYPES @@ -47,7 +49,10 @@ class TaggedUser(Base): __tablename__ = "tagged_users" id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) - user_name: Mapped[str] = mapped_column(unique=True) + user_name: Mapped[str] + user_name_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("user_name"), persisted=True), unique=True + ) created: Mapped[datetime.datetime] last_modified: Mapped[datetime.datetime] version: Mapped[int] = mapped_column() diff --git a/tests/test_storage.py b/tests/test_storage.py index 7541d72..0ff6762 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -20,6 +20,11 @@ from scim2_models import SearchRequest from scim2_models import UniquenessException from scim2_models import User +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table from sqlalchemy import create_engine from sqlalchemy import func from sqlalchemy import select @@ -34,7 +39,11 @@ from scim2_sqlalchemy import Many from scim2_sqlalchemy import ResourceMapping from scim2_sqlalchemy import SqlAlchemyStorage +from scim2_sqlalchemy import UniqueConstraintWarning +from scim2_sqlalchemy import storage as storage_module from scim2_sqlalchemy.storage import _translate +from scim2_sqlalchemy.storage import _violated_columns +from scim2_sqlalchemy.storage import _violation from .models import ENTERPRISE from .models import RANKED @@ -744,20 +753,14 @@ def test_a_string_is_stored_in_an_integer_column_through_a_property( assert [resource.user_name for resource in found] == ["a"] -class TakenMeanwhile: - """Skip the uniqueness check, as when another transaction takes the value right after it.""" - - def _unique_statements(self, resource, comparator, stored, record): - return iter(()) - - -def test_a_value_taken_meanwhile_raises_a_409(storage_factory, user_type): - """The unique constraint of the database catches what the check missed.""" +def test_two_writes_of_a_value_raise_a_409(storage_factory, user_type): + """Two storages write the same name: the unique constraint of the database refuses the second.""" storage_factory().create(user_type, UserModel(user_name="bjensen")) - storage = storage_factory(mixins=[TakenMeanwhile]) - with pytest.raises(UniquenessException): - storage.create(user_type, UserModel(user_name="bjensen")) + with pytest.raises( + UniquenessException, match="^Uniqueness conflict with attribute userName$" + ): + storage_factory().create(user_type, UserModel(user_name="bjensen")) def test_a_resource_without_a_value_its_column_needs_is_refused( @@ -825,21 +828,133 @@ def __init__(self, *args, **attributes): self.__dict__.update(attributes) +class Diagnostic: + """The diagnostic of a PostgreSQL error.""" + + table_name = "users" + constraint_name = "users_user_name_key_key" + + @pytest.mark.parametrize( - "error", + ("error", "expected"), [ - DriverError("duplicate key", sqlstate="23505"), - DriverError("duplicate key", pgcode="23505"), - DriverError("UNIQUE failed", sqlite_errorname="SQLITE_CONSTRAINT_UNIQUE"), - DriverError(1062, "Duplicate entry", sqlstate="23000"), - DriverError("Duplicate entry", errno=1062, sqlstate="23000"), + ( + DriverError("duplicate key", sqlstate="23505", diag=Diagnostic()), + ("users", "users_user_name_key_key", []), + ), + ( + DriverError("duplicate key", pgcode="23505", diag=Diagnostic()), + ("users", "users_user_name_key_key", []), + ), + ( + DriverError( + "UNIQUE constraint failed: users.user_name_key", + sqlite_errorname="SQLITE_CONSTRAINT_UNIQUE", + ), + ("users", None, ["user_name_key"]), + ), + ( + DriverError( + "UNIQUE constraint failed: groups.display_name, groups.external_id", + sqlite_errorname="SQLITE_CONSTRAINT_UNIQUE", + ), + ("groups", None, ["display_name", "external_id"]), + ), + ( + DriverError( + "UNIQUE constraint failed: index 'users_lowered_name'", + sqlite_errorname="SQLITE_CONSTRAINT_UNIQUE", + ), + (None, "users_lowered_name", []), + ), + ( + DriverError( + 1062, + "Duplicate entry 'a' for key 'b'' for key 'user_name_key'", + sqlstate="23000", + ), + (None, "user_name_key", []), + ), + ( + DriverError( + "Duplicate entry 'a' for key 'users.user_name_key'", + errno=1062, + sqlstate="23000", + ), + ("users", "user_name_key", []), + ), + ( + DriverError("duplicate key value", sqlstate="23505"), + (None, None, []), + ), + ], + ids=[ + "psycopg", + "psycopg2", + "sqlite3", + "sqlite3 with several columns", + "sqlite3 with an index", + "PyMySQL", + "MySQL", + "a driver without diagnostic", ], - ids=["psycopg", "psycopg2", "sqlite3", "PyMySQL", "MariaDB Connector"], ) -def test_a_unique_value_taken_raises_a_409_whatever_the_driver(error): - """Each driver tells a unique value taken its own way.""" - with pytest.raises(UniquenessException): - _translate(IntegrityError("INSERT", {}, error)) +def test_each_driver_tells_the_constraint_of_a_unique_value_taken(error, expected): + """The value in the message of MariaDB may look like the end of the message.""" + assert _violation(error) == expected + + +def test_a_violation_without_constraint_names_no_column(): + """The storage does not read the message of an unknown driver, which may hold the value.""" + error = DriverError("duplicate key value", sqlstate="23505") + + assert _violated_columns(None, error, [], None) == [] + + +class Reflected: + """An inspector of MariaDB tables, which name each constraint after its column.""" + + def __init__(self, tables): + self.tables = tables + + def get_unique_constraints(self, table, schema=None): + return [{"name": name, "column_names": [name]} for name in self.tables[table]] + + def get_indexes(self, table, schema=None): + return [] + + def get_pk_constraint(self, table, schema=None): + return {"name": None, "constrained_columns": ["id"]} + + +MARIADB_TABLES = MetaData() +USERS = Table("users", MARIADB_TABLES, Column("id", Integer, primary_key=True)) +ALIASES = Table("users_aliases", MARIADB_TABLES, Column("value", String)) +NICKNAMES = Table("users_nicknames", MARIADB_TABLES, Column("value", String)) + + +@pytest.mark.parametrize( + ("key", "expected"), + [ + ("PRIMARY", [(USERS, "id")]), + ("value", []), + ("users_nicknames.value", [(NICKNAMES, "value")]), + ], + ids=["identifier", "value of two tables", "value of a named table"], +) +def test_a_constraint_of_several_tables_is_found_in_the_table_of_the_record( + monkeypatch, key, expected +): + """MariaDB names the constraint without its table, and the entries of a child table get their key from the database.""" + reflected = Reflected( + {"users": [], "users_aliases": ["value"], "users_nicknames": ["value"]} + ) + monkeypatch.setattr(storage_module, "inspect", lambda connection: reflected) + error = DriverError(1062, f"Duplicate entry 'x' for key '{key}'") + + assert ( + _violated_columns(None, error, [USERS, ALIASES, NICKNAMES], USERS) == expected + ) @pytest.mark.parametrize( @@ -944,32 +1059,6 @@ def test_a_uuid_identifier_matches_its_own_text(storage, user_type, scim_filter, assert total == (1 if found else 0) -def test_an_unchanged_unique_value_is_not_checked_again( - sync_storage_factory, session, user_type, database_url -): - """Another application stored alice and Alice: Alice remains writable while she keeps her name. - - userName is not caseExact, so ALICE is the name she holds, and not a new one. - """ - if database_url.startswith("mariadb"): - pytest.skip("The default collation of MariaDB cannot hold alice and Alice") - now = datetime.datetime.now(datetime.UTC) - for user_name in ("alice", "Alice", "bob"): - session.add(UserRecord(user_name=user_name, created=now, last_modified=now)) - session.flush() - storage = sync_storage_factory() - _, found = search(storage, user_type) - (alice,) = [user for user in found if user.user_name == "Alice"] - alice.display_name = "Alice" - - assert storage.update(user_type, alice).display_name == "Alice" - alice.user_name = "ALICE" - assert storage.update(user_type, alice).user_name == "ALICE" - alice.user_name = "Bob" - with pytest.raises(UniquenessException): - storage.update(user_type, alice) - - def test_a_new_resource_with_the_id_of_another_is_checked(storage, user_type): """A new resource never is the record holding the identifier it carries.""" bjensen = storage.create(user_type, UserModel(user_name="bjensen")) @@ -1104,9 +1193,10 @@ def test_an_identifier_is_found_by_its_exact_text( mapping = users_mapping( {"id": UserRecord.user_name, "userName": UserRecord.display_name} ) - storage = sync_storage_factory( - mappings={"User": mapping, "Group": groups_mapping()} - ) + with pytest.warns(UniqueConstraintWarning, match="User:userName"): + storage = sync_storage_factory( + mappings={"User": mapping, "Group": groups_mapping()} + ) assert storage.get(user_type, "bjensen").id == "bjensen" with pytest.raises(NotFoundException): diff --git a/tests/test_uniqueness.py b/tests/test_uniqueness.py index 4f2b783..00215c4 100644 --- a/tests/test_uniqueness.py +++ b/tests/test_uniqueness.py @@ -1,40 +1,52 @@ -import datetime +import uuid +import warnings from typing import Annotated import pytest from scim2_models import URN from scim2_models import CaseExact +from scim2_models import Email from scim2_models import Extension from scim2_models import Group from scim2_models import GroupMember from scim2_models import Mutability +from scim2_models import Resource from scim2_models import Returned from scim2_models import Uniqueness from scim2_models import UniquenessException from scim2_models import User -from scim2_server.testing import MAILBOX_TYPES -from scim2_server.testing import Mailbox -from scim2_server.testing import MailboxAddress -from scim2_server.testing import MailboxOwner +from sqlalchemy import Column +from sqlalchemy import Computed +from sqlalchemy import ForeignKey +from sqlalchemy import Index +from sqlalchemy import MetaData +from sqlalchemy import String +from sqlalchemy import Table +from sqlalchemy import UniqueConstraint +from sqlalchemy import func +from sqlalchemy import literal_column +from sqlalchemy.dialects import mysql +from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects import sqlite +from sqlalchemy.orm import DeclarativeBase +from sqlalchemy.orm import Mapped +from sqlalchemy.orm import column_property +from sqlalchemy.orm import mapped_column +from sqlalchemy.orm import relationship +from sqlalchemy.schema import CreateTable -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 scim2_sqlalchemy import UniqueConstraintWarning +from scim2_sqlalchemy import comparison_key -from .mailboxes import MAILBOX_MAPPINGS -from .mailboxes import MailboxRecord -from .mailboxes import MailboxView -from .mailboxes import SharedMailboxRecord -from .mailboxes import guarded_mailboxes_mapping -from .mailboxes import mailboxes_mapping -from .mailboxes import work_addresses_mapping -from .models import MAPPINGS +from .models import Base from .models import GroupRecord from .models import UserRecord from .models import users_mapping -MAILBOX_TYPE, SHARED_MAILBOX_TYPE = MAILBOX_TYPES - SEALED = "urn:example:params:scim:schemas:extension:sealed:2.0:User" @@ -44,6 +56,14 @@ class Sealed(Extension): code: Annotated[str | None, Returned.never, Uniqueness.server] = None +class Badge(Resource): + """A badge whose code differs from the others, case included.""" + + __schema__ = URN("urn:example:scim:schemas:2.0:Badge") + + code: Annotated[str | None, Uniqueness.server, CaseExact.true] = None + + class TeamMember(GroupMember): value: Annotated[ str | None, Mutability.immutable, CaseExact.true, Uniqueness.server @@ -51,13 +71,129 @@ class TeamMember(GroupMember): class Team(Group): - """A group whose members belong to no other team.""" + """A group whose members belong to no other team, and whose leader leads no other team.""" members: list[TeamMember] | None = None + leader: TeamMember | None = None + + +class Records(DeclarativeBase): + """Records that only the checks of the mappings read, without tables in the database.""" + + +class BadgeRecord(Records): + __tablename__ = "badges" + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str | None] + unique_code: Mapped[str | None] = mapped_column(unique=True) + indexed_code: Mapped[str | None] + constrained_code: Mapped[str | None] + paired_code: Mapped[str | None] + + __table_args__ = ( + Index("badges_indexed_code", "indexed_code", unique=True), + UniqueConstraint("constrained_code"), + UniqueConstraint("code", "paired_code"), + ) + +BadgeRecord.upper_code = column_property(func.upper(BadgeRecord.code)) -def addresses(*values): - return [MailboxAddress(value=value, type=type) for value, type in values] + +class KeyedBadgeRecord(Records): + __tablename__ = "keyed_badges" + + code: Mapped[str] = mapped_column(primary_key=True) + + +class PersonRecord(Records): + __tablename__ = "people" + + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str | None] + unique_name: Mapped[str | None] = mapped_column(unique=True) + name_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("name"), persisted=True), unique=True + ) + shared_key: Mapped[str | None] = mapped_column( + Computed(comparison_key("unique_name")) + ) + other_key: Mapped[str | None] = mapped_column( + Computed(func.lower(literal_column("unique_name")), persisted=True), + unique=True, + ) + + +team_members = Table( + "team_members", + Records.metadata, + Column("team_id", ForeignKey("teams.id"), primary_key=True), + Column("person_id", ForeignKey("people.id"), primary_key=True), +) + +exclusive_team_members = Table( + "exclusive_team_members", + Records.metadata, + Column("team_id", ForeignKey("teams.id"), primary_key=True), + Column("person_id", ForeignKey("people.id"), primary_key=True, unique=True), +) + + +class TeamRecord(Records): + __tablename__ = "teams" + + id: Mapped[int] = mapped_column(primary_key=True) + leader_id: Mapped[int | None] = mapped_column(ForeignKey("people.id")) + sole_leader_id: Mapped[int | None] = mapped_column( + ForeignKey("people.id"), unique=True + ) + + members: Mapped[list[PersonRecord]] = relationship(secondary=team_members) + exclusive_members: Mapped[list[PersonRecord]] = relationship( + secondary=exclusive_team_members + ) + leader: Mapped[PersonRecord | None] = relationship(foreign_keys=[leader_id]) + sole_leader: Mapped[PersonRecord | None] = relationship( + foreign_keys=[sole_leader_id] + ) + badges: Mapped[list["TeamBadgeRecord"]] = relationship() + + +class TeamBadgeRecord(Records): + __tablename__ = "team_badges" + + id: Mapped[int] = mapped_column(primary_key=True) + team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id")) + code: Mapped[str | None] = mapped_column(unique=True) + + +def unconstrained(model, record, attributes, others=None): + """Return the warnings of a storage serving a mapping, with the mappings it links to.""" + mapping = ResourceMapping(model, record, attributes) + mappings = {"Tested": mapping} | (others or {}) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + SqlAlchemyStorage(mappings, lambda: None, version_key=b"key") + return [ + str(warning.message) + for warning in caught + if issubclass(warning.category, UniqueConstraintWarning) + ] + + +def linked_mappings(): + """Return the mappings the teams link to.""" + return { + "User": ResourceMapping( + User, PersonRecord, {"id": PersonRecord.id, "userName": PersonRecord.name} + ), + "Badge": ResourceMapping( + Badge, + TeamBadgeRecord, + {"id": TeamBadgeRecord.id, "code": TeamBadgeRecord.code}, + ), + } def test_a_unique_value_hidden_from_clients_is_refused(): @@ -74,98 +210,122 @@ def test_a_unique_value_hidden_from_clients_is_refused(): ) -def test_a_unique_index_of_the_entries_accepts_the_values_a_resource_keeps( - storage_factory, -): - """The old entries are deleted before the new ones are inserted, so the index of the application accepts a kept or swapped address.""" - storage = storage_factory(MAPPINGS | {"Mailbox": guarded_mailboxes_mapping()}) - mailbox = storage.create( - MAILBOX_TYPE, - Mailbox( - display_name="Babs", - addresses=addresses( - ("babs@example.com", "work"), ("b@example.com", "home") - ), - ), - ) - mailbox.display_name = "Barbara" - mailbox = storage.update(MAILBOX_TYPE, mailbox) - mailbox.addresses = addresses( - ("babs@example.com", "home"), ("b@example.com", "work") - ) +@pytest.mark.parametrize( + "column", + ["unique_code", "indexed_code", "constrained_code"], +) +def test_a_case_exact_attribute_needs_a_unique_constraint_on_its_column(column): + """A unique column, a unique index and a unique constraint each cover the code.""" + attributes = {"id": BadgeRecord.id, "code": getattr(BadgeRecord, column)} + + assert unconstrained(Badge, BadgeRecord, attributes) == [] + + +def test_the_primary_key_covers_a_unique_attribute(): + """The code of a badge is also its identifier.""" + attributes = {"id": KeyedBadgeRecord.code, "code": KeyedBadgeRecord.code} - updated = storage.update(MAILBOX_TYPE, mailbox) + assert unconstrained(Badge, KeyedBadgeRecord, attributes) == [] - assert updated.display_name == "Barbara" - assert [(a.value, a.type) for a in updated.addresses] == [ - ("babs@example.com", "home"), - ("b@example.com", "work"), + +@pytest.mark.parametrize("column", ["code", "upper_code"]) +def test_a_case_exact_attribute_without_constraint_warns(column): + """The constraint on two columns lets two badges share a code, and a SQL expression has no constraint at all.""" + attributes = {"id": BadgeRecord.id, "code": getattr(BadgeRecord, column)} + + assert unconstrained(Badge, BadgeRecord, attributes) == [ + "No unique constraint covers the unique attribute " + "urn:example:scim:schemas:2.0:Badge:code, " + "so two resources can hold the same value" ] -def test_a_unique_index_of_the_entries_refuses_a_value_a_resource_repeats( - storage_factory, -): - """The index of the application is stricter than SCIM, which lets a resource repeat its value.""" - storage = storage_factory(MAPPINGS | {"Mailbox": guarded_mailboxes_mapping()}) +def test_an_attribute_ignoring_the_case_is_covered_by_its_comparison_key(): + attributes = {"id": PersonRecord.id, "userName": PersonRecord.name} - with pytest.raises(UniquenessException): - storage.create( - MAILBOX_TYPE, - Mailbox( - addresses=addresses( - ("babs@example.com", "work"), ("babs@example.com", "home") - ) - ), - ) + assert unconstrained(User, PersonRecord, attributes) == [] + + +def test_an_attribute_ignoring_the_case_needs_more_than_a_unique_column(): + """The unique column accepts bjensen and BJensen, which the filters find equal. + + Its comparison key is not unique, and the unique lowered column is not the + comparison key. + """ + attributes = {"id": PersonRecord.id, "userName": PersonRecord.unique_name} + + assert len(unconstrained(User, PersonRecord, attributes)) == 1 @pytest.mark.parametrize( - "record", [MailboxRecord, MailboxView], ids=["same class", "same table"] + ("path", "link"), + [ + ("members", Link(TeamRecord.exclusive_members, "User", type="User")), + ("leader", Link(TeamRecord.sole_leader, "User", type="User")), + ("members", Link(TeamRecord.badges, "Badge", type="Badge")), + ], + ids=["unique member", "unique foreign key", "foreign key to the team"], ) -def test_a_resource_does_not_clash_with_itself_through_another_mapping_of_its_record( - storage_factory, record -): - """The shared mailboxes read the work address of the same records, so a mailbox taking its own work address does not clash with itself.""" - storage = storage_factory( - MAPPINGS - | { - "Mailbox": mailboxes_mapping(), - "SharedMailbox": work_addresses_mapping(record), - } - ) - shared = storage.create( - SHARED_MAILBOX_TYPE, - Mailbox(addresses=addresses(("team@example.com", "work"))), - ) - mailbox = storage.get(MAILBOX_TYPE, shared.id) - assert mailbox.addresses is None - mailbox.addresses = addresses(("team@example.com", "work")) +def test_a_unique_link_is_covered_by_its_foreign_key(path, link): + """A record holding the foreign key to its team belongs to one team.""" + attributes = {"id": TeamRecord.id, path: link} - updated = storage.update(MAILBOX_TYPE, mailbox) + assert unconstrained(Team, TeamRecord, attributes, linked_mappings()) == [] - assert [a.value for a in updated.addresses] == ["team@example.com"] - other = storage.create(MAILBOX_TYPE, Mailbox(display_name="Other")) - other.addresses = addresses(("team@example.com", "work")) - with pytest.raises(UniquenessException): - storage.update(MAILBOX_TYPE, other) + +@pytest.mark.parametrize( + ("path", "link"), + [ + ("members", Link(TeamRecord.members, "User", type="User")), + ("leader", Link(TeamRecord.leader, "User", type="User")), + ], + ids=["member", "foreign key"], +) +def test_a_unique_link_whose_foreign_key_repeats_warns(path, link): + """A person can be a member, or the leader, of two teams.""" + attributes = {"id": TeamRecord.id, path: link} + + assert len(unconstrained(Team, TeamRecord, attributes, linked_mappings())) == 1 + + +exclusive_membership = Table( + "exclusive_membership", + Base.metadata, + Column("group_id", ForeignKey("groups.id", ondelete="CASCADE"), primary_key=True), + Column( + "user_id", + ForeignKey("users.id", ondelete="CASCADE"), + primary_key=True, + unique=True, + ), +) + + +class ExclusiveGroupRecord(Base): + """The groups, whose members belong to one group at most.""" + + __table__ = GroupRecord.__table__ + __mapper_args__ = {"version_id_col": __table__.c.version} + + members: Mapped[list[UserRecord]] = relationship(secondary=exclusive_membership) def test_a_unique_member_belongs_to_one_group(storage_factory, user_type, group_type): - """The value of a Link is checked as any other unique value.""" + """The constraint on the member column refuses a user in a second team.""" teams = ResourceMapping( Team, - GroupRecord, + ExclusiveGroupRecord, { - "id": GroupRecord.id, - "displayName": GroupRecord.display_name, - "members": Link(GroupRecord.members, "User", type="User"), - "meta.created": GroupRecord.created, - "meta.lastModified": GroupRecord.last_modified, + "id": ExclusiveGroupRecord.id, + "displayName": ExclusiveGroupRecord.display_name, + "members": Link(ExclusiveGroupRecord.members, "User", type="User"), + "meta.created": ExclusiveGroupRecord.created, + "meta.lastModified": ExclusiveGroupRecord.last_modified, }, - version=GroupRecord.version, + version=ExclusiveGroupRecord.version, ) - storage = storage_factory({"User": users_mapping(), "Group": teams}) + users = users_mapping({"groups": None}) + storage = storage_factory({"User": users, "Group": teams}) bjensen = storage.create(user_type, User(user_name="bjensen")) member = TeamMember(value=bjensen.id, type="User") team = storage.create(group_type, Team(display_name="Sales", members=[member])) @@ -176,42 +336,92 @@ def test_a_unique_member_belongs_to_one_group(storage_factory, user_type, group_ storage.create(group_type, Team(display_name="Support", members=[member])) -def test_an_update_taking_the_value_of_another_resource_type_is_refused( - storage_factory, -): - """Per RFC 7643 erratum 8279, an update looks for its new values in the other resource types too.""" - storage = storage_factory(MAILBOX_MAPPINGS) - mailbox = storage.create(MAILBOX_TYPE, Mailbox(display_name="Babs")) - storage.create( - SHARED_MAILBOX_TYPE, Mailbox(addresses=addresses(("team@example.com", "work"))) +class ExclusiveEmailRecord(Base): + """An email that the application refuses to give to two users, though SCIM does not.""" + + __tablename__ = "exclusive_emails" + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE") ) - mailbox.addresses = addresses(("team@example.com", "work")) + value: Mapped[str | None] = mapped_column(unique=True) - with pytest.raises(UniquenessException): - storage.update(MAILBOX_TYPE, mailbox) +class ExclusiveEmailUserRecord(Base): + """The users, whose emails no other user holds.""" + + __table__ = UserRecord.__table__ + __mapper_args__ = {"version_id_col": __table__.c.version} -def test_a_unique_value_another_resource_type_only_reads_is_taken( - sync_storage_factory, session + emails: Mapped[list[ExclusiveEmailRecord]] = relationship( + cascade="all, delete-orphan", order_by=ExclusiveEmailRecord.id + ) + + +def test_a_constraint_of_the_application_gives_a_409_without_attribute( + storage_factory, user_type ): - """Another application stores the owners of the shared mailboxes, which clients read, so a mailbox cannot take one.""" - shared = ResourceMapping( - Mailbox, - SharedMailboxRecord, + """emails.value is not unique in SCIM, so the 409 tells no attribute.""" + users = ResourceMapping( + User, + ExclusiveEmailUserRecord, { - "id": SharedMailboxRecord.id, - "owner.value": Attribute(SharedMailboxRecord.owner, writable=False), - "meta.created": SharedMailboxRecord.created, - "meta.lastModified": SharedMailboxRecord.last_modified, + "id": ExclusiveEmailUserRecord.id, + "userName": ExclusiveEmailUserRecord.user_name, + "emails": Many( + ExclusiveEmailUserRecord.emails, {"value": ExclusiveEmailRecord.value} + ), + "meta.created": ExclusiveEmailUserRecord.created, + "meta.lastModified": ExclusiveEmailUserRecord.last_modified, }, - version=SharedMailboxRecord.version, + version=ExclusiveEmailUserRecord.version, + ) + storage = storage_factory({"User": users}) + emails = [Email(value="babs@example.com")] + storage.create(user_type, User(user_name="bjensen", emails=emails)) + + with pytest.raises(UniquenessException) as error: + storage.create(user_type, User(user_name="babs", emails=emails)) + + assert error.value.detail == UniquenessException().detail + + +def test_a_409_tells_the_attribute_that_ignores_the_case(storage, user_type): + """The unique column computed from the comparison key refuses BJensen.""" + storage.create(user_type, User(user_name="bjensen")) + + with pytest.raises( + UniquenessException, match="^Uniqueness conflict with attribute userName$" + ): + storage.create(user_type, User(user_name="BJensen")) + + +@pytest.mark.parametrize( + ("dialect", "expected"), + [ + (postgresql.dialect(), 'normalize("userName", NFC)'), + (mysql.dialect(is_mariadb=True), "CONVERT(`userName` USING utf8mb4)"), + (sqlite.dialect(), 'lower("userName")'), + ], + ids=["postgresql", "mariadb", "sqlite"], +) +def test_the_comparison_key_quotes_its_column(dialect, expected): + """Unquoted, PostgreSQL would read the column username.""" + table = Table( + "accounts", + MetaData(), + Column("userName", String(255)), + Column("key", String(255), Computed(comparison_key("userName"))), ) - storage = sync_storage_factory( - MAPPINGS | {"Mailbox": mailboxes_mapping(), "SharedMailbox": shared} + + assert expected in str(CreateTable(table).compile(dialect=dialect)) + + +def test_a_409_tells_no_attribute_read_through_a_sql_expression(): + """No column holds the upper code, so a constraint refusing it names another column.""" + mapping = ResourceMapping( + Badge, BadgeRecord, {"id": BadgeRecord.id, "code": BadgeRecord.upper_code} ) - now = datetime.datetime.now(datetime.UTC) - session.add(SharedMailboxRecord(owner="bjensen", created=now, last_modified=now)) - session.flush() - with pytest.raises(UniquenessException): - storage.create(MAILBOX_TYPE, Mailbox(owner=MailboxOwner(value="BJensen"))) + assert list(mapping._unique_columns()) == [(BadgeRecord.__table__, "id")] diff --git a/uv.lock b/uv.lock index ec3a1fb..40b4089 100644 --- a/uv.lock +++ b/uv.lock @@ -1435,14 +1435,14 @@ wheels = [ [[package]] name = "scim2-server" -version = "0.10.0" +version = "0.11.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "scim2-models" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d8/f3/30ad252c00dd72a8c1270cb0e9f98daa0df5ac4ccdc6f0e5e7bed7a8c212/scim2_server-0.10.0.tar.gz", hash = "sha256:29eba120c131e919560d3a5c5632ce17e6e4da326659efd41c5d16971acbd077", size = 93498, upload-time = "2026-11-27T14:28:56.195Z" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/ba/251b27ba688e26190f485b2ea4603475973e259ddf0f9a7a3b26112b795e/scim2_server-0.11.0.tar.gz", hash = "sha256:5f20c3f642e8c6ddea2863715c041d108f063f67eaecf7f234125134a15e2493", size = 94410, upload-time = "2026-11-28T14:41:55.139Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f4/d0/d28e1c1eb4bf576cd6a7afc020cf043689fd0064084833f5f79b7e7a3716/scim2_server-0.10.0-py3-none-any.whl", hash = "sha256:94a4a34f0196fa8654ee91d49a570f4d408b901661df0394d4792dea73abba1c", size = 100433, upload-time = "2026-11-27T14:28:54.84Z" }, + { url = "https://files.pythonhosted.org/packages/7a/e8/49c89de57d4af549c31d60ffc9644702b91e7bbcef9bf09a1b0083660905/scim2_server-0.11.0-py3-none-any.whl", hash = "sha256:94bbd173b8c11ca36073c0426f66a08bacef99d45a965ce3896b4b1aaa727d0a", size = 101363, upload-time = "2026-11-28T14:41:53.803Z" }, ] [package.optional-dependencies] @@ -1496,7 +1496,7 @@ doc = [ [package.metadata] requires-dist = [ { name = "scim2-models", specifier = ">=0.12.7" }, - { name = "scim2-server", specifier = ">=0.10.0" }, + { name = "scim2-server", specifier = ">=0.11.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.10.0" }, + { name = "scim2-server", extras = ["testing"], specifier = ">=0.11.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" },