Coverage for fastapi_restly/query/_impl.py: 96%

950 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-09 21:47 +0000

1import collections.abc as _abc 

2import dataclasses 

3import datetime as _dt 

4import decimal as _decimal 

5import enum 

6import functools 

7import re 

8import weakref 

9from collections import defaultdict 

10from typing import ( 

11 Annotated, 

12 Any, 

13 Callable, 

14 Iterator, 

15 Literal, 

16 Optional, 

17 cast, 

18 get_args, 

19 get_origin, 

20) 

21 

22import pydantic 

23import sqlalchemy 

24from pydantic import Field, PydanticInvalidForJsonSchema 

25from pydantic.fields import FieldInfo 

26from pydantic.json_schema import GenerateJsonSchema 

27from pydantic_core import ( 

28 PydanticCustomError, 

29 PydanticOmit, 

30 SchemaValidator, 

31 ValidationError, 

32 core_schema, 

33) 

34from sqlalchemy import ColumnElement, Select, TypeDecorator 

35from sqlalchemy.orm import DeclarativeBase, aliased 

36from sqlalchemy.orm.attributes import InstrumentedAttribute 

37from sqlalchemy.orm.properties import ColumnProperty 

38from sqlalchemy.orm.util import AliasedClass 

39from sqlalchemy.types import NullType 

40from starlette.datastructures import QueryParams 

41 

42from .._columns import check_text, column_value 

43from .._pagination import ( 

44 _DEFAULT_PAGINATION, 

45 _SORT_QUERY_PARAM, 

46 Pagination, 

47 _check_query_param, 

48 _settings_of, 

49) 

50from .._times import value_error_reason 

51from ..exc import BadQueryParam, RestlyConfigurationError 

52from ..schemas._base import ( 

53 IDRef, 

54 IDSchema, 

55 _hides_value, 

56 _schema_role_name, 

57 _unwrap_type, 

58) 

59from ._paged import _pagination_of_list_params, _takes_page_fields 

60from ._shared import ( 

61 SortNulls, 

62 _append_pk_tiebreak, 

63 _can_be_null, 

64 _class_attribute, 

65 _escape_like_value, 

66 _sort_term, 

67) 

68 

69_SchemaClass = type[pydantic.BaseModel] 

70_JoinAliases = dict[tuple[str, ...], AliasedClass[Any]] 

71 

72_AnyPagination = Pagination | None 

73 

74#: The names of the settings that choose the generated keys, in order. 

75_KEY_SETTINGS = ( 

76 "include_filters", 

77 "exclude_filters", 

78 "include_sort_keys", 

79 "exclude_sort_keys", 

80) 

81 

82#: The value of each key setting when no one sets it: the keys on the 

83#: resource's own fields, and no dotted keys. 

84_KEY_SETTING_DEFAULTS: dict[str, tuple[str, ...]] = { 

85 "include_filters": ("*",), 

86 "exclude_filters": (), 

87 "include_sort_keys": ("*",), 

88 "exclude_sort_keys": (), 

89} 

90 

91 

92_NO_DEFAULT: Any = object() 

93 

94 

95@dataclasses.dataclass(frozen=True) 

96class _OwnFilter: 

97 """A filter key of the view's own, from a method with 

98 ``@fr.list_filter``.""" 

99 

100 key: str 

101 #: The name of the method on the view. 

102 method: str 

103 #: The type of the method's value. 

104 annotation: Any 

105 #: The default of the value, or ``_NO_DEFAULT``. 

106 default: Any 

107 description: str | None 

108 

109 @property 

110 def always(self) -> bool: 

111 """Whether Restly calls the method on every request: its value has 

112 a default. Without one, it calls the method when the key has a 

113 value.""" 

114 return self.default is not _NO_DEFAULT 

115 

116 

117@dataclasses.dataclass(frozen=True) 

118class _ListParamsRecord: 

119 """What Restly generated a list params model with. 

120 

121 :func:`apply_list_params` and view registration read it back. 

122 """ 

123 

124 pagination: _AnyPagination 

125 #: The key settings, as tuples of patterns in Python names. 

126 include_filters: tuple[str, ...] 

127 exclude_filters: tuple[str, ...] 

128 include_sort_keys: tuple[str, ...] 

129 exclude_sort_keys: tuple[str, ...] 

130 #: The name of the sort parameter. 

131 sort_query_param: str 

132 #: The sort when the request has none, as a client writes it. 

133 default_sort: str | None 

134 #: The keys of ``default_sort``, as a client writes them. 

135 default_sort_keys: tuple[str, ...] 

136 #: The sort keys that are on, as a client writes them, in the order of 

137 #: the schema. 

138 sort_keys: tuple[str, ...] 

139 #: The view's own filter keys. 

140 own_filters: tuple[_OwnFilter, ...] 

141 

142 def own_filter_values( 

143 self, list_params: pydantic.BaseModel 

144 ) -> list[tuple[_OwnFilter, Any]]: 

145 """The own filters to apply to ``list_params``, each with its 

146 value.""" 

147 values = [] 

148 for own in self.own_filters: 

149 value = getattr(list_params, own.key) 

150 if own.always or value is not None: 

151 values.append((own, value)) 

152 return values 

153 

154 

155_RECORDS: "weakref.WeakKeyDictionary[type, _ListParamsRecord]" = ( 

156 weakref.WeakKeyDictionary() 

157) 

158 

159 

160class _FromParams: 

161 """The default of :func:`apply_list_params`'s ``pagination``: the one its 

162 params model was created with.""" 

163 

164 def __repr__(self) -> str: 

165 # the default as the API reference shows it; the docstring explains it 

166 return "..." 

167 

168 

169_FROM_PARAMS = _FromParams() 

170 

171 

172def _record_of(params_model: type) -> _ListParamsRecord | None: 

173 """What generated list params were created with, or ``None`` for 

174 hand-written ones. 

175 

176 A subclass of generated list params has the record of its base, so it 

177 reads its values as the base does. 

178 """ 

179 for klass in params_model.__mro__: 

180 record = _RECORDS.get(klass) 

181 if record is not None: 

182 return record 

183 return None 

184 

185 

186def _check_default_sort(label: str, value: Any) -> None: 

187 """Reject a ``default_sort`` that is not sort keys, written as the sort 

188 parameter takes them. 

189 

190 :raises RestlyConfigurationError: ``value`` is not ``None`` or a string 

191 of keys separated by commas, or it has a key more than once. 

192 """ 

193 if value is None: 

194 return 

195 if not isinstance(value, str): 

196 raise RestlyConfigurationError( 

197 f"{label} must be a string such as '-created_at,name', or None, " 

198 f"got {value!r}." 

199 ) 

200 keys = [term.removeprefix("-") for term in value.split(",")] 

201 if not all(keys): 

202 raise RestlyConfigurationError( 

203 f"{label} must be sort keys separated by commas, such as " 

204 f"'-created_at,name', got {value!r}." 

205 ) 

206 repeated = _repeated_key(keys) 

207 if repeated is not None: 

208 raise RestlyConfigurationError( 

209 f"{label} has the sort key {repeated!r} more than once, got {value!r}." 

210 ) 

211 

212 

213def _repeated_key(keys: _abc.Iterable[str]) -> str | None: 

214 """The first key that comes a second time, or ``None``. ``name,-name`` 

215 sorts twice on one column, and the second term changes nothing.""" 

216 seen: set[str] = set() 

217 for key in keys: 

218 if key in seen: 

219 return key 

220 seen.add(key) 

221 return None 

222 

223 

224def _check_key_setting(label: str, value: Any) -> tuple[str, ...]: 

225 """The value of a key setting as a tuple of patterns. 

226 

227 :param label: The setting in messages, such as ``ItemView.include_filters``. 

228 

229 :raises RestlyConfigurationError: ``value`` is a string, holds something 

230 that is not a string, or uses a wildcard that Restly does not have. 

231 """ 

232 if isinstance(value, str): 

233 raise RestlyConfigurationError( 

234 f"{label} must be a tuple of keys, got the string {value!r}. " 

235 f"For one key, write ({value!r},) with a comma." 

236 ) 

237 if isinstance(value, _abc.Iterator): 

238 # the class-definition check would use it up before registration 

239 raise RestlyConfigurationError( 

240 f"{label} must be a tuple of keys, got an iterator, which can be " 

241 "read only once. Write tuple(...) around it." 

242 ) 

243 try: 

244 entries = tuple(value) 

245 except TypeError: 

246 raise RestlyConfigurationError( 

247 f"{label} must be a tuple of keys, got {value!r}." 

248 ) from None 

249 for entry in entries: 

250 if not isinstance(entry, str) or not entry: 

251 raise RestlyConfigurationError( 

252 f"{label} must hold keys as strings, got {entry!r}." 

253 ) 

254 if "**" in entry: 

255 raise RestlyConfigurationError( 

256 f"{label}: {entry!r} uses '**'. A key pattern has one " 

257 "wildcard, '*', for any characters except '.'. Write one " 

258 "entry for each level, such as ('vendor.*', 'vendor.*.*')." 

259 ) 

260 if any(char in entry for char in "?[]"): 

261 raise RestlyConfigurationError( 

262 f"{label}: {entry!r} uses '?' or '[...]'. A key pattern " 

263 "has one wildcard, '*', for any characters except '.'." 

264 ) 

265 return entries 

266 

267 

268@functools.cache 

269def _pattern_regex(pattern: str) -> "re.Pattern[str]": 

270 """A regular expression for a key pattern, for ``fullmatch``. 

271 

272 ``*`` matches any characters except ``.``. Every other character, ``.`` 

273 too, matches only itself. 

274 """ 

275 return re.compile("[^.]*".join(re.escape(part) for part in pattern.split("*"))) 

276 

277 

278def _matches(patterns: tuple[str, ...], key: str) -> bool: 

279 return any(_pattern_regex(pattern).fullmatch(key) for pattern in patterns) 

280 

281 

282def _pick_keys( 

283 keys: list[str], include: tuple[str, ...], exclude: tuple[str, ...] 

284) -> list[str]: 

285 """The keys that ``include`` matches and ``exclude`` does not, in order.""" 

286 return [ 

287 key for key in keys if _matches(include, key) and not _matches(exclude, key) 

288 ] 

289 

290 

291def _reserved_names( 

292 pagination: _AnyPagination, sort_query_param: str = _SORT_QUERY_PARAM 

293) -> frozenset[str]: 

294 """Query parameters the schema produces besides filters. 

295 

296 A filter column whose public name is one of these would shadow pagination 

297 or sort, which would silently break the endpoint contract. Treated as a 

298 hard error. 

299 """ 

300 return frozenset({sort_query_param, *_settings_of(pagination)._query_params()}) 

301 

302 

303# Types that support SQL ``<``/``<=``/``>``/``>=`` comparisons. Booleans are 

304# excluded: ordering booleans is rarely meaningful, and ``WHERE active >= true`` 

305# raises ``sqlalchemy.exc.ArgumentError`` at query time, which would otherwise 

306# surface to the client as a 500. 

307_ORDERABLE_TYPES: tuple[type, ...] = ( 

308 int, 

309 float, 

310 _decimal.Decimal, 

311 _dt.date, 

312 _dt.datetime, 

313 _dt.time, 

314 _dt.timedelta, 

315) 

316 

317 

318def _holds_text(column: Any) -> bool: 

319 """Whether ``column`` has a text type, also inside ``TypeDecorator`` layers. 

320 An ``Enum`` type is a text type to SQLAlchemy, but it holds labels.""" 

321 sql_type = getattr(column, "type", None) 

322 while isinstance(sql_type, TypeDecorator): 

323 sql_type = sql_type.impl_instance 

324 return isinstance(sql_type, sqlalchemy.String) and not isinstance( 

325 sql_type, sqlalchemy.Enum 

326 ) 

327 

328 

329def _is_label_field(field: FieldInfo) -> bool: 

330 """Whether ``field`` takes one of a set of labels: an enum, a ``Literal`` or 

331 a bool.""" 

332 annotation, _ = _unwrap_type(field.annotation) 

333 if get_origin(annotation) is Literal or annotation is bool: 

334 return True 

335 return isinstance(annotation, type) and issubclass(annotation, enum.Enum) 

336 

337 

338def _supports_text_search(field: FieldInfo, column: Any) -> bool: 

339 """Whether ``field`` gets ``__icontains``. The column decides, because SQL 

340 searches the column: ``url: HttpUrl`` on a text column has it, and ``name: 

341 str`` on another column has not. Labels have it on no column. A column that 

342 names no type, such as an expression, leaves it to the field. 

343 

344 A ``TypeDecorator`` needs a text type inside and a ``str`` field. 

345 SQLAlchemy runs its ``process_bind_param`` on the search text too, so a 

346 type that stores another value as text, such as a money amount or an 

347 encrypted text, would search for something else. 

348 """ 

349 if _is_label_field(field): 

350 return False 

351 sql_type = getattr(column, "type", None) 

352 is_text_field = _unwrap_type(field.annotation)[0] is str 

353 if isinstance(sql_type, NullType): 

354 return is_text_field 

355 if isinstance(sql_type, TypeDecorator): 

356 return is_text_field and _holds_text(column) 

357 return _holds_text(column) 

358 

359 

360def _is_idref_field(field: FieldInfo) -> bool: 

361 """True for a scalar ``IDRef[T]`` FK field (e.g. ``post_id: IDRef[Post]``). 

362 

363 That ``*_id``-named spelling is discouraged -- the misuse lint steers it to 

364 ``fr.MustExist[int, Post]`` -- but the query layer still handles it here so 

365 the field keeps its filter param. 

366 

367 ``IDRef`` is a ``BaseModel`` subclass, so without this it would be recursed 

368 into as a nested schema and yield only ``post_id.id`` -- which never resolves 

369 (``post_id`` is a scalar column, not a relationship), leaving the FK with no 

370 filter param at all. Treated as a leaf, it filters on its own public name. 

371 Targets ``IDRef`` specifically, not ``IDSchema``: a nested *resource* schema 

372 that embeds its ``id`` also subclasses ``IDSchema`` and must keep its dotted 

373 traversal. ``list[IDRef[T]]`` (to-many) is unaffected -- its annotation is a 

374 list, so it is never a nested schema here. 

375 """ 

376 annotation, _ = _unwrap_type(field.annotation) 

377 return isinstance(annotation, type) and issubclass(annotation, IDRef) 

378 

379 

380def _supports_scalar_operators(field: FieldInfo) -> bool: 

