sqlalchemy-filtering 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {sqlalchemy-filtering-0.1.2/sqlalchemy_filtering.egg-info → sqlalchemy_filtering-0.2.0}/PKG-INFO +43 -10
  2. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/README.md +16 -3
  3. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/pyproject.toml +2 -3
  4. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/setup.py +14 -8
  5. sqlalchemy_filtering-0.2.0/sqlalchemy_filtering/fields.py +22 -0
  6. sqlalchemy_filtering-0.2.0/sqlalchemy_filtering/filter_util.py +183 -0
  7. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering/operators.py +3 -2
  8. sqlalchemy_filtering-0.2.0/sqlalchemy_filtering/sort_util.py +66 -0
  9. sqlalchemy_filtering-0.2.0/sqlalchemy_filtering/validators.py +140 -0
  10. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0/sqlalchemy_filtering.egg-info}/PKG-INFO +43 -10
  11. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering.egg-info/SOURCES.txt +4 -1
  12. sqlalchemy_filtering-0.2.0/sqlalchemy_filtering.egg-info/requires.txt +10 -0
  13. sqlalchemy_filtering-0.2.0/tests/test_filter.py +231 -0
  14. sqlalchemy_filtering-0.2.0/tests/test_sort.py +82 -0
  15. sqlalchemy-filtering-0.1.2/sqlalchemy_filtering/filter_util.py +0 -155
  16. sqlalchemy-filtering-0.1.2/sqlalchemy_filtering/sort_util.py +0 -70
  17. sqlalchemy-filtering-0.1.2/sqlalchemy_filtering/validators.py +0 -136
  18. sqlalchemy-filtering-0.1.2/sqlalchemy_filtering.egg-info/requires.txt +0 -6
  19. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/LICENSE +0 -0
  20. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/MANIFEST.in +0 -0
  21. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/setup.cfg +0 -0
  22. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering/__init__.py +0 -0
  23. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering/exceptions.py +0 -0
  24. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering.egg-info/dependency_links.txt +0 -0
  25. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering.egg-info/top_level.txt +0 -0
  26. {sqlalchemy-filtering-0.1.2 → sqlalchemy_filtering-0.2.0}/sqlalchemy_filtering.egg-info/zip-safe +0 -0
@@ -1,24 +1,45 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: sqlalchemy-filtering
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: SQLAlchemy query filtering and sorting wrapper in JSON format.
5
5
  Home-page: https://github.com/cnatsis/sqlalchemy-filtering
6
6
  Author: Christos Natsis
7
7
  Author-email: christos_na@hotmail.com
8
8
  License: Apache License, Version 2.0
9
9
  Project-URL: Issues Tracker, https://github.com/cnatsis/sqlalchemy-filtering/issues
10
- Platform: UNKNOWN
11
10
  Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.6
13
- Classifier: Programming Language :: Python :: 3.8
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
14
17
  Classifier: License :: OSI Approved :: Apache Software License
15
18
  Classifier: Operating System :: OS Independent
16
19
  Classifier: Topic :: Database
17
- Requires-Python: >=3.6
20
+ Requires-Python: >=3.10
18
21
  Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: sqlalchemy>=1.4
19
24
  Provides-Extra: postgresql
25
+ Requires-Dist: psycopg2>=2.9.13; extra == "postgresql"
20
26
  Provides-Extra: mysql
21
- License-File: LICENSE
27
+ Requires-Dist: mysqlclient>=2.3.2; extra == "mysql"
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest>=9.2.0; extra == "test"
30
+ Dynamic: author
31
+ Dynamic: author-email
32
+ Dynamic: classifier
33
+ Dynamic: description
34
+ Dynamic: description-content-type
35
+ Dynamic: home-page
36
+ Dynamic: license
37
+ Dynamic: license-file
38
+ Dynamic: project-url
39
+ Dynamic: provides-extra
40
+ Dynamic: requires-dist
41
+ Dynamic: requires-python
42
+ Dynamic: summary
22
43
 
