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
6 changes: 3 additions & 3 deletions doc/_examples/async_library_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
from scim2_models import ResourceType
from scim2_models import ResponseParameters
from scim2_models import SearchRequest
from scim2_models import UniquenessException

from doc._examples.library_storage import TABLES
from doc._examples.library_storage import uniqueness_conflict_of
from scim2_server.storage import AsyncScimStorage
from scim2_server.storage import SearchPage

Expand Down Expand Up @@ -127,9 +127,9 @@ async def writing(self) -> AsyncIterator[aiosqlite.Connection]:
try:
yield connection
await connection.commit()
except sqlite3.IntegrityError:
except sqlite3.IntegrityError as error:
await connection.rollback()
raise UniquenessException from None
raise uniqueness_conflict_of(error) from None

async def search(
self,
Expand Down
9 changes: 6 additions & 3 deletions doc/_examples/async_sqlite_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
from scim2_models import ResponseParameters
from scim2_models import ScimProvider
from scim2_models import SearchRequest
from scim2_models import UniquenessException

from doc._examples.sqlite_storage import TABLE
from doc._examples.sqlite_storage import USER_NAME
from scim2_server.storage import AsyncScimStorage
from scim2_server.storage import SearchPage
from scim2_server.storage import uniqueness_conflict


class AsyncSQLiteStorage(AsyncScimStorage):
Expand Down Expand Up @@ -149,9 +150,11 @@ async def writing(self) -> AsyncIterator[aiosqlite.Connection]:
try:
yield connection
await connection.commit()
except sqlite3.IntegrityError:
except sqlite3.IntegrityError as error:
await connection.rollback()
raise UniquenessException from None
if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE":
raise
raise uniqueness_conflict(USER_NAME) from None

async def search(
self,
Expand Down
22 changes: 18 additions & 4 deletions doc/_examples/library_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,19 @@
from scim2_models import Mutability
from scim2_models import Name
from scim2_models import NotFoundException
from scim2_models import Path
from scim2_models import PreconditionFailedException
from scim2_models import Required
from scim2_models import Resource
from scim2_models import ResourceType
from scim2_models import ResponseParameters
from scim2_models import SearchRequest
from scim2_models import Uniqueness
from scim2_models import UniquenessException
from scim2_models import User

from scim2_server.storage import ScimStorage
from scim2_server.storage import SearchPage
from scim2_server.storage import uniqueness_conflict

MEMBERS = """
CREATE TABLE IF NOT EXISTS members (
Expand All @@ -47,7 +48,7 @@
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
isbn TEXT UNIQUE,
isbn TEXT UNIQUE COLLATE NOCASE,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
Expand All @@ -67,6 +68,19 @@ class Book(Resource):

Member = User[LibraryMember]

UNIQUE_COLUMNS = {
"members.login": Path[Member]("userName").resolve(),
"books.isbn": Path[Book]("isbn").resolve(),
}


def uniqueness_conflict_of(error: sqlite3.IntegrityError) -> Exception:
"""Return the 409 of a violated UNIQUE constraint, or the error itself for another constraint."""
if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE":
return error
column = str(error).removeprefix("UNIQUE constraint failed: ")
return uniqueness_conflict(UNIQUE_COLUMNS[column])


def meta(resource_type: str, row: sqlite3.Row) -> Meta:
return Meta(
Expand Down Expand Up @@ -230,8 +244,8 @@ def writing(self) -> Iterator[None]:
try:
with self.connection:
yield
except sqlite3.IntegrityError:
raise UniquenessException from None
except sqlite3.IntegrityError as error:
raise uniqueness_conflict_of(error) from None

def search(
self,
Expand Down
12 changes: 9 additions & 3 deletions doc/_examples/sqlite_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@

from scim2_models import Meta
from scim2_models import NotFoundException
from scim2_models import Path
from scim2_models import PreconditionFailedException
from scim2_models import Resource
from scim2_models import ResourceType
from scim2_models import ResponseParameters
from scim2_models import ScimProvider
from scim2_models import SearchRequest
from scim2_models import UniquenessException
from scim2_models import User

from scim2_server.storage import ScimStorage
from scim2_server.storage import SearchPage
from scim2_server.storage import uniqueness_conflict

USER_NAME = Path[User]("userName").resolve()

TABLE = """
CREATE TABLE IF NOT EXISTS resources (
Expand Down Expand Up @@ -145,8 +149,10 @@ def writing(self) -> Iterator[None]:
try:
with self.connection:
yield
except sqlite3.IntegrityError:
raise UniquenessException from None
except sqlite3.IntegrityError as error:
if error.sqlite_errorname != "SQLITE_CONSTRAINT_UNIQUE":
raise
raise uniqueness_conflict(USER_NAME) from None

def search(
self,
Expand Down
28 changes: 27 additions & 1 deletion doc/changelog.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
Changelog
=========

[Unreleased]
------------

Added
^^^^^
- :meth:`AsyncInMemoryStorage.generate_id <scim2_server.memory.AsyncInMemoryStorage.generate_id>`
can await, for instance to take the identifier of an account created in another service.
- A resource holding the same unique value twice is refused with a 400.
- :func:`~scim2_server.storage.uniqueness_conflict` builds a 409 whose detail tells the
attribute, never the value.

Changed
^^^^^^^
- A unique value is unique within its resource type. A storage relies on the unique constraints
of its database. :data:`~scim2_server.testing.MAILBOX_TYPE` replaces ``MAILBOX_TYPES``.
- :meth:`ResourceMapping.unique_attributes <scim2_server.mapping.ResourceMapping.unique_attributes>`
is public.
- The in-memory storages call ``generate_id`` after the uniqueness checks, and it may return
``None``. An identifier already taken gives a 409 instead of replacing the resource.
:class:`~scim2_server.memory.AsyncInMemoryStorage` no longer calls the ``create`` method of the
storage it serves.

Removed
^^^^^^^
- ``scim2_server.storage.unique_values`` and ``scim2_server.mapping.filters.holds_any``.

[0.10.0] - 2026-11-27
---------------------

Expand All @@ -9,7 +35,7 @@ Added
- :class:`~scim2_server.testing.ScimStorageContract` checks the uniqueness of sub-attributes and
of multi-valued attributes, for a storage setting
:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes`.
:func:`~scim2_server.storage.unique_values` lists the values a storage checks.
``scim2_server.storage.unique_values`` lists the values a storage checks.

Changed
^^^^^^^
Expand Down
7 changes: 4 additions & 3 deletions doc/how-to/check-a-storage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ The suite checks what the method signatures do not tell: the copies, the 404 and
the dates and versions, the uniqueness of ``userName``, and the filters, sorting and paging of
the searches. It runs each filter and each sort of a list, and compares the answer of the
storage with the rules of SCIM. It uses the ``User`` and ``Group`` resource types of :rfc:`RFC 7643 <7643>`.
Run it on the database engine the application uses: a missing unique constraint then fails the
tests of the uniqueness.

Run the suite
-------------
Expand Down Expand Up @@ -125,9 +127,8 @@ to :data:`False`.

The suite checks the uniqueness of sub-attributes and of multi-valued attributes on
:class:`~scim2_server.testing.Mailbox` resources. To run these tests, set
:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes` to :data:`True`, and serve the
``Mailbox`` and ``SharedMailbox`` resource types. Both use the
:class:`~scim2_server.testing.Mailbox` model.
:attr:`~scim2_server.testing.ScimStorageContract.stores_mailboxes` to :data:`True`, and serve
:data:`~scim2_server.testing.MAILBOX_TYPE`.

A storage refuses a filter it cannot translate with :class:`~scim2_models.InvalidFilterException`,
and a sort with :class:`~scim2_models.InvalidPathException`. The suite skips the filters and the
Expand Down
33 changes: 23 additions & 10 deletions doc/how-to/write-a-storage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,21 @@ and start its version at 1:
Refuse a duplicate value
------------------------

In the default user resource, the ``userName`` of a user is unique, whatever its case. Compare the
values in the form :meth:`AttributeBinding.comparable <scim2_models.AttributeBinding.comparable>`
returns, as the filters do. The example relies on ``COLLATE NOCASE``, which only ignores the case
of ASCII letters: ``Élise`` and ``élise`` remain two users. On a creation and on an update, raise
:class:`~scim2_models.UniquenessException` when another user already has the value. The ``UNIQUE`` constraint of the table refuses such a write, even when two
requests arrive at the same time. The example commits each write, and turns the refusal into the
exception:
In the default user resource, the ``userName`` of a user is unique, whatever its case. Let the
database refuse a duplicate value with a unique constraint: it holds even when two requests arrive
at the same time. Two values that the filters find equal must be equal for the constraint too,
or a filter with ``eq`` finds two users. The filters compare the values in the form
:meth:`AttributeBinding.comparable <scim2_models.AttributeBinding.comparable>` returns. The
example relies on ``COLLATE NOCASE``, which only ignores the case of ASCII letters: ``Élise`` and
``élise`` remain two users. Document such differences for the users of the storage.

On a creation and on an update, raise :class:`~scim2_models.UniquenessException` when the
constraint refuses the write. Build it with :func:`~scim2_server.storage.uniqueness_conflict`: its
detail tells the attribute, and never the value. For a constraint on a field that holds no SCIM
attribute, raise the exception without detail, and do not pass on the message of the database,
which may hold the value. Turn only the violations of a unique constraint
into this exception: another error, such as a missing value, is a bug. The example commits each
write, and turns the refusal into the exception:

.. tab-set::
:class: outline
Expand All @@ -187,9 +195,14 @@ exception:
:dedent: 4

A sub-attribute can be unique too, such as the ``value`` of an email in a model of yours. Each
value of a multi-valued attribute then counts on its own, and two equal values in the same
resource do not clash. :func:`~scim2_server.storage.unique_values` lists the unique values of a
resource, by attribute.
value of a multi-valued attribute then counts on its own: put the constraint on the column of the
table holding the entries. The server refuses a resource holding the same unique value twice
before calling the storage. On an update, delete the former entries before inserting the new
ones, in the same transaction. A resource keeping a value, or swapping values between its
entries, then breaks no constraint.

The uniqueness holds within a resource type. Two resource types stored in two tables do not share
their unique values.

Update a resource
-----------------
Expand Down
4 changes: 2 additions & 2 deletions doc/reference/mapping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Resolution
----------

.. autoclass:: scim2_server.mapping.ResourceMapping
:members: schemas
:members: schemas, unique_attributes

.. autoclass:: scim2_server.mapping.MappingProblem

Expand All @@ -53,7 +53,7 @@ Filters and sorts
-----------------

.. automodule:: scim2_server.mapping.filters
:members: Predicates, where, compare, present, entry_present, sort_target, holds, holds_any
:members: Predicates, where, compare, present, entry_present, sort_target, holds

Reading and writing
-------------------
Expand Down
4 changes: 2 additions & 2 deletions doc/reference/storages.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ resources in memory.
.. autoclass:: scim2_server.storage.SearchPage
:members:

.. autofunction:: scim2_server.storage.unique_values
.. autofunction:: scim2_server.storage.uniqueness_conflict

.. autoclass:: scim2_server.memory.InMemoryStorage
:members: generate_id, next_version, operation

.. autoclass:: scim2_server.memory.AsyncInMemoryStorage
:members: resources
:members: resources, generate_id

Keyset pagination
-----------------
Expand Down
3 changes: 3 additions & 0 deletions doc/reference/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ The test suites checking that a storage follows the storage contract. They need

.. autoclass:: scim2_server.testing.MailboxOwner()

.. autodata:: scim2_server.testing.MAILBOX_TYPE
:no-value:

.. autoclass:: scim2_server.testing.AsyncScimStorageContract
12 changes: 6 additions & 6 deletions scim2_server/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,9 @@ def apply_bulk_operation(
request the operation stands for.
"""
if operation.method == BulkOperation.Method.post:
return self.storage.create(
resource_type, cast(Resource[Any], operation.data)
)
resource = cast(Resource[Any], operation.data)
self.service.check_unique_values(resource)
return self.storage.create(resource_type, resource)

resource_id = cast(str, operation.resource_id)
conditions = Conditions(if_match=operation.version)
Expand Down Expand Up @@ -649,9 +649,9 @@ async def apply_bulk_operation(
request the operation stands for.
"""
if operation.method == BulkOperation.Method.post:
return await self.storage.create(
resource_type, cast(Resource[Any], operation.data)
)
resource = cast(Resource[Any], operation.data)
self.service.check_unique_values(resource)
return await self.storage.create(resource_type, resource)

resource_id = cast(str, operation.resource_id)
conditions = Conditions(if_match=operation.version)
Expand Down
36 changes: 0 additions & 36 deletions scim2_server/mapping/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from typing import Any
from typing import Protocol
from typing import TypeVar
from typing import cast

from scim2_models import AttributeBinding
from scim2_models import InvalidFilterException
Expand Down Expand Up @@ -456,41 +455,6 @@ def compare(
)


def holds_any(
mapping: ResourceMapping,
conditions: Predicates[C],
policy: ScimPolicy,
binding: AttributeBinding,
values: list[Any],
) -> C:
"""Return the condition that a record holds one of some values of an attribute.

The attribute is one of the unique attributes of the mapping, and the
values are those of a resource, as
:func:`~scim2_server.storage.unique_values` returns them. The values are
compared as a filter with ``eq`` compares them, in the record, in an
Entry, in the entries of a collection or in a Link. The condition does
not leave out the written resource: the storage does.
"""

def any_value(inner: Predicates[C], column: Column) -> C:
return inner.any(
compare(mapping, inner, policy, column, CompareOperator.eq, value)
for value in values
)

holders = [
(collection, cast(Column, column))
for collection, column in mapping._lookup(binding)
]
return conditions.any(
any_value(conditions, column)
if collection is None
else conditions.exists(collection, partial(any_value, column=column))
for collection, column in holders
)


def _compare_constant(
mapping: ResourceMapping,
conditions: Predicates[C],
Expand Down
11 changes: 6 additions & 5 deletions scim2_server/mapping/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,13 +850,14 @@ def _string_columns(self) -> Iterator[Column]:
if column.is_string:
yield column

def _unique_attributes(self) -> dict[str, AttributeBinding]:
def unique_attributes(self) -> dict[str, AttributeBinding]:
"""Return the attributes whose values no two resources share, by URN.

They may be held by the record, by an Entry, by the entries of a
collection, or be the value of a Link. A value the storage only reads
counts too, as clients read it. The id is left out: the storage
generates it.
A storage puts a unique constraint on the fields holding them. They
may be held by the record, by an Entry, by the entries of a
collection, or be the value of a Link. A field the storage only reads
counts too, as clients read it. The id is left out: it is the primary
key.
"""
columns = [
*(column for column in self._columns.values() if column is not self._id),
Expand Down
Loading
Loading