381 """False for collection-typed fields (``dict``, ``list[str]``, ``Sequence``, 

382 ...) that no query-string value can coerce into: ``eq``/``__in``/``__ne`` 

383 (and range) filters on such a field would always fail at request time, so 

384 only ``__isnull`` is generated -- the same advertise-only-what-works 

385 principle applied to non-column fields. 

386 

387 The check mirrors what the request path's ``_value_parser`` (full Pydantic 

388 field validation) will accept. A ``pydantic.Json[...]`` field follows the 

389 type inside: ``Json[int]`` is scalar, and ``Json[list]`` and 

390 ``Json[dict]`` are not, because a list or a dict is no value of a column. 

391 ``str``/``bytes`` are collections in the abc sense but coerce fine, so 

392 they stay scalar. 

393 """ 

394 annotation, _ = _unwrap_type(field.annotation) 

395 origin = get_origin(annotation) or annotation 

396 # a flag, such as an IntFlag, is a Collection on Python 3.11+ because it 

397 # can hold several flags, but a value from the URL is one flag value 

398 return not ( 

399 isinstance(origin, type) 

400 and issubclass(origin, _abc.Collection) 

401 and not issubclass(origin, (str, bytes, enum.Flag)) 

402 ) 

403 

404 

405def _is_sortable(field: FieldInfo, column: Any) -> bool: 

406 """Whether a sort key on ``field`` has an order that a client means. 

407 

408 A field that gets only ``__isnull``, such as a ``dict``, a ``list`` or a 

409 field on a JSON column, gets no sort key either, and neither does a 

410 nested model: a document or a list has no such order, and PostgreSQL's 

411 ``json`` type has no order at all, so a sort on it fails on every 

412 request. A reference, such as ``IDRef[User]``, sorts by its id. 

413 

414 :param column: The column of the field. 

415 """ 

416 if _get_nested_schema(field) is not None and not _is_idref_field(field): 416 ↛ 417line 416 didn't jump to line 417 because the condition on line 416 was never true

417 return False 

418 return _supports_scalar_operators(field) and not _has_json_type(column) 

419 

420 

421def _supports_range_operators(field: FieldInfo, column: Any) -> bool: 

422 if _enum_type(column) is not None: 

423 # an Enum column holds labels, whatever the type of the field 

424 return False 

425 annotation, _ = _unwrap_type(field.annotation) 

426 if _holds_text(column): 

427 # SQL compares text, so ``?value__gte=9`` on an int misses 10. Only the 

428 # text of a date always sorts as the date does. A datetime does not: 

429 # ``...05.5Z`` sorts before ``...05Z``. 

430 return annotation is _dt.date 

431 if annotation is bool: 

432 return False 

433 if get_origin(annotation) is Literal: 

434 # labels too, unless they are numbers 

435 return all( 

436 isinstance(value, (int, float)) and not isinstance(value, bool) 

437 for value in get_args(annotation) 

438 ) 

439 # ``Any`` is a class from Python 3.11 on; it is still an unknown type. 

440 if annotation is Any: 

441 # the column decides, such as a Boolean or a Uuid column of the id 

442 # of fr.IDSchema 

443 try: 

444 annotation = column.type.python_type 

445 except (AttributeError, NotImplementedError): 

446 return True 

447 if not isinstance(annotation, type): 447 ↛ 448line 447 didn't jump to line 448 because the condition on line 447 was never true

448 return True 

449 if issubclass(annotation, bool): 

450 return False 

451 if issubclass(annotation, enum.Enum): 

452 # labels; an int enum has the order of its numbers, but the numbers 

453 # of a flag have no order 

454 return issubclass(annotation, int) and not issubclass(annotation, enum.Flag) 

455 return issubclass(annotation, _ORDERABLE_TYPES) 

456 

457 

458def _enum_type(column: Any) -> sqlalchemy.Enum | None: 

459 """The ``Enum`` type of ``column``, also inside ``TypeDecorator`` 

460 layers, or ``None``. Such a column holds labels: the names of the 

461 members, or the strings that it was given.""" 

462 sql_type = getattr(column, "type", None) 

463 while isinstance(sql_type, TypeDecorator): 

464 sql_type = sql_type.impl_instance 

465 return sql_type if isinstance(sql_type, sqlalchemy.Enum) else None 

466 

467 

468def _has_json_type(column: Any) -> bool: 

469 """Whether ``column`` has SQLAlchemy's ``JSON`` type, also inside 

470 ``TypeDecorator`` layers, such as ``fr.models.PydanticJSON``. ``JSONB`` is such 

471 a type too. 

472 

473 Such a column holds JSON text, such as ``"x"`` with its quotes. 

474 SQLAlchemy compares it with a value such as ``x``, without the quotes, so 

475 a filter finds no row on SQLite and fails on PostgreSQL. 

476 """ 

477 sql_type = getattr(column, "type", None) 

478 while isinstance(sql_type, TypeDecorator): 

479 sql_type = sql_type.impl_instance 

480 return isinstance(sql_type, sqlalchemy.JSON) 

481 

482 

483def derive_list_params_schema( 

484 response_schema: _SchemaClass, 

485 model: type[Any], 

486 *, 

487 pagination: _AnyPagination = _DEFAULT_PAGINATION, 

488 include_filters: _abc.Iterable[str] = ("*",), 

489 exclude_filters: _abc.Iterable[str] = (), 

490 include_sort_keys: _abc.Iterable[str] = ("*",), 

491 exclude_sort_keys: _abc.Iterable[str] = (), 

492 sort_query_param: str = "sort", 

493 default_sort: str | None = None, 

494) -> _SchemaClass: 

495 """ 

496 Build the list params: a Pydantic model that describes and validates the 

497 URL query parameters of a list endpoint. A view keeps it in 

498 :attr:`~fastapi_restly.views.BaseRestView.list_params_schema`. 

499 

500 The generated model accepts pagination (``page`` and ``page_size``, or 

501 ``limit`` and ``offset``), sorting (``sort``), and filters. Each field of ``response_schema`` that maps to a 

502 column of ``model`` gives filter keys, and its type decides which ones. 

503 Every such field gives the plain key and the keys with the suffixes 

504 ``__in``, ``__ne`` and ``__not_in``. A column that can be NULL also gives 

505 ``__isnull``, and so does each dotted key, because a related row can be 

506 missing. A type with an order, such as a number, a date or an int enum, 

507 also gives ``__gte``, ``__lte``, ``__gt`` and ``__lt``, unless the column 

508 has SQLAlchemy's ``Enum`` type, which holds labels. A text column gives 

509 ``__icontains``, and range keys only for a field of type ``date``. 

510 

511 A field that does not map to a column, such as a relationship, gives no 

512 keys. A WriteOnly field gives none either, because a filter on it would 

513 let a client find out its value. A name with ``.`` or ``__`` gives none, 

514 because a key could not be read back. A field whose type is a collection 

515 (``dict``/``list``, e.g. a ``JSON`` or ``ARRAY`` column) gives only 

516 ``__isnull``: a value from the URL cannot become a collection. A field on 

517 a JSON column gives only ``__isnull`` too, also when it holds one value, 

518 such as a ``str``: the database compares the JSON text, not the value. A 

519 field of a nested schema gives dotted keys, such as ``vendor.name``. 

520 

521 The model forbids a key that it does not have, so a route of your own 

522 answers ``422`` for it. A view passes on only the keys that it knows when 

523 its ``unknown_query_params`` is ``"ignore"``. 

524 

525 Each key has the type of the field and its validators, without its bounds, 

526 such as ``gt``: a filter compares a value, and does not store it. Only 

527 ``__in`` and ``__not_in`` take several values, separated by commas or from a 

528 repeated key. 

529 

530 The four key settings choose which of these keys the model has. Each 

531 entry is a key with the Python name of its field, also for a field with 

532 an alias, or a pattern. An entry with the name in the URL of such a field 

533 raises an error. ``*`` in a pattern 

534 matches any characters except ``.``, so it stays within one level. 

535 By default the model has the keys of the resource's own fields, and no 

536 dotted keys. An entry that matches no key raises an error. 

537 

538 With a ``pagination`` (the default is ``page`` and ``page_size``), its two 

539 query parameters are added under its names and validated by Pydantic with 

540 bounds. With a :class:`~fastapi_restly.views.NumberedPagination`, the page 

541 is at least 1 and at most ``max_page`` when set, and the page size is from 

542 1 to ``max_page_size``. With an 

543 :class:`~fastapi_restly.views.OffsetPagination`, the limit is from 1 to 

544 ``max_limit``, and the offset is at least 0 and at most ``max_offset`` when 

545 set. The resulting SQL offset must also fit in a signed 64-bit integer. 

546 Out-of-range values produce a standard 422 response from FastAPI. With a 

547 :class:`~fastapi_restly.views.NoPagination` 

548 or ``None``, no pagination parameters are emitted at all -- the endpoint 

549 returns every matching row -- while sorting and filtering stay available. 

550 

551 :param response_schema: The response schema whose fields decide the 

552 available filter parameters. A view passes its ``response_schema``, so 

553 a client can filter only on a field of that class. 

554 :param model: The SQLAlchemy model the list endpoint queries. Used to verify 

555 each field resolves to a filterable column; non-column fields are 

556 omitted from the generated params. 

557 :param pagination: The view's pagination settings. A ``NoPagination`` or 

558 ``None`` is an unpaginated view, which returns the full result set. 

559 :param include_filters: The filter keys to keep. ``("*", "*.*")`` keeps 

560 the own keys and the dotted keys one level down, and ``()`` keeps 

561 none. Each entry must match a key, so ``"*.*"`` needs a nested 

562 schema. 

563 :param exclude_filters: The filter keys to remove, after 

564 ``include_filters``. A name without a suffix removes the whole field: 

565 the plain key and each key with a suffix. 

566 :param include_sort_keys: The keys that ``sort`` accepts. A sort key has 

567 no suffix, and never goes through a to-many relationship. With 

568 ``()``, the model has no ``sort``. 

569 :param exclude_sort_keys: The sort keys to remove, after 

570 ``include_sort_keys``. 

571 :param sort_query_param: The name of the sort parameter, such as 

572 ``"order_by"``. 

573 :param default_sort: The sort when the request has none, with the 

574 Python names of the fields, such as ``"-created_at"``. It becomes the 

575 default of the sort parameter, with the names in the URL. A key must 

576 be a field that a sort key could have, but 

577 ``include_sort_keys`` does not have to keep it. 

578 :raises fastapi_restly.exc.RestlyConfigurationError: An entry of a key 

579 setting matches no key, matches only names in the URL, or is not a 

580 key or pattern. The sort 

581 parameter has the name of a page parameter. A key of 

582 ``default_sort`` is not a field to sort on, or appears twice. 

583 """ 

584 return _derive_list_params( 

585 response_schema, 

586 model, 

587 pagination=pagination, 

588 settings={ 

589 "include_filters": include_filters, 

590 "exclude_filters": exclude_filters, 

591 "include_sort_keys": include_sort_keys, 

592 "exclude_sort_keys": exclude_sort_keys, 

593 }, 

594 sort_query_param=sort_query_param, 

595 default_sort=default_sort, 

596 ) 

597 

598 

599def _derive_list_params( 

600 response_schema: _SchemaClass, 

601 model: type[DeclarativeBase], 

602 *, 

603 pagination: _AnyPagination, 

604 settings: _abc.Mapping[str, Any], 

605 owner: str | None = None, 

606 inherited: _abc.Mapping[str, str] | None = None, 

607 own_filters: _abc.Sequence[_OwnFilter] = (), 

608 sort_query_param: str = _SORT_QUERY_PARAM, 

609 default_sort: str | None = None, 

610 default_sort_from: str | None = None, 

611) -> _SchemaClass: 

612 """:func:`derive_list_params_schema`, for a view too. 

613 

614 :param owner: The view, for the messages. 

615 :param inherited: The key settings that a view inherits, each with the 

616 view that sets it. Their entries may match no key, because a base 

617 view serves many schemas. 

618 :param own_filters: The view's own filter keys, which are always on. 

619 :param default_sort_from: The base view that ``default_sort`` comes 

620 from, for the messages. It is checked too: an order that does not 

621 apply would change the list without a sign. 

622 """ 

623 patterns = { 

624 name: _check_key_setting(_setting_label(owner, name), settings[name]) 

625 for name in _KEY_SETTINGS 

626 } 

627 _check_query_param(_setting_label(owner, "sort_query_param"), sort_query_param) 

628 _check_default_sort(_setting_label(owner, "default_sort"), default_sort) 

629 settings = _settings_of(pagination) 

630 if sort_query_param in settings._query_params(): 

631 raise RestlyConfigurationError( 

632 f"{_setting_label(owner, 'sort_query_param')} cannot be " 

633 f"{sort_query_param!r}: it is a page parameter of the pagination. " 

634 "Choose another name for one of them." 

635 ) 

636 fields: dict[str, Any] = settings._list_params_fields() 

637 

638 reserved = _reserved_names(pagination, sort_query_param) 

639 # The key settings name a field by its Python name, and a client by the 

640 # name that a response shows. So each key below is in Python names, and 

641 # its value holds the key in the URL. 

642 filter_fields: dict[str, tuple[str, Any]] = {} 

643 # The filter keys of each field, for the messages. 

644 keys_of_field: dict[str, list[str]] = {} 

645 # The name in the URL of each field with a column. 

646 url_names: dict[str, str] = {} 

647 sort_keys: dict[str, str] = {} 

648 for url_name, name, field in _iter_fields_including_nested(response_schema): 

649 # Only emit params for fields that resolve to a filterable column on the 

650 # model -- using the very predicate the request path applies. A 

651 # relationship/collection field (e.g. ``books: list[BookRef]``) or a 

652 # reference traversal that does not resolve would otherwise advertise 

653 # filters in OpenAPI that always fail at request time. 

654 try: 

655 relationships, column = _resolve_column(model, url_name, response_schema) 

656 except BadQueryParam: 

657 continue 

658 url_names[name] = url_name 

659 # ``sort=tags.name`` has no clear meaning when an item has several 

660 # tags, and the join repeats rows. 

661 if _is_sortable(field, column) and not any( 

662 relationship.property.uselist for relationship in relationships 

663 ): 

664 sort_keys[name] = url_name 

665 field_filters = _filter_fields(response_schema, url_name, field, column) 

666 keys_of_field[name] = [] 

