industrial-model 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- industrial_model/__init__.py +27 -0
- industrial_model/cognite_adapters/__init__.py +56 -0
- industrial_model/cognite_adapters/filter_mapper.py +99 -0
- industrial_model/cognite_adapters/optimizer.py +74 -0
- industrial_model/cognite_adapters/query_mapper.py +181 -0
- industrial_model/cognite_adapters/query_result_mapper.py +216 -0
- industrial_model/cognite_adapters/schemas.py +121 -0
- industrial_model/cognite_adapters/sort_mapper.py +21 -0
- industrial_model/cognite_adapters/utils.py +33 -0
- industrial_model/cognite_adapters/view_mapper.py +16 -0
- industrial_model/config.py +10 -0
- industrial_model/constants.py +24 -0
- industrial_model/engines/__init__.py +4 -0
- industrial_model/engines/async_engine.py +37 -0
- industrial_model/engines/engine.py +62 -0
- industrial_model/models/__init__.py +19 -0
- industrial_model/models/base.py +46 -0
- industrial_model/models/entities.py +55 -0
- industrial_model/py.typed +0 -0
- industrial_model/queries/__init__.py +10 -0
- industrial_model/queries/models.py +37 -0
- industrial_model/queries/params.py +42 -0
- industrial_model/statements/__init__.py +70 -0
- industrial_model/statements/expressions.py +165 -0
- industrial_model/utils.py +38 -0
- industrial_model-0.1.0.dist-info/METADATA +23 -0
- industrial_model-0.1.0.dist-info/RECORD +28 -0
- industrial_model-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from .config import DataModelId
|
|
2
|
+
from .engines import AsyncEngine, Engine
|
|
3
|
+
from .models import (
|
|
4
|
+
InstanceId,
|
|
5
|
+
PaginatedResult,
|
|
6
|
+
TViewInstance,
|
|
7
|
+
ValidationMode,
|
|
8
|
+
ViewInstance,
|
|
9
|
+
ViewInstanceConfig,
|
|
10
|
+
)
|
|
11
|
+
from .statements import and_, col, or_, select
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"and_",
|
|
15
|
+
"or_",
|
|
16
|
+
"col",
|
|
17
|
+
"select",
|
|
18
|
+
"ViewInstance",
|
|
19
|
+
"InstanceId",
|
|
20
|
+
"TViewInstance",
|
|
21
|
+
"DataModelId",
|
|
22
|
+
"ValidationMode",
|
|
23
|
+
"Engine",
|
|
24
|
+
"AsyncEngine",
|
|
25
|
+
"PaginatedResult",
|
|
26
|
+
"ViewInstanceConfig",
|
|
27
|
+
]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from cognite.client import CogniteClient
|
|
4
|
+
|
|
5
|
+
from industrial_model.cognite_adapters.optimizer import QueryOptimizer
|
|
6
|
+
from industrial_model.config import DataModelId
|
|
7
|
+
from industrial_model.models import TViewInstance
|
|
8
|
+
from industrial_model.statements import Statement
|
|
9
|
+
|
|
10
|
+
from .query_mapper import QueryMapper
|
|
11
|
+
from .query_result_mapper import (
|
|
12
|
+
QueryResultMapper,
|
|
13
|
+
)
|
|
14
|
+
from .view_mapper import ViewMapper
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CogniteAdapter:
|
|
18
|
+
def __init__(
|
|
19
|
+
self, cognite_client: CogniteClient, data_model_id: DataModelId
|
|
20
|
+
):
|
|
21
|
+
self._cognite_client = cognite_client
|
|
22
|
+
|
|
23
|
+
dm = cognite_client.data_modeling.data_models.retrieve(
|
|
24
|
+
ids=data_model_id.as_tuple(),
|
|
25
|
+
inline_views=True,
|
|
26
|
+
).latest_version()
|
|
27
|
+
view_mapper = ViewMapper(dm.views)
|
|
28
|
+
self._query_mapper = QueryMapper(view_mapper)
|
|
29
|
+
self._result_mapper = QueryResultMapper(view_mapper)
|
|
30
|
+
self._optmizer = QueryOptimizer(cognite_client)
|
|
31
|
+
|
|
32
|
+
def query(
|
|
33
|
+
self, statement: Statement[TViewInstance], all_pages: bool
|
|
34
|
+
) -> tuple[list[dict[str, Any]], str | None]:
|
|
35
|
+
self._optmizer.optimize(statement)
|
|
36
|
+
cognite_query = self._query_mapper.map(statement)
|
|
37
|
+
view_external_id = statement.entity.get_view_external_id()
|
|
38
|
+
|
|
39
|
+
data: list[dict[str, Any]] = []
|
|
40
|
+
while True:
|
|
41
|
+
query_result = self._cognite_client.data_modeling.instances.query(
|
|
42
|
+
cognite_query
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
page_result, next_cursor = self._result_mapper.map_nodes(
|
|
46
|
+
view_external_id, query_result
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
data.extend(page_result)
|
|
50
|
+
|
|
51
|
+
last_page = len(page_result) < statement.limit_ or not next_cursor
|
|
52
|
+
next_cursor_ = None if last_page else next_cursor
|
|
53
|
+
cognite_query.cursors = {view_external_id: next_cursor_}
|
|
54
|
+
|
|
55
|
+
if not all_pages or last_page:
|
|
56
|
+
return data, next_cursor
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
|
|
3
|
+
import cognite.client.data_classes.filters as cdf_filters
|
|
4
|
+
from cognite.client.data_classes.data_modeling import MappedProperty, View
|
|
5
|
+
|
|
6
|
+
from industrial_model.cognite_adapters.utils import get_property_ref
|
|
7
|
+
from industrial_model.statements import (
|
|
8
|
+
BoolExpression,
|
|
9
|
+
Expression,
|
|
10
|
+
LeafExpression,
|
|
11
|
+
)
|
|
12
|
+
from industrial_model.utils import datetime_to_ms_iso_timestamp
|
|
13
|
+
|
|
14
|
+
from .view_mapper import ViewMapper
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FilterMapper:
|
|
18
|
+
def __init__(self, view_mapper: ViewMapper):
|
|
19
|
+
self._view_mapper = view_mapper
|
|
20
|
+
|
|
21
|
+
def map(
|
|
22
|
+
self, expressions: list[Expression], root_view: View
|
|
23
|
+
) -> list[cdf_filters.Filter]:
|
|
24
|
+
result: list[cdf_filters.Filter] = []
|
|
25
|
+
for expression in expressions:
|
|
26
|
+
if isinstance(expression, BoolExpression):
|
|
27
|
+
result.append(self.to_cdf_filter_bool(expression, root_view))
|
|
28
|
+
elif isinstance(expression, LeafExpression):
|
|
29
|
+
result.append(self.to_cdf_filter_leaf(expression, root_view))
|
|
30
|
+
else:
|
|
31
|
+
cls_name = expression.__class__.__name__
|
|
32
|
+
raise ValueError(f"Expression not implemented {cls_name}")
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
def to_cdf_filter_bool(
|
|
36
|
+
self, expression: BoolExpression, root_view: View
|
|
37
|
+
) -> cdf_filters.Filter:
|
|
38
|
+
arguments = self.map(expression.filters, root_view)
|
|
39
|
+
|
|
40
|
+
if expression.operator == "and":
|
|
41
|
+
return cdf_filters.And(*arguments)
|
|
42
|
+
elif expression.operator == "or":
|
|
43
|
+
return cdf_filters.Or(*arguments)
|
|
44
|
+
elif expression.operator == "not":
|
|
45
|
+
return cdf_filters.Not(*arguments)
|
|
46
|
+
|
|
47
|
+
raise NotImplementedError(f"Operator {self.operator} not implemented")
|
|
48
|
+
|
|
49
|
+
def to_cdf_filter_leaf(
|
|
50
|
+
self,
|
|
51
|
+
expression: LeafExpression,
|
|
52
|
+
root_view: View,
|
|
53
|
+
) -> cdf_filters.Filter:
|
|
54
|
+
property_ref = get_property_ref(expression.property, root_view)
|
|
55
|
+
|
|
56
|
+
value_ = expression.value
|
|
57
|
+
if isinstance(value_, datetime):
|
|
58
|
+
value_ = datetime_to_ms_iso_timestamp(value_)
|
|
59
|
+
|
|
60
|
+
if expression.operator == "==":
|
|
61
|
+
return cdf_filters.Equals(property_ref, value_)
|
|
62
|
+
elif expression.operator == "in":
|
|
63
|
+
return cdf_filters.In(property_ref, value_)
|
|
64
|
+
elif expression.operator == ">":
|
|
65
|
+
return cdf_filters.Range(property_ref, gt=value_)
|
|
66
|
+
elif expression.operator == ">=":
|
|
67
|
+
return cdf_filters.Range(property_ref, gte=value_)
|
|
68
|
+
elif expression.operator == "<":
|
|
69
|
+
return cdf_filters.Range(property_ref, lt=value_)
|
|
70
|
+
elif expression.operator == "<=":
|
|
71
|
+
return cdf_filters.Range(property_ref, lte=value_)
|
|
72
|
+
elif expression.operator == "nested":
|
|
73
|
+
target_view = self._get_nested_target_view(
|
|
74
|
+
expression.property, root_view
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
assert isinstance(value_, Expression)
|
|
78
|
+
|
|
79
|
+
return cdf_filters.Nested(
|
|
80
|
+
property_ref,
|
|
81
|
+
self.map([value_], target_view)[0],
|
|
82
|
+
)
|
|
83
|
+
elif expression.operator == "exists":
|
|
84
|
+
return cdf_filters.Exists(property_ref)
|
|
85
|
+
elif expression.operator == "prefix":
|
|
86
|
+
return cdf_filters.Prefix(property_ref, value_)
|
|
87
|
+
elif expression.operator == "containsAll":
|
|
88
|
+
return cdf_filters.ContainsAll(property_ref, value_)
|
|
89
|
+
elif expression.operator == "containsAny":
|
|
90
|
+
return cdf_filters.ContainsAny(property_ref, value_)
|
|
91
|
+
raise NotImplementedError(
|
|
92
|
+
f"Operator {expression.operator} not implemented"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def _get_nested_target_view(self, property: str, root_view: View) -> View:
|
|
96
|
+
view_definiton = root_view.properties[property]
|
|
97
|
+
assert isinstance(view_definiton, MappedProperty)
|
|
98
|
+
assert view_definiton.source
|
|
99
|
+
return self._view_mapper.get_view(view_definiton.source.external_id)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from cognite.client import CogniteClient
|
|
2
|
+
|
|
3
|
+
from industrial_model.models import TViewInstance
|
|
4
|
+
from industrial_model.statements import (
|
|
5
|
+
BoolExpression,
|
|
6
|
+
Expression,
|
|
7
|
+
LeafExpression,
|
|
8
|
+
Statement,
|
|
9
|
+
col,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
SPACE_PROPERTY = "space"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class QueryOptimizer:
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
cognite_client: CogniteClient,
|
|
19
|
+
):
|
|
20
|
+
self._all_spaces: list[str] | None = None
|
|
21
|
+
self._cognite_client = cognite_client
|
|
22
|
+
|
|
23
|
+
def optimize(self, statement: Statement[TViewInstance]) -> None:
|
|
24
|
+
instance_spaces = statement.entity.view_config.get("instance_spaces")
|
|
25
|
+
instance_spaces_prefix = statement.entity.view_config.get(
|
|
26
|
+
"instance_spaces_prefix"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if not instance_spaces and not instance_spaces_prefix:
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
if self._has_space_filter(statement.where_clauses):
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
filter_spaces = (
|
|
36
|
+
self._find_spaces(instance_spaces_prefix)
|
|
37
|
+
if instance_spaces_prefix
|
|
38
|
+
else []
|
|
39
|
+
)
|
|
40
|
+
if instance_spaces:
|
|
41
|
+
filter_spaces.extend(instance_spaces)
|
|
42
|
+
|
|
43
|
+
if filter_spaces:
|
|
44
|
+
statement.where(col(SPACE_PROPERTY).in_(filter_spaces))
|
|
45
|
+
|
|
46
|
+
def _has_space_filter(self, where_clauses: list[Expression]) -> bool:
|
|
47
|
+
for where_clause in where_clauses:
|
|
48
|
+
if isinstance(
|
|
49
|
+
where_clause, BoolExpression
|
|
50
|
+
) and self._has_space_filter(where_clause.filters):
|
|
51
|
+
return True
|
|
52
|
+
elif isinstance(where_clause, LeafExpression):
|
|
53
|
+
return where_clause.property == SPACE_PROPERTY
|
|
54
|
+
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
def _find_spaces(self, instance_spaces_prefix: str) -> list[str]:
|
|
58
|
+
all_spaces = self._get_all_spaces()
|
|
59
|
+
|
|
60
|
+
return [
|
|
61
|
+
space
|
|
62
|
+
for space in all_spaces
|
|
63
|
+
if space.startswith(instance_spaces_prefix)
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
def _get_all_spaces(self) -> list[str]:
|
|
67
|
+
all_spaces = self._all_spaces
|
|
68
|
+
if all_spaces is None:
|
|
69
|
+
all_spaces = self._cognite_client.data_modeling.spaces.list(
|
|
70
|
+
limit=-1
|
|
71
|
+
).as_ids()
|
|
72
|
+
|
|
73
|
+
self._all_spaces = all_spaces
|
|
74
|
+
return all_spaces
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import cognite.client.data_classes.filters as filters
|
|
2
|
+
from cognite.client.data_classes.data_modeling import (
|
|
3
|
+
EdgeConnection,
|
|
4
|
+
MappedProperty,
|
|
5
|
+
View,
|
|
6
|
+
ViewId,
|
|
7
|
+
)
|
|
8
|
+
from cognite.client.data_classes.data_modeling.query import (
|
|
9
|
+
EdgeResultSetExpression,
|
|
10
|
+
NodeResultSetExpression,
|
|
11
|
+
ResultSetExpression,
|
|
12
|
+
Select,
|
|
13
|
+
SourceSelector,
|
|
14
|
+
)
|
|
15
|
+
from cognite.client.data_classes.data_modeling.query import (
|
|
16
|
+
Query as CogniteQuery,
|
|
17
|
+
)
|
|
18
|
+
from cognite.client.data_classes.data_modeling.views import (
|
|
19
|
+
MultiReverseDirectRelation,
|
|
20
|
+
SingleReverseDirectRelation,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from industrial_model.constants import EDGE_MARKER, MAX_LIMIT, NESTED_SEP
|
|
24
|
+
from industrial_model.models import TViewInstance
|
|
25
|
+
from industrial_model.statements import Statement
|
|
26
|
+
|
|
27
|
+
from .filter_mapper import (
|
|
28
|
+
FilterMapper,
|
|
29
|
+
)
|
|
30
|
+
from .schemas import get_schema_properties
|
|
31
|
+
from .sort_mapper import SortMapper
|
|
32
|
+
from .view_mapper import ViewMapper
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class QueryMapper:
|
|
36
|
+
def __init__(self, view_mapper: ViewMapper):
|
|
37
|
+
self._view_mapper = view_mapper
|
|
38
|
+
self._filter_mapper = FilterMapper(view_mapper)
|
|
39
|
+
self._sort_mapper = SortMapper()
|
|
40
|
+
|
|
41
|
+
def map(self, statement: Statement[TViewInstance]) -> CogniteQuery:
|
|
42
|
+
root_node = statement.entity.get_view_external_id()
|
|
43
|
+
|
|
44
|
+
root_view = self._view_mapper.get_view(root_node)
|
|
45
|
+
root_view_id = root_view.as_id()
|
|
46
|
+
|
|
47
|
+
filters_: list[filters.Filter] = [
|
|
48
|
+
filters.HasData(views=[root_view_id])
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
filters_.extend(
|
|
52
|
+
self._filter_mapper.map(statement.where_clauses, root_view)
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
with_: dict[str, ResultSetExpression] = {
|
|
56
|
+
root_node: NodeResultSetExpression(
|
|
57
|
+
filter=filters.And(*filters_),
|
|
58
|
+
sort=self._sort_mapper.map(statement.sort_clauses, root_view),
|
|
59
|
+
limit=statement.limit_,
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
select_: dict[str, Select] = {}
|
|
63
|
+
|
|
64
|
+
relations = get_schema_properties(
|
|
65
|
+
statement.entity, NESTED_SEP, root_node
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
properties = self._include_statements(
|
|
69
|
+
root_node, root_view, relations, with_, select_
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
select_[root_node] = self._get_select(root_view_id, properties)
|
|
73
|
+
|
|
74
|
+
return CogniteQuery(
|
|
75
|
+
with_=with_, select=select_, cursors={root_node: statement.cursor_}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def _get_select(self, view_id: ViewId, properties: list[str]) -> Select:
|
|
79
|
+
return (
|
|
80
|
+
Select(
|
|
81
|
+
sources=[SourceSelector(source=view_id, properties=properties)]
|
|
82
|
+
)
|
|
83
|
+
if properties
|
|
84
|
+
else Select()
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def _include_statements(
|
|
88
|
+
self,
|
|
89
|
+
key: str,
|
|
90
|
+
view: View,
|
|
91
|
+
relations_to_include: list[str] | None,
|
|
92
|
+
with_: dict[str, ResultSetExpression],
|
|
93
|
+
select_: dict[str, Select],
|
|
94
|
+
) -> list[str]:
|
|
95
|
+
if not relations_to_include:
|
|
96
|
+
return []
|
|
97
|
+
|
|
98
|
+
select_properties: list[str] = []
|
|
99
|
+
for property_name, property in view.properties.items():
|
|
100
|
+
property_key = f"{key}{NESTED_SEP}{property_name}"
|
|
101
|
+
if property_key not in relations_to_include:
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
if isinstance(property, MappedProperty) and not property.source:
|
|
105
|
+
select_properties.append(property_name)
|
|
106
|
+
elif isinstance(property, MappedProperty) and property.source:
|
|
107
|
+
select_properties.append(property_name)
|
|
108
|
+
|
|
109
|
+
props = self._include_statements(
|
|
110
|
+
property_key,
|
|
111
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
112
|
+
relations_to_include,
|
|
113
|
+
with_,
|
|
114
|
+
select_,
|
|
115
|
+
)
|
|
116
|
+
if props:
|
|
117
|
+
with_[property_key] = NodeResultSetExpression(
|
|
118
|
+
from_=key,
|
|
119
|
+
through=view.as_property_ref(property_name),
|
|
120
|
+
limit=MAX_LIMIT,
|
|
121
|
+
)
|
|
122
|
+
select_[property_key] = self._get_select(
|
|
123
|
+
property.source, props
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
elif (
|
|
127
|
+
isinstance(property, MultiReverseDirectRelation)
|
|
128
|
+
or isinstance(property, SingleReverseDirectRelation)
|
|
129
|
+
and property.source
|
|
130
|
+
):
|
|
131
|
+
props = self._include_statements(
|
|
132
|
+
property_key,
|
|
133
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
134
|
+
relations_to_include,
|
|
135
|
+
with_,
|
|
136
|
+
select_,
|
|
137
|
+
)
|
|
138
|
+
if not props:
|
|
139
|
+
with_[property_key] = NodeResultSetExpression(
|
|
140
|
+
from_=key,
|
|
141
|
+
direction="inwards",
|
|
142
|
+
through=property.source.as_property_ref(
|
|
143
|
+
property.through.property
|
|
144
|
+
),
|
|
145
|
+
limit=MAX_LIMIT,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
select_[property_key] = self._get_select(
|
|
149
|
+
property.source, props
|
|
150
|
+
)
|
|
151
|
+
elif isinstance(property, EdgeConnection) and property.source:
|
|
152
|
+
edge_property_key = f"{property_key}{NESTED_SEP}{EDGE_MARKER}"
|
|
153
|
+
|
|
154
|
+
with_[edge_property_key] = EdgeResultSetExpression(
|
|
155
|
+
from_=key,
|
|
156
|
+
max_distance=1,
|
|
157
|
+
filter=filters.Equals(
|
|
158
|
+
["edge", "type"], property.type.dump()
|
|
159
|
+
),
|
|
160
|
+
direction=property.direction,
|
|
161
|
+
limit=MAX_LIMIT,
|
|
162
|
+
)
|
|
163
|
+
with_[property_key] = NodeResultSetExpression(
|
|
164
|
+
from_=edge_property_key,
|
|
165
|
+
limit=MAX_LIMIT,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
select_[edge_property_key] = Select()
|
|
169
|
+
|
|
170
|
+
props = self._include_statements(
|
|
171
|
+
property_key,
|
|
172
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
173
|
+
relations_to_include,
|
|
174
|
+
with_,
|
|
175
|
+
select_,
|
|
176
|
+
)
|
|
177
|
+
select_[property_key] = self._get_select(
|
|
178
|
+
property.source, props
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
return select_properties
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
from collections import defaultdict
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from cognite.client.data_classes.data_modeling import (
|
|
5
|
+
Edge,
|
|
6
|
+
EdgeConnection,
|
|
7
|
+
MappedProperty,
|
|
8
|
+
Node,
|
|
9
|
+
View,
|
|
10
|
+
)
|
|
11
|
+
from cognite.client.data_classes.data_modeling.query import (
|
|
12
|
+
QueryResult,
|
|
13
|
+
)
|
|
14
|
+
from cognite.client.data_classes.data_modeling.views import (
|
|
15
|
+
MultiReverseDirectRelation,
|
|
16
|
+
SingleReverseDirectRelation,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from industrial_model.constants import EDGE_DIRECTION, EDGE_MARKER, NESTED_SEP
|
|
20
|
+
|
|
21
|
+
from .view_mapper import ViewMapper
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class QueryResultMapper:
|
|
25
|
+
def __init__(self, view_mapper: ViewMapper):
|
|
26
|
+
self._view_mapper = view_mapper
|
|
27
|
+
|
|
28
|
+
def map_nodes(
|
|
29
|
+
self, root_node: str, query_result: QueryResult
|
|
30
|
+
) -> tuple[list[dict[str, Any]], str | None]:
|
|
31
|
+
if root_node not in query_result:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
f"{root_node} is not available in the query result"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
root_view = self._view_mapper.get_view(root_node)
|
|
37
|
+
|
|
38
|
+
values = self._map_node_property(root_node, root_view, query_result)
|
|
39
|
+
if not values:
|
|
40
|
+
return [], None
|
|
41
|
+
|
|
42
|
+
data = [
|
|
43
|
+
node
|
|
44
|
+
for nodes in values.values()
|
|
45
|
+
for node in self._nodes_to_dict(nodes)
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
return data, query_result.cursors.get(root_node)
|
|
49
|
+
|
|
50
|
+
def _map_node_property(
|
|
51
|
+
self,
|
|
52
|
+
key: str,
|
|
53
|
+
view: View,
|
|
54
|
+
query_result: QueryResult,
|
|
55
|
+
result_property_key: str | None = None,
|
|
56
|
+
) -> dict[tuple[str, str], list[Node]] | None:
|
|
57
|
+
if key not in query_result:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
mappings = self._get_property_mappings(key, view, query_result)
|
|
61
|
+
|
|
62
|
+
view_id = view.as_id()
|
|
63
|
+
|
|
64
|
+
nodes = (
|
|
65
|
+
node
|
|
66
|
+
for node in query_result.get_nodes(key)
|
|
67
|
+
if isinstance(node, Node)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def get_node_id(node: Node) -> tuple[str, str]:
|
|
71
|
+
if not result_property_key:
|
|
72
|
+
return (node.space, node.external_id)
|
|
73
|
+
|
|
74
|
+
entry = properties.get(result_property_key)
|
|
75
|
+
if not isinstance(entry, dict):
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"Invalid result property key {result_property_key}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
return entry.get("space", ""), entry.get("externalId", "")
|
|
81
|
+
|
|
82
|
+
result: defaultdict[tuple[str, str], list[Node]] = defaultdict(list)
|
|
83
|
+
for node in nodes:
|
|
84
|
+
properties = node.properties.get(view_id, {})
|
|
85
|
+
node_id = get_node_id(node)
|
|
86
|
+
for mapping_key, (values, is_list) in mappings.items():
|
|
87
|
+
element = properties.get(mapping_key)
|
|
88
|
+
|
|
89
|
+
element_key: tuple[str, str] = (
|
|
90
|
+
(element.get("space", ""), element.get("externalId", ""))
|
|
91
|
+
if isinstance(element, dict)
|
|
92
|
+
else node_id
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
entries = values.get(element_key)
|
|
96
|
+
if not entries:
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
entry_data = self._nodes_to_dict(entries)
|
|
100
|
+
properties[mapping_key] = (
|
|
101
|
+
entry_data if is_list else entry_data[0]
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
node.properties[view_id] = properties
|
|
105
|
+
|
|
106
|
+
result[node_id].append(node)
|
|
107
|
+
|
|
108
|
+
return dict(result)
|
|
109
|
+
|
|
110
|
+
def _get_property_mappings(
|
|
111
|
+
self, key: str, view: View, query_result: QueryResult
|
|
112
|
+
) -> dict[str, tuple[dict[tuple[str, str], list[Node]], bool]]:
|
|
113
|
+
mappings: dict[
|
|
114
|
+
str, tuple[dict[tuple[str, str], list[Node]], bool]
|
|
115
|
+
] = {}
|
|
116
|
+
|
|
117
|
+
for property_name, property in view.properties.items():
|
|
118
|
+
property_key = f"{key}{NESTED_SEP}{property_name}"
|
|
119
|
+
|
|
120
|
+
entry: dict[tuple[str, str], list[Node]] | None = None
|
|
121
|
+
is_list = False
|
|
122
|
+
|
|
123
|
+
if isinstance(property, MappedProperty) and property.source:
|
|
124
|
+
entry = self._map_node_property(
|
|
125
|
+
property_key,
|
|
126
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
127
|
+
query_result,
|
|
128
|
+
)
|
|
129
|
+
is_list = False
|
|
130
|
+
elif (
|
|
131
|
+
isinstance(property, SingleReverseDirectRelation)
|
|
132
|
+
and property.source
|
|
133
|
+
):
|
|
134
|
+
entry = self._map_node_property(
|
|
135
|
+
property_key,
|
|
136
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
137
|
+
query_result,
|
|
138
|
+
property.through.property,
|
|
139
|
+
)
|
|
140
|
+
is_list = False
|
|
141
|
+
elif (
|
|
142
|
+
isinstance(property, MultiReverseDirectRelation)
|
|
143
|
+
and property.source
|
|
144
|
+
):
|
|
145
|
+
entry = self._map_node_property(
|
|
146
|
+
property_key,
|
|
147
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
148
|
+
query_result,
|
|
149
|
+
property.through.property,
|
|
150
|
+
)
|
|
151
|
+
is_list = True
|
|
152
|
+
|
|
153
|
+
elif isinstance(property, EdgeConnection) and property.source:
|
|
154
|
+
entry = self._map_edge_property(
|
|
155
|
+
property_key,
|
|
156
|
+
self._view_mapper.get_view(property.source.external_id),
|
|
157
|
+
query_result,
|
|
158
|
+
property.direction,
|
|
159
|
+
)
|
|
160
|
+
is_list = True
|
|
161
|
+
|
|
162
|
+
if entry:
|
|
163
|
+
mappings[property_name] = entry, is_list
|
|
164
|
+
|
|
165
|
+
return mappings
|
|
166
|
+
|
|
167
|
+
def _map_edge_property(
|
|
168
|
+
self,
|
|
169
|
+
key: str,
|
|
170
|
+
view: View,
|
|
171
|
+
query_result: QueryResult,
|
|
172
|
+
edge_direction: EDGE_DIRECTION,
|
|
173
|
+
) -> dict[tuple[str, str], list[Node]] | None:
|
|
174
|
+
edge_key = f"{key}{NESTED_SEP}{EDGE_MARKER}"
|
|
175
|
+
if key not in query_result or edge_key not in query_result:
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
nodes = self._map_node_property(key, view, query_result)
|
|
179
|
+
if not nodes:
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
result: defaultdict[tuple[str, str], list[Node]] = defaultdict(list)
|
|
183
|
+
|
|
184
|
+
edges = (
|
|
185
|
+
edge
|
|
186
|
+
for edge in query_result.get_edges(edge_key)
|
|
187
|
+
if isinstance(edge, Edge)
|
|
188
|
+
)
|
|
189
|
+
for edge in edges:
|
|
190
|
+
entry_key, node_key = (
|
|
191
|
+
(
|
|
192
|
+
edge.end_node.as_tuple(),
|
|
193
|
+
edge.start_node.as_tuple(),
|
|
194
|
+
)
|
|
195
|
+
if edge_direction == "inwards"
|
|
196
|
+
else (edge.start_node.as_tuple(), edge.end_node.as_tuple())
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
if node_item := nodes.get(node_key):
|
|
200
|
+
result[entry_key].extend(node_item)
|
|
201
|
+
|
|
202
|
+
return dict(result)
|
|
203
|
+
|
|
204
|
+
def _nodes_to_dict(self, nodes: list[Node]) -> list[dict[str, Any]]:
|
|
205
|
+
return [self._node_to_dict(node) for node in nodes]
|
|
206
|
+
|
|
207
|
+
def _node_to_dict(self, node: Node) -> dict[str, Any]:
|
|
208
|
+
entry = node.dump()
|
|
209
|
+
properties: dict[str, dict[str, dict[str, Any]]] = (
|
|
210
|
+
entry.pop("properties") or {}
|
|
211
|
+
)
|
|
212
|
+
for space_mapping in properties.values():
|
|
213
|
+
for view_mapping in space_mapping.values():
|
|
214
|
+
entry.update(view_mapping)
|
|
215
|
+
|
|
216
|
+
return entry
|