Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions doc/_examples/intranet/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""The tables of an intranet application, before it serves SCIM."""
"""The tables of an intranet application, ready to serve SCIM."""

import datetime
import hashlib
import os
import uuid

from sqlalchemy import Column
from sqlalchemy import Computed
from sqlalchemy import ForeignKey
from sqlalchemy import Table
from sqlalchemy import func
Expand All @@ -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)
Expand All @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion doc/_examples/intranet/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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]
Expand Down
21 changes: 21 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -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
--------------------

Expand Down
86 changes: 55 additions & 31 deletions doc/explanation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
------------------------------------

Expand Down
14 changes: 8 additions & 6 deletions doc/how-to/compare-strings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -83,13 +84,14 @@ The comparisons happen in two places:
- :doc:`scim2-models <scim2_models:index>` and :doc:`scim2-server <scim2_server:index>` 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
Expand Down
4 changes: 4 additions & 0 deletions doc/how-to/generate-the-tables.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
40 changes: 40 additions & 0 deletions doc/how-to/map-a-data-model.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------

Expand Down
5 changes: 4 additions & 1 deletion doc/overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sqlalchemy:mapper_version_counter>`, declared as the
Expand Down
4 changes: 2 additions & 2 deletions doc/reference/errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions doc/reference/mapping.rst
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

Expand All @@ -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",
Expand Down Expand Up @@ -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]
Expand Down
4 changes: 4 additions & 0 deletions src/scim2_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -17,5 +19,7 @@
"Link",
"ResourceMapping",
"SqlAlchemyStorage",
"UniqueConstraintWarning",
"comparison_key",
"generate_mappings",
]
Loading