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,143 @@
1
+ import datetime
2
+ import decimal
3
+ import uuid
4
+ from collections.abc import Callable
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ from scim2_models import InvalidCursorException
10
+ from sqlalchemy import ColumnElement
11
+ from sqlalchemy import and_
12
+ from sqlalchemy import false
13
+ from sqlalchemy import nulls_first
14
+ from sqlalchemy import nulls_last
15
+ from sqlalchemy import or_
16
+ from sqlalchemy import tuple_
17
+
18
+ _TAGGED: dict[str, tuple[type, Callable[[Any], str], Callable[[str], Any]]] = {
19
+ "datetime": (
20
+ datetime.datetime,
21
+ datetime.datetime.isoformat,
22
+ datetime.datetime.fromisoformat,
23
+ ),
24
+ "date": (datetime.date, datetime.date.isoformat, datetime.date.fromisoformat),
25
+ "decimal": (decimal.Decimal, str, decimal.Decimal),
26
+ "uuid": (uuid.UUID, str, uuid.UUID),
27
+ }
28
+
29
+
30
+ def _encode(value: Any) -> Any:
31
+ """Return a sort value as a value JSON can hold, tagged with its type when JSON has none."""
32
+ if value is None or isinstance(value, bool | int | float | str):
33
+ return value
34
+ for tag, (python_type, dump, _) in _TAGGED.items():
35
+ if isinstance(value, python_type):
36
+ return {tag: dump(value)}
37
+ raise TypeError(f"Cannot page on a sort value of type {type(value).__name__}")
38
+
39
+
40
+ def _decode(value: Any) -> Any:
41
+ """Return the sort value a position holds."""
42
+ if value is None or isinstance(value, bool | int | float | str):
43
+ return value
44
+ if not isinstance(value, dict) or len(value) != 1:
45
+ raise InvalidCursorException
46
+ ((tag, text),) = value.items()
47
+ if tag not in _TAGGED or not isinstance(text, str):
48
+ raise InvalidCursorException
49
+ try:
50
+ return _TAGGED[tag][2](text)
51
+ except (ValueError, decimal.InvalidOperation):
52
+ raise InvalidCursorException from None
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class _Anchor:
57
+ """The row a cursor page starts after, or ends before.
58
+
59
+ ties are the values that order the rows sharing a sort value: the
60
+ identifier as text, preceded at the root by the position of the resource
61
+ type.
62
+ """
63
+
64
+ forward: bool
65
+ key: Any
66
+ ties: tuple[Any, ...]
67
+
68
+
69
+ def _anchor(position: Any, root: bool) -> _Anchor | None:
70
+ """Read the position a storage gave, or return None for the first page."""
71
+ if position is None:
72
+ return None
73
+ names = {"d", "k", "t", "i"} if root else {"d", "k", "i"}
74
+ if not isinstance(position, dict) or set(position) != names:
75
+ raise InvalidCursorException
76
+ if position["d"] not in ("next", "previous") or not isinstance(position["i"], str):
77
+ raise InvalidCursorException
78
+ ties: tuple[Any, ...] = (position["i"],)
79
+ if root:
80
+ if type(position["t"]) is not int:
81
+ raise InvalidCursorException
82
+ ties = (position["t"], position["i"])
83
+ return _Anchor(position["d"] == "next", _decode(position["k"]), ties)
84
+
85
+
86
+ def _position(direction: str, key: Any, ties: Sequence[Any]) -> Any:
87
+ """Return the position of the page before or after a row, as a value JSON can hold.
88
+
89
+ The sort value is null when the search has no sort.
90
+ """
91
+ position: dict[str, Any] = {"d": direction, "k": _encode(key)}
92
+ if len(ties) == 2:
93
+ position["t"] = ties[0]
94
+ position["i"] = ties[-1]
95
+ return position
96
+
97
+
98
+ def _key_order(key: Any, ascending: bool) -> Any:
99
+ """Per RFC 7644 §3.4.2.3, resources without a value come last when ascending and first when descending."""
100
+ if ascending:
101
+ return nulls_last(key.asc())
102
+ return nulls_first(key.desc())
103
+
104
+
105
+ def _keyset_order(
106
+ key: Any, ties: Sequence[Any], descending: bool, forward: bool
107
+ ) -> list[Any]:
108
+ """Return the ORDER BY terms of a search: the sort value, then the ties.
109
+
110
+ A previous page is read backward, in the reverse order of the sort.
111
+ """
112
+ terms = [] if key is None else [_key_order(key, descending != forward)]
113
+ return [*terms, *(tie.asc() if forward else tie.desc() for tie in ties)]
114
+
115
+
116
+ def _beyond(
117
+ key: Any,
118
+ ties: Sequence[Any],
119
+ anchor: _Anchor,
120
+ values: Sequence[Any],
121
+ descending: bool,
122
+ ) -> ColumnElement[bool]:
123
+ """Return the condition keeping the rows past the anchor, in the reading direction.
124
+
125
+ values are the ties of the anchor, in the types of the ties. The
126
+ condition on the sort value is written out, as a row comparison would not
127
+ place NULL where the sort does.
128
+ """
129
+ tie_after: ColumnElement[bool]
130
+ if len(ties) == 1:
131
+ tie_after = ties[0] > values[0] if anchor.forward else ties[0] < values[0]
132
+ else:
133
+ row, bound = tuple_(*ties), tuple_(*values)
134
+ tie_after = row > bound if anchor.forward else row < bound
135
+ if key is None:
136
+ return tie_after
137
+
138
+ ascending = descending != anchor.forward
139
+ if anchor.key is None:
140
+ key_after = key.is_not(None) if not ascending else false()
141
+ return or_(key_after, and_(key.is_(None), tie_after))
142
+ key_after = or_(key > anchor.key, key.is_(None)) if ascending else key < anchor.key
143
+ return or_(key_after, and_(key == anchor.key, tie_after))