667 for url_key, filter_field in field_filters.items(): 

668 key = name + url_key.removeprefix(url_name) 

669 filter_fields[key] = (url_key, filter_field) 

670 keys_of_field[name].append(key) 

671 

672 schema_name = _written_name(response_schema) 

673 url_filter_keys = {key: url_key for key, (url_key, _) in filter_fields.items()} 

674 inherited = inherited or {} 

675 for name in _KEY_SETTINGS: 

676 is_filter_setting = name in ("include_filters", "exclude_filters") 

677 label = _setting_label(owner, name) 

678 # also for a setting that the view inherits: the entry would leave 

679 # the keys on, or off, without a sign 

680 _check_url_names( 

681 f"{label} (from {inherited[name]})" if name in inherited else label, 

682 patterns[name], 

683 url_filter_keys if is_filter_setting else sort_keys, 

684 url_names, 

685 whole_fields=name == "exclude_filters", 

686 ) 

687 if name in inherited or patterns[name] == _KEY_SETTING_DEFAULTS[name]: 

688 continue 

689 if is_filter_setting: 

690 _check_filter_entries( 

691 label, 

692 patterns[name], 

693 keys_of_field, 

694 url_names, 

695 schema_name, 

696 whole_fields=name == "exclude_filters", 

697 ) 

698 else: 

699 _check_sort_entries( 

700 label, patterns[name], sort_keys, url_names, schema_name 

701 ) 

702 

703 label = _setting_label(owner, "default_sort") 

704 default_sort_keys = _default_sort_keys( 

705 f"{label} (from {default_sort_from})" if default_sort_from else label, 

706 default_sort, 

707 sort_keys, 

708 url_names, 

709 schema_name, 

710 hint=( 

711 f" Set {label} = None for primary key order." if default_sort_from else "" 

712 ), 

713 ) 

714 # OpenAPI and the record hold the sort as a client writes it 

715 url_default_sort = ( 

716 None 

717 if default_sort is None 

718 else ",".join( 

719 ("-" if term.startswith("-") else "") + sort_keys[term.removeprefix("-")] 

720 for term in default_sort.split(",") 

721 ) 

722 ) 

723 url_sort_keys = [ 

724 sort_keys[key] 

725 for key in _pick_keys( 

726 list(sort_keys), 

727 patterns["include_sort_keys"], 

728 patterns["exclude_sort_keys"], 

729 ) 

730 ] 

731 if url_sort_keys: 

732 fields[sort_query_param] = _sort_field(url_sort_keys, url_default_sort) 

733 for key in _pick_keys( 

734 list(filter_fields), 

735 patterns["include_filters"], 

736 _whole_fields(patterns["exclude_filters"], keys_of_field, keys_of_field), 

737 ): 

738 url_key, filter_field = filter_fields[key] 

739 if url_key in reserved: 

740 raise RestlyConfigurationError( 

741 f"{_setting_label(owner, 'list_params_schema')}: the filter key " 

742 f"{url_key!r} of {schema_name} is also a page or sort parameter. " 

743 "Give the field a Pydantic alias, rename the page or sort " 

744 "parameter, or leave the field out with " 

745 f"exclude_filters = ({key!r},)." 

746 ) 

747 fields[url_key] = filter_field 

748 for own in own_filters: 

749 _check_own_key( 

750 _setting_label(owner, own.method), 

751 own.key, 

752 fields, 

753 reserved, 

754 url_names, 

755 {url_key: key for key, url_key in url_filter_keys.items()}, 

756 schema_name, 

757 ) 

758 annotation = own.annotation if own.always else Optional[own.annotation] 

759 default = own.default if own.always else None 

760 fields[own.key] = ( 

761 Annotated[annotation, Field(description=own.description)], 

762 default, 

763 ) 

764 

765 params_model = pydantic.create_model( # type: ignore[call-overload] 

766 _schema_role_name(response_schema, "ListParams"), 

767 # also on a route outside a view, which reads the model with Query() 

768 __config__=pydantic.ConfigDict(extra="forbid"), 

769 __validators__=settings._list_params_validators(), 

770 **fields, 

771 ) 

772 _RECORDS[params_model] = _ListParamsRecord( 

773 pagination=pagination, 

774 **patterns, 

775 sort_query_param=sort_query_param, 

776 default_sort=url_default_sort, 

777 default_sort_keys=tuple(sort_keys[key] for key in default_sort_keys), 

778 sort_keys=tuple(url_sort_keys), 

779 own_filters=tuple(own_filters), 

780 ) 

781 return params_model 

782 

783 

784def _default_sort_keys( 

785 label: str, 

786 default_sort: str | None, 

787 sort_keys: _abc.Mapping[str, str], 

788 url_names: _abc.Mapping[str, str], 

789 schema_name: str, 

790 *, 

791 hint: str = "", 

792) -> tuple[str, ...]: 

793 """The keys of ``default_sort``, in Python names. 

794 

795 :param sort_keys: Every key that the schema can sort on, before the key 

796 settings choose, with its name in the URL. 

797 :param url_names: The name in the URL of each field with a column. 

798 :param hint: The end of the message. 

799 :raises RestlyConfigurationError: a key is not in ``sort_keys``. 

800 """ 

801 if default_sort is None: 

802 return () 

803 keys = tuple(term.removeprefix("-") for term in default_sort.split(",")) 

804 for key in keys: 

805 if key in sort_keys: 

806 continue 

807 python_name = _python_name_of(key, url_names) 

808 if python_name in sort_keys: 

809 message = ( 

810 f"{label}: {key!r} is the name in the URL. A key is the Python " 

811 f"name of a field, so write {python_name!r}." 

812 ) 

813 else: 

814 message = ( 

815 f"{label}: {key!r} is not a field of {schema_name} to sort on. " 

816 "A key is the Python name of a field." 

817 ) 

818 if sort_keys: 818 ↛ 823line 818 didn't jump to line 823 because the condition on line 818 was always true

819 message += ( 

820 f" The fields to sort on are: {_names(sort_keys, url_names)}." 

821 ) 

822 else: 

823 message += f" {schema_name} has no fields to sort on." 

824 raise RestlyConfigurationError(message + hint) 

825 return keys 

826 

827 

828def _python_name_of(url_name: str, url_names: _abc.Mapping[str, str]) -> str | None: 

829 """The Python name of the field that has ``url_name`` in the URL, when the 

830 two names differ.""" 

831 return next( 

832 ( 

833 name 

834 for name, url in url_names.items() 

835 if url == url_name and name != url_name 

836 ), 

837 None, 

838 ) 

839 

840 

841def _names(names: _abc.Iterable[str], url_names: _abc.Mapping[str, str]) -> str: 

842 """Fields for a message, each with its name in the URL when that differs, 

843 such as ``id, created_at (createdAt in the URL)``.""" 

844 return ", ".join(_name(name, url_names) for name in names) 

845 

846 

847def _name(name: str, url_names: _abc.Mapping[str, str]) -> str: 

848 url_name = url_names.get(name, name) 

849 return name if url_name == name else f"{name} ({url_name} in the URL)" 

850 

851 

852def _quoted_name(name: str, url_names: _abc.Mapping[str, str]) -> str: 

853 """A field for a message, as :func:`_name`, with quotes: ``'created_at' 

854 (createdAt in the URL)``.""" 

855 return repr(name) + _name(name, url_names).removeprefix(name) 

856 

857 

858def _check_url_names( 

859 label: str, 

860 entries: tuple[str, ...], 

861 url_keys: _abc.Mapping[str, str], 

862 url_names: _abc.Mapping[str, str], 

863 *, 

864 whole_fields: bool = False, 

865) -> None: 

866 """Raise for an entry that matches a key only by its name in the URL. 

867 

868 The key settings take Python names. Such an entry would leave the keys 

869 on, or off, without a sign, so this check runs also for a setting that a 

870 view inherits. 

871 

872 :param url_keys: Each key in Python names, with the key in the URL. 

873 :param whole_fields: A bare name stands for the whole field, as in 

874 ``exclude_filters``; see :func:`_whole_fields`. 

875 """ 

876 for entry in entries: 

877 patterns = _whole_fields((entry,), url_names) if whole_fields else (entry,) 

878 regexes = [_pattern_regex(pattern) for pattern in patterns] 

879 if any(regex.fullmatch(key) for regex in regexes for key in url_keys): 

880 continue 

881 matched = next( 

882 ( 

883 (key, url_key) 

884 for key, url_key in url_keys.items() 

885 if any(regex.fullmatch(url_key) for regex in regexes) 

886 ), 

887 None, 

888 ) 

889 if matched is None: 

890 continue 

891 key, url_key = matched 

892 field, _ = _split_key(entry) 

893 python_name = _python_name_of(field, url_names) 

894 if "*" not in entry and python_name is not None: 

895 raise RestlyConfigurationError( 

896 f"{label}: {entry!r} is the name in the URL. The key settings " 

897 "take the Python name of a field, so write " 

898 f"{python_name + entry.removeprefix(field)!r}." 

899 ) 

900 raise RestlyConfigurationError( 

901 f"{label}: {entry!r} matches only names in the URL, such as " 

902 f"{url_key!r}. The key settings take the Python names of the " 

903 f"fields, such as {key!r}." 

904 ) 

905 

906 

907def _split_key(key: str) -> tuple[str, str]: 

908 """The field and the operator of a filter key, such as ``("vendor.name", 

909 "icontains")``. The operator is ``""`` for a key without one. The last 

910 ``__`` splits them, so a field may end in ``_``, as ``type___in`` does.""" 

911 field, separator, operator = key.rpartition("__") 

912 return (field, operator) if separator else (key, "") 

913 

914 

915def _check_own_key( 

916 label: str, 

917 key: str, 

918 fields: dict[str, Any], 

919 reserved: _abc.Set[str], 

920 url_names: _abc.Mapping[str, str], 

921 python_keys: _abc.Mapping[str, str], 

922 schema_name: str, 

923) -> None: 

924 """Reject an own filter key that the list params already have, or that 

925 does not read as the generated keys do. An own key is a key in the URL. 

926 

927 :param url_names: The name in the URL of each field with a column. 

928 :param python_keys: Each generated filter key in the URL, also the keys 

929 that are off, with the key in Python names, for the messages. 

930 

931 :raises RestlyConfigurationError: the key is a page parameter or the 

932 sort parameter, or a generated filter key that is on, or it has 

933 ``__`` or ``.`` and does not start with a field with filters. 

934 """ 

935 if key in reserved: 

936 raise RestlyConfigurationError( 

937 f"{label}: the key {key!r} is a page parameter or the sort " 

938 "parameter. Choose another key." 

939 ) 

940 # ``__`` splits a field from an operator, and ``.`` walks to a related 

941 # field, in every key 

942 field, _ = _split_key(key) 

943 if ("__" in key or "." in key) and field not in url_names.values(): 

944 what = ( 

945 f"the key {key!r} starts with {field!r}, which is" 

946 if field != key 

947 else f"the key {key!r} is" 

948 ) 

949 message = ( 

950 f"{label}: {what} not a field of {schema_name} with filters. A key " 

951 "with '__' or '.' starts with a field, as the generated keys do. Or " 

952 "choose a key without '__' and '.'." 

953 ) 

954 if url_names: 954 ↛ 957line 954 didn't jump to line 957 because the condition on line 954 was always true

955 message += f" The fields with filters are: {', '.join(url_names.values())}." 

956 else: 

957 message += f" {schema_name} has no fields with filters." 

958 raise RestlyConfigurationError(message) 

959 if key in fields: 

960 python_key = python_keys.get(key, key) 

961 message = ( 

962 f"{label}: the key {key!r} is also a generated filter key. To " 

963 f"replace it, leave it out with exclude_filters = ({python_key!r},)." 

964 ) 

965 if "__" not in key: 

966 message += ( 

967 f" That also removes {python_key}__in and the other keys of the " 

968 "field. To keep them, list the keys you want in include_filters " 

969 "instead." 

970 ) 

971 raise RestlyConfigurationError(message) 

972 

973 

974def _setting_label(owner: str | None, name: str) -> str: 

975 return f"{owner}.{name}" if owner else name 

976 

977 

978def _filter_fields( 

979 response_schema: _SchemaClass, name: str, field: FieldInfo, column: Any 

980) -> dict[str, Any]: 

981 """The filter keys of one field, as fields of the list params model. 

982 

983 A key has the type of its field, and takes one value. Only ``__in`` and 

984 ``__not_in`` take several. A text search takes one piece of text, and 

985 ``__isnull`` a bool, and only a column that can be NULL has it. A field 

986 that holds a collection, such as a ``dict``, or that has a JSON column, has 

987 no other key. A value from the URL cannot become a collection, and a JSON 

988 column holds JSON text, so a filter on it finds no row on SQLite and fails 

989 on PostgreSQL. 

990 

991 :param response_schema: The schema that the key ``name`` starts from. 

992 :param name: The field as the client names it, such as ``vendor.name``. 

993 :param field: The field. 

994 :param column: The column of the field, whose type can take the range 

995 keys away. 

996 """ 

997 fields: dict[str, Any] = {} 

998 supports_scalar = _supports_scalar_operators(field) and not _has_json_type(column) 

999 # a related row can be missing, so a dotted key can always be NULL 

1000 has_isnull = "." in name or _can_be_null(column) 

1001 if supports_scalar: 

1002 schema_cls, field_name = _field_of(response_schema, name) 

1003 values = _KeyValues( 

1004 schema_cls, 

1005 field_name, 

1006 column, 

1007 isnull_key=f"{name}__isnull" if has_isnull else None, 

1008 ) 

1009 

1010 def one_value(description: str) -> Any: 

1011 return _key_field( 

1012 lambda: values.json_schema, _one_value(values.read), description 

1013 ) 

1014 

1015 def several_values(description: str) -> Any: 

1016 return _key_field( 

1017 lambda: {"type": "array", "items": values.json_schema}, 

1018 _several_values(values.read), 

1019 description, 

1020 annotation=Optional[list[Any]], 

1021 ) 

1022 

1023 fields[name] = one_value(f"Rows where ``{name}`` is this value.") 

1024 fields[f"{name}__in"] = several_values( 

1025 f"Rows where ``{name}`` is one of these values. Separate the values " 

1026 "with commas, or repeat the key." 

1027 ) 

1028 fields[f"{name}__ne"] = one_value(f"Rows where ``{name}`` is not this value.") 

