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.
File without changes
@@ -0,0 +1,558 @@
1
+ import operator
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+ from typing import TypeVarTuple
5
+
6
+ from scim2_models import AttributeBinding
7
+ from scim2_models import InvalidCursorException
8
+ from scim2_models import InvalidFilterException
9
+ from scim2_models import InvalidPathException
10
+ from scim2_models import ResponseParameters
11
+ from scim2_models import ScimFilter
12
+ from scim2_models import SearchRequest
13
+ from scim2_models.path import AttrPath
14
+ from scim2_models.path import CompareOperator
15
+ from scim2_models.path import Comparison
16
+ from scim2_models.path import FilterVisitor
17
+ from scim2_models.path import LogicalExpr
18
+ from scim2_models.path import LogicalOperator
19
+ from scim2_models.path import Not
20
+ from scim2_models.path import Present
21
+ from scim2_models.path import ValuePath
22
+ from scim2_models.path import coerce_value
23
+ from sqlalchemy import ColumnElement
24
+ from sqlalchemy import Select
25
+ from sqlalchemy import String
26
+ from sqlalchemy import and_
27
+ from sqlalchemy import cast
28
+ from sqlalchemy import false
29
+ from sqlalchemy import func
30
+ from sqlalchemy import inspect
31
+ from sqlalchemy import literal
32
+ from sqlalchemy import not_
33
+ from sqlalchemy import null
34
+ from sqlalchemy import nulls_last
35
+ from sqlalchemy import or_
36
+ from sqlalchemy import select
37
+ from sqlalchemy import true
38
+ from sqlalchemy import union_all
39
+ from sqlalchemy.orm import Mapper
40
+
41
+ from .comparison import _SUBSTRINGS
42
+ from .comparison import _Comparator
43
+ from .conversion import _as_stored
44
+ from .keyset import _Anchor
45
+ from .keyset import _beyond
46
+ from .keyset import _keyset_order
47
+ from .mapping import ResourceMapping
48
+ from .mapping import _Collection
49
+ from .mapping import _Column
50
+ from .mapping import _python_type
51
+
52
+ _ORDERINGS: dict[CompareOperator, Callable[[Any, Any], Any]] = {
53
+ CompareOperator.eq: operator.eq,
54
+ CompareOperator.gt: operator.gt,
55
+ CompareOperator.ge: operator.ge,
56
+ CompareOperator.lt: operator.lt,
57
+ CompareOperator.le: operator.le,
58
+ }
59
+
60
+
61
+ _Row = TypeVarTuple("_Row")
62
+
63
+
64
+ def _as_key(column: _Column, value: Any) -> Any:
65
+ """Return an identifier in the type of its column, or None when it cannot have that type."""
66
+ python_type = _python_type(column.expression)
67
+ if python_type is None:
68
+ return value
69
+ try:
70
+ return python_type(value)
71
+ except (TypeError, ValueError):
72
+ return None
73
+
74
+
75
+ def _exact_key(column: _Column, value: str) -> Any:
76
+ """Return an identifier in the type of its column, or None when the column holds no such identifier.
77
+
78
+ The column holds it only when it would return the same text, so "01"
79
+ does not find the identifier 1.
80
+ """
81
+ key = _as_key(column, value)
82
+ if key is None or str(key) != value:
83
+ return None
84
+ return key
85
+
86
+
87
+ def _unmapped(binding: AttributeBinding) -> InvalidFilterException:
88
+ """Return the error of a filter on an attribute the mapping does not let filters read."""
89
+ return InvalidFilterException(detail=f"Cannot filter on '{binding.urn}'")
90
+
91
+
92
+ class _FilterTranslator(FilterVisitor[ColumnElement[bool]]):
93
+ """Turn a SCIM filter into a condition on the records of a mapping.
94
+
95
+ The condition keeps the records whose resources ScimFilter.match keeps.
96
+ Every condition is true or false, never NULL, so that the negation of a
97
+ comparison with a missing value holds.
98
+
99
+ scope is the collection that a value selection, such as
100
+ emails[type eq "work"], applies its filter to.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ mapping: ResourceMapping,
106
+ scim_filter: ScimFilter[Any],
107
+ comparator: _Comparator,
108
+ scope: tuple[AttrPath, _Collection] | None = None,
109
+ ) -> None:
110
+ self.mapping = mapping
111
+ self.filter = scim_filter
112
+ self.comparator = comparator
113
+ self.scope = scope
114
+
115
+ def _resolve(
116
+ self,
117
+ attr_path: AttrPath,
118
+ resolve: Callable[..., AttributeBinding | None],
119
+ ) -> AttributeBinding | None:
120
+ """Bind the attribute path of a comparison or of a presence test.
121
+
122
+ Within a value selection of a simple attribute, such as
123
+ tags[value eq "x"], value is the entry itself, and any other attribute
124
+ matches nothing, as ScimFilter.match has it.
125
+ """
126
+ if self.scope is None:
127
+ return resolve(attr_path, strict=False)
128
+ scope_path, scope = self.scope
129
+ if scope.simple:
130
+ own = attr_path.attr.lower() == "value" and not attr_path.sub_attr
131
+ return scope.binding if own else None
132
+ return resolve(
133
+ AttrPath(scope_path.attr, attr_path.attr, scope_path.uri), strict=False
134
+ )
135
+
136
+ def _lookup(
137
+ self, binding: AttributeBinding
138
+ ) -> list[tuple[_Collection | None, _Column | None]]:
139
+ """Return the collections holding an attribute, with its column in each, as the mapping does.
140
+
141
+ Within a value selection, only the collection of the selection holds
142
+ the attribute.
143
+ """
144
+ pairs = self.mapping._lookup(binding)
145
+ if self.scope is None:
146
+ return pairs
147
+ _, scope = self.scope
148
+ return [
149
+ (collection, column) for collection, column in pairs if collection is scope
150
+ ]
151
+
152
+ def _targets(
153
+ self, binding: AttributeBinding
154
+ ) -> list[tuple[_Collection | None, _Column]]:
155
+ """Return the collections holding an attribute with its column in each, refusing an attribute that one of them does not let filters read."""
156
+ pairs = self._lookup(binding)
157
+ if any(column is None or not column.readable for _, column in pairs):
158
+ raise _unmapped(binding)
159
+ return pairs # type: ignore[return-value]
160
+
161
+ def _in_collection(
162
+ self, collection: _Collection | None, condition: ColumnElement[bool]
163
+ ) -> ColumnElement[bool]:
164
+ """Apply a condition to the entries of a collection, or to the record itself outside of any collection.
165
+
166
+ Within a value selection, the condition already applies to the entries.
167
+ """
168
+ if collection is None or self.scope is not None:
169
+ return condition
170
+ return collection.exists(condition)
171
+
172
+ def visit_comparison(self, node: Comparison) -> ColumnElement[bool]:
173
+ """Keep the records with a value matching the comparison, in any collection holding the attribute."""
174
+ binding = self._resolve(node.attr_path, self.filter.resolve_comparison)
175
+ if binding is None:
176
+ return false()
177
+ targets = self._targets(binding)
178
+ value = coerce_value(binding, node.value, node.op)
179
+
180
+ # 'emails ne "x"' holds when no email is "x", while
181
+ # 'emails[value ne "x"]' holds when one email is not "x".
182
+ if (
183
+ node.op == CompareOperator.ne
184
+ and targets[0][0] is not None
185
+ and self.scope is None
186
+ ):
187
+ return not_(
188
+ or_(
189
+ *(
190
+ collection.exists( # type: ignore[union-attr]
191
+ _compare(self.comparator, column, CompareOperator.eq, value)
192
+ )
193
+ for collection, column in targets
194
+ )
195
+ )
196
+ )
197
+ return or_(
198
+ *(
199
+ self._in_collection(
200
+ collection, _compare(self.comparator, column, node.op, value)
201
+ )
202
+ for collection, column in targets
203
+ )
204
+ )
205
+
206
+ def visit_present(self, node: Present) -> ColumnElement[bool]:
207
+ """Keep the records with a value for the attribute.
208
+
209
+ A complex attribute is present when one of its sub-attributes is.
210
+ """
211
+ binding = self._resolve(node.attr_path, self.filter.resolve)
212
+ if binding is None:
213
+ return false()
214
+ pairs = self._lookup(binding)
215
+ in_collection = pairs[0][0] is not None
216
+ if in_collection and binding.sub_field_name is None and pairs[0][1] is None:
217
+ return or_(*(collection.exists() for collection, _ in pairs)) # type: ignore[union-attr]
218
+ if all(column is not None and column.readable for _, column in pairs):
219
+ return or_(
220
+ *(
221
+ self._in_collection(collection, _present(column)) # type: ignore[arg-type]
222
+ for collection, column in pairs
223
+ )
224
+ )
225
+
226
+ sub_columns = [
227
+ column for column in self.mapping._sub_columns(binding) if column.readable
228
+ ]
229
+ if in_collection or not sub_columns:
230
+ raise _unmapped(binding)
231
+ return or_(*(_present(column) for column in sub_columns))
232
+
233
+ def visit_not(self, node: Not) -> ColumnElement[bool]:
234
+ """Keep the records the inner filter does not keep."""
235
+ return not_(self.visit(node.expr))
236
+
237
+ def visit_logical_expr(self, node: LogicalExpr) -> ColumnElement[bool]:
238
+ """Combine the conditions of the terms with AND or OR."""
239
+ combine = and_ if node.op == LogicalOperator.and_ else or_
240
+ return combine(*(self.visit(term) for term in node.terms))
241
+
242
+ def visit_value_path(self, node: ValuePath) -> ColumnElement[bool]:
243
+ """Keep the records with an entry of the attribute matching the inner filter."""
244
+ binding = self.filter.resolve(node.attr_path, strict=False)
245
+ if binding is None:
246
+ return false()
247
+ collections = [
248
+ collection
249
+ for collection, _ in self.mapping._lookup(binding)
250
+ if collection is not None
251
+ ]
252
+ if not collections:
253
+ raise _unmapped(binding)
254
+ return or_(
255
+ *(
256
+ collection.exists(
257
+ _FilterTranslator(
258
+ self.mapping,
259
+ self.filter,
260
+ self.comparator,
261
+ (node.attr_path, collection),
262
+ ).visit(node.val_filter)
263
+ )
264
+ for collection in collections
265
+ )
266
+ )
267
+
268
+
269
+ def _present(column: _Column) -> ColumnElement[bool]:
270
+ """Per RFC 7644 §3.4.2.2, an empty string is no value."""
271
+ expression = column.compared
272
+ if column.is_string:
273
+ return and_(expression.is_not(None), expression != "")
274
+ return expression.is_not(None)
275
+
276
+
277
+ def _compare(
278
+ comparator: _Comparator, column: _Column, op: CompareOperator, value: Any
279
+ ) -> ColumnElement[bool]:
280
+ """Compare a column with a value, strings in the form the policy compares them under.
281
+
282
+ A string the policy cannot prepare is equal to no other value, so only ne
283
+ holds against it.
284
+ """
285
+ expression = column.compared
286
+ value = _as_stored(value)
287
+ if value is None:
288
+ if op == CompareOperator.eq:
289
+ return expression.is_(None)
290
+ if op == CompareOperator.ne:
291
+ return expression.is_not(None)
292
+ return false()
293
+
294
+ if column.textual and op in (CompareOperator.eq, CompareOperator.ne):
295
+ # The identifier is compared in its own type, so that the database
296
+ # uses its index, and does not depend on how it writes a UUID as text.
297
+ key = _exact_key(column, value)
298
+ if key is None:
299
+ return true() if op == CompareOperator.ne else false()
300
+ if op == CompareOperator.ne:
301
+ return or_(column.expression.is_(None), column.expression != key)
302
+ equal: ColumnElement[bool] = column.expression == key
303
+ return equal
304
+
305
+ if not column.is_string:
306
+ if op == CompareOperator.ne:
307
+ return or_(expression.is_(None), expression != value)
308
+ if op in _SUBSTRINGS:
309
+ return false()
310
+ return and_(expression.is_not(None), _ORDERINGS[op](expression, value))
311
+
312
+ try:
313
+ column.binding.comparable(value, comparator.policy)
314
+ except ValueError:
315
+ return true() if op == CompareOperator.ne else false()
316
+
317
+ left = comparator.column(column)
318
+ if op == CompareOperator.ne:
319
+ return or_(left.is_(None), left != comparator.operand(column, value))
320
+ if op in _SUBSTRINGS:
321
+ condition = comparator.substring(op, column, value)
322
+ else:
323
+ condition = _ORDERINGS[op](left, comparator.operand(column, value))
324
+ return and_(left.is_not(None), condition)
325
+
326
+
327
+ def _sort_key(
328
+ mapping: ResourceMapping,
329
+ search_request: SearchRequest[Any],
330
+ comparator: _Comparator,
331
+ ) -> Any:
332
+ """Return the expression the records of a mapping sort on.
333
+
334
+ Return None when the search has no sortBy, or when the model of the
335
+ mapping does not declare its attribute.
336
+ """
337
+ binding = search_request.sort_binding(mapping.model)
338
+ if binding is None:
339
+ return None
340
+ collection, column = mapping._lookup(binding)[0]
341
+ if (
342
+ column is None
343
+ or not column.readable
344
+ or (collection is not None and not collection.owned)
345
+ ):
346
+ raise InvalidPathException(
347
+ path=str(search_request.sort_by),
348
+ detail=f"Cannot sort on '{binding.urn}'",
349
+ )
350
+ expression: Any = column.expression
351
+ if column.is_string:
352
+ expression = comparator.column(column)
353
+ if collection is not None:
354
+ expression = _first_entry(collection, expression)
355
+ return expression
356
+
357
+
358
+ def _first_entry(collection: _Collection, expression: Any) -> Any:
359
+ """Return the value of the primary entry of a collection, or else of its first one."""
360
+ relationship = collection.relationship_property
361
+ entry_mapper: Mapper[Any] = inspect(collection.entry_class)
362
+ order: list[Any] = []
363
+ primary = collection.columns.get("primary")
364
+ if primary is not None:
365
+ order.append(nulls_last(primary.expression.desc()))
366
+ order.extend(relationship.order_by or entry_mapper.primary_key)
367
+ return (
368
+ select(expression)
369
+ .where(relationship.primaryjoin)
370
+ .order_by(*order)
371
+ .limit(1)
372
+ .scalar_subquery()
373
+ )
374
+
375
+
376
+ def _where(
377
+ mapping: ResourceMapping,
378
+ search_request: SearchRequest[Any],
379
+ comparator: _Comparator,
380
+ ) -> ColumnElement[bool]:
381
+ """Return the condition keeping the records matching the filter of a search, or every record without filter."""
382
+ if search_request.filter is None:
383
+ return true()
384
+ scim_filter = ScimFilter[mapping.model](str(search_request.filter)) # type: ignore[name-defined]
385
+ return _FilterTranslator(mapping, scim_filter, comparator).visit(scim_filter.ast)
386
+
387
+
388
+ def _cursor_page(
389
+ page: Select[*_Row], search_request: SearchRequest[Any]
390
+ ) -> Select[*_Row]:
391
+ """Limit a cursor page to count + 1 rows, the last one telling whether a page follows."""
392
+ if search_request.count is None:
393
+ return page
394
+ return page.limit(search_request.count + 1)
395
+
396
+
397
+ def _index_page(
398
+ page: Select[*_Row], search_request: SearchRequest[Any]
399
+ ) -> Select[*_Row]:
400
+ """Limit a page to the records from startIndex, at most count of them."""
401
+ page = page.offset(search_request.start_index_0 or 0)
402
+ if search_request.count is None:
403
+ return page
404
+ return page.limit(search_request.count)
405
+
406
+
407
+ def _search_statements(
408
+ mapping: ResourceMapping,
409
+ search_request: SearchRequest[Any],
410
+ comparator: _Comparator,
411
+ anchor: _Anchor | None = None,
412
+ ) -> tuple[Select[int], Select[Any, Any, str]]:
413
+ """Return the statement counting the matching records, and the one selecting a page of them.
414
+
415
+ The page lists each record with its sort value and its identifier as
416
+ text. The records are ordered by sort value, then by identifier: without
417
+ the identifier, records sharing a sort value could change pages from a
418
+ request to the next. A cursor page is read from the anchor, in the reverse
419
+ order for a previous page.
420
+ """
421
+ condition = _where(mapping, search_request, comparator)
422
+ count = select(func.count()).select_from(mapping.record).where(condition)
423
+ key = _sort_key(mapping, search_request, comparator)
424
+ record_id = mapping._id.expression
425
+ descending = search_request.sort_order == SearchRequest.SortOrder.descending
426
+ forward = anchor is None or anchor.forward
427
+ page = (
428
+ select(
429
+ mapping.record,
430
+ (null() if key is None else key).label("key"),
431
+ cast(record_id, String).label("id"),
432
+ )
433
+ .where(condition)
434
+ .order_by(*_keyset_order(key, [record_id], descending, forward))
435
+ .options(
436
+ *mapping._loader_options(mapping._returned_collections(search_request))
437
+ )
438
+ )
439
+ if search_request.cursor is None:
440
+ return count, _index_page(page, search_request)
441
+ if anchor is not None:
442
+ value = _as_key(mapping._id, anchor.ties[0])
443
+ if value is None:
444
+ raise InvalidCursorException
445
+ page = page.where(_beyond(key, [record_id], anchor, [value], descending))
446
+ return count, _cursor_page(page, search_request)
447
+
448
+
449
+ def _root_statements(
450
+ mappings: list[ResourceMapping],
451
+ search_request: SearchRequest[Any],
452
+ comparator: _Comparator,
453
+ anchor: _Anchor | None = None,
454
+ ) -> tuple[Select[int], Select[int, str, Any]]:
455
+ """Return the statement counting the matching records of several mappings, and the one selecting a page of them.
456
+
457
+ The page lists the position of the mapping, the identifier of each
458
+ record as text, so that the identifiers of every table fit in one column,
459
+ and its sort value. A mapping whose model does not declare the sort
460
+ attribute sorts its records as having no value.
461
+ """
462
+ conditions = [_where(mapping, search_request, comparator) for mapping in mappings]
463
+ keys = [_sort_key(mapping, search_request, comparator) for mapping in mappings]
464
+ key_type = next((key.type for key in keys if key is not None), None)
465
+
466
+ matching = union_all(
467
+ *(
468
+ select(literal(1)).select_from(mapping.record).where(condition)
469
+ for mapping, condition in zip(mappings, conditions, strict=True)
470
+ )
471
+ ).subquery()
472
+ count = select(func.count()).select_from(matching)
473
+
474
+ branches = []
475
+ for position, (mapping, condition, key) in enumerate(
476
+ zip(mappings, conditions, keys, strict=True)
477
+ ):
478
+ columns: list[Any] = [
479
+ literal(position).label("position"),
480
+ cast(mapping._id.expression, String).label("id"),
481
+ ]
482
+ if key_type is not None:
483
+ # PostgreSQL needs the type of a NULL to unite it with the keys
484
+ # of the other tables.
485
+ key = cast(null(), key_type) if key is None else key
486
+ columns.append(key.label("key"))
487
+ branches.append(select(*columns).where(condition))
488
+ rows = union_all(*branches).subquery()
489
+ row_key = None if key_type is None else rows.c.key
490
+ ties = [rows.c.position, rows.c.id]
491
+ descending = search_request.sort_order == SearchRequest.SortOrder.descending
492
+ forward = anchor is None or anchor.forward
493
+ page = select(
494
+ rows.c.position, rows.c.id, (null() if row_key is None else row_key)
495
+ ).order_by(*_keyset_order(row_key, ties, descending, forward))
496
+ if search_request.cursor is None:
497
+ return count, _index_page(page, search_request)
498
+ if anchor is not None:
499
+ if anchor.ties[0] not in range(len(mappings)):
500
+ raise InvalidCursorException
501
+ page = page.where(_beyond(row_key, ties, anchor, anchor.ties, descending))
502
+ return count, _cursor_page(page, search_request)
503
+
504
+
505
+ def _records_statement(
506
+ mapping: ResourceMapping, ids: list[str], parameters: ResponseParameters[Any]
507
+ ) -> Select[str, Any]:
508
+ """Return the statement loading the records of a page, each with its identifier as text."""
509
+ keys = [_as_key(mapping._id, value) for value in ids]
510
+ return (
511
+ select(cast(mapping._id.expression, String), mapping.record)
512
+ .where(mapping._id.expression.in_(keys))
513
+ .options(*mapping._loader_options(mapping._returned_collections(parameters)))
514
+ )
515
+
516
+
517
+ def _load_statement(
518
+ mapping: ResourceMapping,
519
+ resource_id: str | None,
520
+ parameters: ResponseParameters[Any] | None = None,
521
+ ) -> Select[Any] | None:
522
+ """Return the statement loading a record, or None when no record can have this identifier.
523
+
524
+ Only the collections the response keeps are loaded, all of them without parameters.
525
+ """
526
+ key = _as_key(mapping._id, resource_id)
527
+ if key is None:
528
+ return None
529
+ return (
530
+ select(mapping.record)
531
+ .where(mapping._id.expression == key)
532
+ .options(*mapping._loader_options(mapping._returned_collections(parameters)))
533
+ )
534
+
535
+
536
+ def _taken_statement(
537
+ mapping: ResourceMapping,
538
+ column: _Column,
539
+ value: Any,
540
+ resource_id: str | None,
541
+ comparator: _Comparator,
542
+ ) -> Select[Any]:
543
+ """Return the statement finding another record holding a unique value."""
544
+ condition = _compare(comparator, column, CompareOperator.eq, value)
545
+ key = None if resource_id is None else _as_key(mapping._id, resource_id)
546
+ if key is not None:
547
+ condition = and_(condition, mapping._id.expression != key)
548
+ return select(mapping._id.expression).where(condition).limit(1)
549
+
550
+
551
+ def _links_statement(collection: _Collection, ids: list[str]) -> Select[Any]:
552
+ """Return the statement loading the records a Link links to."""
553
+ target = collection.target
554
+ assert target is not None
555
+ keys = [
556
+ key for key in (_as_key(target._id, value) for value in ids) if key is not None
557
+ ]
558
+ return select(target.record).where(target._id.expression.in_(keys))