23
44
  # SQLAlchemy filtering & sorting utility
24
45
 
@@ -34,6 +55,7 @@ License-File: LICENSE
34
55
  - [Comparison operators](#comparison-operators)
35
56
  - [PostgreSQL specific JSON operators](#postgresql-specific-json-operators)
36
57
  - [Versions tested](#versions-tested)
58
+ - [Install](#install)
37
59
 
38
60
  ## Purpose
39
61
 
@@ -170,14 +192,17 @@ obj = {
170
192
 
171
193
  ```python
172
194
  from sqlalchemy_filtering.filter_util import filter_apply
173
- from sqlalchemy_filtering.operators import SQLDialect
174
195
  from sqlalchemy_filtering.validators import FilterRequest
175
196
 
176
197
  from tests import models
177
198
 
178
- query = filter_apply(query=query, entity=models.UserInfo, obj=FilterRequest(obj), dialect=SQLDialect.POSTGRESQL)
199
+ query = filter_apply(query=query, entity=models.UserInfo, obj=FilterRequest(obj))
179
200
  ```
180
201
 
202
+ Values inside JSON columns are cast to match the filter value's type (text, number or boolean) using SQLAlchemy's
203
+ portable JSON casts, so the same request works on PostgreSQL, MySQL and SQLite. The former `dialect` argument is
204
+ deprecated and ignored.
205
+
181
206
  #### Filtering operators
182
207
 
183
208
  Filtering operators AND (`and_`), OR (`or_`) and NOT (`not_`) are supported and can be used all together.
@@ -278,6 +303,8 @@ The list of the available comparison operators can be found below:
278
303
 
279
304
  #### PostgreSQL specific JSON operators
280
305
 
306
+ These operators are only valid on PostgreSQL; other databases reject them.
307
+
281
308
  - `@>`
282
309
  - `<@`
283
310
  - `@?`
@@ -290,5 +317,11 @@ The list of the available comparison operators can be found below:
290
317
  | PostgreSQL | 9.2, 12.7 |
291
318
  | MySQL | 8.0.20, 8.0.27 |
292
319
  | SQLite | 3.37 |
293
- | SQLAlchemy | >= 1.4.0 |
320
+ | SQLAlchemy | 1.4, 2.0, 2.1 |
321
+ | Python | 3.10 – 3.15 |
322
+
323
+ ## Install
324
+
325
+ This Python project is available in the PyPi package index and can be installed using `pip`.
294
326
 
327
+ `pip install sqlalchemy-filtering==0.1.2`
@@ -12,6 +12,7 @@
12
12
  - [Comparison operators](#comparison-operators)
13
13
  - [PostgreSQL specific JSON operators](#postgresql-specific-json-operators)
14
14
  - [Versions tested](#versions-tested)
15
+ - [Install](#install)
15
16
 
16
17
  ## Purpose
17
18
 
@@ -148,14 +149,17 @@ obj = {
148
149
 
149
150
  ```python
150
151
  from sqlalchemy_filtering.filter_util import filter_apply
151
- from sqlalchemy_filtering.operators import SQLDialect
152
152
  from sqlalchemy_filtering.validators import FilterRequest
153
153
 
154
154
  from tests import models
155
155
 
156
- query = filter_apply(query=query, entity=models.UserInfo, obj=FilterRequest(obj), dialect=SQLDialect.POSTGRESQL)
156
+ query = filter_apply(query=query, entity=models.UserInfo, obj=FilterRequest(obj))
157
157
  ```
158
158
 
159
+ Values inside JSON columns are cast to match the filter value's type (text, number or boolean) using SQLAlchemy's
160
+ portable JSON casts, so the same request works on PostgreSQL, MySQL and SQLite. The former `dialect` argument is
161
+ deprecated and ignored.
162
+
159
163
  #### Filtering operators
160
164
 
161
165
  Filtering operators AND (`and_`), OR (`or_`) and NOT (`not_`) are supported and can be used all together.
@@ -256,6 +260,8 @@ The list of the available comparison operators can be found below:
256
260
 
257
261
  #### PostgreSQL specific JSON operators
258
262
 
263
+ These operators are only valid on PostgreSQL; other databases reject them.
264
+
259
265
  - `@>`
260
266
  - `<@`
261
267
  - `@?`
@@ -268,4 +274,11 @@ The list of the available comparison operators can be found below:
268
274
  | PostgreSQL | 9.2, 12.7 |
269
275
  | MySQL | 8.0.20, 8.0.27 |
270
276
  | SQLite | 3.37 |
271
- | SQLAlchemy | >= 1.4.0 |
277
+ | SQLAlchemy | 1.4, 2.0, 2.1 |
278
+ | Python | 3.10 – 3.15 |
279
+
280
+ ## Install
281
+
282
+ This Python project is available in the PyPi package index and can be installed using `pip`.
283
+
284
+ `pip install sqlalchemy-filtering==0.1.2`
@@ -1,7 +1,6 @@
1
1
  [build-system]
2
2
  requires = [
3
- "setuptools>=57.0.0",
4
- "sqlalchemy>=1.4.0",
5
- "wheel"
3
+ "setuptools>=84.2.1",
4
+ "wheel>=0.48.0"
6
5
  ]
7
6
  build-backend = "setuptools.build_meta"
@@ -5,7 +5,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
5
5
 
6
6
  setuptools.setup(
7
7
  name="sqlalchemy-filtering",
8
- version="0.1.2",
8
+ version="0.2.0",
9
9
  author="Christos Natsis",
10
10
  author_email="christos_na@hotmail.com",
11
11
  description="SQLAlchemy query filtering and sorting wrapper in JSON format.",
@@ -15,22 +15,28 @@ setuptools.setup(
15
15
  project_urls={
16
16
  "Issues Tracker": "https://github.com/cnatsis/sqlalchemy-filtering/issues",
17
17
  },
18
+ install_requires=[
19
+ 'sqlalchemy>=1.4',
20
+ ],
18
21
  extras_require={
19
- 'postgresql': ['psycopg2==2.8.4'],
20
- 'mysql': ['mysqlclient==2.1.0'],
22
+ 'postgresql': ['psycopg2>=2.9.13'],
23
+ 'mysql': ['mysqlclient>=2.3.2'],
24
+ 'test': ['pytest>=9.2.0'],
21
25
  },
22
26
  zip_safe=True,
23
27
  classifiers=[
24
28
  "Programming Language :: Python :: 3",
25
- "Programming Language :: Python :: 3.6",
26
- "Programming Language :: Python :: 3.8",
29
+ "Programming Language :: Python :: 3.10",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ "Programming Language :: Python :: 3.13",
33
+ "Programming Language :: Python :: 3.14",
34
+ "Programming Language :: Python :: 3.15",
27
35
  "License :: OSI Approved :: Apache Software License",
28
36
  "Operating System :: OS Independent",
29
37
  "Topic :: Database",
30
38
  ],
31
- # package_dir={"": "sqlalchemy_filtering"},
32
- # packages=setuptools.find_packages(where="sqlalchemy_filtering"),
33
39
  packages=["sqlalchemy_filtering"],
34
- python_requires=">=3.6",
40
+ python_requires=">=3.10",
35
41
  license='Apache License, Version 2.0',
36
42
  )
@@ -0,0 +1,22 @@
1
+ from sqlalchemy import inspect
2
+
3
+ from sqlalchemy_filtering.exceptions import FieldNotFoundException
4
+
5
+
6
+ def resolve_field(entity, field, node=None):
7
+ """
8
+ Resolve a Field of an Entity, optionally narrowed by a Node, into a SQLAlchemy column expression.
9
+
10
+ :param entity: SQLAlchemy model class.
11
+ :param field: Name of a column on ``entity``.
12
+ :param node: Optional dot-separated path of keys into a JSON column, e.g. ``"nested.field1"``.
13
+ :raises FieldNotFoundException: if ``field`` is not a column of ``entity``.
14
+ :returns: The column attribute, or a JSON index expression when ``node`` is given.
15
+ """
16
+ if field not in inspect(entity).columns.keys():
17
+ raise FieldNotFoundException('Field `{}` not found in model `{}`.'.format(field, entity))
18
+
19
+ expression = getattr(entity, field)
20
+ for key in node.split('.') if node else ():
21
+ expression = expression[key]
22
+ return expression
@@ -0,0 +1,183 @@
1
+ import json
2
+ import warnings
3
+
4
+ from sqlalchemy import and_
5
+ from sqlalchemy.sql.elements import BinaryExpression
6
+
7
+ from sqlalchemy_filtering.operators import SQLDialect
8
+ from sqlalchemy_filtering.fields import resolve_field
9
+ from sqlalchemy_filtering.validators import FilterRequest, Filter, Group, _get_numeric_types
10
+
11
+
12
+ def filter_apply(query, entity, obj=None, dialect: SQLDialect = None):
13
+ """
14
+ Construct filters on SQLAlchemy query
15
+
16
+ :param query: Query object of type :class:`sqlalchemy.orm.Query`.
17
+ :param entity: SQLAlchemy model class.
18
+ :param obj: :class:`FilterRequest` object or the raw request dict.
19
+ :param dialect: Deprecated and ignored; JSON values are cast portably for every database.
20
+
21
+ Example object
22
+
23
+ -- Simple request
24
+ obj = {
25
+ "filter": [
26
+ {
27
+ "field": "demographics",
28
+ "node": "age",
29
+ "operator": ">=",
30
+ "value": 20
31
+ },
32
+ {
33
+ "field": "demographics",
34
+ "node": "first_name",
35
+ "operator": "like",
36
+ "value": "%Test%"
37
+ }
38
+ ],
39
+ "sort": [...]
40
+ }
41
+
42
+ --- Simple request with operators
43
+ obj = {
44
+ "filter": [
45
+ "and": [
46
+ {
47
+ "field": "demographics",
48
+ "node": "age",
49
+ "operator": ">=",
50
+ "value": 20
51
+ },
52
+ {
53
+ "field": "demographics",
54
+ "node": "first_name",
55
+ "operator": "like",
56
+ "value": "%Test%"
57
+ }
58
+ ]
59
+ ],
60
+ "sort": [...]
61
+ }
62
+
63
+ -- JSON request
64
+ obj =
65
+ "filter": [
66
+ {
67
+ "field": "details",
68
+ "node": "user_details",
69
+ "operator": "@>",
70
+ "valueType": "jsonb",
71
+ "value": "[{\"skill\":\"Fighting\",\"rating\":10}]"
72
+ }
73
+ ],
74
+ "sort": [...]
75
+ }
76
+
77
+ :returns: Query object of type :class:`sqlalchemy.orm.Query` with applied filters.
78
+ """
79
+ if dialect is not None:
80
+ _warn_dialect_deprecated()
81
+ clause = build_filter(entity, obj)
82
+ return query if clause is None else query.filter(clause)
83
+
84
+
85
+ def build_filter(entity, request=None, dialect: SQLDialect = None):
86
+ """
87
+ Compile a filter request into a single SQLAlchemy clause.
88
+
89
+ Top-level groups are combined with AND. Groups (``{"and" | "or" | "not": [...]}``) may be nested at any depth.
90
+ A Filter whose ``value`` is another Filter extends the JSON path:
91
+ ``{"field": "details", "node": "a", "value": {"field": "b", "operator": "==", "value": 1}}``
92
+ compares ``details -> a -> b`` with ``1``.
93
+
94
+ :param entity: SQLAlchemy model class.
95
+ :param request: :class:`FilterRequest` object or the raw request dict (it is not modified).
96
+ :param dialect: Deprecated and ignored; JSON values are cast portably for every database.
97
+ :returns: A SQLAlchemy clause, or ``None`` when the request contains no filters.
98
+ """
99
+ if dialect is not None:
100
+ _warn_dialect_deprecated()
101
+ if not isinstance(request, FilterRequest):
102
+ request = FilterRequest(request)
103
+ if not request.filter:
104
+ return None
105
+
106
+ clauses = [_compile_group(entity, Group(key, children)) for key, children in request.filter.items()]
107
+ return clauses[0] if len(clauses) == 1 else and_(*clauses)
108
+
109
+
110
+ def _warn_dialect_deprecated():
111
+ warnings.warn(
112
+ "The `dialect` argument is deprecated and ignored: JSON values are now cast portably for every database.",
113
+ DeprecationWarning,
114
+ stacklevel=3,
115
+ )
116
+
117
+
118
+ def _compile_node(entity, node):
119
+ if isinstance(node, Group):
120
+ return _compile_group(entity, node)
121
+ return _compile_filter(entity, node)
122
+
123
+
124
+ def _compile_group(entity, group: Group):
125
+ return group.operator.execute(*[_compile_node(entity, child) for child in group.children])
126
+
127
+
128
+ def _compile_filter(entity, f: Filter):
129
+ nodes = [f.node]
130
+ leaf = f
131
+ # A Nested Filter (a Filter used as a value) extends the Node of its parent.
132
+ while isinstance(leaf.value, Filter):
133
+ leaf = leaf.value
134
+ nodes += [leaf.field, leaf.node]
135
+
136
+ statement = resolve_field(entity, f.field, '.'.join(n for n in nodes if n))
137
+ statement = _cast_json_value(statement, leaf.value)
138
+ return leaf.operator.execute(left=statement, right=leaf.value)
139
+
140
+
141
+ # Exact comparison for JSON numbers; values are rounded at 10 decimal places.
142
+ _NUMERIC_PRECISION, _NUMERIC_SCALE = 38, 10
143
+
144
+
145
+ def _cast_json_value(statement, value):
146
+ """
147
+ Cast a JSON Node expression so it compares correctly with ``value`` on every database.
148
+
149
+ Plain columns are returned unchanged. For JSON Nodes the cast follows the value's type: booleans compare as
150
+ booleans, numbers as ``NUMERIC(38, 10)``, strings and ``None`` as text. A string that parses as JSON (e.g. the
151
+ operand of ``@>``) is left uncast. Lists are cast by their first element; an empty list is not cast.
152
+
153
+ :param statement: Column attribute or JSON index expression from :func:`resolve_field`.
154
+ :param value: The Filter's comparison value.
155
+ """
156
+ if not isinstance(statement, BinaryExpression):
157
+ return statement
158
+
159
+ if type(value) is list:
160
+ if not value:
161
+ return statement
162
+ value = value[0]
163
+ elif type(value) is str and _is_json(value):
164
+ return statement
165
+
166
+ if value is None:
167
+ # Text cast makes null checks match a missing key or JSON null on every database.
168
+ return statement.as_string()
169
+ if type(value) is bool:
170
+ return statement.as_boolean()
171
+ if type(value) in _get_numeric_types():
172
+ return statement.as_numeric(_NUMERIC_PRECISION, _NUMERIC_SCALE)
173
+ if type(value) is str:
174
+ return statement.as_string()
175
+ return statement
176
+
177
+
178
+ def _is_json(value: str) -> bool:
179
+ try:
180
+ json.loads(value)
181
+ return True
182
+ except ValueError:
183
+ return False
@@ -15,8 +15,9 @@ class ComparisonOperator:
15
15
  '!=': lambda left, right: left != right,
16
16
  'ne': lambda left, right: left != right,
17
17
 
18
- 'is_null': lambda left: left.is_(None),
19
- 'is_not_null': lambda left: left.isnot(None),
18
+ # Null checks ignore the filter's value.
19
+ 'is_null': lambda left, right=None: left.is_(None),
20
+ 'is_not_null': lambda left, right=None: left.isnot(None),
20
21
 
21
22
  '>': lambda left, right: left > right,
22
23
  'gt': lambda left, right: left > right,
@@ -0,0 +1,66 @@
1
+ from sqlalchemy import nullslast
2
+
3
+ from sqlalchemy_filtering.fields import resolve_field
4
+ from sqlalchemy_filtering.validators import SortRequest, SortDirection, Sort
5
+
6
+
7
+ def sort_apply(query, entity, obj=None):
8
+ """
9
+ Construct sorting statements on SQLAlchemy query
10
+ :param query: Query object of type :class:`sqlalchemy.orm.Query`.
11
+ :param entity: SQLAlchemy model class.
12
+ :param obj: :class:`SortRequest` object or the raw request dict.
13
+
14
+ Example object
15
+
16
+ -- Simple request
17
+ obj = {
18
+ "filter": [...],
19
+ "sort": [
20
+ {
21
+ "field": "demographics",
22
+ "node": "age",
23
+ "direction": "asc",
24
+ "nullsLast": True
25
+ }
26
+ ]
27
+ }
28
+
29
+ -- Nested request
30
+ obj = {
31
+ "filter": [...],
32
+ "sort": [
33
+ {
34
+ "field": "demographics",
35
+ "node": "nested.field1",
36
+ "direction": "asc",
37
+ "nullsLast": True
38
+ }
39
+ ]
40
+ }
41
+
42
+ :return: Query object of type :class:`sqlalchemy.orm.Query` with applied sorting statements.
43
+ """
44
+ clauses = build_sort(entity, obj)
45
+ return query.order_by(*clauses) if clauses else query
46
+
47
+
48
+ def build_sort(entity, request=None):
49
+ """
50
+ Compile a sort request into a list of SQLAlchemy ordering clauses.
51
+
52
+ ``direction`` defaults to ``asc``; ``nullsLast`` defaults to ``False``.
53
+
54
+ :param entity: SQLAlchemy model class.
55
+ :param request: :class:`SortRequest` object or the raw request dict (it is not modified).
56
+ :returns: A list of ordering clauses, empty when the request contains no sorts.
57
+ """
58
+ if not isinstance(request, SortRequest):
59
+ request = SortRequest(request)
60
+ return [_compile_sort(entity, sort) for sort in request.sort]
61
+
62
+
63
+ def _compile_sort(entity, sort: Sort):
64
+ expression = resolve_field(entity, sort.field, sort.node)
65
+ expression = expression.desc() if sort.direction == SortDirection.DESC else expression.asc()
66
+ return nullslast(expression) if sort.nullsLast else expression
@@ -0,0 +1,140 @@
1
+ import enum
2
+
3
+ from sqlalchemy_filtering.operators import ComparisonOperator, FilterOperator
4
+
5
+
6
+ def _construct_field(obj, field):
7
+ if field in obj:
8
+ value = obj[field]
9
+ # Numbers, booleans and None keep their type; anything else is stringified.
10
+ if value is None or type(value) is bool or type(value) in _get_numeric_types():
11
+ return value
12
+ return str(value)
13
+ else:
14
+ return None
15
+
16
+
17
+ def __cast_value_field(obj, field):
18
+ attr = getattr(obj, field)
19
+ if isinstance(attr, dict):
20
+ return Filter(attr)
21
+ else:
22
+ return attr
23
+
24
+
25
+ def _construct_value_field(obj, field, class_type):
26
+ if field in obj:
27
+ if type(obj[field]) is list:
28
+ # list of dict objects or simple list
29
+ values = []
30
+ for o in obj[field]:
31
+ if type(o) is dict and class_type in (Filter, Sort):
32
+ values.append(class_type(o))
33
+ else:
34
+ values.append(o)
35
+ return values
36
+ else:
37
+ # dict or str cases
38
+ if isinstance(obj[field], dict) and class_type in (Filter, Sort):
39
+ return class_type(obj[field])
40
+ else:
41
+ return _construct_field(obj, field)
42
+ else:
43
+ return None
44
+
45
+
46
+ def _is_group(expression):
47
+ """A group is a dict with a single logical operator key mapping to a list, e.g. {"or": [...]}."""
48
+ if not isinstance(expression, dict) or len(expression) != 1:
49
+ return False
50
+ key, children = next(iter(expression.items()))
51
+ return key in FilterOperator.OPERATORS and isinstance(children, list)
52
+
53
+
54
+ def _parse_filter_node(expression):
55
+ if isinstance(expression, (Filter, Group)):
56
+ return expression
57
+ if _is_group(expression):
58
+ key, children = next(iter(expression.items()))
59
+ return Group(key, children)
60
+ return Filter(expression)
61
+
62
+
63
+ def _construct_filter_object(request):
64
+ """
65
+ Parse the request's ``filter`` entry into ``{group_operator: [Filter | Group, ...]}``.
66
+
67
+ A plain list is treated as an implicit ``and`` group. Returns ``None`` when there is nothing to filter.
68
+ The input request is never modified.
69
+ """
70
+ if not request:
71
+ return None
72
+ expression = request.get('filter')
73
+ if not expression:
74
+ return None
75
+
76
+ if isinstance(expression, list):
77
+ return {'and': [_parse_filter_node(e) for e in expression]}
78
+
79
+ groups = {}
80
+ for key, children in expression.items():
81
+ FilterOperator(key) # validates the operator name
82
+ groups[key] = [_parse_filter_node(e) for e in children]
83
+ return groups
84
+
85
+
86
+ def _get_numeric_types():
87
+ return float, int, complex
88
+
89
+
90
+ class FilterRequest(object):
91
+
92
+ def __init__(self, request) -> None:
93
+ super().__init__()
94
+ self.filter: dict = _construct_filter_object(request)
95
+
96
+
97
+ class Group(object):
98
+ """A logical operator (``and`` / ``or`` / ``not``) applied to a list of Filter or Group children."""
99
+
100
+ def __init__(self, operator, children) -> None:
101
+ super().__init__()
102
+ self.operator: FilterOperator = FilterOperator(operator)
103
+ self.children: list = [_parse_filter_node(c) for c in children]
104
+
105
+
106
+ class Filter(object):
107
+
108
+ def __init__(self, obj) -> None:
109
+ super().__init__()
110
+ self.field: str = _construct_field(obj, 'field')
111
+ self.node: str = _construct_field(obj, 'node')
112
+ self.operator: ComparisonOperator = ComparisonOperator(_construct_field(obj, 'operator'))
113
+ self.value = _construct_value_field(obj, 'value', Filter)
114
+
115
+ def _get_values_class(self):
116
+ return type(self.value).__name__
117
+
118
+
119
+ class SortRequest(object):
120
+ def __init__(self, request) -> None:
121
+ super().__init__()
122
+ sort = request.get('sort') if request else None
123
+ if isinstance(sort, dict):
124
+ sort = [sort]
125
+ self.sort: list = [s if isinstance(s, Sort) else Sort(s) for s in sort or []]
126
+
127
+
128
+ class Sort(object):
129
+
130
+ def __init__(self, obj) -> None:
131
+ super().__init__()
132
+ self.field: str = _construct_field(obj, 'field')
133
+ self.node: str = _construct_field(obj, 'node')
134
+ self.direction: SortDirection = SortDirection(str(obj.get('direction') or 'asc').upper())
135
+ self.nullsLast: bool = bool(obj.get('nullsLast', False))
136
+
137
+
138
+ class SortDirection(enum.Enum):
139
+ ASC = 'ASC'
140
+ DESC = 'DESC'