1029 fields[f"{name}__not_in"] = several_values( 

1030 f"Rows where ``{name}`` is none of these values. Separate the values " 

1031 "with commas, or repeat the key." 

1032 ) 

1033 if has_isnull: 

1034 fields[f"{name}__isnull"] = ( 

1035 Annotated[ 

1036 Optional[bool], 

1037 Field( 

1038 description=( 

1039 f"``true`` matches rows where ``{name}`` IS NULL; " 

1040 f"``false`` matches IS NOT NULL." 

1041 ) 

1042 ), 

1043 ], 

1044 None, 

1045 ) 

1046 

1047 if supports_scalar and _supports_range_operators(field, column): 

1048 for suffix, sql in ( 

1049 ("__gte", ">="), 

1050 ("__lte", "<="), 

1051 ("__gt", ">"), 

1052 ("__lt", "<"), 

1053 ): 

1054 fields[f"{name}{suffix}"] = one_value(f"``{name} {sql} value``.") 

1055 

1056 if supports_scalar and _supports_text_search(field, column): 

1057 fields[f"{name}__icontains"] = _key_field( 

1058 lambda: {"type": "string"}, 

1059 _search_value, 

1060 f"Rows where ``{name}`` holds this text, in any case.", 

1061 ) 

1062 return fields 

1063 

1064 

1065class _KeyValues: 

1066 """How the filter keys of one field read a value, and its type in 

1067 OpenAPI. 

1068 

1069 Restly builds each of them when something first needs it: a request, or 

1070 OpenAPI. Both need the core schema of the whole schema class, which a 

1071 class that names a schema defined later does not have yet when the view 

1072 registers. And a key that the settings leave out costs nothing. 

1073 """ 

1074 

1075 def __init__( 

1076 self, 

1077 schema_cls: _SchemaClass, 

1078 field_name: str, 

1079 column: Any, 

1080 *, 

1081 isnull_key: str | None = None, 

1082 ) -> None: 

1083 self._schema_cls = schema_cls 

1084 self._field_name = field_name 

1085 self._column = column 

1086 self._isnull_key = isnull_key 

1087 

1088 @functools.cached_property 

1089 def _reader(self) -> Callable[[Any], Any]: 

1090 return _checked_reader( 

1091 self._schema_cls, 

1092 self._field_name, 

1093 self._column, 

1094 isnull_key=self._isnull_key, 

1095 ) 

1096 

1097 def read(self, value: Any) -> Any: 

1098 """The value of a key, from the value in the URL; see 

1099 :func:`_checked_reader`.""" 

1100 return self._reader(value) 

1101 

1102 @functools.cached_property 

1103 def json_schema(self) -> dict[str, Any]: 

1104 """The JSON schema of one value; see :func:`_value_json_schema`.""" 

1105 return _value_json_schema(self._schema_cls, self._field_name, self._column) 

1106 

1107 

1108@dataclasses.dataclass(frozen=True) 

1109class _KeyJsonSchema: 

1110 """The JSON schema of a filter key in OpenAPI, built when OpenAPI is 

1111 first written. It replaces the schema that Pydantic would write, as 

1112 ``pydantic.WithJsonSchema`` does. 

1113 

1114 ``value_schema`` gives the JSON schema of the key's value. The key can 

1115 always be left out, so the schema also allows ``null``. 

1116 """ 

1117 

1118 value_schema: Callable[[], dict[str, Any]] 

1119 

1120 def __get_pydantic_json_schema__(self, schema: Any, handler: Any) -> dict[str, Any]: 

1121 value_schema = self.value_schema() 

1122 if not value_schema: 

1123 return {} 

1124 options = ( 

1125 value_schema["anyOf"] if set(value_schema) == {"anyOf"} else [value_schema] 

1126 ) 

1127 return {"anyOf": [*options, {"type": "null"}]} 

1128 

1129 

1130def _key_field( 

1131 value_schema: Callable[[], dict[str, Any]], 

1132 validate: Callable[[Any], Any], 

1133 description: str, 

1134 *, 

1135 annotation: Any = Optional[Any], 

1136) -> tuple[Any, None]: 

1137 """A filter key as a field of the list params model, with no default. 

1138 

1139 Restly validates the value itself, so the type in OpenAPI comes from 

1140 ``value_schema``: the type of the field, without its bounds. 

1141 

1142 :param value_schema: Gives the JSON schema of the key's value. 

1143 :param validate: Gives the value of the key, from the value in the URL. 

1144 :param description: The text of the key in OpenAPI. 

1145 :param annotation: The type of the key, a list for a key with several 

1146 values, so that the list route reads each value of a repeated key. 

1147 """ 

1148 return ( 

1149 Annotated[ 

1150 annotation, 

1151 pydantic.PlainValidator(validate), 

1152 _KeyJsonSchema(value_schema), 

1153 Field(description=description), 

1154 ], 

1155 None, 

1156 ) 

1157 

1158 

1159def _one_value(read: Callable[[Any], Any]) -> Callable[[Any], Any]: 

1160 """The validator of a filter key that takes one value.""" 

1161 

1162 def validate(value: Any) -> Any: 

1163 if value is None: 

1164 return None 

1165 try: 

1166 return read(value) 

1167 except _BadValue as exc: 

1168 raise PydanticCustomError( 

1169 cast(Any, exc.error_type), cast(Any, exc.reason) 

1170 ) from exc 

1171 

1172 return validate 

1173 

1174 

1175def _several_values(read: Callable[[Any], Any]) -> Callable[[Any], Any]: 

1176 """The validator of ``__in`` and ``__not_in``. An error names the position 

1177 of the value that fails. A value cannot be ``None``: SQL compares no value 

1178 with NULL, so ``NOT IN ('a', NULL)`` would leave out every row.""" 

1179 

1180 def validate(value: Any) -> Any: 

1181 if value is None: 1181 ↛ 1182line 1181 didn't jump to line 1182 because the condition on line 1181 was never true

1182 return None 

1183 values: list[Any] = [] 

1184 errors: list[Any] = [] 

1185 for position, item in enumerate(_listed_values(value)): 

1186 try: 

1187 result = read(item) 

1188 if result is None: 

1189 raise _BadValue("value_error", _NULL_IN_LIST) 

1190 values.append(result) 

1191 except _BadValue as exc: 

1192 errors.append( 

1193 { 

1194 "type": PydanticCustomError( 

1195 cast(Any, exc.error_type), cast(Any, exc.reason) 

1196 ), 

1197 "loc": (position,), 

1198 "input": item, 

1199 } 

1200 ) 

1201 if errors: 

1202 raise ValidationError.from_exception_data("list", errors) 

1203 return values 

1204 

1205 return validate 

1206 

1207 

1208#: Why ``__in`` or ``__not_in`` refuses ``None``, for the messages. 

1209_NULL_IN_LIST = "A list of values cannot hold null." 

1210 

1211 

1212def _listed_values(value: Any) -> list[Any]: 

1213 """The values of ``__in`` and ``__not_in``. One text is split at each comma, 

1214 and spaces around each part go. With several values, as from a repeated key, 

1215 each value stays as it is, so a value can hold a comma.""" 

1216 values = ( 

1217 list(value) if isinstance(value, (list, tuple, set, frozenset)) else [value] 

1218 ) 

1219 if len(values) == 1 and isinstance(values[0], str): 

1220 return [part.strip() for part in values[0].split(",")] 

1221 return values 

1222 

1223 

1224def _search_value(value: Any) -> str | None: 

1225 """The value of a text search: one piece of text, without spaces around 

1226 it. An empty value is no filter. 

1227 

1228 :raises ValueError: the value is a collection, such as a list from code, 

1229 or the text holds a NUL character. 

1230 """ 

1231 if value is None: 1231 ↛ 1232line 1231 didn't jump to line 1232 because the condition on line 1231 was never true

1232 return None 

1233 if isinstance(value, (list, tuple, set, frozenset, dict)): 

1234 raise ValueError("A text search takes one piece of text.") 

1235 text = str(value).strip() 

1236 check_text(text) 

1237 return text or None 

1238 

1239 

1240#: Why a field has no key but ``__isnull``, for the messages. 

1241_ISNULL_ONLY_HINT = ( 

1242 "A field that holds a dict or a list, or that has a JSON column, has only __isnull." 

1243) 

1244 

1245#: Why a field has no key with this suffix, for the messages. 

1246_SUFFIX_HINTS = { 

1247 "icontains": ( 

1248 "Only a field on a text column has __icontains, and not an enum, a Literal " 

1249 "or a bool. On a TypeDecorator column, the field must be a str." 

1250 ), 

1251 "isnull": "Only a column that can be NULL has __isnull.", 

1252 **dict.fromkeys( 

1253 ("gte", "lte", "gt", "lt"), 

1254 "Only fields with an order, such as numbers, dates and int enums, have " 

1255 "__gte, __lte, __gt and __lt. A column of SQLAlchemy's Enum type has none, " 

1256 "and a text column has them only for a field of type date.", 

1257 ), 

1258 **dict.fromkeys(("", "in", "ne", "not_in"), _ISNULL_ONLY_HINT), 

1259} 

1260 

1261 

1262def _whole_fields( 

1263 entries: tuple[str, ...], 

1264 field_names: _abc.Container[str], 

1265 keys_of_field: _abc.Mapping[str, _abc.Sequence[str]] | None = None, 

1266) -> tuple[str, ...]: 

1267 """The patterns of ``exclude_filters``: a name without a suffix stands for 

1268 the whole field, the plain key and each key with a suffix. So a bare name 

1269 never leaves a client more than you named. 

1270 

1271 :param field_names: The Python name of each field. A field name with 

1272 ``__``, such as ``cost__internal``, is a whole field too. 

1273 :param keys_of_field: The filter keys of each field. For a field name, 

1274 the patterns are then these keys, so ``cost`` leaves out no key of a 

1275 field ``cost__internal``. 

1276 """ 

1277 patterns: list[str] = [] 

1278 for entry in entries: 

1279 patterns.append(entry) 

1280 if keys_of_field is not None and entry in keys_of_field: 

1281 patterns.extend(keys_of_field[entry]) 

1282 elif "*" not in entry and ("__" not in entry or entry in field_names): 

1283 patterns.append(f"{entry}__*") 

1284 return tuple(patterns) 

1285 

1286 

1287def _check_filter_entries( 

1288 label: str, 

1289 entries: tuple[str, ...], 

1290 keys_of_field: dict[str, list[str]], 

1291 url_names: _abc.Mapping[str, str], 

1292 schema_name: str, 

1293 *, 

1294 whole_fields: bool = False, 

1295) -> None: 

1296 """Raise for the first entry that matches no filter key. 

1297 

1298 The message lists the keys of the field that the entry names, or the 

1299 fields that have filters. 

1300 

1301 :param keys_of_field: The filter keys of each field, in Python names. 

1302 :param url_names: The name in the URL of each field with a column. 

1303 :param whole_fields: A bare name stands for the whole field, as in 

1304 ``exclude_filters``; see :func:`_whole_fields`. 

1305 """ 

1306 keys = [key for field_keys in keys_of_field.values() for key in field_keys] 

1307 for entry in entries: 

1308 patterns = ( 

1309 _whole_fields((entry,), keys_of_field, keys_of_field) 

1310 if whole_fields 

1311 else (entry,) 

1312 ) 

1313 if any( 

1314 _pattern_regex(pattern).fullmatch(key) 

1315 for pattern in patterns 

1316 for key in keys 

1317 ): 

1318 continue 

1319 message = f"{label}: {entry!r} matches no filter key of {schema_name}." 

1320 field, suffix = _split_key(entry) 

1321 if "*" not in field and field in keys_of_field: 

1322 field_keys = ", ".join(keys_of_field[field]) 

1323 named = _quoted_name(field, url_names) 

1324 if field_keys: 

1325 message += f" The filter keys of {named} are: {field_keys}." 

1326 else: 

1327 message += f" {named} has no filter keys." 

1328 if keys_of_field[field] in ([], [f"{field}__isnull"]): 

1329 message += f" {_ISNULL_ONLY_HINT}" 

1330 if not keys_of_field[field]: 

1331 message += f" {_SUFFIX_HINTS['isnull']}" 

1332 elif suffix in _SUFFIX_HINTS: 1332 ↛ 1341line 1332 didn't jump to line 1341 because the condition on line 1332 was always true

1333 message += f" {_SUFFIX_HINTS[suffix]}" 

1334 elif "*" not in entry: 

1335 if keys_of_field: 1335 ↛ 1340line 1335 didn't jump to line 1340 because the condition on line 1335 was always true

1336 message += ( 

1337 f" The fields with filters are: {_names(keys_of_field, url_names)}." 

1338 ) 

1339 else: 

1340 message += f" {schema_name} has no fields with filters." 

1341 raise RestlyConfigurationError(message) 

1342 

1343 

1344def _check_sort_entries( 

1345 label: str, 

1346 entries: tuple[str, ...], 

1347 sort_keys: _abc.Collection[str], 

1348 url_names: _abc.Mapping[str, str], 

1349 schema_name: str, 

1350) -> None: 

1351 """Raise for the first entry that matches no sort key. 

1352 

1353 :param sort_keys: Every sort key, in Python names. 

1354 :param url_names: The name in the URL of each field with a column. 

1355 """ 

1356 for entry in entries: 

1357 if any(_pattern_regex(entry).fullmatch(key) for key in sort_keys): 

1358 continue 

1359 message = f"{label}: {entry!r} matches no sort key of {schema_name}." 

1360 if "__" in entry: 

1361 message += " A sort key has no suffix." 

1362 if sort_keys: 1362 ↛ 1365line 1362 didn't jump to line 1365 because the condition on line 1362 was always true

1363 message += f" The sort keys are: {_names(sort_keys, url_names)}." 

1364 else: 

1365 message += f" {schema_name} has no sort keys." 

1366 raise RestlyConfigurationError(message) 

1367 

1368 

1369def _sort_field(sort_keys: list[str], default: str | None) -> tuple[Any, str | None]: 

1370 """The ``sort`` field of a list params model, which accepts ``sort_keys``. 

1371 

1372 :param default: The sort when the request has none. It does not have to 

1373 be in ``sort_keys``. 

1374 """ 

1375 allowed = frozenset(sort_keys) 

1376 

1377 def check_sort_keys(value: str | None) -> str | None: 

1378 if value == default: 

1379 # FastAPI validates the default that it fills in 

1380 return value 

1381 keys = [term.removeprefix("-") for term in (value or "").split(",") if term] 

