Debian Codegraph @

cassandra/datastax/graph/fluent/__init__.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 import copy
17
18 from concurrent.futures import Future
19
20 HAVE_GREMLIN = False
21 try:
22 import gremlin_python
23 HAVE_GREMLIN = True
24 except ImportError:
25 # gremlinpython is not installed.
26 pass
27
28 if HAVE_GREMLIN:
29 from gremlin_python.structure.graph import Graph
30 from gremlin_python.driver.remote_connection import RemoteConnection, RemoteTraversal
31 from gremlin_python.process.traversal import Traverser, TraversalSideEffects
32 from gremlin_python.process.graph_traversal import GraphTraversal
33
34 from cassandra.cluster import Session, GraphExecutionProfile, EXEC_PROFILE_GRAPH_DEFAULT
35 from cassandra.datastax.graph import GraphOptions, GraphProtocol
36 from cassandra.datastax.graph.query import _GraphSONContextRowFactory
37
38 from cassandra.datastax.graph.fluent.serializers import (
39 GremlinGraphSONReaderV2,
40 GremlinGraphSONReaderV3,
41 dse_graphson2_deserializers,
42 gremlin_graphson2_deserializers,
43 dse_graphson3_deserializers,
44 gremlin_graphson3_deserializers
45 )
46 from cassandra.datastax.graph.fluent.query import _DefaultTraversalBatch, _query_from_traversal
47
48 log = logging.getLogger(__name__)
49
50 __all__ = ['BaseGraphRowFactory', 'graph_traversal_row_factory',
51 'graph_traversal_dse_object_row_factory', 'DSESessionRemoteGraphConnection', 'DseGraph']
52
53 # Traversal result keys
54 _bulk_key = 'bulk'
55 _result_key = 'result'
56
57
58 class BaseGraphRowFactory(_GraphSONContextRowFactory):
59 """
60 Base row factory for graph traversal. This class basically wraps a
61 graphson reader function to handle additional features of Gremlin/DSE
62 and is callable as a normal row factory.
63
64 Currently supported:
65 - bulk results
66 """
67
68 def __call__(self, column_names, rows):
69 for row in rows:
70 parsed_row = self.graphson_reader.readObject(row[0])
71 yield parsed_row[_result_key]
72 bulk = parsed_row.get(_bulk_key, 1)
73 for _ in range(bulk - 1):
74 yield copy.deepcopy(parsed_row[_result_key])
75
76
77 class _GremlinGraphSON2RowFactory(BaseGraphRowFactory):
78 """Row Factory that returns the decoded graphson2."""
79 graphson_reader_class = GremlinGraphSONReaderV2
80 graphson_reader_kwargs = {'deserializer_map': gremlin_graphson2_deserializers}
81
82
83 class _DseGraphSON2RowFactory(BaseGraphRowFactory):
84 """Row Factory that returns the decoded graphson2 as DSE types."""
85 graphson_reader_class = GremlinGraphSONReaderV2
86 graphson_reader_kwargs = {'deserializer_map': dse_graphson2_deserializers}
87
88 gremlin_graphson2_traversal_row_factory = _GremlinGraphSON2RowFactory
89 # TODO remove in next major
90 graph_traversal_row_factory = gremlin_graphson2_traversal_row_factory
91
92 dse_graphson2_traversal_row_factory = _DseGraphSON2RowFactory
93 # TODO remove in next major
94 graph_traversal_dse_object_row_factory = dse_graphson2_traversal_row_factory
95
96
97 class _GremlinGraphSON3RowFactory(BaseGraphRowFactory):
98 """Row Factory that returns the decoded graphson2."""
99 graphson_reader_class = GremlinGraphSONReaderV3
100 graphson_reader_kwargs = {'deserializer_map': gremlin_graphson3_deserializers}
101
102
103 class _DseGraphSON3RowFactory(BaseGraphRowFactory):
104 """Row Factory that returns the decoded graphson3 as DSE types."""
105 graphson_reader_class = GremlinGraphSONReaderV3
106 graphson_reader_kwargs = {'deserializer_map': dse_graphson3_deserializers}
107
108
109 gremlin_graphson3_traversal_row_factory = _GremlinGraphSON3RowFactory
110 dse_graphson3_traversal_row_factory = _DseGraphSON3RowFactory
111
112
113 class DSESessionRemoteGraphConnection(RemoteConnection):
114 """
115 A Tinkerpop RemoteConnection to execute traversal queries on DSE.
116
117 :param session: A DSE session
118 :param graph_name: (Optional) DSE Graph name.
119 :param execution_profile: (Optional) Execution profile for traversal queries. Default is set to `EXEC_PROFILE_GRAPH_DEFAULT`.
120 """
121
122 session = None
123 graph_name = None
124 execution_profile = None
125
126 def __init__(self, session, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT):
127 super(DSESessionRemoteGraphConnection, self).__init__(None, None)
128
129 if not isinstance(session, Session):
130 raise ValueError('A DSE Session must be provided to execute graph traversal queries.')
131
132 self.session = session
133 self.graph_name = graph_name
134 self.execution_profile = execution_profile
135
136 @staticmethod
137 def _traversers_generator(traversers):
138 for t in traversers:
139 yield Traverser(t)
140
141 def _prepare_query(self, bytecode):
142 ep = self.session.execution_profile_clone_update(self.execution_profile)
143 graph_options = ep.graph_options
144 graph_options.graph_name = self.graph_name or graph_options.graph_name
145 graph_options.graph_language = DseGraph.DSE_GRAPH_QUERY_LANGUAGE
146 # We resolve the execution profile options here , to know how what gremlin factory to set
147 self.session._resolve_execution_profile_options(ep)
148
149 context = None
150 if graph_options.graph_protocol == GraphProtocol.GRAPHSON_2_0:
151 row_factory = gremlin_graphson2_traversal_row_factory
152 elif graph_options.graph_protocol == GraphProtocol.GRAPHSON_3_0:
153 row_factory = gremlin_graphson3_traversal_row_factory
154 context = {
155 'cluster': self.session.cluster,
156 'graph_name': graph_options.graph_name.decode('utf-8')
157 }
158 else:
159 raise ValueError('Unknown graph protocol: {}'.format(graph_options.graph_protocol))
160
161 ep.row_factory = row_factory
162 query = DseGraph.query_from_traversal(bytecode, graph_options.graph_protocol, context)
163
164 return query, ep
165
166 @staticmethod
167 def _handle_query_results(result_set, gremlin_future):
168 try:
169 gremlin_future.set_result(
170 RemoteTraversal(DSESessionRemoteGraphConnection._traversers_generator(result_set), TraversalSideEffects())
171 )
172 except Exception as e:
173 gremlin_future.set_exception(e)
174
175 @staticmethod
176 def _handle_query_error(response, gremlin_future):
177 gremlin_future.set_exception(response)
178
179 def submit(self, bytecode):
180 # the only reason I don't use submitAsync here
181 # is to avoid an unuseful future wrap
182 query, ep = self._prepare_query(bytecode)
183
184 traversers = self.session.execute_graph(query, execution_profile=ep)
185 return RemoteTraversal(self._traversers_generator(traversers), TraversalSideEffects())
186
187 def submitAsync(self, bytecode):
188 query, ep = self._prepare_query(bytecode)
189
190 # to be compatible with gremlinpython, we need to return a concurrent.futures.Future
191 gremlin_future = Future()
192 response_future = self.session.execute_graph_async(query, execution_profile=ep)
193 response_future.add_callback(self._handle_query_results, gremlin_future)
194 response_future.add_errback(self._handle_query_error, gremlin_future)
195
196 return gremlin_future
197
198 def __str__(self):
199 return "<DSESessionRemoteGraphConnection: graph_name='{0}'>".format(self.graph_name)
200
201 __repr__ = __str__
202
203
204 class DseGraph(object):
205 """
206 Dse Graph utility class for GraphTraversal construction and execution.
207 """
208
209 DSE_GRAPH_QUERY_LANGUAGE = 'bytecode-json'
210 """
211 Graph query language, Default is 'bytecode-json' (GraphSON).
212 """
213
214 DSE_GRAPH_QUERY_PROTOCOL = GraphProtocol.GRAPHSON_2_0
215 """
216 Graph query language, Default is GraphProtocol.GRAPHSON_2_0.
217 """
218
219 @staticmethod
220 def query_from_traversal(traversal, graph_protocol=DSE_GRAPH_QUERY_PROTOCOL, context=None):
221 """
222 From a GraphTraversal, return a query string based on the language specified in `DseGraph.DSE_GRAPH_QUERY_LANGUAGE`.
223
224 :param traversal: The GraphTraversal object
225 :param graph_protocol: The graph protocol. Default is `DseGraph.DSE_GRAPH_QUERY_PROTOCOL`.
226 :param context: The dict of the serialization context, needed for GraphSON3 (tuple, udt).
227 e.g: {'cluster': cluster, 'graph_name': name}
228 """
229
230 if isinstance(traversal, GraphTraversal):
231 for strategy in traversal.traversal_strategies.traversal_strategies:
232 rc = strategy.remote_connection
233 if (isinstance(rc, DSESessionRemoteGraphConnection) and
234 rc.session or rc.graph_name or rc.execution_profile):
235 log.warning("GraphTraversal session, graph_name and execution_profile are "
236 "only taken into account when executed with TinkerPop.")
237
238 return _query_from_traversal(traversal, graph_protocol, context)
239
240 @staticmethod
241 def traversal_source(session=None, graph_name=None, execution_profile=EXEC_PROFILE_GRAPH_DEFAULT,
242 traversal_class=None):
243 """
244 Returns a TinkerPop GraphTraversalSource binded to the session and graph_name if provided.
245
246 :param session: (Optional) A DSE session
247 :param graph_name: (Optional) DSE Graph name
248 :param execution_profile: (Optional) Execution profile for traversal queries. Default is set to `EXEC_PROFILE_GRAPH_DEFAULT`.
249 :param traversal_class: (Optional) The GraphTraversalSource class to use (DSL).
250
251 .. code-block:: python
252
253 from cassandra.cluster import Cluster
254 from cassandra.datastax.graph.fluent import DseGraph
255
256 c = Cluster()
257 session = c.connect()
258
259 g = DseGraph.traversal_source(session, 'my_graph')
260 print(g.V().valueMap().toList())
261
262 """
263
264 graph = Graph()
265 traversal_source = graph.traversal(traversal_class)
266
267 if session:
268 traversal_source = traversal_source.withRemote(
269 DSESessionRemoteGraphConnection(session, graph_name, execution_profile))
270
271 return traversal_source
272
273 @staticmethod
274 def create_execution_profile(graph_name, graph_protocol=DSE_GRAPH_QUERY_PROTOCOL, **kwargs):
275 """
276 Creates an ExecutionProfile for GraphTraversal execution. You need to register that execution profile to the
277 cluster by using `cluster.add_execution_profile`.
278
279 :param graph_name: The graph name
280 :param graph_protocol: (Optional) The graph protocol, default is `DSE_GRAPH_QUERY_PROTOCOL`.
281 """
282
283 if graph_protocol == GraphProtocol.GRAPHSON_2_0:
284 row_factory = dse_graphson2_traversal_row_factory
285 elif graph_protocol == GraphProtocol.GRAPHSON_3_0:
286 row_factory = dse_graphson3_traversal_row_factory
287 else:
288 raise ValueError('Unknown graph protocol: {}'.format(graph_protocol))
289
290 ep = GraphExecutionProfile(row_factory=row_factory,
291 graph_options=GraphOptions(graph_name=graph_name,
292 graph_language=DseGraph.DSE_GRAPH_QUERY_LANGUAGE,
293 graph_protocol=graph_protocol),
294 **kwargs)
295 return ep
296
297 @staticmethod
298 def batch(*args, **kwargs):
299 """
300 Returns the :class:`cassandra.datastax.graph.fluent.query.TraversalBatch` object allowing to
301 execute multiple traversals in the same transaction.
302 """
303 return _DefaultTraversalBatch(*args, **kwargs)