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