1382 for key in keys: 

1383 if key not in allowed: 

1384 raise PydanticCustomError( 

1385 "unknown_sort_key", "Unknown sort key '{key}'", {"key": key} 

1386 ) 

1387 repeated = _repeated_key(keys) 

1388 if repeated is not None: 

1389 raise PydanticCustomError( 

1390 "repeated_sort_key", 

1391 "Sort key '{key}' appears more than once", 

1392 {"key": repeated}, 

1393 ) 

1394 return value 

1395 

1396 example = ",".join([f"-{sort_keys[0]}", *sort_keys[1:2]]) 

1397 keys = ", ".join(f"``{key}``" for key in sort_keys) 

1398 description = ( 

1399 "Keys to sort by, separated by commas. A ``-`` before a key sorts in " 

1400 f"descending order. Use each key only once. Example: ``{example}``. " 

1401 f"The sort keys are: {keys}." 

1402 ) 

1403 return ( 

1404 Annotated[ 

1405 Optional[str], 

1406 Field(description=description), 

1407 pydantic.AfterValidator(check_sort_keys), 

1408 ], 

1409 default, 

1410 ) 

1411 

1412 

1413def apply_list_params( 

1414 stmt: Select[Any], 

1415 list_params: pydantic.BaseModel | QueryParams, 

1416 model: type[Any], 

1417 response_schema: _SchemaClass, 

1418 *, 

1419 pagination: _AnyPagination = cast(Any, _FROM_PARAMS), 

1420 sort_nulls: SortNulls = "last", 

1421) -> Select[Any]: 

1422 """ 

1423 Apply pagination, sorting, and filtering to ``stmt`` using validated 

1424 list params. 

1425 

1426 ``list_params`` is normally an instance of the model returned by 

1427 :func:`derive_list_params_schema`. The default list endpoints pass a 

1428 validated instance, so the page, the page size and each filter value 

1429 have passed their fields. This function uses the values of such an 

1430 instance as they are. So a value that your code sets without 

1431 validation, as with ``model_copy(update=...)``, must have the type of 

1432 its field: ``True``, not ``"true"``. Other list params, such as a dict or 

1433 a model of your own, go through the validation of each field here. 

1434 ``response_schema`` decides the fields a client can filter and sort on. 

1435 A view passes its response schema. 

1436 

1437 The arguments match the view method 

1438 :meth:`~fastapi_restly.views.RestView.apply_list_params`, which calls this 

1439 function with the view's model, response schema and pagination. 

1440 

1441 With list params from :func:`derive_list_params_schema`, the sort 

1442 parameter has the name that the model was created with, and accepts only 

1443 its sort keys. With raw ``QueryParams`` or a hand-written model, the sort 

1444 parameter is ``sort``. List params 

1445 with a value for a view's own filter key, from 

1446 :func:`~fastapi_restly.views.list_filter`, raise ``ValueError``: only the 

1447 view can apply them. Use the view's ``apply_list_params``. 

1448 

1449 A raw :class:`~starlette.datastructures.QueryParams` is also accepted 

1450 for callers that build the query parameters programmatically. It skips 

1451 the list params model, so nothing checks the bounds of the page, such as 

1452 ``max_page_size`` or ``max_limit``: the caller checks them. Each filter 

1453 value still goes through the validation of its field. Every filter key 

1454 that :func:`derive_list_params_schema` can generate works, also a dotted 

1455 one. 

1456 

1457 ``pagination`` names the page parameters to read, and says how the page 

1458 applies. By default it is the pagination that the list params were created 

1459 with, by :func:`derive_list_params_schema` or by a view. 

1460 :class:`~fastapi_restly.query.OffsetListParams` outside a view read 

1461 ``limit`` and ``offset``. Raw ``QueryParams`` and other hand-written models 

1462 read ``page`` and ``page_size``. 

1463 

1464 A ``NoPagination`` or ``None`` applies no ``LIMIT``/``OFFSET``. With page 

1465 numbers, a missing page-size key also applies neither. With an offset, a 

1466 missing limit applies no ``LIMIT``, and the offset still applies. 

1467 

1468 ``sort_nulls`` says where the sort puts NULLs: ``"last"`` (the default) 

1469 or ``"first"`` in both directions, or ``None`` for where the database 

1470 puts them. Without a sort parameter, the sort is the ``default_sort`` 

1471 that the list params were created with. 

1472 

1473 Examples:: 

1474 

1475 # Pagination 

1476 page=2&page_size=50 

1477 limit=50&offset=50 

1478 

1479 # Sorting 

1480 sort=name,-created_at 

1481 

1482 # Filtering 

1483 name=Bob&status=active&created_at__gte=2024-01-01 

1484 

1485 # Search in text (text columns) 

1486 name__icontains=John&email__icontains=example 

1487 """ 

1488 if sort_nulls not in ("first", "last", None): 

1489 raise ValueError( 

1490 f"sort_nulls must be 'first', 'last' or None, got {sort_nulls!r}." 

1491 ) 

1492 _reject_own_filters(list_params) 

1493 stmt = _apply_filters( 

1494 stmt, list_params, model, response_schema, pagination=pagination 

1495 ) 

1496 return _apply_sort_and_page( 

1497 stmt, 

1498 list_params, 

1499 model, 

1500 response_schema, 

1501 pagination=pagination, 

1502 sort_nulls=sort_nulls, 

1503 ) 

1504 

1505 

1506#: The joins that the filters added to a statement, by the path of 

1507#: relationships. The sort reuses them, so a filter and a sort on the same 

1508#: relationship share one join. A statement that changes after the filters 

1509#: is another object, and its sort joins again. 

1510_STATEMENT_JOINS: "weakref.WeakKeyDictionary[Select[Any], _JoinAliases]" = ( 

1511 weakref.WeakKeyDictionary() 

1512) 

1513 

1514 

1515def _read_list_params( 

1516 list_params: pydantic.BaseModel | QueryParams, pagination: Any 

1517) -> tuple[_ListParamsRecord | None, _AnyPagination, str, dict[str, Any]]: 

1518 """The record of ``list_params``, the pagination to apply, the name of 

1519 the sort parameter, and the values of the list params by query key. 

1520 

1521 Without a record, as for hand-written list params, the sort parameter is 

1522 ``sort``. 

1523 

1524 :raises RestlyConfigurationError: a page parameter has the name of the 

1525 sort parameter. 

1526 """ 

1527 record = ( 

1528 _record_of(type(list_params)) 

1529 if isinstance(list_params, pydantic.BaseModel) 

1530 else None 

1531 ) 

1532 if isinstance(pagination, _FromParams): 

1533 pagination = ( 

1534 record.pagination 

1535 if record 

1536 else _pagination_of_list_params(type(list_params)) 

1537 ) 

1538 sort_query_param = record.sort_query_param if record else _SORT_QUERY_PARAM 

1539 if sort_query_param in _settings_of(pagination)._query_params(): 

1540 # list params from derive_list_params_schema reject this when created 

1541 raise RestlyConfigurationError( 

1542 f"A page parameter of the pagination is {sort_query_param!r}, " 

1543 "which is also the sort parameter of these list params. Give the " 

1544 "page parameter another name." 

1545 ) 

1546 own_keys = {own.key for own in record.own_filters} if record else set() 

1547 values = _list_params_values(list_params, exclude=own_keys, pagination=pagination) 

1548 return record, pagination, sort_query_param, values 

1549 

1550 

1551def _keep_joins(source: Select[Any], stmt: Select[Any]) -> Select[Any]: 

1552 """``stmt``, which adds only conditions to ``source``, with the joins 

1553 that the filters added to ``source``.""" 

1554 joins = _STATEMENT_JOINS.get(source) 

1555 if joins: 

1556 _STATEMENT_JOINS[stmt] = joins 

1557 return stmt 

1558 

1559 

1560def _reject_own_filters(list_params: pydantic.BaseModel | QueryParams) -> None: 

1561 """Reject list params with a value for a view's own filter key. 

1562 

1563 Only the view can call its filter methods. Leaving the key out would 

1564 return more rows than the client asked for. 

1565 

1566 :raises ValueError: an own filter has a value. 

1567 """ 

1568 if not isinstance(list_params, pydantic.BaseModel): 

1569 return 

1570 record = _record_of(type(list_params)) 

1571 if record is None: 

1572 return 

1573 applied = record.own_filter_values(list_params) 

1574 if applied: 

1575 own, _ = applied[0] 

1576 raise ValueError( 

1577 f"apply_list_params cannot apply the key {own.key!r}: it is a " 

1578 f"filter of the view's own, from the method {own.method}. Call " 

1579 "apply_list_params on the view instead." 

1580 ) 

1581 

1582 

1583def _apply_filters( 

1584 stmt: Select[Any], 

1585 list_params: pydantic.BaseModel | QueryParams, 

1586 model: type[DeclarativeBase], 

1587 response_schema: _SchemaClass, 

1588 *, 

1589 pagination: _AnyPagination = cast(Any, _FROM_PARAMS), 

1590) -> Select[Any]: 

1591 """The first step of :func:`apply_list_params`: the generated filters.""" 

1592 record, pagination, sort_query_param, values = _read_list_params( 

1593 list_params, pagination 

1594 ) 

1595 aliases: _JoinAliases = {} 

1596 stmt = _apply_filtering( 

1597 values, 

1598 stmt, 

1599 model, 

1600 response_schema, 

1601 validated=record is not None, 

1602 aliases=aliases, 

1603 pagination=pagination, 

1604 sort_query_param=sort_query_param, 

1605 ) 

1606 if aliases: 

1607 _STATEMENT_JOINS[stmt] = aliases 

1608 return stmt 

1609 

1610 

1611def _apply_sort_and_page( 

1612 stmt: Select[Any], 

1613 list_params: pydantic.BaseModel | QueryParams, 

1614 model: type[DeclarativeBase], 

1615 response_schema: _SchemaClass, 

1616 *, 

1617 pagination: _AnyPagination = cast(Any, _FROM_PARAMS), 

1618 sort_nulls: SortNulls = "last", 

1619) -> Select[Any]: 

1620 """The last steps of :func:`apply_list_params`: the sort, then the page.""" 

1621 record, pagination, sort_query_param, values = _read_list_params( 

1622 list_params, pagination 

1623 ) 

1624 stmt = _apply_sorting( 

1625 values, 

1626 stmt, 

1627 model, 

1628 response_schema, 

1629 aliases=dict(_STATEMENT_JOINS.get(stmt, {})), 

1630 # the default is the value of the sort field, also with a key that 

1631 # the client cannot send 

1632 sort_keys=record.sort_keys + record.default_sort_keys if record else None, 

1633 sort_query_param=sort_query_param, 

1634 default_sort=record.default_sort if record else None, 

1635 sort_nulls=sort_nulls, 

1636 ) 

1637 return _settings_of(pagination)._apply(stmt, values) 

1638 

1639 

1640def _public_name(name: str, field: FieldInfo) -> str: 

1641 """The name of a schema field in the URL: the name that a response shows.""" 

1642 return field.serialization_alias or field.alias or name 

1643 

1644 

1645def _query_key(name: str, field: FieldInfo) -> str: 

1646 """The query key of a list params field: its validation alias, its alias, or 

1647 its name, as FastAPI reads a query model.""" 

1648 if isinstance(field.validation_alias, str): 

1649 return field.validation_alias 

1650 return field.alias or name 

1651 

1652 

1653def _none_in_mapping_message(key: str, isnull_key: str | None = None) -> str: 

1654 """The error for ``None`` as the value of ``key`` in a dict of list 

1655 params. Leaving the key out would return more rows than the code asked 

1656 for, such as every row for ``{"id__in": None}``. 

1657 

1658 :param isnull_key: The ``__isnull`` key of the field, when it has one. 

1659 """ 

1660 message = f"The value of {key!r} is None. Leave the key out for no filter." 

1661 if isnull_key is not None: 

1662 message += f" To find the rows where it is null, use {isnull_key!r}: True." 

1663 return message 

1664 

1665 

1666def _list_params_values( 

1667 list_params: Any, 

1668 *, 

1669 exclude: _abc.Set[str] = frozenset(), 

1670 pagination: _AnyPagination = None, 

1671) -> dict[str, Any]: 

1672 """The values of ``list_params`` by query key, without the keys that have 

1673 no value. 

1674 

1675 Each field of a model goes under its query key. The page fields of list 

1676 params of your own go under the names of ``pagination``, also when code 

1677 created them without a view. In a ``QueryParams``, the last value of a 

1678 repeated key counts, as in FastAPI, except on ``__in`` and ``__not_in``. 

1679 

1680 A generated key holds the value of its field, which stays as it is: a 

1681 dump would make a dataclass a dict. A value of list params of your own 

1682 goes through the validation of its field, as text from a URL does, so it 

1683 comes in its JSON form, such as ``"desc"`` for a member of a ``str`` 

1684 enum, or a list for a tuple. 

1685 

1686 :param exclude: The fields of a model to leave out. 

1687 :param pagination: The pagination to read the page from. 

1688 """ 

1689 if isinstance(list_params, pydantic.BaseModel): 

1690 params_model = type(list_params) 

1691 fields = params_model.model_fields 

1692 page_keys = ( 

1693 pagination._own_list_params_keys() 

1694 if pagination is not None and _takes_page_fields(params_model, pagination) 

1695 else {} 

1696 ) 

1697 if _record_of(params_model) is not None: 

1698 dumped = { 

1699 name: value 

1700 for name in fields 

1701 if name not in exclude 

1702 and (value := getattr(list_params, name)) is not None 

1703 } 

1704 else: 

1705 dumped = list_params.model_dump( 

1706 mode="json", exclude_none=True, by_alias=False, exclude=set(exclude) 

1707 ) 

1708 return { 

1709 page_keys.get(name) 

1710 or (_query_key(name, fields[name]) if name in fields else name): value 

1711 for name, value in dumped.items() 

1712 } 

1713 if isinstance(list_params, _abc.Mapping) and not isinstance( 

1714 list_params, QueryParams 

1715 ): 

1716 for key, value in list_params.items(): 

1717 if value is None: 1717 ↛ 1716line 1717 didn't jump to line 1716 because the condition on line 1717 was always true

1718 raise BadQueryParam(_none_in_mapping_message(key)) 

1719 return dict(list_params) 

1720 query = ( 

1721 list_params 

1722 if isinstance(list_params, QueryParams) 

1723 else QueryParams(list_params) 

1724 ) 

