| 1 |
from ..helpers import quote_string |
| 2 |
from .node import Node |
| 3 |
|
| 4 |
|
| 5 |
class Edge: |
| 6 |
""" |
| 7 |
An edge connecting two nodes. |
| 8 |
""" |
| 9 |
|
| 10 |
def __init__(self, src_node, relation, dest_node, edge_id=None, properties=None): |
| 11 |
""" |
| 12 |
Create a new edge. |
| 13 |
""" |
| 14 |
if src_node is None or dest_node is None: |
| 15 |
# NOTE(bors-42): It makes sense to change AssertionError to |
| 16 |
# ValueError here |
| 17 |
raise AssertionError("Both src_node & dest_node must be provided") |
| 18 |
|
| 19 |
self.id = edge_id |
| 20 |
self.relation = relation or "" |
| 21 |
self.properties = properties or {} |
| 22 |
self.src_node = src_node |
| 23 |
self.dest_node = dest_node |
| 24 |
|
| 25 |
def to_string(self): |
| 26 |
res = "" |
| 27 |
if self.properties: |
| 28 |
props = ",".join( |
| 29 |
key + ":" + str(quote_string(val)) |
| 30 |
for key, val in sorted(self.properties.items()) |
| 31 |
) |
| 32 |
res += "{" + props + "}" |
| 33 |
|
| 34 |
return res |
| 35 |
|
| 36 |
def __str__(self): |
| 37 |
# Source node. |
| 38 |
if isinstance(self.src_node, Node): |
| 39 |
res = str(self.src_node) |
| 40 |
else: |
| 41 |
res = "()" |
| 42 |
|
| 43 |
# Edge |
| 44 |
res += "-[" |
| 45 |
if self.relation: |
| 46 |
res += ":" + self.relation |
| 47 |
if self.properties: |
| 48 |
props = ",".join( |
| 49 |
key + ":" + str(quote_string(val)) |
| 50 |
for key, val in sorted(self.properties.items()) |
| 51 |
) |
| 52 |
res += "{" + props + "}" |
| 53 |
res += "]->" |
| 54 |
|
| 55 |
# Dest node. |
| 56 |
if isinstance(self.dest_node, Node): |
| 57 |
res += str(self.dest_node) |
| 58 |
else: |
| 59 |
res += "()" |
| 60 |
|
| 61 |
return res |
| 62 |
|
| 63 |
def __eq__(self, rhs): |
| 64 |
# Type checking |
| 65 |
if not isinstance(rhs, Edge): |
| 66 |
return False |
| 67 |
|
| 68 |
# Quick positive check, if both IDs are set. |
| 69 |
if self.id is not None and rhs.id is not None and self.id == rhs.id: |
| 70 |
return True |
| 71 |
|
| 72 |
# Source and destination nodes should match. |
| 73 |
if self.src_node != rhs.src_node: |
| 74 |
return False |
| 75 |
|
| 76 |
if self.dest_node != rhs.dest_node: |
| 77 |
return False |
| 78 |
|
| 79 |
# Relation should match. |
| 80 |
if self.relation != rhs.relation: |
| 81 |
return False |
| 82 |
|
| 83 |
# Quick check for number of properties. |
| 84 |
if len(self.properties) != len(rhs.properties): |
| 85 |
return False |
| 86 |
|
| 87 |
# Compare properties. |
| 88 |
if self.properties != rhs.properties: |
| 89 |
return False |
| 90 |
|
| 91 |
return True |