scim2-sqlalchemy 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scim2_sqlalchemy/__init__.py +19 -0
- scim2_sqlalchemy/comparison.py +173 -0
- scim2_sqlalchemy/conversion.py +305 -0
- scim2_sqlalchemy/generation.py +727 -0
- scim2_sqlalchemy/keyset.py +143 -0
- scim2_sqlalchemy/mapping.py +772 -0
- scim2_sqlalchemy/py.typed +0 -0
- scim2_sqlalchemy/query.py +558 -0
- scim2_sqlalchemy/storage.py +797 -0
- scim2_sqlalchemy-0.1.1.dist-info/METADATA +86 -0
- scim2_sqlalchemy-0.1.1.dist-info/RECORD +13 -0
- scim2_sqlalchemy-0.1.1.dist-info/WHEEL +4 -0
- scim2_sqlalchemy-0.1.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
from collections.abc import AsyncGenerator
|
|
3
|
+
from collections.abc import Awaitable
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from collections.abc import Generator
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from contextlib import asynccontextmanager
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from scim2_models import InvalidValueException
|
|
15
|
+
from scim2_models import NotFoundException
|
|
16
|
+
from scim2_models import Path
|
|
17
|
+
from scim2_models import PreconditionFailedException
|
|
18
|
+
from scim2_models import Resource
|
|
19
|
+
from scim2_models import ResourceType
|
|
20
|
+
from scim2_models import ResponseParameters
|
|
21
|
+
from scim2_models import ScimPolicy
|
|
22
|
+
from scim2_models import ScimProvider
|
|
23
|
+
from scim2_models import SearchRequest
|
|
24
|
+
from scim2_models import UniquenessException
|
|
25
|
+
from scim2_server.storage import AsyncScimStorage
|
|
26
|
+
from scim2_server.storage import ScimStorage
|
|
27
|
+
from scim2_server.storage import SearchPage
|
|
28
|
+
from sqlalchemy import Select
|
|
29
|
+
from sqlalchemy.exc import IntegrityError
|
|
30
|
+
from sqlalchemy.orm import Session
|
|
31
|
+
from sqlalchemy.orm.exc import StaleDataError
|
|
32
|
+
|
|
33
|
+
from .comparison import _Comparator
|
|
34
|
+
from .comparison import _comparator
|
|
35
|
+
from .conversion import _check_storable
|
|
36
|
+
from .conversion import _from_scim
|
|
37
|
+
from .conversion import _link_entries
|
|
38
|
+
from .conversion import _to_scim
|
|
39
|
+
from .conversion import _version
|
|
40
|
+
from .keyset import _Anchor
|
|
41
|
+
from .keyset import _anchor
|
|
42
|
+
from .keyset import _position
|
|
43
|
+
from .mapping import ResourceMapping
|
|
44
|
+
from .mapping import _Collection
|
|
45
|
+
from .query import _as_key
|
|
46
|
+
from .query import _links_statement
|
|
47
|
+
from .query import _load_statement
|
|
48
|
+
from .query import _records_statement
|
|
49
|
+
from .query import _root_statements
|
|
50
|
+
from .query import _search_statements
|
|
51
|
+
from .query import _taken_statement
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _utcnow() -> datetime.datetime:
|
|
58
|
+
"""Return the current time, in UTC."""
|
|
59
|
+
return datetime.datetime.now(datetime.UTC)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _expire(
|
|
63
|
+
session: "Session | AsyncSession", mapping: ResourceMapping, resource_id: str | None
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Expire the record of an identifier when the session holds it, so that loading it reads the database again.
|
|
66
|
+
|
|
67
|
+
Only this record is read again: a record linking to itself, such as a
|
|
68
|
+
group holding itself, is then loaded once, with all its collections.
|
|
69
|
+
"""
|
|
70
|
+
key = _as_key(mapping._id, resource_id)
|
|
71
|
+
if key is None:
|
|
72
|
+
return
|
|
73
|
+
record = session.identity_map.get(session.identity_key(mapping.record, key))
|
|
74
|
+
if record is not None:
|
|
75
|
+
session.expire(record)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _holds_id(collection: _Collection, record: Any, value: str) -> bool:
|
|
79
|
+
"""Tell whether a record a Link links to has an identifier."""
|
|
80
|
+
target_id = collection.target._id # type: ignore[union-attr]
|
|
81
|
+
return bool(getattr(record, target_id.key) == _as_key(target_id, value))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _by_position(rows: Sequence[Any]) -> dict[int, list[str]]:
|
|
85
|
+
"""Group the identifiers of a page at the root by position of their resource type."""
|
|
86
|
+
ids: dict[int, list[str]] = {}
|
|
87
|
+
for position, record_id, _ in rows:
|
|
88
|
+
ids.setdefault(position, []).append(record_id)
|
|
89
|
+
return ids
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _page_rows(
|
|
93
|
+
rows: Sequence[Any], search_request: SearchRequest[Any], anchor: _Anchor | None
|
|
94
|
+
) -> tuple[list[Any], bool]:
|
|
95
|
+
"""Return the rows of a page in the sort order, and whether more rows follow in the reading direction.
|
|
96
|
+
|
|
97
|
+
The rows of a cursor page were read count + 1 at a time, in the reverse
|
|
98
|
+
order for a previous page.
|
|
99
|
+
"""
|
|
100
|
+
if search_request.cursor is None:
|
|
101
|
+
return list(rows), False
|
|
102
|
+
count = search_request.count
|
|
103
|
+
more = count is not None and len(rows) > count
|
|
104
|
+
page = list(rows if count is None else rows[:count])
|
|
105
|
+
if anchor is not None and not anchor.forward:
|
|
106
|
+
page.reverse()
|
|
107
|
+
return page, more
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _cursor_page(
|
|
111
|
+
total: int,
|
|
112
|
+
resources: list[Resource[Any]],
|
|
113
|
+
bounds: list[tuple[Any, tuple[Any, ...]]],
|
|
114
|
+
more: bool,
|
|
115
|
+
anchor: _Anchor | None,
|
|
116
|
+
) -> SearchPage:
|
|
117
|
+
"""Return a cursor page with the positions of the pages around it.
|
|
118
|
+
|
|
119
|
+
bounds holds the sort value and the ties of the first and the last rows
|
|
120
|
+
of the page. A page is known to follow in the reading direction only. In
|
|
121
|
+
the other direction, the page the client comes from is assumed to still
|
|
122
|
+
exist.
|
|
123
|
+
"""
|
|
124
|
+
page = SearchPage(total, resources)
|
|
125
|
+
if not bounds:
|
|
126
|
+
return page
|
|
127
|
+
forward = anchor is None or anchor.forward
|
|
128
|
+
if more or not forward:
|
|
129
|
+
page.next = _position("next", *bounds[-1])
|
|
130
|
+
if anchor is not None and (more or forward):
|
|
131
|
+
page.previous = _position("previous", *bounds[0])
|
|
132
|
+
return page
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _nothing() -> None:
|
|
136
|
+
"""Check nothing, as the default uniqueness check of a flush."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def _nothing_async() -> None:
|
|
140
|
+
"""Check nothing, as the default uniqueness check of a flush."""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class _StorageBase:
|
|
144
|
+
"""What the synchronous and asynchronous storages share: everything but the queries."""
|
|
145
|
+
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
mappings: Mapping[str, ResourceMapping],
|
|
149
|
+
provider: ScimProvider | None,
|
|
150
|
+
) -> None:
|
|
151
|
+
self.mappings = dict(mappings)
|
|
152
|
+
self.provider = provider
|
|
153
|
+
self._policy = provider.policy if provider else ScimPolicy()
|
|
154
|
+
self._comparators: dict[str, _Comparator] = {}
|
|
155
|
+
self._endpoints = {
|
|
156
|
+
str(resource_type.name): str(resource_type.endpoint).strip("/")
|
|
157
|
+
for resource_type in (provider.resource_types if provider else ())
|
|
158
|
+
}
|
|
159
|
+
for mapping in self.mappings.values():
|
|
160
|
+
mapping._bind(self.mappings)
|
|
161
|
+
|
|
162
|
+
def _mapping(self, resource_type: ResourceType) -> ResourceMapping:
|
|
163
|
+
"""Return the mapping of a resource type."""
|
|
164
|
+
return self.mappings[resource_type.name] # type: ignore[index]
|
|
165
|
+
|
|
166
|
+
def _root_page(
|
|
167
|
+
self,
|
|
168
|
+
resource_types: list[ResourceType],
|
|
169
|
+
rows: Sequence[Any],
|
|
170
|
+
records: dict[tuple[int, str], Any],
|
|
171
|
+
search_request: SearchRequest[Any],
|
|
172
|
+
) -> list[Resource[Any]]:
|
|
173
|
+
"""Build the resources of a page at the root, in the order of the page.
|
|
174
|
+
|
|
175
|
+
records holds the loaded records by position of their resource type
|
|
176
|
+
and identifier as text. A record deleted after the page was selected
|
|
177
|
+
is left out.
|
|
178
|
+
"""
|
|
179
|
+
return [
|
|
180
|
+
self._to_scim(
|
|
181
|
+
resource_types[position], records[position, record_id], search_request
|
|
182
|
+
)
|
|
183
|
+
for position, record_id, _ in rows
|
|
184
|
+
if (position, record_id) in records
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
def _root_search_page(
|
|
188
|
+
self,
|
|
189
|
+
resource_types: list[ResourceType],
|
|
190
|
+
total: int,
|
|
191
|
+
rows: list[Any],
|
|
192
|
+
more: bool,
|
|
193
|
+
records: dict[tuple[int, str], Any],
|
|
194
|
+
search_request: SearchRequest[Any],
|
|
195
|
+
anchor: _Anchor | None,
|
|
196
|
+
) -> SearchPage:
|
|
197
|
+
"""Build the page of a search at the root, from its rows and the records they load."""
|
|
198
|
+
resources = self._root_page(resource_types, rows, records, search_request)
|
|
199
|
+
if search_request.cursor is None:
|
|
200
|
+
return SearchPage(total, resources)
|
|
201
|
+
bounds = [
|
|
202
|
+
(key, (type_position, record_id))
|
|
203
|
+
for type_position, record_id, key in rows[:1] + rows[-1:]
|
|
204
|
+
]
|
|
205
|
+
return _cursor_page(total, resources, bounds, more, anchor)
|
|
206
|
+
|
|
207
|
+
def _page(
|
|
208
|
+
self,
|
|
209
|
+
resource_type: ResourceType,
|
|
210
|
+
total: int,
|
|
211
|
+
rows: Sequence[Any],
|
|
212
|
+
search_request: SearchRequest[Any],
|
|
213
|
+
anchor: _Anchor | None,
|
|
214
|
+
) -> SearchPage:
|
|
215
|
+
"""Build the page of a search on one resource type, from its records with their sort value and identifier."""
|
|
216
|
+
page, more = _page_rows(rows, search_request, anchor)
|
|
217
|
+
resources = [
|
|
218
|
+
self._to_scim(resource_type, record, search_request)
|
|
219
|
+
for record, _, _ in page
|
|
220
|
+
]
|
|
221
|
+
if search_request.cursor is None:
|
|
222
|
+
return SearchPage(total, resources)
|
|
223
|
+
bounds = [(key, (record_id,)) for _, key, record_id in page[:1] + page[-1:]]
|
|
224
|
+
return _cursor_page(total, resources, bounds, more, anchor)
|
|
225
|
+
|
|
226
|
+
def _model(self, resource_type: ResourceType) -> type[Resource[Any]]:
|
|
227
|
+
"""Return the model of the resources of a resource type: the one of the provider, if any."""
|
|
228
|
+
model = self.provider.model_for(resource_type) if self.provider else None
|
|
229
|
+
return model or self._mapping(resource_type).model # type: ignore[return-value]
|
|
230
|
+
|
|
231
|
+
def _to_scim(
|
|
232
|
+
self,
|
|
233
|
+
resource_type: ResourceType,
|
|
234
|
+
record: Any,
|
|
235
|
+
parameters: ResponseParameters[Any] | None = None,
|
|
236
|
+
) -> Resource[Any]:
|
|
237
|
+
"""Build the resource a record stores, with the collections the response keeps."""
|
|
238
|
+
mapping = self._mapping(resource_type)
|
|
239
|
+
model = self._model(resource_type)
|
|
240
|
+
collections = mapping._returned_collections(parameters)
|
|
241
|
+
return _to_scim(
|
|
242
|
+
mapping,
|
|
243
|
+
record,
|
|
244
|
+
resource_type.name, # type: ignore[arg-type]
|
|
245
|
+
model,
|
|
246
|
+
self._endpoints,
|
|
247
|
+
collections,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
def _check_storable(
|
|
251
|
+
self, resource_type: ResourceType, resource: Resource[Any], record: Any
|
|
252
|
+
) -> None:
|
|
253
|
+
"""Refuse a change the mapping cannot store. record is None for a new resource."""
|
|
254
|
+
stored = None if record is None else self._to_scim(resource_type, record)
|
|
255
|
+
_check_storable(self._mapping(resource_type), resource, stored)
|
|
256
|
+
|
|
257
|
+
@staticmethod
|
|
258
|
+
def _not_found(
|
|
259
|
+
resource_type: ResourceType, resource_id: str | None
|
|
260
|
+
) -> NotFoundException:
|
|
261
|
+
"""Return the error of a resource that does not exist."""
|
|
262
|
+
return NotFoundException(
|
|
263
|
+
detail=f"{resource_type.name} {resource_id!r} not found"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
@staticmethod
|
|
267
|
+
def _check_version(
|
|
268
|
+
mapping: ResourceMapping, record: Any, expected_version: str | None
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Refuse to change a record whose version is not the expected one."""
|
|
271
|
+
if (
|
|
272
|
+
expected_version is not None
|
|
273
|
+
and _version(mapping, record) != expected_version
|
|
274
|
+
):
|
|
275
|
+
raise PreconditionFailedException
|
|
276
|
+
|
|
277
|
+
def _comparator(self, dialect: str) -> _Comparator:
|
|
278
|
+
"""Return how a database compares strings, built once for each dialect."""
|
|
279
|
+
if dialect not in self._comparators:
|
|
280
|
+
self._comparators[dialect] = _comparator(
|
|
281
|
+
dialect, self._policy, self.mappings.values()
|
|
282
|
+
)
|
|
283
|
+
return self._comparators[dialect]
|
|
284
|
+
|
|
285
|
+
@staticmethod
|
|
286
|
+
def _unique_statements(
|
|
287
|
+
mapping: ResourceMapping, resource: Resource[Any], comparator: _Comparator
|
|
288
|
+
) -> Iterator[Select[Any]]:
|
|
289
|
+
"""Yield the statements finding another record holding a unique value of the resource.
|
|
290
|
+
|
|
291
|
+
A missing value never clashes, as a SQL NULL does not.
|
|
292
|
+
"""
|
|
293
|
+
for column in mapping._unique_columns():
|
|
294
|
+
value = Path(column.binding.urn).get(resource, strict=False)
|
|
295
|
+
if value is not None:
|
|
296
|
+
yield _taken_statement(mapping, column, value, resource.id, comparator)
|
|
297
|
+
|
|
298
|
+
def _assign_links(
|
|
299
|
+
self, found: list[tuple[_Collection, list[Any]]], entries: list[Any]
|
|
300
|
+
) -> dict[_Collection, list[Any]]:
|
|
301
|
+
"""Give each entry of an attribute the record it links to, in the collection of the first Link holding that record.
|
|
302
|
+
|
|
303
|
+
found holds the records each Link of the attribute holds among the
|
|
304
|
+
values of the entries. An entry with a type links to a Link giving
|
|
305
|
+
the same type.
|
|
306
|
+
"""
|
|
307
|
+
links: dict[_Collection, list[Any]] = {
|
|
308
|
+
collection: [] for collection, _ in found
|
|
309
|
+
}
|
|
310
|
+
urn = found[0][0].binding.urn
|
|
311
|
+
for entry in entries:
|
|
312
|
+
matches = [
|
|
313
|
+
(collection, record)
|
|
314
|
+
for collection, records in found
|
|
315
|
+
for record in records
|
|
316
|
+
if _holds_id(collection, record, entry.value)
|
|
317
|
+
]
|
|
318
|
+
if not matches:
|
|
319
|
+
raise InvalidValueException(
|
|
320
|
+
detail=f"'{urn}' links to an unknown resource"
|
|
321
|
+
)
|
|
322
|
+
entry_type = getattr(entry, "type", None)
|
|
323
|
+
if entry_type is not None:
|
|
324
|
+
matches = [
|
|
325
|
+
(collection, record)
|
|
326
|
+
for collection, record in matches
|
|
327
|
+
if self._same_type(collection, entry_type)
|
|
328
|
+
]
|
|
329
|
+
if not matches:
|
|
330
|
+
raise InvalidValueException(
|
|
331
|
+
detail=f"'{urn}' links to {entry.value!r}, which is not "
|
|
332
|
+
f"of type {entry_type!r}"
|
|
333
|
+
)
|
|
334
|
+
collection, record = matches[0]
|
|
335
|
+
if record not in links[collection]:
|
|
336
|
+
links[collection].append(record)
|
|
337
|
+
return links
|
|
338
|
+
|
|
339
|
+
def _same_type(self, collection: _Collection, value: str) -> bool:
|
|
340
|
+
"""Tell whether a type is the one a Link gives, compared as filters compare it."""
|
|
341
|
+
binding = collection.type_column.binding # type: ignore[union-attr]
|
|
342
|
+
try:
|
|
343
|
+
return bool(
|
|
344
|
+
binding.comparable(value, self._policy)
|
|
345
|
+
== binding.comparable(collection.link_type, self._policy)
|
|
346
|
+
)
|
|
347
|
+
except ValueError:
|
|
348
|
+
return False
|
|
349
|
+
|
|
350
|
+
def _new_record(self, resource_type: ResourceType, resource: Resource[Any]) -> Any:
|
|
351
|
+
"""Build an empty record for a new resource, with its dates.
|
|
352
|
+
|
|
353
|
+
The resource is written once the record is in the session, so that the
|
|
354
|
+
records it links to do not pull a record the session does not know.
|
|
355
|
+
"""
|
|
356
|
+
mapping = self._mapping(resource_type)
|
|
357
|
+
record = mapping.record()
|
|
358
|
+
now = _utcnow()
|
|
359
|
+
setattr(record, mapping._created.key, now)
|
|
360
|
+
setattr(record, mapping._last_modified.key, now)
|
|
361
|
+
return record
|
|
362
|
+
|
|
363
|
+
def _write_record(
|
|
364
|
+
self,
|
|
365
|
+
mapping: ResourceMapping,
|
|
366
|
+
resource: Resource[Any],
|
|
367
|
+
record: Any,
|
|
368
|
+
links: dict[_Collection, list[Any]],
|
|
369
|
+
) -> None:
|
|
370
|
+
"""Write a resource in its record, and date the write.
|
|
371
|
+
|
|
372
|
+
The date changes the row even when only links change, such as the
|
|
373
|
+
members of a group, so that the version changes too.
|
|
374
|
+
"""
|
|
375
|
+
_from_scim(mapping, resource, record, links, creating=False)
|
|
376
|
+
setattr(record, mapping._last_modified.key, _utcnow())
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class SqlAlchemyStorage(_StorageBase, ScimStorage):
|
|
380
|
+
"""Store SCIM resources in the records of SQLAlchemy models.
|
|
381
|
+
|
|
382
|
+
The storage never commits: committing the request is left to the
|
|
383
|
+
application. Each write is :ref:`flushed <sqlalchemy:session_flushing>`, so that the database fills the
|
|
384
|
+
identifiers and checks its constraints.
|
|
385
|
+
|
|
386
|
+
A change the mappings cannot store raises an error rather than being lost:
|
|
387
|
+
:class:`~scim2_models.InvalidValueException` for an attribute no mapping
|
|
388
|
+
stores, and :class:`~scim2_models.MutabilityException` for an attribute
|
|
389
|
+
the mapping only reads. A value equal to the stored one is accepted, so a
|
|
390
|
+
resource read and sent back can always be written.
|
|
391
|
+
|
|
392
|
+
:param mappings: The mapping of each resource type, by resource type name.
|
|
393
|
+
:param session: Return the current :class:`~sqlalchemy.orm.Session`, such
|
|
394
|
+
as a :class:`~sqlalchemy.orm.scoped_session`.
|
|
395
|
+
:param provider: The provider of the server. The storage then returns
|
|
396
|
+
instances of its models, rather than of the models of the mappings,
|
|
397
|
+
and gives each link a ``$ref`` relative to the SCIM root, from the
|
|
398
|
+
endpoints of its resource types. Strings are compared with the
|
|
399
|
+
:attr:`~scim2_models.ScimPolicy.comparison_key` of its policy.
|
|
400
|
+
"""
|
|
401
|
+
|
|
402
|
+
supports_cursors = True
|
|
403
|
+
|
|
404
|
+
def __init__(
|
|
405
|
+
self,
|
|
406
|
+
mappings: Mapping[str, ResourceMapping],
|
|
407
|
+
session: Callable[[], Session],
|
|
408
|
+
provider: ScimProvider | None = None,
|
|
409
|
+
) -> None:
|
|
410
|
+
super().__init__(mappings, provider)
|
|
411
|
+
self.session = session
|
|
412
|
+
|
|
413
|
+
@contextmanager
|
|
414
|
+
def operation(self) -> Generator[None]:
|
|
415
|
+
"""Run the operation in a savepoint.
|
|
416
|
+
|
|
417
|
+
The savepoint comes from :meth:`~sqlalchemy.orm.Session.begin_nested`.
|
|
418
|
+
A failed operation of a bulk request is then rolled back alone
|
|
419
|
+
(:rfc:`RFC 7644 §3.7 <7644#section-3.7>`).
|
|
420
|
+
"""
|
|
421
|
+
with self.session().begin_nested():
|
|
422
|
+
yield
|
|
423
|
+
|
|
424
|
+
def get(
|
|
425
|
+
self,
|
|
426
|
+
resource_type: ResourceType,
|
|
427
|
+
resource_id: str,
|
|
428
|
+
*,
|
|
429
|
+
response_parameters: ResponseParameters[Any] | None = None,
|
|
430
|
+
) -> Resource[Any]:
|
|
431
|
+
"""Return a resource, with the attributes the response keeps."""
|
|
432
|
+
record = self._load(resource_type, resource_id, response_parameters)
|
|
433
|
+
return self._to_scim(resource_type, record, response_parameters)
|
|
434
|
+
|
|
435
|
+
def search(
|
|
436
|
+
self,
|
|
437
|
+
resource_types: list[ResourceType],
|
|
438
|
+
search_request: SearchRequest[Any],
|
|
439
|
+
*,
|
|
440
|
+
position: Any = None,
|
|
441
|
+
) -> SearchPage:
|
|
442
|
+
"""Return a page of the resources matching a search, on one resource type or at the root."""
|
|
443
|
+
if not resource_types:
|
|
444
|
+
return SearchPage(0, [])
|
|
445
|
+
session = self.session()
|
|
446
|
+
comparator = self._ready_comparator(session)
|
|
447
|
+
mappings = [self._mapping(resource_type) for resource_type in resource_types]
|
|
448
|
+
anchor = _anchor(position, root=len(mappings) > 1)
|
|
449
|
+
if len(mappings) == 1:
|
|
450
|
+
count, statement = _search_statements(
|
|
451
|
+
mappings[0], search_request, comparator, anchor
|
|
452
|
+
)
|
|
453
|
+
total = session.scalar(count) or 0
|
|
454
|
+
rows = session.execute(statement).all()
|
|
455
|
+
return self._page(resource_types[0], total, rows, search_request, anchor)
|
|
456
|
+
|
|
457
|
+
count, statement = _root_statements(
|
|
458
|
+
mappings, search_request, comparator, anchor
|
|
459
|
+
)
|
|
460
|
+
total = session.scalar(count) or 0
|
|
461
|
+
rows, more = _page_rows(
|
|
462
|
+
session.execute(statement).all(), search_request, anchor
|
|
463
|
+
)
|
|
464
|
+
records = {}
|
|
465
|
+
for type_position, ids in _by_position(rows).items():
|
|
466
|
+
loading = _records_statement(mappings[type_position], ids, search_request)
|
|
467
|
+
for record_id, record in session.execute(loading):
|
|
468
|
+
records[type_position, record_id] = record
|
|
469
|
+
return self._root_search_page(
|
|
470
|
+
resource_types, total, rows, more, records, search_request, anchor
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
def create(
|
|
474
|
+
self, resource_type: ResourceType, resource: Resource[Any]
|
|
475
|
+
) -> Resource[Any]:
|
|
476
|
+
"""Store a new resource, and return it as stored."""
|
|
477
|
+
mapping = self._mapping(resource_type)
|
|
478
|
+
self._check_storable(resource_type, resource, None)
|
|
479
|
+
self._check_uniqueness(mapping, resource)
|
|
480
|
+
links = self._links(mapping, resource)
|
|
481
|
+
record = self._new_record(resource_type, resource)
|
|
482
|
+
|
|
483
|
+
def change() -> None:
|
|
484
|
+
self.session().add(record)
|
|
485
|
+
_from_scim(mapping, resource, record, links, creating=True)
|
|
486
|
+
|
|
487
|
+
self._flush(change, lambda: self._check_uniqueness(mapping, resource))
|
|
488
|
+
return self.get(resource_type, str(getattr(record, mapping._id.key)))
|
|
489
|
+
|
|
490
|
+
def update(
|
|
491
|
+
self,
|
|
492
|
+
resource_type: ResourceType,
|
|
493
|
+
resource: Resource[Any],
|
|
494
|
+
*,
|
|
495
|
+
expected_version: str | None = None,
|
|
496
|
+
) -> Resource[Any]:
|
|
497
|
+
"""Replace a resource, and return it as stored."""
|
|
498
|
+
mapping = self._mapping(resource_type)
|
|
499
|
+
record = self._load(resource_type, resource.id)
|
|
500
|
+
self._check_version(mapping, record, expected_version)
|
|
501
|
+
self._check_storable(resource_type, resource, record)
|
|
502
|
+
self._check_uniqueness(mapping, resource)
|
|
503
|
+
links = self._links(mapping, resource)
|
|
504
|
+
self._flush(
|
|
505
|
+
lambda: self._write_record(mapping, resource, record, links),
|
|
506
|
+
lambda: self._check_uniqueness(mapping, resource),
|
|
507
|
+
)
|
|
508
|
+
return self.get(resource_type, resource.id) # type: ignore[arg-type]
|
|
509
|
+
|
|
510
|
+
def delete(
|
|
511
|
+
self,
|
|
512
|
+
resource_type: ResourceType,
|
|
513
|
+
resource_id: str,
|
|
514
|
+
*,
|
|
515
|
+
expected_version: str | None = None,
|
|
516
|
+
) -> None:
|
|
517
|
+
"""Delete a resource."""
|
|
518
|
+
mapping = self._mapping(resource_type)
|
|
519
|
+
record = self._load(resource_type, resource_id)
|
|
520
|
+
self._check_version(mapping, record, expected_version)
|
|
521
|
+
self._flush(lambda: self.session().delete(record))
|
|
522
|
+
|
|
523
|
+
def _load(
|
|
524
|
+
self,
|
|
525
|
+
resource_type: ResourceType,
|
|
526
|
+
resource_id: str | None,
|
|
527
|
+
parameters: ResponseParameters[Any] | None = None,
|
|
528
|
+
) -> Any:
|
|
529
|
+
"""Load a record, with the collections the response keeps."""
|
|
530
|
+
mapping = self._mapping(resource_type)
|
|
531
|
+
statement = _load_statement(mapping, resource_id, parameters)
|
|
532
|
+
_expire(self.session(), mapping, resource_id)
|
|
533
|
+
record = None if statement is None else self.session().scalar(statement)
|
|
534
|
+
if record is None:
|
|
535
|
+
raise self._not_found(resource_type, resource_id)
|
|
536
|
+
return record
|
|
537
|
+
|
|
538
|
+
def _check_uniqueness(
|
|
539
|
+
self, mapping: ResourceMapping, resource: Resource[Any]
|
|
540
|
+
) -> None:
|
|
541
|
+
"""Refuse a resource with a unique value another resource already has."""
|
|
542
|
+
session = self.session()
|
|
543
|
+
comparator = self._ready_comparator(session)
|
|
544
|
+
for statement in self._unique_statements(mapping, resource, comparator):
|
|
545
|
+
if session.scalar(statement) is not None:
|
|
546
|
+
raise UniquenessException
|
|
547
|
+
|
|
548
|
+
def _ready_comparator(self, session: Session) -> _Comparator:
|
|
549
|
+
"""Return how the database of the session compares strings, ready to compare them."""
|
|
550
|
+
connection = session.connection()
|
|
551
|
+
comparator = self._comparator(connection.dialect.name)
|
|
552
|
+
comparator.prepare(connection.connection.driver_connection)
|
|
553
|
+
return comparator
|
|
554
|
+
|
|
555
|
+
def _links(
|
|
556
|
+
self, mapping: ResourceMapping, resource: Resource[Any]
|
|
557
|
+
) -> dict[_Collection, list[Any]]:
|
|
558
|
+
"""Return the records each Link of a resource links to, refusing a value that links to nothing."""
|
|
559
|
+
links: dict[_Collection, list[Any]] = {}
|
|
560
|
+
for collections, entries in _link_entries(mapping, resource):
|
|
561
|
+
ids = [entry.value for entry in entries]
|
|
562
|
+
found = [
|
|
563
|
+
(
|
|
564
|
+
collection,
|
|
565
|
+
list(
|
|
566
|
+
self.session().scalars(_links_statement(collection, ids)).all()
|
|
567
|
+
),
|
|
568
|
+
)
|
|
569
|
+
for collection in collections
|
|
570
|
+
]
|
|
571
|
+
links |= self._assign_links(found, entries)
|
|
572
|
+
return links
|
|
573
|
+
|
|
574
|
+
def _flush(
|
|
575
|
+
self,
|
|
576
|
+
change: Callable[[], None],
|
|
577
|
+
check_uniqueness: Callable[[], None] = _nothing,
|
|
578
|
+
) -> None:
|
|
579
|
+
"""Apply a change in a savepoint, and flush it.
|
|
580
|
+
|
|
581
|
+
A version changed in the meantime by another transaction raises a 412.
|
|
582
|
+
On an integrity error, check_uniqueness runs again, so that a unique
|
|
583
|
+
value taken in the meantime raises a 409.
|
|
584
|
+
"""
|
|
585
|
+
session = self.session()
|
|
586
|
+
try:
|
|
587
|
+
with session.begin_nested():
|
|
588
|
+
change()
|
|
589
|
+
session.flush()
|
|
590
|
+
except StaleDataError as exception:
|
|
591
|
+
raise PreconditionFailedException from exception
|
|
592
|
+
except IntegrityError:
|
|
593
|
+
check_uniqueness()
|
|
594
|
+
raise
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
class AsyncSqlAlchemyStorage(_StorageBase, AsyncScimStorage):
|
|
598
|
+
"""The asynchronous variant of :class:`SqlAlchemyStorage`.
|
|
599
|
+
|
|
600
|
+
It needs the ``asyncio`` extra, which installs the asynchronous support of
|
|
601
|
+
SQLAlchemy: ``pip install "scim2-sqlalchemy[asyncio]"``.
|
|
602
|
+
|
|
603
|
+
:param mappings: The mapping of each resource type, by resource type name.
|
|
604
|
+
:param session: Return the current
|
|
605
|
+
:class:`~sqlalchemy.ext.asyncio.AsyncSession`, such as an
|
|
606
|
+
:class:`~sqlalchemy.ext.asyncio.async_scoped_session`.
|
|
607
|
+
:param provider: The provider of the server. The storage then returns
|
|
608
|
+
instances of its models, rather than of the models of the mappings.
|
|
609
|
+
Strings are compared with the
|
|
610
|
+
:attr:`~scim2_models.ScimPolicy.comparison_key` of its policy.
|
|
611
|
+
"""
|
|
612
|
+
|
|
613
|
+
supports_cursors = True
|
|
614
|
+
|
|
615
|
+
def __init__(
|
|
616
|
+
self,
|
|
617
|
+
mappings: Mapping[str, ResourceMapping],
|
|
618
|
+
session: Callable[[], "AsyncSession"],
|
|
619
|
+
provider: ScimProvider | None = None,
|
|
620
|
+
) -> None:
|
|
621
|
+
super().__init__(mappings, provider)
|
|
622
|
+
self.session = session
|
|
623
|
+
|
|
624
|
+
@asynccontextmanager
|
|
625
|
+
async def operation(self) -> AsyncGenerator[None]:
|
|
626
|
+
"""Run the operation in a savepoint. See :meth:`SqlAlchemyStorage.operation`."""
|
|
627
|
+
async with self.session().begin_nested():
|
|
628
|
+
yield
|
|
629
|
+
|
|
630
|
+
async def get(
|
|
631
|
+
self,
|
|
632
|
+
resource_type: ResourceType,
|
|
633
|
+
resource_id: str,
|
|
634
|
+
*,
|
|
635
|
+
response_parameters: ResponseParameters[Any] | None = None,
|
|
636
|
+
) -> Resource[Any]:
|
|
637
|
+
"""Return a resource, with the attributes the response keeps."""
|
|
638
|
+
record = await self._load(resource_type, resource_id, response_parameters)
|
|
639
|
+
return self._to_scim(resource_type, record, response_parameters)
|
|
640
|
+
|
|
641
|
+
async def search(
|
|
642
|
+
self,
|
|
643
|
+
resource_types: list[ResourceType],
|
|
644
|
+
search_request: SearchRequest[Any],
|
|
645
|
+
*,
|
|
646
|
+
position: Any = None,
|
|
647
|
+
) -> SearchPage:
|
|
648
|
+
"""Return a page of the resources matching a search, on one resource type or at the root."""
|
|
649
|
+
if not resource_types:
|
|
650
|
+
return SearchPage(0, [])
|
|
651
|
+
session = self.session()
|
|
652
|
+
comparator = await self._ready_comparator(session)
|
|
653
|
+
mappings = [self._mapping(resource_type) for resource_type in resource_types]
|
|
654
|
+
anchor = _anchor(position, root=len(mappings) > 1)
|
|
655
|
+
if len(mappings) == 1:
|
|
656
|
+
count, statement = _search_statements(
|
|
657
|
+
mappings[0], search_request, comparator, anchor
|
|
658
|
+
)
|
|
659
|
+
total = await session.scalar(count) or 0
|
|
660
|
+
rows = (await session.execute(statement)).all()
|
|
661
|
+
return self._page(resource_types[0], total, rows, search_request, anchor)
|
|
662
|
+
|
|
663
|
+
count, statement = _root_statements(
|
|
664
|
+
mappings, search_request, comparator, anchor
|
|
665
|
+
)
|
|
666
|
+
total = await session.scalar(count) or 0
|
|
667
|
+
rows, more = _page_rows(
|
|
668
|
+
(await session.execute(statement)).all(), search_request, anchor
|
|
669
|
+
)
|
|
670
|
+
records = {}
|
|
671
|
+
for type_position, ids in _by_position(rows).items():
|
|
672
|
+
loading = _records_statement(mappings[type_position], ids, search_request)
|
|
673
|
+
for record_id, record in await session.execute(loading):
|
|
674
|
+
records[type_position, record_id] = record
|
|
675
|
+
return self._root_search_page(
|
|
676
|
+
resource_types, total, rows, more, records, search_request, anchor
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
async def create(
|
|
680
|
+
self, resource_type: ResourceType, resource: Resource[Any]
|
|
681
|
+
) -> Resource[Any]:
|
|
682
|
+
"""Store a new resource, and return it as stored."""
|
|
683
|
+
mapping = self._mapping(resource_type)
|
|
684
|
+
self._check_storable(resource_type, resource, None)
|
|
685
|
+
await self._check_uniqueness(mapping, resource)
|
|
686
|
+
links = await self._links(mapping, resource)
|
|
687
|
+
record = self._new_record(resource_type, resource)
|
|
688
|
+
|
|
689
|
+
async def change() -> None:
|
|
690
|
+
self.session().add(record)
|
|
691
|
+
_from_scim(mapping, resource, record, links, creating=True)
|
|
692
|
+
|
|
693
|
+
await self._flush(change, lambda: self._check_uniqueness(mapping, resource))
|
|
694
|
+
return await self.get(resource_type, str(getattr(record, mapping._id.key)))
|
|
695
|
+
|
|
696
|
+
async def update(
|
|
697
|
+
self,
|
|
698
|
+
resource_type: ResourceType,
|
|
699
|
+
resource: Resource[Any],
|
|
700
|
+
*,
|
|
701
|
+
expected_version: str | None = None,
|
|
702
|
+
) -> Resource[Any]:
|
|
703
|
+
"""Replace a resource, and return it as stored."""
|
|
704
|
+
mapping = self._mapping(resource_type)
|
|
705
|
+
record = await self._load(resource_type, resource.id)
|
|
706
|
+
self._check_version(mapping, record, expected_version)
|
|
707
|
+
self._check_storable(resource_type, resource, record)
|
|
708
|
+
await self._check_uniqueness(mapping, resource)
|
|
709
|
+
links = await self._links(mapping, resource)
|
|
710
|
+
|
|
711
|
+
async def change() -> None:
|
|
712
|
+
self._write_record(mapping, resource, record, links)
|
|
713
|
+
|
|
714
|
+
await self._flush(change, lambda: self._check_uniqueness(mapping, resource))
|
|
715
|
+
return await self.get(resource_type, resource.id) # type: ignore[arg-type]
|
|
716
|
+
|
|
717
|
+
async def delete(
|
|
718
|
+
self,
|
|
719
|
+
resource_type: ResourceType,
|
|
720
|
+
resource_id: str,
|
|
721
|
+
*,
|
|
722
|
+
expected_version: str | None = None,
|
|
723
|
+
) -> None:
|
|
724
|
+
"""Delete a resource."""
|
|
725
|
+
mapping = self._mapping(resource_type)
|
|
726
|
+
record = await self._load(resource_type, resource_id)
|
|
727
|
+
self._check_version(mapping, record, expected_version)
|
|
728
|
+
|
|
729
|
+
async def change() -> None:
|
|
730
|
+
await self.session().delete(record)
|
|
731
|
+
|
|
732
|
+
await self._flush(change)
|
|
733
|
+
|
|
734
|
+
async def _load(
|
|
735
|
+
self,
|
|
736
|
+
resource_type: ResourceType,
|
|
737
|
+
resource_id: str | None,
|
|
738
|
+
parameters: ResponseParameters[Any] | None = None,
|
|
739
|
+
) -> Any:
|
|
740
|
+
"""Load a record, with the collections the response keeps."""
|
|
741
|
+
mapping = self._mapping(resource_type)
|
|
742
|
+
statement = _load_statement(mapping, resource_id, parameters)
|
|
743
|
+
_expire(self.session(), mapping, resource_id)
|
|
744
|
+
record = None if statement is None else await self.session().scalar(statement)
|
|
745
|
+
if record is None:
|
|
746
|
+
raise self._not_found(resource_type, resource_id)
|
|
747
|
+
return record
|
|
748
|
+
|
|
749
|
+
async def _check_uniqueness(
|
|
750
|
+
self, mapping: ResourceMapping, resource: Resource[Any]
|
|
751
|
+
) -> None:
|
|
752
|
+
"""Refuse a resource with a unique value another resource already has."""
|
|
753
|
+
session = self.session()
|
|
754
|
+
comparator = await self._ready_comparator(session)
|
|
755
|
+
for statement in self._unique_statements(mapping, resource, comparator):
|
|
756
|
+
if await session.scalar(statement) is not None:
|
|
757
|
+
raise UniquenessException
|
|
758
|
+
|
|
759
|
+
async def _ready_comparator(self, session: "AsyncSession") -> _Comparator:
|
|
760
|
+
"""Return how the database of the session compares strings, ready to compare them."""
|
|
761
|
+
connection = await session.connection()
|
|
762
|
+
comparator = self._comparator(connection.dialect.name)
|
|
763
|
+
raw = await connection.get_raw_connection()
|
|
764
|
+
await comparator.prepare_async(raw.driver_connection)
|
|
765
|
+
return comparator
|
|
766
|
+
|
|
767
|
+
async def _links(
|
|
768
|
+
self, mapping: ResourceMapping, resource: Resource[Any]
|
|
769
|
+
) -> dict[_Collection, list[Any]]:
|
|
770
|
+
"""Return the records each Link of a resource links to, refusing a value that links to nothing."""
|
|
771
|
+
links: dict[_Collection, list[Any]] = {}
|
|
772
|
+
for collections, entries in _link_entries(mapping, resource):
|
|
773
|
+
ids = [entry.value for entry in entries]
|
|
774
|
+
found = []
|
|
775
|
+
for collection in collections:
|
|
776
|
+
statement = _links_statement(collection, ids)
|
|
777
|
+
records = (await self.session().scalars(statement)).all()
|
|
778
|
+
found.append((collection, list(records)))
|
|
779
|
+
links |= self._assign_links(found, entries)
|
|
780
|
+
return links
|
|
781
|
+
|
|
782
|
+
async def _flush(
|
|
783
|
+
self,
|
|
784
|
+
change: Callable[[], Awaitable[None]],
|
|
785
|
+
check_uniqueness: Callable[[], Awaitable[None]] = _nothing_async,
|
|
786
|
+
) -> None:
|
|
787
|
+
"""Apply a change in a savepoint, and flush it, as the synchronous storage does."""
|
|
788
|
+
session = self.session()
|
|
789
|
+
try:
|
|
790
|
+
async with session.begin_nested():
|
|
791
|
+
await change()
|
|
792
|
+
await session.flush()
|
|
793
|
+
except StaleDataError as exception:
|
|
794
|
+
raise PreconditionFailedException from exception
|
|
795
|
+
except IntegrityError:
|
|
796
|
+
await check_uniqueness()
|
|
797
|
+
raise
|