1725 return { 

1726 key: query.getlist(key) if _takes_several_values(key) else query[key] 

1727 for key in query.keys() 

1728 } 

1729 

1730 

1731def _takes_several_values(key: str) -> bool: 

1732 """Whether a generated filter key takes several values.""" 

1733 return _split_key(key)[1] in {"in", "not_in"} 

1734 

1735 

1736def _apply_sorting( 

1737 values: _abc.Mapping[str, Any], 

1738 stmt: Select[Any], 

1739 model: type[DeclarativeBase], 

1740 schema_cls: _SchemaClass, 

1741 *, 

1742 aliases: _JoinAliases | None = None, 

1743 sort_keys: tuple[str, ...] | None = None, 

1744 sort_query_param: str = _SORT_QUERY_PARAM, 

1745 default_sort: str | None = None, 

1746 sort_nulls: SortNulls = "last", 

1747) -> Select[Any]: 

1748 """Apply the sort parameter to ``stmt``, with the primary key 

1749 last. 

1750 

1751 :param sort_keys: The keys that ``sort`` may use. ``None`` allows every 

1752 key that resolves to a column, as for hand-written list params. 

1753 :param default_sort: The sort when the sort parameter has no value. 

1754 :param sort_nulls: Where the sort puts NULLs. 

1755 :raises BadQueryParam: ``Unknown sort key``, or a key that appears more 

1756 than once. 

1757 """ 

1758 if aliases is None: 

1759 aliases = {} 

1760 sorted_on: list[InstrumentedAttribute[Any]] = [] 

1761 sort = values.get(sort_query_param) or "" 

1762 # a sort field of your own can be a list, such as ``sort: list[str]`` 

1763 sort = ",".join(map(str, sort)) if isinstance(sort, list) else str(sort) 

1764 if not sort.strip(","): 

1765 # also a sort of only commas, which has no keys 

1766 sort = default_sort or "" 

1767 seen: set[str] = set() 

1768 for column_name in sort.split(","): 

1769 if not column_name: 

1770 continue 

1771 descending = column_name.startswith("-") 

1772 column_name = column_name.removeprefix("-") 

1773 # The model checked ``sort``, but ``model_copy(update=...)`` does 

1774 # not validate. 

1775 if sort_keys is not None and column_name not in sort_keys: 

1776 raise BadQueryParam(f"Unknown sort key: {column_name!r}") 

1777 if column_name in seen: 

1778 raise BadQueryParam(f"Sort key {column_name!r} appears more than once") 

1779 seen.add(column_name) 

1780 stmt, column = _join_column( 

1781 stmt, model, column_name, schema_cls, aliases, kind="sort" 

1782 ) 

1783 stmt = stmt.order_by( 

1784 _sort_term( 

1785 column, 

1786 descending=descending, 

1787 nulls=sort_nulls, 

1788 joined="." in column_name, 

1789 ) 

1790 ) 

1791 sorted_on.append(column) 

1792 return _append_pk_tiebreak(stmt, model, sorted_on) 

1793 

1794 

1795def _written_name(schema_cls: _SchemaClass) -> str: 

1796 """The name of the class that the user wrote: for a response schema that 

1797 Restly derived, the main schema.""" 

1798 return schema_cls.__dict__.get("__restly_response_of__", schema_cls).__name__ 

1799 

1800 

1801def _iter_fields_including_nested( 

1802 schema_cls: _SchemaClass, 

1803 prefix: str = "", 

1804 python_prefix: str = "", 

1805 _followed: frozenset[_SchemaClass] = frozenset(), 

1806) -> Iterator[tuple[str, str, FieldInfo]]: 

1807 """Each field that can have keys, with its path in the URL and its path 

1808 in Python names, such as ``("vendor.createdAt", "vendor.created_at", 

1809 field)``.""" 

1810 for name, field in schema_cls.model_fields.items(): 

1811 # A field whose value a response never shows, such as a WriteOnly 

1812 # field or a SecretStr, is never a filter or sort key. 

1813 if _hides_value(field): 

1814 continue 

1815 public_name = _public_name(name, field) 

1816 # ``__`` splits a field from an operator, and ``.`` walks to a related 

1817 # field, so a name that holds either cannot be read from a key. Pydantic 

1818 # takes a name that starts with ``_`` as a private attribute, so the list 

1819 # params cannot hold a field for it. Such a field gets no keys, and the 

1820 # view still starts. 

1821 if "__" in public_name or "." in public_name or public_name.startswith("_"): 

1822 continue 

1823 full_name = f"{prefix}.{public_name}" if prefix else public_name 

1824 python_name = f"{python_prefix}.{name}" if python_prefix else name 

1825 nested = _get_nested_schema(field) 

1826 if nested and not _is_idref_field(field): 

1827 # Follow each nested schema once in a path. A schema that names 

1828 # itself, such as ``parent: CategorySchema | None``, then gets 

1829 # ``parent.name`` but not ``parent.parent.name``, and the walk ends. 

1830 if nested not in _followed: 

1831 yield from _iter_fields_including_nested( 

1832 nested, full_name, python_name, _followed | {nested} 

1833 ) 

1834 else: 

1835 yield full_name, python_name, field 

1836 

1837 

1838def _resolve_field_name(schema_cls: _SchemaClass, public_name: str) -> str | None: 

1839 """Return the Python field name for a public URL field name. 

1840 

1841 The public name is the name that a response shows: see 

1842 :func:`_public_name`. An aliased field is *only* reachable by that name — 

1843 Python field names are never part of the public URL contract, even when 

1844 the schema has ``populate_by_name=True`` (which only affects how Pydantic 

1845 parses input bodies, not the generated list params). 

1846 

1847 A field whose value a response never shows never resolves: a WriteOnly 

1848 field, one with ``exclude=True``, or one of Pydantic's secret types. 

1849 Filtering or sorting on it would let a client read back the value. 

1850 """ 

1851 resolved: str | None = None 

1852 for field_name, field in schema_cls.model_fields.items(): 

1853 if _public_name(field_name, field) == public_name: 

1854 resolved = field_name 

1855 break 

1856 if resolved is not None and _hides_value(schema_cls.model_fields[resolved]): 

1857 return None 

1858 return resolved 

1859 

1860 

1861def _join_column( 

1862 stmt: Select[Any], 

1863 model: type[DeclarativeBase], 

1864 column_path: str, 

1865 schema_cls: _SchemaClass, 

1866 aliases: _JoinAliases, 

1867 *, 

1868 kind: str = "filter", 

1869) -> tuple[Select[Any], InstrumentedAttribute[Any]]: 

1870 """Join each relationship path once and return its aliased leaf column. 

1871 

1872 Each join is a LEFT OUTER JOIN, so a row without the related row has NULL 

1873 in the column, in a filter and in a sort. 

1874 """ 

1875 relationships, column = _resolve_column(model, column_path, schema_cls, kind=kind) 

1876 source: type[DeclarativeBase] | AliasedClass[Any] = model 

1877 path: tuple[str, ...] = () 

1878 for relationship in relationships: 

1879 # The full path distinguishes home_city.country from work_city.country 

1880 # and successive hops through a self-referential relationship. 

1881 path += (relationship.key,) 

1882 target = aliases.get(path) 

1883 if target is None: 

1884 target = aliased(relationship.property.mapper) 

1885 stmt = stmt.join_from( 

1886 source, getattr(source, relationship.key).of_type(target), isouter=True 

1887 ) 

1888 aliases[path] = target 

1889 source = target 

1890 return stmt, getattr(source, column.key) 

1891 

1892 

1893def _resolve_column( 

1894 model: type[DeclarativeBase], 

1895 column_path: str, 

1896 schema_cls: _SchemaClass, 

1897 *, 

1898 kind: str = "filter", 

1899) -> tuple[list[InstrumentedAttribute[Any]], InstrumentedAttribute[Any]]: 

1900 """Resolve a (possibly dotted) public column path to its SQLAlchemy column, 

1901 plus the relationship attributes that need to be joined. 

1902 

1903 Strict: every path segment must resolve through the schema's public name 

1904 (alias when set, Python field name otherwise). Falling back to a raw 

1905 model attribute lookup would let URLs reach columns the schema didn't 

1906 expose — for example, a Python field name on an aliased schema field — 

1907 and silently bypass the public-name contract. 

1908 

1909 A sort key never goes through a to-many relationship: an item with 

1910 several tags has no single ``tags.name`` to sort on. 

1911 

1912 :raises BadQueryParam: ``Unknown <kind> key``, with ``kind`` such as 

1913 ``"filter"`` or ``"sort"``. 

1914 """ 

1915 unknown = BadQueryParam(f"Unknown {kind} key: {column_path!r}") 

1916 joins: list[InstrumentedAttribute[Any]] = [] 

1917 current_model = model 

1918 current_schema: _SchemaClass | None = schema_cls 

1919 name = column_path 

1920 while "." in name: 

1921 relation, _, name = name.partition(".") 

1922 if current_schema is None: 1922 ↛ 1923line 1922 didn't jump to line 1923 because the condition on line 1922 was never true

1923 raise unknown 

1924 field_name = _resolve_field_name(current_schema, relation) 

1925 if field_name is None: 

1926 raise unknown 

1927 rel = _class_attribute(current_model, field_name) 

1928 if not isinstance(rel, InstrumentedAttribute) or not hasattr( 

1929 rel.property, "mapper" 

1930 ): 

1931 raise unknown 

1932 if kind == "sort" and rel.property.uselist: 

1933 raise unknown 

1934 joins.append(rel) 

1935 current_model = rel.property.mapper.class_ 

1936 current_schema = _get_nested_schema(current_schema.model_fields[field_name]) 

1937 

1938 if current_schema is None: 1938 ↛ 1939line 1938 didn't jump to line 1939 because the condition on line 1938 was never true

1939 raise unknown 

1940 field_name = _resolve_field_name(current_schema, name) 

1941 if field_name is None: 

1942 raise unknown 

1943 column = _class_attribute(current_model, field_name) 

1944 if ( 

1945 column is None 

1946 or not isinstance(column, InstrumentedAttribute) 

1947 or not isinstance(column.property, ColumnProperty) 

1948 ): 

1949 raise unknown 

1950 return joins, cast(InstrumentedAttribute[Any], column) 

1951 

1952 

1953def _apply_filtering( 

1954 values: _abc.Mapping[str, Any], 

1955 stmt: Select[Any], 

1956 model: type[DeclarativeBase], 

1957 schema_cls: _SchemaClass, 

1958 *, 

1959 validated: bool = False, 

1960 aliases: _JoinAliases | None = None, 

1961 pagination: _AnyPagination = _DEFAULT_PAGINATION, 

1962 sort_query_param: str = _SORT_QUERY_PARAM, 

1963) -> Select[Any]: 

1964 """Apply ``key=value`` and ``key__op=value`` filters to ``stmt``. All 

1965 filters are combined with AND. 

1966 

1967 :param values: The values by key, as :func:`_list_params_values` gives them. 

1968 :param validated: The values come from generated list params, whose keys 

1969 validated them. So only the form of the column is left. Other values 

1970 still go through the validation of their field. 

1971 """ 

1972 if aliases is None: 

1973 aliases = {} 

1974 reserved = _reserved_names(pagination, sort_query_param) 

1975 filters: dict[InstrumentedAttribute[Any], list[ColumnElement[Any]]] = defaultdict( 

1976 list 

1977 ) 

1978 

1979 for key, value in values.items(): 

1980 if key in reserved: 

1981 continue 

1982 

1983 column_name, op = _split_key(key) 

1984 op = op or "eq" 

1985 

1986 stmt, column = _join_column(stmt, model, column_name, schema_cls, aliases) 

1987 parse = ( 

1988 _column_value_parser(column, key) 

1989 if validated 

1990 else _filter_value_parser(schema_cls, column_name, column) 

1991 ) 

1992 if op in {"in", "not_in"}: 

1993 # generated keys have split their values already 

1994 several = validated and isinstance(value, list) 

1995 terms = [value if several else _listed_values(value)] 

1996 else: 

1997 # a list field of your own, such as ``name__icontains: list[str]``, 

1998 # needs each of its values 

1999 terms = value if isinstance(value, list) else [value] 

2000 for term in terms: 

2001 clause = _filter_clause(column, op, term, parse, key) 

2002 if clause is not None: 

2003 filters[column].append(clause) 

2004 

2005 for column, clauses in filters.items(): 

2006 and_clause = clauses[0] if len(clauses) == 1 else sqlalchemy.and_(*clauses) 

2007 stmt = stmt.where(and_clause) 

2008 return stmt 

2009 

2010 

2011def _filter_clause( 

2012 column: InstrumentedAttribute[Any], 

2013 op: str, 

2014 value: Any, 

2015 parse: Callable[[Any], Any], 

2016 key: str, 

2017) -> ColumnElement[Any] | None: 

2018 """The condition of one filter key, or ``None`` when it asks for nothing, 

2019 as an empty text search does. 

2020 

2021 :raises BadQueryParam: the value fails, or the operator does not exist. 

2022 """ 

2023 if op == "isnull": 

2024 try: 

2025 is_null = _BOOL_ADAPTER.validate_python(value) 

2026 except pydantic.ValidationError as exc: 

2027 raise BadQueryParam( 

2028 f"Invalid filter value for {key!r}: {value!r}. Use true or false." 

2029 ) from exc 

2030 return column.is_(None) if is_null else column.isnot(None) 

2031 if op == "icontains": 

2032 # LIKE takes the text as it is, without the field's validation 

2033 try: 

2034 text = _search_value(value) 

2035 except ValueError as exc: 

2036 raise BadQueryParam( 

2037 f"Invalid filter value for {key!r}: {value!r}. " 

2038 f"{value_error_reason(exc)}" 

2039 ) from exc 

2040 if text is None: 

2041 return None 

2042 return column.ilike(f"%{_escape_like_value(text)}%", escape="\\") 

2043 if op in {"in", "not_in"}: 

2044 items = [parse(item) for item in value] 

2045 if any(item is None for item in items): 2045 ↛ 2047line 2045 didn't jump to line 2047 because the condition on line 2045 was never true

2046 # SQL compares no value with NULL: NOT IN ('a', NULL) is never true 

2047 raise BadQueryParam( 

2048 f"Invalid filter value for {key!r}: {value!r}. {_NULL_IN_LIST}" 

2049 ) 

2050 if op == "in": 

2051 return column.in_(items) 

