scim2-sqlalchemy 0.1.2__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scim2-sqlalchemy
3
- Version: 0.1.2
3
+ Version: 0.3.0
4
4
  Summary: Painless SCIM integration for SQLAlchemy
5
5
  Keywords: scim,scim2,provisioning,sqlalchemy,rfc7643,rfc7644
6
6
  Author: Éloi Rivard
@@ -18,8 +18,8 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
18
18
  Classifier: Environment :: Web Environment
19
19
  Classifier: Programming Language :: Python
20
20
  Classifier: Operating System :: OS Independent
21
- Requires-Dist: scim2-models>=0.12.2
22
- Requires-Dist: scim2-server>=0.8.1
21
+ Requires-Dist: scim2-models>=0.12.7
22
+ Requires-Dist: scim2-server>=0.8.9
23
23
  Requires-Dist: sqlalchemy>=2.0.41
24
24
  Requires-Dist: sqlalchemy[asyncio]>=2.0.41 ; extra == 'asyncio'
25
25
  Requires-Python: >=3.11
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["uv_build>=0.12.13,<0.13.0"]
2
+ requires = ["uv_build>=0.12.13,<0.14.0"]
3
3
  build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-sqlalchemy"
7
- version = "0.1.2"
7
+ version = "0.3.0"
8
8
  description = "Painless SCIM integration for SQLAlchemy"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -32,8 +32,8 @@ classifiers = [
32
32
  ]
33
33
  requires-python = ">=3.11"
34
34
  dependencies = [
35
- "scim2-models>=0.12.2",
36
- "scim2-server>=0.8.1",
35
+ "scim2-models>=0.12.7",
36
+ "scim2-server>=0.8.9",
37
37
  "sqlalchemy>=2.0.41",
38
38
  ]
39
39
 
@@ -60,10 +60,13 @@ dev = [
60
60
  "pytest-cov>=7.1.0",
61
61
  "pytest-postgresql>=9.1.0",
62
62
  "scim2-client>=0.14.0",
63
- "scim2-server[testing]>=0.8.4",
63
+ "scim2-server[testing]>=0.8.9",
64
64
  "scim2-tester[testing]>=0.6.2",
65
65
  "tox-uv>=1.36.0",
66
66
  "werkzeug>=3.1.8",
67
+ "pytest-mysql>=5.0.1",
68
+ "pymysql>=1.2.4",
69
+ "asyncmy>=0.2.18",
67
70
  ]
