| 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 json |
| 16 |
from warnings import warn |
| 17 |
|
| 18 |
from cassandra import ConsistencyLevel |
| 19 |
from cassandra.query import Statement, SimpleStatement |
| 20 |
from cassandra.datastax.graph.types import Vertex, Edge, Path, VertexProperty |
| 21 |
from cassandra.datastax.graph.graphson import GraphSON2Reader, GraphSON3Reader |
| 22 |
|
| 23 |
|
| 24 |
__all__ = [ |
| 25 |
'GraphProtocol', 'GraphOptions', 'GraphStatement', 'SimpleGraphStatement', |
| 26 |
'single_object_row_factory', 'graph_result_row_factory', 'graph_object_row_factory', |
| 27 |
'graph_graphson2_row_factory', 'Result', 'graph_graphson3_row_factory' |
| 28 |
] |
| 29 |
|
| 30 |
# (attr, description, server option) |
| 31 |
_graph_options = ( |
| 32 |
('graph_name', 'name of the targeted graph.', 'graph-name'), |
| 33 |
('graph_source', 'choose the graph traversal source, configured on the server side.', 'graph-source'), |
| 34 |
('graph_language', 'the language used in the queries (default "gremlin-groovy")', 'graph-language'), |
| 35 |
('graph_protocol', 'the graph protocol that the server should use for query results (default "graphson-1-0")', 'graph-results'), |
| 36 |
('graph_read_consistency_level', '''read `cassandra.ConsistencyLevel <http://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/#cassandra.ConsistencyLevel>`_ for graph queries (if distinct from session default). |
| 37 |
Setting this overrides the native `Statement.consistency_level <http://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/query/#cassandra.query.Statement.consistency_level>`_ for read operations from Cassandra persistence''', 'graph-read-consistency'), |
| 38 |
('graph_write_consistency_level', '''write `cassandra.ConsistencyLevel <http://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/#cassandra.ConsistencyLevel>`_ for graph queries (if distinct from session default). |
| 39 |
Setting this overrides the native `Statement.consistency_level <http://docs.datastax.com/en/developer/python-driver/latest/api/cassandra/query/#cassandra.query.Statement.consistency_level>`_ for write operations to Cassandra persistence.''', 'graph-write-consistency') |
| 40 |
) |
| 41 |
_graph_option_names = tuple(option[0] for option in _graph_options) |
| 42 |
|
| 43 |
# this is defined by the execution profile attribute, not in graph options |
| 44 |
_request_timeout_key = 'request-timeout' |
| 45 |
|
| 46 |
|
| 47 |
class GraphProtocol(object): |
| 48 |
|
| 49 |
GRAPHSON_1_0 = b'graphson-1.0' |
| 50 |
""" |
| 51 |
GraphSON1 |
| 52 |
""" |
| 53 |
|
| 54 |
GRAPHSON_2_0 = b'graphson-2.0' |
| 55 |
""" |
| 56 |
GraphSON2 |
| 57 |
""" |
| 58 |
|
| 59 |
GRAPHSON_3_0 = b'graphson-3.0' |
| 60 |
""" |
| 61 |
GraphSON3 |
| 62 |
""" |
| 63 |
|
| 64 |
|
| 65 |
class GraphOptions(object): |
| 66 |
""" |
| 67 |
Options for DSE Graph Query handler. |
| 68 |
""" |
| 69 |
# See _graph_options map above for notes on valid options |
| 70 |
|
| 71 |
DEFAULT_GRAPH_PROTOCOL = GraphProtocol.GRAPHSON_1_0 |
| 72 |
DEFAULT_GRAPH_LANGUAGE = b'gremlin-groovy' |
| 73 |
|
| 74 |
def __init__(self, **kwargs): |
| 75 |
self._graph_options = {} |
| 76 |
kwargs.setdefault('graph_source', 'g') |
| 77 |
kwargs.setdefault('graph_language', GraphOptions.DEFAULT_GRAPH_LANGUAGE) |
| 78 |
for attr, value in kwargs.items(): |
| 79 |
if attr not in _graph_option_names: |
| 80 |
warn("Unknown keyword argument received for GraphOptions: {0}".format(attr)) |
| 81 |
setattr(self, attr, value) |
| 82 |
|
| 83 |
def copy(self): |
| 84 |
new_options = GraphOptions() |
| 85 |
new_options._graph_options = self._graph_options.copy() |
| 86 |
return new_options |
| 87 |
|
| 88 |
def update(self, options): |
| 89 |
self._graph_options.update(options._graph_options) |
| 90 |
|
| 91 |
def get_options_map(self, other_options=None): |
| 92 |
""" |
| 93 |
Returns a map for these options updated with other options, |
| 94 |
and mapped to graph payload types. |
| 95 |
""" |
| 96 |
options = self._graph_options.copy() |
| 97 |
if other_options: |
| 98 |
options.update(other_options._graph_options) |
| 99 |
|
| 100 |
# cls are special-cased so they can be enums in the API, and names in the protocol |
| 101 |
for cl in ('graph-write-consistency', 'graph-read-consistency'): |
| 102 |
cl_enum = options.get(cl) |
| 103 |
if cl_enum is not None: |
| 104 |
options[cl] = ConsistencyLevel.value_to_name[cl_enum].encode() |
| 105 |
return options |
| 106 |
|
| 107 |
def set_source_default(self): |
| 108 |
""" |
| 109 |
Sets ``graph_source`` to the server-defined default traversal source ('default') |
| 110 |
""" |
| 111 |
self.graph_source = 'default' |
| 112 |
|
| 113 |
def set_source_analytics(self): |
| 114 |
""" |
| 115 |
Sets ``graph_source`` to the server-defined analytic traversal source ('a') |
| 116 |
""" |
| 117 |
self.graph_source = 'a' |
| 118 |
|
| 119 |
def set_source_graph(self): |
| 120 |
""" |
| 121 |
Sets ``graph_source`` to the server-defined graph traversal source ('g') |
| 122 |
""" |
| 123 |
self.graph_source = 'g' |
| 124 |
|
| 125 |
def set_graph_protocol(self, protocol): |
| 126 |
""" |
| 127 |
Sets ``graph_protocol`` as server graph results format (See :class:`cassandra.datastax.graph.GraphProtocol`) |
| 128 |
""" |
| 129 |
self.graph_protocol = protocol |
| 130 |
|
| 131 |
@property |
| 132 |
def is_default_source(self): |
| 133 |
return self.graph_source in (b'default', None) |
| 134 |
|
| 135 |
@property |
| 136 |
def is_analytics_source(self): |
| 137 |
""" |
| 138 |
True if ``graph_source`` is set to the server-defined analytics traversal source ('a') |
| 139 |
""" |
| 140 |
return self.graph_source == b'a' |
| 141 |
|
| 142 |
@property |
| 143 |
def is_graph_source(self): |
| 144 |
""" |
| 145 |
True if ``graph_source`` is set to the server-defined graph traversal source ('g') |
| 146 |
""" |
| 147 |
return self.graph_source == b'g' |
| 148 |
|
| 149 |
|
| 150 |
for opt in _graph_options: |
| 151 |
|
| 152 |
def get(self, key=opt[2]): |
| 153 |
return self._graph_options.get(key) |
| 154 |
|
| 155 |
def set(self, value, key=opt[2]): |
| 156 |
if value is not None: |
| 157 |
# normalize text here so it doesn't have to be done every time we get options map |
| 158 |
if isinstance(value, str): |
| 159 |
value = value.encode() |
| 160 |
self._graph_options[key] = value |
| 161 |
else: |
| 162 |
self._graph_options.pop(key, None) |
| 163 |
|
| 164 |
def delete(self, key=opt[2]): |
| 165 |
self._graph_options.pop(key, None) |
| 166 |
|
| 167 |
setattr(GraphOptions, opt[0], property(get, set, delete, opt[1])) |
| 168 |
|
| 169 |
|
| 170 |
class GraphStatement(Statement): |
| 171 |
""" An abstract class representing a graph query.""" |
| 172 |
|
| 173 |
@property |
| 174 |
def query(self): |
| 175 |
raise NotImplementedError() |
| 176 |
|
| 177 |
def __str__(self): |
| 178 |
return u'<GraphStatement query="{0}">'.format(self.query) |
| 179 |
__repr__ = __str__ |
| 180 |
|
| 181 |
|
| 182 |
class SimpleGraphStatement(GraphStatement, SimpleStatement): |
| 183 |
""" |
| 184 |
Simple graph statement for :meth:`.Session.execute_graph`. |
| 185 |
Takes the same parameters as :class:`.SimpleStatement`. |
| 186 |
""" |
| 187 |
@property |
| 188 |
def query(self): |
| 189 |
return self._query_string |
| 190 |
|
| 191 |
|
| 192 |
def single_object_row_factory(column_names, rows): |
| 193 |
""" |
| 194 |
returns the JSON string value of graph results |
| 195 |
""" |
| 196 |
return [row[0] for row in rows] |
| 197 |
|
| 198 |
|
| 199 |
def graph_result_row_factory(column_names, rows): |
| 200 |
""" |
| 201 |
Returns a :class:`Result <cassandra.datastax.graph.Result>` object that can load graph results and produce specific types. |
| 202 |
The Result JSON is deserialized and unpacked from the top-level 'result' dict. |
| 203 |
""" |
| 204 |
return [Result(json.loads(row[0])['result']) for row in rows] |
| 205 |
|
| 206 |
|
| 207 |
def graph_object_row_factory(column_names, rows): |
| 208 |
""" |
| 209 |
Like :func:`~.graph_result_row_factory`, except known element types (:class:`~.Vertex`, :class:`~.Edge`) are |
| 210 |
converted to their simplified objects. Some low-level metadata is shed in this conversion. Unknown result types are |
| 211 |
still returned as :class:`Result <cassandra.datastax.graph.Result>`. |
| 212 |
""" |
| 213 |
return _graph_object_sequence(json.loads(row[0])['result'] for row in rows) |
| 214 |
|
| 215 |
|
| 216 |
def _graph_object_sequence(objects): |
| 217 |
for o in objects: |
| 218 |
res = Result(o) |
| 219 |
if isinstance(o, dict): |
| 220 |
typ = res.value.get('type') |
| 221 |
if typ == 'vertex': |
| 222 |
res = res.as_vertex() |
| 223 |
elif typ == 'edge': |
| 224 |
res = res.as_edge() |
| 225 |
yield res |
| 226 |
|
| 227 |
|
| 228 |
class _GraphSONContextRowFactory(object): |
| 229 |
graphson_reader_class = None |
| 230 |
graphson_reader_kwargs = None |
| 231 |
|
| 232 |
def __init__(self, cluster): |
| 233 |
context = {'cluster': cluster} |
| 234 |
kwargs = self.graphson_reader_kwargs or {} |
| 235 |
self.graphson_reader = self.graphson_reader_class(context, **kwargs) |
| 236 |
|
| 237 |
def __call__(self, column_names, rows): |
| 238 |
return [self.graphson_reader.read(row[0])['result'] for row in rows] |
| 239 |
|
| 240 |
|
| 241 |
class _GraphSON2RowFactory(_GraphSONContextRowFactory): |
| 242 |
"""Row factory to deserialize GraphSON2 results.""" |
| 243 |
graphson_reader_class = GraphSON2Reader |
| 244 |
|
| 245 |
|
| 246 |
class _GraphSON3RowFactory(_GraphSONContextRowFactory): |
| 247 |
"""Row factory to deserialize GraphSON3 results.""" |
| 248 |
graphson_reader_class = GraphSON3Reader |
| 249 |
|
| 250 |
|
| 251 |
graph_graphson2_row_factory = _GraphSON2RowFactory |
| 252 |
graph_graphson3_row_factory = _GraphSON3RowFactory |
| 253 |
|
| 254 |
|
| 255 |
class Result(object): |
| 256 |
""" |
| 257 |
Represents deserialized graph results. |
| 258 |
Property and item getters are provided for convenience. |
| 259 |
""" |
| 260 |
|
| 261 |
value = None |
| 262 |
""" |
| 263 |
Deserialized value from the result |
| 264 |
""" |
| 265 |
|
| 266 |
def __init__(self, value): |
| 267 |
self.value = value |
| 268 |
|
| 269 |
def __getattr__(self, attr): |
| 270 |
if not isinstance(self.value, dict): |
| 271 |
raise ValueError("Value cannot be accessed as a dict") |
| 272 |
|
| 273 |
if attr in self.value: |
| 274 |
return self.value[attr] |
| 275 |
|
| 276 |
raise AttributeError("Result has no top-level attribute %r" % (attr,)) |
| 277 |
|
| 278 |
def __getitem__(self, item): |
| 279 |
if isinstance(self.value, dict) and isinstance(item, str): |
| 280 |
return self.value[item] |
| 281 |
elif isinstance(self.value, list) and isinstance(item, int): |
| 282 |
return self.value[item] |
| 283 |
else: |
| 284 |
raise ValueError("Result cannot be indexed by %r" % (item,)) |
| 285 |
|
| 286 |
def __str__(self): |
| 287 |
return str(self.value) |
| 288 |
|
| 289 |
def __repr__(self): |
| 290 |
return "%s(%r)" % (Result.__name__, self.value) |
| 291 |
|
| 292 |
def __eq__(self, other): |
| 293 |
return self.value == other.value |
| 294 |
|
| 295 |
def as_vertex(self): |
| 296 |
""" |
| 297 |
Return a :class:`Vertex` parsed from this result |
| 298 |
|
| 299 |
Raises TypeError if parsing fails (i.e. the result structure is not valid). |
| 300 |
""" |
| 301 |
try: |
| 302 |
return Vertex(self.id, self.label, self.type, self.value.get('properties', {})) |
| 303 |
except (AttributeError, ValueError, TypeError): |
| 304 |
raise TypeError("Could not create Vertex from %r" % (self,)) |
| 305 |
|
| 306 |
def as_edge(self): |
| 307 |
""" |
| 308 |
Return a :class:`Edge` parsed from this result |
| 309 |
|
| 310 |
Raises TypeError if parsing fails (i.e. the result structure is not valid). |
| 311 |
""" |
| 312 |
try: |
| 313 |
return Edge(self.id, self.label, self.type, self.value.get('properties', {}), |
| 314 |
self.inV, self.inVLabel, self.outV, self.outVLabel) |
| 315 |
except (AttributeError, ValueError, TypeError): |
| 316 |
raise TypeError("Could not create Edge from %r" % (self,)) |
| 317 |
|
| 318 |
def as_path(self): |
| 319 |
""" |
| 320 |
Return a :class:`Path` parsed from this result |
| 321 |
|
| 322 |
Raises TypeError if parsing fails (i.e. the result structure is not valid). |
| 323 |
""" |
| 324 |
try: |
| 325 |
return Path(self.labels, self.objects) |
| 326 |
except (AttributeError, ValueError, TypeError): |
| 327 |
raise TypeError("Could not create Path from %r" % (self,)) |
| 328 |
|
| 329 |
def as_vertex_property(self): |
| 330 |
return VertexProperty(self.value.get('label'), self.value.get('value'), self.value.get('properties', {})) |