2052 # NULL is none of these values, so the row stays; SQL leaves it out 

2053 return sqlalchemy.or_(column.is_(None), column.not_in(items)) 

2054 

2055 parsed = parse(value) 

2056 if op == "eq": 

2057 return column == parsed 

2058 if op == "ne": 

2059 # NULL is not this value, so the row stays; SQL leaves it out 

2060 return column.is_distinct_from(parsed) 

2061 if op == "gte": 

2062 return column >= parsed 

2063 if op == "lte": 

2064 return column <= parsed 

2065 if op == "gt": 

2066 return column > parsed 

2067 if op == "lt": 

2068 return column < parsed 

2069 raise BadQueryParam(f"Unsupported filter operator: {op!r}") 

2070 

2071 

2072_BOOL_ADAPTER = pydantic.TypeAdapter(bool) 

2073 

2074 

2075class _BadValue(Exception): 

2076 """A filter value that fails: the client's error. 

2077 

2078 A generated key reports it as a ``422``. :class:`FilterKey` reports it as a 

2079 ``400``, because such a key is inside the value of another key. 

2080 """ 

2081 

2082 def __init__(self, error_type: str, reason: str) -> None: 

2083 super().__init__(reason) 

2084 #: The type of the error, as in Pydantic. 

2085 self.error_type = error_type 

2086 #: Why the value fails, such as ``Input should be a valid integer``. 

2087 self.reason = reason 

2088 

2089 

2090def _enum_value(enum_type: sqlalchemy.Enum, value: Any) -> Any: 

2091 """``value`` as a column of ``enum_type`` takes it: one of its labels, or 

2092 a member of its enum class. 

2093 

2094 A value that equals a member, such as ``1`` for a member of an 

2095 ``IntEnum``, becomes that member: SQLAlchemy binds a plain number as a 

2096 number, and the column holds labels. SQLAlchemy passes any other string 

2097 on, and a native ENUM on PostgreSQL rejects it with an error, which would 

2098 be a 500 for the client. 

2099 

2100 :raises _BadValue: the value is no label of the column. 

2101 """ 

2102 if value in enum_type.enums: 

2103 return value 

2104 for member in enum_type.enum_class or (): 

2105 if value == member: 

2106 return member 

2107 raise _BadValue("enum", f"Use one of: {', '.join(enum_type.enums)}.") 

2108 

2109 

2110def _filter_value_parser( 

2111 schema_cls: _SchemaClass, column_name: str, column: Any 

2112) -> Callable[[Any], Any]: 

2113 """The parser of the values of a generated filter key, also a dotted one; 

2114 see :func:`_value_parser`. 

2115 

2116 :param column: The column, or ``None`` to leave each value as the field 

2117 gives it. 

2118 """ 

2119 field_schema, field_name = _field_of(schema_cls, column_name) 

2120 return _value_parser(field_schema, field_name, column, column_name) 

2121 

2122 

2123def _field_of(schema_cls: _SchemaClass, column_name: str) -> tuple[_SchemaClass, str]: 

2124 """The schema that holds the field of a filter key, also of a dotted 

2125 one, and the Python name of the field. 

2126 

2127 :raises BadQueryParam: ``Unknown filter key``. 

2128 """ 

2129 *relations, name = column_name.split(".") 

2130 for relation in relations: 

2131 field = schema_cls.model_fields.get( 

2132 _resolve_field_name(schema_cls, relation) or relation 

2133 ) 

2134 nested = _get_nested_schema(field) 

2135 if nested is None: 2135 ↛ 2136line 2135 didn't jump to line 2136 because the condition on line 2135 was never true

2136 raise BadQueryParam(f"Unknown filter key: {column_name!r}") 

2137 schema_cls = nested 

2138 

2139 field_name = _resolve_field_name(schema_cls, name) 

2140 if field_name is None: 

2141 raise BadQueryParam(f"Unknown filter key: {column_name!r}") 

2142 return schema_cls, field_name 

2143 

2144 

2145def _value_parser( 

2146 schema_cls: _SchemaClass, field_name: str, column: Any, key: str 

2147) -> Callable[[Any], Any]: 

2148 """The parser of the values of one filter key: each value as a value for 

2149 ``column``. See :func:`_value_reader` and :func:`_column_step`. 

2150 

2151 The generated filters and 

2152 :class:`~fastapi_restly.query.FilterKey` build one parser for each key, 

2153 so the work for the key is done once. 

2154 

2155 :param schema_cls: The schema that holds the field. 

2156 :param column: The column, or ``None`` to leave each value as the field 

2157 gives it. 

2158 :param key: The filter key that the client used, for the message. 

2159 """ 

2160 read = _value_reader(schema_cls, field_name, column) 

2161 to_column = _column_step(column) 

2162 

2163 def parse(value: Any) -> Any: 

2164 """``value`` as a value for the column. 

2165 

2166 :raises BadQueryParam: when the value fails one of the steps. The 

2167 message has the reason, such as Pydantic's 

2168 ``Input should be a valid integer``. 

2169 """ 

2170 try: 

2171 return to_column(read(value)) 

2172 except _BadValue as exc: 

2173 raise _invalid_filter_value(key, value, exc) from exc 

2174 

2175 return parse 

2176 

2177 

2178def _column_value_parser(column: Any, key: str) -> Callable[[Any], Any]: 

2179 """The parser of a value that its key has validated: only the form of the 

2180 column is left. See :func:`_column_step`.""" 

2181 to_column = _column_step(column) 

2182 

2183 def parse(value: Any) -> Any: 

2184 try: 

2185 return to_column(value) 

2186 except _BadValue as exc: 

2187 raise _invalid_filter_value(key, value, exc) from exc 

2188 

2189 return parse 

2190 

2191 

2192def _invalid_filter_value(key: str, value: Any, exc: _BadValue) -> BadQueryParam: 

2193 return BadQueryParam(f"Invalid filter value for {key!r}: {value!r}. {exc.reason}") 

2194 

2195 

2196def _checked_reader( 

2197 schema_cls: _SchemaClass, 

2198 field_name: str, 

2199 column: Any, 

2200 *, 

2201 isnull_key: str | None = None, 

2202) -> Callable[[Any], Any]: 

2203 """The value of a generated key: the value of its field, as code reads it 

2204 from the list params, such as a ``Decimal``. It also checks that the 

2205 column can take the value, so a bad value fails with the other values of 

2206 the request. 

2207 

2208 :param isnull_key: The ``__isnull`` key of the field, for the messages. 

2209 """ 

2210 read = _value_reader(schema_cls, field_name, column, isnull_key=isnull_key) 

2211 to_column = _column_step(column) 

2212 

2213 def read_and_check(value: Any) -> Any: 

2214 result = read(value) 

2215 to_column(result) 

2216 return result 

2217 

2218 return read_and_check 

2219 

2220 

2221def _value_reader( 

2222 schema_cls: _SchemaClass, 

2223 field_name: str, 

2224 column: Any, 

2225 *, 

2226 isnull_key: str | None = None, 

2227) -> Callable[[Any], Any]: 

2228 """A function that gives a value the type and the validators of its field. 

2229 

2230 A value goes through the validation of its field, without the bounds; see 

2231 :func:`_field_validator`: a text from a URL, or a value from JSON. ``None`` 

2232 stays ``None``, for ``IS NULL``. A value that a validator turns into 

2233 ``None``, such as an empty text, fails: a filter needs a value, and the 

2234 client did not ask for NULL. A number must be between ``-1e50`` and 

2235 ``1e50``, with at most 50 digits after the point; see 

2236 :func:`_check_number_size`. A ``Literal`` of numbers and an 

2237 enum whose values are numbers read the number from the text first; see 

2238 :func:`_has_number_labels`. An ``IDRef`` gives its id. A JSON column 

2239 takes only ``None``: it holds JSON text, so SQL cannot compare it with a 

2240 value. A value that becomes a list, a dict or a set, as a 

2241 ``pydantic.Json`` field can give, fails: a column holds one value. A field 

2242 of type ``Any``, such as the ``id`` of ``fr.IDSchema``, and the id of a 

2243 reference get the Python type of the column, such as a ``UUID`` from its 

2244 text. 

2245 

2246 The function raises :class:`_BadValue` for a value that fails. Only a 

2247 validation error is the client's fault. Another exception from a validator 

2248 is a bug, as it is for a request body. 

2249 

2250 :param isnull_key: The ``__isnull`` key of the field, for the messages. 

2251 """ 

2252 validator = _field_validator(schema_cls, field_name) 

2253 becomes_null = ( 

2254 "The value becomes null after validation, and a filter needs a value." 

2255 ) 

2256 if isnull_key is not None: 

2257 becomes_null += f" To find the rows where it is null, send {isnull_key}=true." 

2258 column_type = getattr(column, "type", None) 

2259 json_column = _has_json_type(column) 

2260 annotation = _unwrap_type(schema_cls.model_fields[field_name].annotation)[0] 

2261 # A field of type Any, such as the id of fr.IDSchema, gives the value as 

2262 # it came, and so does a reference for its id. 

2263 untyped = annotation is Any 

2264 number_labels = _has_number_labels(annotation) 

2265 # a column of SQLAlchemy's Enum type takes its labels; see _column_step 

2266 enum_type = _enum_type(column) 

2267 to_python_type = None if enum_type is not None else _python_type_parser(column_type) 

2268 # a field of type Any shows the value of a member; see _member_of_value 

2269 value_enum = enum_type.enum_class if untyped and enum_type is not None else None 

2270 

2271 def read(value: Any) -> Any: 

2272 if json_column and value is not None: 

2273 raise _BadValue( 

2274 "value_error", 

2275 "A filter on a JSON column can only check whether it is null.", 

2276 ) 

2277 if number_labels and isinstance(value, str): 

2278 value = _number_from_text(value) 

2279 try: 

2280 values, _, _ = validator.validate_python({field_name: value}) 

2281 result = values[field_name] 

2282 if result is None: 

2283 if value is not None: 

2284 raise _BadValue("value_error", becomes_null) 

2285 return None 

2286 # An IDRef[T] FK field validates to an IDRef object; the SQL bind 

2287 # value is its scalar id, not the reference wrapper (which cannot bind). 

2288 reference = isinstance(result, IDSchema) 

2289 if reference: 

2290 result = result.id 

2291 if isinstance(result, (list, tuple, set, frozenset, dict)): 

2292 # such as from a pydantic.Json field: a column holds one value 

2293 raise _BadValue( 

2294 "value_error", 

2295 "A filter value is one value, not a list or an object.", 

2296 ) 

2297 if (untyped or reference) and to_python_type is not None: 

2298 result = to_python_type(result) 

2299 if value_enum is not None: 

2300 result = _member_of_value(value_enum, result) 

2301 _check_number_size(result) 

2302 return result 

2303 except pydantic.ValidationError as exc: 

2304 error = exc.errors()[0] 

2305 raise _BadValue(error["type"], error["msg"]) from exc 

2306 

2307 return read 

2308 

2309 

2310def _member_of_value(enum_class: type[enum.Enum], value: Any) -> Any: 

2311 """The member of ``enum_class`` whose value is ``value``, or ``value`` 

2312 when no member has it. A text from a URL matches a number value too. 

2313 

2314 A field of type ``Any`` shows the value of a member in a response and in 

2315 OpenAPI, such as ``"R"`` for ``red = "R"``, so a client sends that. The 

2316 value comes before the label: for ``red = "blue"``, ``blue`` is the row 

2317 that shows ``blue``. 

2318 """ 

2319 number = _number_from_text(value) if isinstance(value, str) else value 

2320 for member in enum_class: 2320 ↛ 2328line 2320 didn't jump to line 2328 because the loop on line 2320 didn't complete

2321 member_value = member.value 

2322 if value == member_value or ( 2322 ↛ 2320line 2322 didn't jump to line 2320 because the condition on line 2322 was always true

2323 isinstance(member_value, (int, float)) 

2324 and not isinstance(member_value, bool) 

2325 and number == member_value 

2326 ): 

2327 return member 

2328 return value 

2329 

2330 

2331def _has_number_labels(annotation: Any) -> bool: 

2332 """Whether a field takes labels that are all numbers: a ``Literal`` such 

2333 as ``Literal[1, 2]``, or an enum whose values are all numbers. 

2334 

2335 A value from a URL is text, and Pydantic does not read ``"1"`` as ``1`` 

2336 for such a field, as it does for an ``IntEnum``. Without help, the 

2337 filter key of such a field would refuse each value. A ``bool`` is no 

2338 number here, and ``Literal[1, "1"]`` stays as it is. 

2339 """ 

2340 if get_origin(annotation) is Literal: 

2341 values: _abc.Sequence[Any] = get_args(annotation) 

2342 elif isinstance(annotation, type) and issubclass(annotation, enum.Enum): 

2343 values = [member.value for member in annotation] 

2344 else: 

2345 return False 

2346 return bool(values) and all( 

2347 isinstance(value, (int, float)) and not isinstance(value, bool) 

2348 for value in values 

2349 ) 

2350 

2351 

2352def _number_from_text(text: str) -> Any: 

2353 """The number in ``text``: an ``int``, else a ``float``. Text that holds no 

2354 number stays as it is, and the validation of the field refuses it.""" 

2355 for parse in (int, float): 

2356 try: 

2357 return parse(text) 

2358 except ValueError: 

2359 pass 

2360 return text 

2361 

2362 

2363#: The biggest number that a filter takes, as in django-filter. A filter 

2364#: leaves out the bounds of its field, and without a limit a huge number 

2365#: reaches the database: PostgreSQL then fails on ``1e400`` for a ``Float`` 

2366#: column, or on a ``Decimal`` with many digits, which is a 500. 

2367_NUMBER_LIMIT = 1e50 

2368#: The most digits after the point of a ``Decimal`` in a filter. PostgreSQL 

2369#: fails with an error, a 500, for a value such as ``1e-100000``. 

2370_FRACTION_DIGITS_LIMIT = 50 

2371 

2372 

2373def _check_number_size(value: Any) -> None: 

2374 """Refuse a number above ``1e50`` or below ``-1e50``, and a ``Decimal`` 

2375 with more than 50 digits after the point. NaN stays: a field that allows 

2376 it has a reason. 

2377 

2378 :raises _BadValue: the number is too big, an infinity, or too long. 

2379 """ 

2380 if isinstance(value, bool) or not isinstance(value, (int, float, _decimal.Decimal)): 

2381 return 