68
71
  doc = [
69
72
  "shibuya>=2024.5.15",
@@ -126,7 +129,10 @@ testpaths = [
126
129
  addopts = "--doctest-modules --doctest-glob='*.rst' --ignore=doc/conf.py"
127
130
  pythonpath = ["doc/_examples"]
128
131
  doctest_optionflags = "ALLOW_UNICODE ELLIPSIS NORMALIZE_WHITESPACE"
129
- filterwarnings = ["error::scim2_tester.testing.ScimDeviationWarning"]
132
+ filterwarnings = [
133
+ "error::scim2_tester.testing.ScimDeviationWarning",
134
+ "error:The column .* needs a value:UserWarning",
135
+ ]
130
136
 
131
137
  [tool.uv]
132
138
  exclude-newer = "14 days"
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["uv_build>=0.12.13,<0.13.0"]
2
+ requires = ["uv_build>=0.12.13,<0.14.0"]
3
3
  build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "scim2-sqlalchemy"
7
- version = "0.1.2"
7
+ version = "0.3.0"
8
8
  description = "Painless SCIM integration for SQLAlchemy"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -28,8 +28,8 @@ authors = [
28
28
  ]
29
29
  requires-python = ">=3.11"
30
30
  dependencies = [
31
- "scim2-models>=0.12.2",
32
- "scim2-server>=0.8.1",
31
+ "scim2-models>=0.12.7",
32
+ "scim2-server>=0.8.9",
33
33
  "sqlalchemy>=2.0.41",
34
34
  ]
35
35
 
@@ -54,10 +54,13 @@ dev = [
54
54
  "pytest-cov>=7.1.0",
55
55
  "pytest-postgresql>=9.1.0",
56
56
  "scim2-client>=0.14.0",
57
- "scim2-server[testing]>=0.8.4",
57
+ "scim2-server[testing]>=0.8.9",
58
58
  "scim2-tester[testing]>=0.6.2",
59
59
  "tox-uv>=1.36.0",
60
60
  "werkzeug>=3.1.8",
61
+ "pytest-mysql>=5.0.1",
62
+ "pymysql>=1.2.4",
63
+ "asyncmy>=0.2.18",
61
64
  ]
62
65
  doc = [
63
66
  "shibuya>=2024.5.15",
@@ -114,7 +117,10 @@ testpaths = ["tests", "doc"]
114
117
  addopts = "--doctest-modules --doctest-glob='*.rst' --ignore=doc/conf.py"
115
118
  pythonpath = ["doc/_examples"]
116
119
  doctest_optionflags = "ALLOW_UNICODE ELLIPSIS NORMALIZE_WHITESPACE"
117
- filterwarnings = ["error::scim2_tester.testing.ScimDeviationWarning"]
120
+ filterwarnings = [
121
+ "error::scim2_tester.testing.ScimDeviationWarning",
122
+ "error:The column .* needs a value:UserWarning",
123
+ ]
118
124
 
119
125
  [tool.uv]
120
126
  exclude-newer = "14 days"
@@ -1,5 +1,7 @@
1
1
  import unicodedata
2
2
  import warnings
3
+ from abc import ABC
4
+ from abc import abstractmethod
3
5
  from collections.abc import Iterable
4
6
  from typing import Any
5
7
 
@@ -8,11 +10,16 @@ from scim2_models import ScimPolicy
8
10
  from scim2_models import default_comparison_key
9
11
  from scim2_models.path import CompareOperator
10
12
  from sqlalchemy import ColumnElement
13
+ from sqlalchemy import Dialect
14
+ from sqlalchemy import FunctionElement
11
15
  from sqlalchemy import String
12
16
  from sqlalchemy import func
13
17
  from sqlalchemy import literal
14
18
  from sqlalchemy import literal_column
19
+ from sqlalchemy.ext.compiler import compiles
20
+ from sqlalchemy.sql.compiler import SQLCompiler
15
21
 
22
+ from .mapping import _MARIADB
16
23
  from .mapping import ResourceMapping
17
24
  from .mapping import _Column
18
25
 
@@ -26,6 +33,9 @@ _SUBSTRINGS = {
26
33
 
27
34
  _KEY_FUNCTION = "scim2_key"
28
35
 
36
+ _MARIADB_VERSION = (10, 10)
37
+ """The first MariaDB version with the uca1400 collations."""
38
+
29
39
 
30
40
  def _escape(value: str) -> str:
31
41
  """Escape the LIKE wildcards of a value, so that they match themselves."""
@@ -72,7 +82,26 @@ class _Comparator:
72
82
  return method(pattern, escape=_ESCAPE) # type: ignore[no-any-return]
73
83
 
74
84
 
75
- class _Normalizer(_Comparator):
85
+ class _Formed(_Comparator, ABC):
86
+ """Compare strings in a form the database computes on both sides.
87
+
88
+ The value of a filter is normalized to NFC in Python first.
89
+ """
90
+
91
+ @abstractmethod
92
+ def _form(self, column: _Column, expression: Any) -> ColumnElement[Any]:
93
+ """Return a string expression in the form it is compared under."""
94
+
95
+ def column(self, column: _Column) -> ColumnElement[Any]:
96
+ """Return a string column in the form it is compared under."""
97
+ return self._form(column, column.compared)
98
+
99
+ def operand(self, column: _Column, value: str) -> Any:
100
+ """Return a string normalized to NFC, in the form it is compared under."""
101
+ return self._form(column, literal(unicodedata.normalize("NFC", value)))
102
+
103
+
104
+ class _Normalizer(_Formed):
76
105
  """Compare strings in PostgreSQL, normalized to NFC on both sides.
77
106
 
78
107
  The lower() of PostgreSQL follows the locale of the database, so the
@@ -89,13 +118,39 @@ class _Normalizer(_Comparator):
89
118
  )
90
119
  return normalized.collate("C")
91
120
 
92
- def column(self, column: _Column) -> ColumnElement[Any]:
93
- """Return a string column normalized to NFC."""
94
- return self._form(column, column.compared)
95
121
 
96
- def operand(self, column: _Column, value: str) -> Any:
97
- """Return a string normalized to NFC, in Python then in the database."""
98
- return self._form(column, literal(unicodedata.normalize("NFC", value)))
122
+ class _Utf8mb4(FunctionElement[str]):
123
+ """A string converted to utf8mb4, the character set of the MariaDB collations."""
124
+
125
+ type = String()
126
+ inherit_cache = True
127
+
128
+
129
+ @compiles(_Utf8mb4)
130
+ def _compile_utf8mb4(element: _Utf8mb4, compiler: SQLCompiler, **kw: Any) -> str:
131
+ """Write the conversion of a string to utf8mb4."""
132
+ (expression,) = element.clauses
133
+ return f"CONVERT({compiler.process(expression, **kw)} USING utf8mb4)"
134
+
135
+
136
+ class _CodePoints(_Formed):
137
+ """Compare strings in MariaDB by code point.
138
+
139
+ The default collations ignore the case and the accents, and the trailing
140
+ spaces. utf8mb4_nopad_bin compares and orders by code point, as
141
+ scim2-models does. lower() only knows recent letters under a uca1400
142
+ collation. MariaDB has no normalize(), so a stored value is compared in
143
+ the form it was written in.
144
+ """
145
+
146
+ def _form(self, column: _Column, expression: Any) -> ColumnElement[Any]:
147
+ """Return a string expression in utf8mb4, lowered if the column ignores the case, under a binary collation."""
148
+ converted: ColumnElement[Any] = _Utf8mb4(expression)
149
+ if column.casefolded:
150
+ converted = func.lower(
151
+ converted.collate("utf8mb4_uca1400_nopad_as_cs"), type_=String
152
+ )
153
+ return converted.collate("utf8mb4_nopad_bin")
99
154
 
100
155
 
101
156
  class _KeyFunction(_Comparator):
@@ -157,17 +212,32 @@ class _KeyFunction(_Comparator):
157
212
 
158
213
 
159
214
  def _comparator(
160
- dialect: str, policy: ScimPolicy, mappings: Iterable[ResourceMapping]
215
+ dialect: Dialect, policy: ScimPolicy, mappings: Iterable[ResourceMapping]
161
216
  ) -> _Comparator:
162
- """Return how a database compares strings, warning when it cannot follow the policy."""
163
- if dialect == "sqlite":
217
+ """Return how a database compares strings, warning when it cannot follow the policy.
218
+
219
+ MySQL and MariaDB before 10.10 raise a ValueError.
220
+ """
221
+ if dialect.name == "sqlite":
164
222
  return _KeyFunction(policy, mappings)
223
+ mariadb = dialect.name in _MARIADB
224
+ if mariadb and not (
225
+ getattr(dialect, "is_mariadb", False)
226
+ and dialect.server_version_info is not None
227
+ and dialect.server_version_info >= _MARIADB_VERSION
228
+ ):
229
+ raise ValueError(
230
+ "The storage needs MariaDB 10.10 or later: MySQL and the older "
231
+ "versions of MariaDB cannot compare strings by code point"
232
+ )
165
233
  if policy.comparison_key is not default_comparison_key:
166
234
  warnings.warn(
167
- f"The {dialect} storage cannot compare strings with the comparison key "
168
- "of the policy: filters and uniqueness checks only approach it",
235
+ f"The {dialect.name} storage cannot compare strings with the comparison "
236
+ "key of the policy: filters and uniqueness checks only approach it",
169
237
  stacklevel=2,
170
238
  )
171
- if dialect == "postgresql":
239
+ if dialect.name == "postgresql":
172
240
  return _Normalizer(policy)
241
+ if mariadb:
242
+ return _CodePoints(policy)
173
243
  return _Comparator(policy)
@@ -44,9 +44,9 @@ def _as_stored(value: Any) -> Any:
44
44
 
45
45
 
46
46
  def _read(column: _Column, record: Any) -> Any:
47
- """Return the SCIM value of a column of a record, or None if the column is not read."""
47
+ """Return the SCIM value of a column of a record."""
48
48
  value = getattr(record, column.key)
49
- if value is None or not column.readable:
49
+ if value is None:
50
50
  return None
51
51
  if isinstance(value, Enum) and column.enumeration is not None:
52
52
  return column.stored_string(column.enumeration, value)
@@ -154,26 +154,31 @@ def _from_scim(
154
154
  ) -> None:
155
155
  """Write a resource into a record.
156
156
 
157
- Read-only attributes are left as they are, and so is a write-only attribute
158
- the resource has no value for, since a resource never carries it back.
159
- When creating the record, a missing value is not written, so that the
160
- column keeps its default. links holds the records each Link of the
161
- resource links to.
157
+ Read-only attributes are left as they are. A value equal to the stored one
158
+ is not written again, so that a hash given back as it was read is not
159
+ hashed again. When creating the record, a missing value is not written, so
160
+ that the column keeps its default. links holds the records each Link of
161
+ the resource links to.
162
162
  """
163
163
  for column in mapping._columns.values():
164
164
  if not column.writable:
165
165
  continue
166
166
  value = Path(column.binding.urn).get(resource, strict=False)
167
- if value is None and (creating or not column.readable):
167
+ if value is None and creating:
168
168
  continue
169
- setattr(record, column.key, None if value is None else _as_stored(value))
169
+ stored = None if value is None else _as_stored(value)
170
+ if not creating and stored == getattr(record, column.key):
171
+ continue
172
+ setattr(record, column.key, stored)
170
173
 
171
174
  for collection in mapping._all_collections():
172
175
  if not collection.writable:
173
176
  continue
174
177
  if collection.owned:
175
- entries = Path(collection.binding.urn).get(resource, strict=False) or []
176
- value = [_write_entry(collection, entry) for entry in entries]
178
+ value = [
179
+ _write_entry(collection, entry)
180
+ for entry in _entries(collection, resource)
181
+ ]
177
182
  elif collection.single:
178
183
  value = next(iter(links[collection]), None)
179
184
  else:
@@ -188,8 +193,6 @@ def _write_entry(collection: _Collection, entry: Any) -> Any:
188
193
  setattr(record, collection.columns[None].key, _as_stored(entry))
189
194
  return record
190
195
  for column in collection.columns.values():
191
- if not column.writable:
192
- continue
193
196
  value = getattr(entry, column.binding.target_field_name, None)
194
197
  if value is not None:
195
198
  setattr(record, column.key, _as_stored(value))
@@ -229,9 +232,12 @@ def _check_storable(
229
232
  for a new one. A value equal to the stored one changes nothing, so a
230
233
  resource read and sent back is accepted. A missing value changes nothing
231
234
  either, except for a stored value whose column cannot hold none: removing it
232
- raises MutabilityException. The read-only attributes of the model of the resource are skipped,
233
- as RFC 7644 §3.5.1 has them ignored, and so are the derived ones.
235
+ raises MutabilityException. A new resource needs a value for each column
236
+ that cannot hold none and has no default. The read-only attributes of the
237
+ model of the resource are skipped, as RFC 7644 §3.5.1 has them ignored, and
238
+ so are the derived ones.
234
239
  """
240
+ _check_entries(mapping, resource)
235
241
  model = type(resource)
236
242
  for path in Path[model].iter_paths(): # type: ignore[valid-type]
237
243
  binding = path.resolve()
@@ -252,6 +258,10 @@ def _check_storable(
252
258
  current = _comparable(Path(binding.urn).get(stored, strict=False))
253
259
  if storage == _Storage.written:
254
260
  _check_enumerated(mapping, binding, value)
261
+ if value is None and stored is None and mapping._required(binding.urn):
262
+ raise InvalidValueException(
263
+ detail=f"'{binding.urn}' is required on this server"
264
+ )
255
265
  if (
256
266
  value is None
257
267
  and current is not None
@@ -278,6 +288,20 @@ def _check_storable(
278
288
  )
279
289
 
280
290
 
291
+ def _check_entries(mapping: ResourceMapping, resource: Resource[Any]) -> None:
292
+ """Refuse an entry without a value that its column needs, rather than failing in the database."""
293
+ for collection in mapping._all_collections():
294
+ if not collection.owned or collection.simple or not collection.writable:
295
+ continue
296
+ required = [column for column in collection.columns.values() if column.required]
297
+ for entry in _entries(collection, resource):
298
+ for column in required:
299
+ if getattr(entry, column.binding.target_field_name, None) is None:
300
+ raise InvalidValueException(
301
+ detail=f"'{column.binding.urn}' is required on this server"
302
+ )
303
+
304
+
281
305
  def _check_enumerated(
282
306
  mapping: ResourceMapping, binding: AttributeBinding, value: Any
283
307
  ) -> None:
@@ -12,12 +12,13 @@ from scim2_models import Mutability
12
12
  from scim2_models import Path
13
13
  from scim2_models import Required
14
14
  from scim2_models import ResourceType
15
+ from scim2_models import Returned
15
16
  from scim2_models import ScimProvider
16
17
  from scim2_models import Uniqueness
17
18
  from sqlalchemy import Boolean
18
19
  from sqlalchemy import Column
19
20
  from sqlalchemy import DateTime
20
- from sqlalchemy import Float
21
+ from sqlalchemy import Double
21
22
  from sqlalchemy import ForeignKey
22
23
  from sqlalchemy import Integer
23
24
  from sqlalchemy import LargeBinary
@@ -25,12 +26,14 @@ from sqlalchemy import MetaData
25
26
  from sqlalchemy import String
26
27
  from sqlalchemy import Table
27
28
  from sqlalchemy import Uuid
29
+ from sqlalchemy.dialects import mysql
28
30
  from sqlalchemy.orm import DeclarativeBase
29
31
  from sqlalchemy.orm import mapped_column
30
32
  from sqlalchemy.orm import relationship
31
33
  from sqlalchemy.types import TypeEngine
32
34
 
33
- from .mapping import Attribute
35
+ from .mapping import _MARIADB
36
+ from .mapping import _MARIADB_TEXT
34
37
  from .mapping import Link
35
38
  from .mapping import Many
36
39
  from .mapping import ResourceMapping
@@ -41,13 +44,24 @@ _MEMBERS = "urn:ietf:params:scim:schemas:core:2.0:Group:members"
41
44
  _MAX_NAME_LENGTH = 63
42
45
  """The longest identifier PostgreSQL keeps."""
43
46
 
47
+
48
+ def _string() -> TypeEngine[Any]:
49
+ """Return the type of a string column, a TEXT on MariaDB."""
50
+ return String().with_variant(_MARIADB_TEXT, *_MARIADB)
51
+
52
+
53
+ def _date_time() -> TypeEngine[Any]:
54
+ """Return the type of a date column, which keeps the microseconds on MariaDB too."""
55
+ return DateTime(timezone=True).with_variant(mysql.DATETIME(fsp=6), *_MARIADB)
56
+
57
+
44
58
  _SQL_TYPES: dict[SchemaAttribute.Type, Callable[[], TypeEngine[Any]]] = {
45
- SchemaAttribute.Type.string: String,
46
- SchemaAttribute.Type.reference: String,
59
+ SchemaAttribute.Type.string: _string,
60
+ SchemaAttribute.Type.reference: _string,
47
61
  SchemaAttribute.Type.boolean: Boolean,
48
62
  SchemaAttribute.Type.integer: Integer,
49
- SchemaAttribute.Type.decimal: Float,
50
- SchemaAttribute.Type.date_time: lambda: DateTime(timezone=True),
63
+ SchemaAttribute.Type.decimal: Double,
64
+ SchemaAttribute.Type.date_time: _date_time,
51
65
  SchemaAttribute.Type.binary: LargeBinary,
52
66
  }
53
67
 
@@ -95,6 +109,14 @@ class _Forward:
95
109
  inverse_keys: dict[str, str]
96
110
 
97
111
 
112
+ def _hidden(attribute: Any) -> bool:
113
+ """Tell whether clients never read an attribute back."""
114
+ return bool(
115
+ attribute.mutability == Mutability.write_only
116
+ or attribute.returned == Returned.never
117
+ )
118
+
119
+
98
120
  class _Class:
99
121
  """The namespace of a record class being built, and the attributes of its mapping."""
100
122
 
@@ -195,6 +217,9 @@ class _Generator:
195
217
  continue
196
218
  if attribute.mutability == Mutability.read_only:
197
219
  continue
220
+ if attribute.multi_valued and _hidden(attribute):
221
+ self.decisions[urn] = False
222
+ continue
198
223
  if attribute.type != SchemaAttribute.Type.complex:
199
224
  if self._ask_column(model, urn, attribute):
200
225
  clear.append(urn)
@@ -206,6 +231,7 @@ class _Generator:
206
231
  if (
207
232
  not sub.multi_valued
208
233
  and sub.mutability != Mutability.read_only
234
+ and not (attribute.multi_valued and _hidden(sub))
209
235
  and self._ask_column(model, sub_urn, sub)
210
236
  ):
211
237
  clear.append(sub_urn)
@@ -334,15 +360,15 @@ class _Generator:
334
360
  version = mapped_column(Integer, nullable=False)
335
361
  for key, value, path in [
336
362
  ("id", mapped_column(Uuid, primary_key=True, default=uuid.uuid4), "id"),
337
- ("external_id", mapped_column(String), "externalId"),
363
+ ("external_id", mapped_column(_string()), "externalId"),
338
364
  (
339
365
  "meta_created",
340
- mapped_column(DateTime(timezone=True), nullable=False),
366
+ mapped_column(_date_time(), nullable=False),
341
367
  "meta.created",
342
368
  ),
343
369
  (
344
370
  "meta_last_modified",
345
- mapped_column(DateTime(timezone=True), nullable=False),
371
+ mapped_column(_date_time(), nullable=False),
346
372
  "meta.lastModified",
347
373
  ),
348
374
  ("meta_version", version, "meta.version"),
@@ -443,10 +469,7 @@ class _Generator:
443
469
  ),
444
470
  path,
445
471
  )
446
- getter = self._getter(name, key)
447
- if attribute.mutability != Mutability.write_only:
448
- return getter
449
- return lambda: Attribute(getter(), readable=False)
472
+ return self._getter(name, key)
450
473
 
451
474
  @staticmethod
452
475
  def _type(attribute: Any, decision: bool | TypeEngine[Any]) -> TypeEngine[Any]:
@@ -560,8 +583,6 @@ class _Generator:
560
583
  urn: str,
561
584
  ) -> None:
562
585
  """Add the child table of a multi-valued simple attribute, with a value column."""
563
- if attribute.mutability == Mutability.write_only:
564
- return
565
586
  child, key = self._child(name, record_class, path, key)
566
587
  child.add(
567
588
  "value",
@@ -0,0 +1,141 @@
1
+ import decimal
2
+ from collections.abc import Sequence
3
+ from typing import Any
4
+
5
+ from scim2_models import InvalidCursorException
6
+ from scim2_server.keyset import Position
7
+ from sqlalchemy import BigInteger
8
+ from sqlalchemy import ColumnElement
9
+ from sqlalchemy import Integer
10
+ from sqlalchemy import and_
11
+ from sqlalchemy import false
12
+ from sqlalchemy import literal
13
+ from sqlalchemy import nulls_first
14
+ from sqlalchemy import nulls_last
15
+ from sqlalchemy import or_
16
+ from sqlalchemy import tuple_
17
+ from sqlalchemy.ext.compiler import compiles
18
+ from sqlalchemy.sql.compiler import SQLCompiler
19
+ from sqlalchemy.sql.visitors import InternalTraversal
20
+
21
+ from .mapping import _INTEGERS
22
+ from .mapping import _python_type
23
+
24
+
25
+ class _Sorted(ColumnElement[Any]):
26
+ """A sort term on a value, placing the NULL values first or last."""
27
+
28
+ inherit_cache = True
29
+ _traverse_internals = [
30
+ ("value", InternalTraversal.dp_clauseelement),
31
+ ("ascending", InternalTraversal.dp_boolean),
32
+ ("last", InternalTraversal.dp_boolean),
33
+ ]
34
+
35
+ def __init__(self, value: Any, ascending: bool, last: bool) -> None:
36
+ self.value = value
37
+ self.ascending = ascending
38
+ self.last = last
39
+
40
+
41
+ @compiles(_Sorted)
42
+ def _compile_sorted(element: _Sorted, compiler: SQLCompiler, **kw: Any) -> str:
43
+ """Write the sort term with NULLS FIRST or NULLS LAST."""
44
+ term = element.value.asc() if element.ascending else element.value.desc()
45
+ placed = nulls_last(term) if element.last else nulls_first(term)
46
+ return compiler.process(placed, **kw)
47
+
48
+
49
+ @compiles(_Sorted, "mariadb")
50
+ @compiles(_Sorted, "mysql")
51
+ def _compile_sorted_mariadb(element: _Sorted, compiler: SQLCompiler, **kw: Any) -> str:
52
+ """Write the sort term for MariaDB, which has no NULLS FIRST or NULLS LAST.
53
+
54
+ MariaDB places NULL first when ascending and last when descending. A sort
55
+ on whether the value is NULL comes first when it places NULL otherwise.
56
+ """
57
+ key = element.value
58
+ term = compiler.process(key.asc() if element.ascending else key.desc(), **kw)
59
+ if element.last != element.ascending:
60
+ return term
61
+ nulls = key.is_(None)
62
+ placed = nulls.asc() if element.last else nulls.desc()
63
+ return f"{compiler.process(placed, **kw)}, {term}"
64
+
65
+
66
+ def _key_order(key: Any, ascending: bool) -> Any:
67
+ """Per RFC 7644 §3.4.2.3, resources without a value come last when ascending and first when descending."""
68
+ return _Sorted(key, ascending, last=ascending)
69
+
70
+
71
+ def _keyset_order(
72
+ key: Any, ties: Sequence[Any], descending: bool, forward: bool
73
+ ) -> list[Any]:
74
+ """Return the ORDER BY terms of a search: the sort value, then the ties.
75
+
76
+ A previous page is read backward, in the reverse order of the sort.
77
+ """
78
+ terms = [] if key is None else [_key_order(key, descending != forward)]
79
+ return [*terms, *(tie.asc() if forward else tie.desc() for tie in ties)]
80
+
81
+
82
+ def _beyond(
83
+ key: Any,
84
+ ties: Sequence[Any],
85
+ anchor: Position,
86
+ values: Sequence[Any],
87
+ descending: bool,
88
+ ) -> ColumnElement[bool]:
89
+ """Return the condition keeping the rows past the anchor, in the reading direction.
90
+
91
+ values are the ties of the anchor, in the types of the ties. The
92
+ condition on the sort value is written out, as a row comparison would not
93
+ place NULL where the sort does.
94
+ """
95
+ tie_after: ColumnElement[bool]
96
+ if len(ties) == 1:
97
+ tie_after = ties[0] > values[0] if anchor.forward else ties[0] < values[0]
98
+ else:
99
+ row, bound = tuple_(*ties), tuple_(*values)
100
+ tie_after = row > bound if anchor.forward else row < bound
101
+ if key is None:
102
+ return tie_after
103
+
104
+ ascending = descending != anchor.forward
105
+ if anchor.key is None:
106
+ key_after = key.is_not(None) if not ascending else false()
107
+ return or_(key_after, and_(key.is_(None), tie_after))
108
+ value = _sort_value(key, anchor.key)
109
+ key_after = or_(key > value, key.is_(None)) if ascending else key < value
110
+ return or_(key_after, and_(key == value, tie_after))
111
+
112
+
113
+ _ACCEPTED: dict[type, tuple[type, ...]] = {
114
+ float: (float, int),
115
+ decimal.Decimal: (decimal.Decimal, int),
116
+ }
117
+ """The types of the sort values a key of decimal numbers accepts."""
118
+
119
+
120
+ def _sort_value(key: Any, value: Any) -> Any:
121
+ """Return the sort value of an anchor, ready to compare with the sort key.
122
+
123
+ A value of another type than the key is refused, such as a cursor given
124
+ before the sort attribute moved to another column. An integer is a value
125
+ of a key of decimal numbers, since a database may return a whole number
126
+ as an integer. An integer no database stores is refused too. An integer
127
+ compared with a key of integers is sent as a BIGINT, as filters send it.
128
+ """
129
+ python_type = _python_type(key)
130
+ if python_type is not None and (
131
+ not isinstance(value, _ACCEPTED.get(python_type, python_type))
132
+ or (isinstance(value, bool) and python_type is not bool)
133
+ ):
134
+ raise InvalidCursorException
135
+ if not isinstance(value, int) or isinstance(value, bool):
136
+ return value
137
+ if value not in _INTEGERS:
138
+ raise InvalidCursorException
139
+ if isinstance(key.type, Integer):
140
+ return literal(value, BigInteger)
141
+ return value