Debian Codegraph @

cassandra/datastax/graph/fluent/_query.py

raw
1 # Copyright DataStax, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import logging
16
17 from cassandra.graph import SimpleGraphStatement, GraphProtocol
18 from cassandra.cluster import EXEC_PROFILE_GRAPH_DEFAULT
19
20 from gremlin_python.process.graph_traversal import GraphTraversal
21 from gremlin_python.structure.io.graphsonV2d0 import GraphSONWriter as GraphSONWriterV2
22 from gremlin_python.structure.io.graphsonV3d0 import GraphSONWriter as GraphSONWriterV3
23
24 from cassandra.datastax.graph.fluent.serializers import GremlinUserTypeIO, \
25 dse_graphson2_serializers, dse_graphson3_serializers
26
27 log = logging.getLogger(__name__)
28
29
30 __all__ = ['TraversalBatch', '_query_from_traversal', '_DefaultTraversalBatch']
31
32
33 class _GremlinGraphSONWriterAdapter(object):
34
35 def __init__(self, context, **kwargs):
36 super(_GremlinGraphSONWriterAdapter, self).__init__(**kwargs)
37 self.context = context
38 self.user_types = None
39
40 def serialize(self, value, _):
41 return self.toDict(value)
42
43 def get_serializer(self, value):
44 serializer = None
45 try:
46 serializer = self.serializers[type(value)]
47 except KeyError:
48 for key, ser in self.serializers.items():
49 if isinstance(value, key):
50 serializer = ser
51
52 if self.context:
53 # Check if UDT
54 if self.user_types is None:
55 try:
56 user_types = self.context['cluster']._user_types[self.context['graph_name']]
57 self.user_types = dict(map(reversed, user_types.items()))
58 except KeyError:
59 self.user_types = {}
60
61 # Custom detection to map a namedtuple to udt
62 if (tuple in self.serializers and serializer is self.serializers[tuple] and hasattr(value, '_fields') or
63 (not serializer and type(value) in self.user_types)):
64 serializer = GremlinUserTypeIO
65
66 if serializer:
67 try:
68 # A serializer can have specialized serializers (e.g for Int32 and Int64, so value dependant)
69 serializer = serializer.get_specialized_serializer(value)
70 except AttributeError:
71 pass
72
73 return serializer
74
75 def toDict(self, obj):
76 serializer = self.get_serializer(obj)
77 return serializer.dictify(obj, self) if serializer else obj
78
79 def definition(self, value):
80 serializer = self.get_serializer(value)
81 return serializer.definition(value, self)
82
83
84 class GremlinGraphSON2Writer(_GremlinGraphSONWriterAdapter, GraphSONWriterV2):
85 pass
86
87
88 class GremlinGraphSON3Writer(_GremlinGraphSONWriterAdapter, GraphSONWriterV3):
89 pass
90
91
92 graphson2_writer = GremlinGraphSON2Writer
93 graphson3_writer = GremlinGraphSON3Writer
94
95
96 def _query_from_traversal(traversal, graph_protocol, context=None):
97 """
98 From a GraphTraversal, return a query string.
99
100 :param traversal: The GraphTraversal object
101 :param graphson_protocol: The graph protocol to determine the output format.
102 """
103 if graph_protocol == GraphProtocol.GRAPHSON_2_0:
104 graphson_writer = graphson2_writer(context, serializer_map=dse_graphson2_serializers)
105 elif graph_protocol == GraphProtocol.GRAPHSON_3_0:
106 if context is None:
107 raise ValueError('Missing context for GraphSON3 serialization requires.')
108 graphson_writer = graphson3_writer(context, serializer_map=dse_graphson3_serializers)
109 else:
110 raise ValueError('Unknown graph protocol: {}'.format(graph_protocol))
111
112 try:
113 query = graphson_writer.writeObject(traversal)
114 except Exception:
115 log.exception("Error preparing graphson traversal query:")
116 raise
117
118 return query
119
120
121 class TraversalBatch(object):
122 """
123 A `TraversalBatch` is used to execute multiple graph traversals in a
124 single transaction. If any traversal in the batch fails, the entire
125 batch will fail to apply.
126
127 If a TraversalBatch is bounded to a DSE session, it can be executed using
128 `traversal_batch.execute()`.
129 """
130
131 _session = None
132 _execution_profile = None
133
134 def __init__(self, session=None, execution_profile=None):
135 """
136 :param session: (Optional) A DSE session
137 :param execution_profile: (Optional) The execution profile to use for the batch execution
138 """
139 self._session = session
140 self._execution_profile = execution_profile
141
142 def add(self, traversal):
143 """
144 Add a traversal to the batch.
145
146 :param traversal: A gremlin GraphTraversal
147 """
148 raise NotImplementedError()
149
150 def add_all(self, traversals):
151 """
152 Adds a sequence of traversals to the batch.
153
154 :param traversals: A sequence of gremlin GraphTraversal
155 """
156 raise NotImplementedError()
157
158 def execute(self):
159 """
160 Execute the traversal batch if bounded to a `DSE Session`.
161 """
162 raise NotImplementedError()
163
164 def as_graph_statement(self, graph_protocol=GraphProtocol.GRAPHSON_2_0):
165 """
166 Return the traversal batch as GraphStatement.
167
168 :param graph_protocol: The graph protocol for the GraphSONWriter. Default is GraphProtocol.GRAPHSON_2_0.
169 """
170 raise NotImplementedError()
171
172 def clear(self):
173 """
174 Clear a traversal batch for reuse.
175 """
176 raise NotImplementedError()
177
178 def __len__(self):
179 raise NotImplementedError()
180
181 def __str__(self):
182 return u'<TraversalBatch traversals={0}>'.format(len(self))
183 __repr__ = __str__
184
185
186 class _DefaultTraversalBatch(TraversalBatch):
187
188 _traversals = None
189
190 def __init__(self, *args, **kwargs):
191 super(_DefaultTraversalBatch, self).__init__(*args, **kwargs)
192 self._traversals = []
193
194 def add(self, traversal):
195 if not isinstance(traversal, GraphTraversal):
196 raise ValueError('traversal should be a gremlin GraphTraversal')
197
198 self._traversals.append(traversal)
199 return self
200
201 def add_all(self, traversals):
202 for traversal in traversals:
203 self.add(traversal)
204
205 def as_graph_statement(self, graph_protocol=GraphProtocol.GRAPHSON_2_0, context=None):
206 statements = [_query_from_traversal(t, graph_protocol, context) for t in self._traversals]
207 query = u"[{0}]".format(','.join(statements))
208 return SimpleGraphStatement(query)
209
210 def execute(self):
211 if self._session is None:
212 raise ValueError('A DSE Session must be provided to execute the traversal batch.')
213
214 execution_profile = self._execution_profile if self._execution_profile else EXEC_PROFILE_GRAPH_DEFAULT
215 graph_options = self._session.get_execution_profile(execution_profile).graph_options
216 context = {
217 'cluster': self._session.cluster,
218 'graph_name': graph_options.graph_name
219 }
220 statement = self.as_graph_statement(graph_options.graph_protocol, context=context) \
221 if graph_options.graph_protocol else self.as_graph_statement(context=context)
222 return self._session.execute_graph(statement, execution_profile=execution_profile)
223
224 def clear(self):
225 del self._traversals[:]
226
227 def __len__(self):
228 return len(self._traversals)