2382 if isinstance(value, _decimal.Decimal) and value.is_nan(): 

2383 return 

2384 if abs(value) > _NUMBER_LIMIT: 

2385 raise _BadValue( 

2386 "value_error", "A number in a filter must be between -1e50 and 1e50." 

2387 ) 

2388 if isinstance(value, _decimal.Decimal) and value.is_finite(): 

2389 exponent = value.as_tuple().exponent 

2390 if isinstance(exponent, int) and exponent < -_FRACTION_DIGITS_LIMIT: 

2391 raise _BadValue( 

2392 "value_error", 

2393 "A number in a filter has at most 50 digits after the point.", 

2394 ) 

2395 

2396 

2397def _column_step(column: Any) -> Callable[[Any], Any]: 

2398 """A function that gives a value the form of its column. 

2399 

2400 A column of SQLAlchemy's ``Enum`` type takes only its labels. Any other 

2401 value goes through ``column_value``: a text column takes text, a time gets 

2402 the form of its column, a number must fit an integer column, and text must 

2403 hold no NUL character. Its length is not checked: the filter compares the 

2404 text, and PostgreSQL compares text of any length. 

2405 

2406 The function raises :class:`_BadValue` for a value that does not fit. 

2407 """ 

2408 column_type = getattr(column, "type", None) 

2409 enum_type = _enum_type(column) 

2410 

2411 def to_column(value: Any) -> Any: 

2412 if value is None: 

2413 return None 

2414 if enum_type is not None: 

2415 return _enum_value(enum_type, value) 

2416 try: 

2417 return column_value(column_type, value) 

2418 except ValueError as exc: 

2419 raise _BadValue("value_error", value_error_reason(exc)) from exc 

2420 

2421 return to_column 

2422 

2423 

2424def _value_json_schema( 

2425 schema_cls: _SchemaClass, field_name: str, column: Any 

2426) -> dict[str, Any]: 

2427 """The JSON schema of one value of a filter key: the type of the field, 

2428 without its bounds, as :func:`_field_validator` validates it. A field of 

2429 type ``Any`` and a reference have the type of the column.""" 

2430 field = schema_cls.model_fields[field_name] 

2431 if _unwrap_type(field.annotation)[0] is Any or _is_idref_field(field): 

2432 return _column_json_schema(column) 

2433 field_schema, definitions, _ = _field_core_schema(schema_cls, field_name) 

2434 while field_schema.get("type") in {"default", "nullable"}: 

2435 field_schema = field_schema["schema"] 

2436 if definitions: 

2437 field_schema = { 

2438 "type": "definitions", 

2439 "schema": field_schema, 

2440 "definitions": definitions, 

2441 } 

2442 try: 

2443 generated = GenerateJsonSchema().generate(field_schema) 

2444 except (PydanticInvalidForJsonSchema, PydanticOmit): 

2445 # PydanticOmit: SkipJsonSchema on the field, which OpenAPI leaves out 

2446 return {} 

2447 schema = _inline_definitions(generated, generated.get("$defs", {})) 

2448 schema.pop("$defs", None) 

2449 return _value_schema_only(schema) 

2450 

2451 

2452def _column_json_schema(column: Any) -> dict[str, Any]: 

2453 """The JSON schema of the Python type of ``column``, or ``{}`` when the 

2454 column names none or Pydantic does not know the type.""" 

2455 try: 

2456 python_type = getattr(column, "type", None).python_type # type: ignore[union-attr] 

2457 schema = pydantic.TypeAdapter(python_type).json_schema() 

2458 except ( 

2459 AttributeError, 

2460 NotImplementedError, 

2461 pydantic.PydanticSchemaGenerationError, 

2462 PydanticInvalidForJsonSchema, 

2463 ): 

2464 return {} 

2465 schema = _inline_definitions(schema, schema.get("$defs", {})) 

2466 schema.pop("$defs", None) 

2467 return _value_schema_only(schema) 

2468 

2469 

2470def _value_schema_only(schema: dict[str, Any]) -> dict[str, Any]: 

2471 """``schema`` without the names of its class and without ``null``. The key 

2472 has its own title and description, and can always be left out.""" 

2473 schema = {k: v for k, v in schema.items() if k not in {"title", "description"}} 

2474 options = schema.get("anyOf") 

2475 if options is not None and set(schema) == {"anyOf"}: 

2476 options = [option for option in options if option != {"type": "null"}] 

2477 return options[0] if len(options) == 1 else {"anyOf": options} 

2478 return schema 

2479 

2480 

2481def _inline_definitions( 

2482 schema: Any, definitions: dict[str, Any], _inside: frozenset[str] = frozenset() 

2483) -> Any: 

2484 """``schema`` with each ``#/$defs/...`` reference replaced by its target. 

2485 

2486 A type that holds itself, such as a tree, would never end. Its reference 

2487 inside itself becomes a schema without a type. 

2488 

2489 :param _inside: The definitions that the walk is inside. 

2490 """ 

2491 if isinstance(schema, list): 

2492 return [_inline_definitions(item, definitions, _inside) for item in schema] 

2493 if not isinstance(schema, dict): 

2494 return schema 

2495 inlined = { 

2496 key: _inline_definitions(value, definitions, _inside) 

2497 for key, value in schema.items() 

2498 if key != "$ref" 

2499 } 

2500 reference = schema.get("$ref") 

2501 if isinstance(reference, str) and reference.startswith("#/$defs/"): 

2502 name = reference.removeprefix("#/$defs/") 

2503 if name in _inside: 

2504 return inlined 

2505 target = _inline_definitions(definitions[name], definitions, _inside | {name}) 

2506 return {**target, **inlined} 

2507 return inlined 

2508 

2509 

2510def _python_type_parser(column_type: Any) -> Callable[[Any], Any] | None: 

2511 """A function that gives a value the Python type of ``column_type``, such 

2512 as a ``UUID`` from its text, or ``None`` when the type names none. 

2513 

2514 The function raises ``pydantic.ValidationError`` for a value that is not 

2515 valid for the type. 

2516 """ 

2517 try: 

2518 python_type = column_type.python_type 

2519 except (AttributeError, NotImplementedError): 

2520 return None 

2521 adapter = _python_type_adapter(python_type) 

2522 

2523 def to_python_type(value: Any) -> Any: 

2524 if isinstance(value, python_type): 

2525 return value 

2526 return adapter.validate_python(value) 

2527 

2528 return to_python_type 

2529 

2530 

2531@functools.cache 

2532def _python_type_adapter(python_type: type) -> pydantic.TypeAdapter[Any]: 

2533 """The adapter that validates a value as ``python_type``.""" 

2534 if python_type is str: 

2535 # A number filters a text column: JSON has 5 for the text "5". 

2536 config = pydantic.ConfigDict(coerce_numbers_to_str=True) 

2537 return pydantic.TypeAdapter(str, config=config) 

2538 try: 

2539 return pydantic.TypeAdapter(python_type) 

2540 except pydantic.PydanticSchemaGenerationError: 

2541 # A type that Pydantic does not know: call it with the value. 

2542 def construct(value: Any) -> Any: 

2543 try: 

2544 return python_type(value) 

2545 except (TypeError, ArithmeticError) as exc: 

2546 raise ValueError(str(exc)) from exc 

2547 

2548 return pydantic.TypeAdapter(Annotated[Any, pydantic.AfterValidator(construct)]) 

2549 

2550 

2551#: The settings of a type in Pydantic's core schema that only refuse a value. 

2552_REFUSING_SETTINGS = frozenset( 

2553 { 

2554 "gt", 

2555 "ge", 

2556 "lt", 

2557 "le", 

2558 "multiple_of", 

2559 "max_digits", 

2560 "decimal_places", 

2561 "min_length", 

2562 "max_length", 

2563 "pattern", 

2564 "now_op", 

2565 "now_utc_offset", 

2566 "tz_constraint", 

2567 "allowed_schemes", 

2568 "host_required", 

2569 "version", 

2570 "strict", 

2571 } 

2572) 

2573 

2574#: The types of Pydantic's core schema that hold one value. 

2575_SINGLE_VALUE_TYPES = frozenset( 

2576 { 

2577 "bool", 

2578 "int", 

2579 "float", 

2580 "decimal", 

2581 "str", 

2582 "bytes", 

2583 "date", 

2584 "time", 

2585 "datetime", 

2586 "timedelta", 

2587 "uuid", 

2588 "url", 

2589 "multi-host-url", 

2590 "enum", 

2591 } 

2592) 

2593 

2594#: Where a part of Pydantic's core schema holds other parts. 

2595_INNER_SCHEMA_KEYS = ( 

2596 "schema", 

2597 "lax_schema", 

2598 "strict_schema", 

2599 "json_schema", 

2600 "python_schema", 

2601) 

2602 

2603 

2604def _without_refusals(schema: Any) -> Any: 

2605 """``schema``, a part of Pydantic's core schema, without the settings that 

2606 only refuse a value. What changes a value stays, such as a validator or 

2607 ``strip_whitespace``. 

2608 

2609 A bound that Pydantic cannot put on the type itself stays, because it is a 

2610 function in the schema: on a union such as ``Decimal | int``, after a 

2611 validator of your own, or on a type such as ``HttpUrl``. 

2612 """ 

2613 if not isinstance(schema, dict): 2613 ↛ 2614line 2613 didn't jump to line 2614 because the condition on line 2613 was never true

2614 return schema 

2615 copied = dict(schema) 

2616 kind = copied.get("type") 

2617 if kind in _SINGLE_VALUE_TYPES: 

2618 for setting in _REFUSING_SETTINGS: 

2619 copied.pop(setting, None) 

2620 # False refuses infinity and NaN, and True allows them on a Decimal 

2621 if copied.get("allow_inf_nan") is False: 2621 ↛ 2622line 2621 didn't jump to line 2622 because the condition on line 2621 was never true

2622 del copied["allow_inf_nan"] 

2623 for key in _INNER_SCHEMA_KEYS: 

2624 if key in copied and kind != "model": 

2625 copied[key] = _without_refusals(copied[key]) 

2626 if isinstance(copied.get("steps"), list): 2626 ↛ 2627line 2626 didn't jump to line 2627 because the condition on line 2626 was never true

2627 copied["steps"] = [_without_refusals(step) for step in copied["steps"]] 

2628 if isinstance(copied.get("choices"), list): 

2629 copied["choices"] = [ 

2630 (_without_refusals(choice[0]), choice[1]) 

2631 if isinstance(choice, tuple) 

2632 else _without_refusals(choice) 

2633 for choice in copied["choices"] 

2634 ] 

2635 return copied 

2636 

2637 

2638def _field_core_schema( 

2639 schema_cls: _SchemaClass, field_name: str 

2640) -> tuple[Any, Any, Any]: 

2641 """The core schema of one field, without the settings that only refuse a 

2642 value; see :func:`_without_refusals`. Also the definitions, without them 

2643 too, and the config of the model. 

2644 """ 

2645 core: Any = schema_cls.__pydantic_core_schema__ 

2646 definitions = core.get("definitions") if core.get("type") == "definitions" else None 

2647 definitions_by_ref = { 

2648 definition["ref"]: definition for definition in definitions or () 

2649 } 

2650 config = None 

2651 node: Any = core 

2652 while node is not None and node.get("type") != "model-fields": 

2653 # Recursive models keep their model schema in the definitions. 

2654 if node.get("type") == "definition-ref": 

2655 node = definitions_by_ref[node["schema_ref"]] 

2656 continue 

2657 if node.get("type") == "model" and config is None: 

2658 config = node.get("config") 

2659 node = node.get("schema") 

2660 if node is None: 2660 ↛ 2661line 2660 didn't jump to line 2661 because the condition on line 2660 was never true

2661 raise LookupError(f"{schema_cls.__name__} has no model-fields core schema") 

2662 if definitions: 

2663 # a type alias that two fields use, such as a bounded number, is a 

2664 # definition 

2665 definitions = [_without_refusals(definition) for definition in definitions] 

2666 return _without_refusals(node["fields"][field_name]["schema"]), definitions, config 

2667 

2668 

2669@functools.cache 

2670def _field_validator(schema_cls: _SchemaClass, field_name: str) -> SchemaValidator: 

2671 """A validator for a one-field mapping, cut from the model's core schema. 

2672 

2673 The named field supplies ``ValidationInfo.field_name``. No other fields 

2674 are validated, so ``ValidationInfo.data`` is empty. 

2675 

2676 The type, the field validators and the model config apply. Bounds do not, 

2677 such as ``gt`` or ``min_length``: a filter compares a value, and does not 

2678 store it, so ``?price__gte=0`` is fine on a field with ``gt=0``. What 

2679 changes a value stays. Model validators do not apply either. A filter value 

2680 is one column, so a cross-field rule has nothing to compare against and 

2681 would only reject legal filters (as validating through 

2682 ``validate_assignment`` on a ``model_construct()`` skeleton did). 

2683 

2684 A number becomes text for a text field. A value from a URL is text 

2685 already, and JSON, such as react-admin's ``filter``, has ``5`` for the 

2686 text ``"5"``. For the same reason a value is never strict. 

2687 """ 

2688 field_core, definitions, config = _field_core_schema(schema_cls, field_name) 

2689 field_schema: Any = core_schema.model_fields_schema( 

2690 {field_name: core_schema.model_field(field_core)} 

2691 ) 

2692 if definitions: 

2693 # A field typed with a class the schema uses more than once is a 

2694 # definition-ref; it validates only next to the definitions. 

2695 field_schema = { 

2696 "type": "definitions", 

2697 "schema": field_schema, 

2698 "definitions": definitions, 

2699 } 

2700 # the bounds of the model config go too 

2701 kept = { 

2702 name: value 

2703 for name, value in (config or {}).items() 

2704 if name not in {"str_max_length", "str_min_length"} 

2705 } 

2706 filter_config = cast( 

2707 core_schema.CoreConfig, {**kept, "coerce_numbers_to_str": True, "strict": False} 

2708 ) 

2709 return SchemaValidator(field_schema, filter_config) 

2710 

2711 

2712def _get_nested_schema(field: FieldInfo | None) -> _SchemaClass | None: 

2713 if field is None: 2713 ↛ 2714line 2713 didn't jump to line 2714 because the condition on line 2713 was never true

2714 return None 

2715 annotation, _ = _unwrap_type(field.annotation) 

2716 if isinstance(annotation, type) and issubclass(annotation, pydantic.BaseModel): 

2717 return annotation 

2718 return None