|
| 1 | +import re |
| 2 | +import uuid |
| 3 | +from typing import Any, Optional |
| 4 | + |
| 5 | +from neo4j_viz import Node, Relationship, VisualizationGraph |
| 6 | + |
| 7 | + |
| 8 | +def _parse_value(value_str: str) -> Any: |
| 9 | + value_str = value_str.strip() |
| 10 | + if not value_str: |
| 11 | + return None |
| 12 | + |
| 13 | + # Parse object |
| 14 | + if value_str.startswith("{") and value_str.endswith("}"): |
| 15 | + inner = value_str[1:-1].strip() |
| 16 | + result = {} |
| 17 | + depth = 0 |
| 18 | + in_string = None |
| 19 | + start_idx = 0 |
| 20 | + for i, ch in enumerate(inner): |
| 21 | + if in_string is None: |
| 22 | + if ch in ["'", '"']: |
| 23 | + in_string = ch |
| 24 | + elif ch in ["{", "["]: |
| 25 | + depth += 1 |
| 26 | + elif ch in ["}", "]"]: |
| 27 | + depth -= 1 |
| 28 | + elif ch == "," and depth == 0: |
| 29 | + segment = inner[start_idx:i].strip() |
| 30 | + if ":" not in segment: |
| 31 | + return None |
| 32 | + k, v = segment.split(":", 1) |
| 33 | + k = k.strip().strip("'\"") |
| 34 | + result[k] = _parse_value(v) |
| 35 | + start_idx = i + 1 |
| 36 | + else: |
| 37 | + if ch == in_string: |
| 38 | + in_string = None |
| 39 | + if inner[start_idx:]: |
| 40 | + segment = inner[start_idx:].strip() |
| 41 | + if ":" not in segment: |
| 42 | + return None |
| 43 | + k, v = segment.split(":", 1) |
| 44 | + k = k.strip().strip("'\"") |
| 45 | + result[k] = _parse_value(v) |
| 46 | + return result |
| 47 | + |
| 48 | + # Parse list |
| 49 | + if value_str.startswith("[") and value_str.endswith("]"): |
| 50 | + inner = value_str[1:-1].strip() |
| 51 | + items = [] |
| 52 | + depth = 0 |
| 53 | + in_string = None |
| 54 | + start_idx = 0 |
| 55 | + for i, ch in enumerate(inner): |
| 56 | + if in_string is None: |
| 57 | + if ch in ["'", '"']: |
| 58 | + in_string = ch |
| 59 | + elif ch in ["{", "["]: |
| 60 | + depth += 1 |
| 61 | + elif ch in ["}", "]"]: |
| 62 | + depth -= 1 |
| 63 | + elif ch == "," and depth == 0: |
| 64 | + items.append(_parse_value(inner[start_idx:i])) |
| 65 | + start_idx = i + 1 |
| 66 | + else: |
| 67 | + if ch == in_string: |
| 68 | + in_string = None |
| 69 | + if inner[start_idx:]: |
| 70 | + items.append(_parse_value(inner[start_idx:])) |
| 71 | + return items |
| 72 | + |
| 73 | + # Parse boolean, float, int, or string |
| 74 | + if re.match(r"^-?\d+$", value_str): |
| 75 | + return int(value_str) |
| 76 | + if re.match(r"^-?\d+\.\d+$", value_str): |
| 77 | + return float(value_str) |
| 78 | + if value_str.lower() == "true": |
| 79 | + return True |
| 80 | + if value_str.lower() == "false": |
| 81 | + return False |
| 82 | + if value_str.lower() == "null": |
| 83 | + return None |
| 84 | + return value_str.strip("'\"") |
| 85 | + |
| 86 | + |
| 87 | +def _get_snippet(q: str, idx: int, context: int = 15) -> str: |
| 88 | + start = max(0, idx - context) |
| 89 | + end = min(len(q), idx + context) |
| 90 | + return q[start:end].replace("\n", " ") |
| 91 | + |
| 92 | + |
| 93 | +def from_gql_create(query: str) -> VisualizationGraph: |
| 94 | + """ |
| 95 | + Parse a GQL CREATE query and return a VisualizationGraph object representing the graph it creates. |
| 96 | +
|
| 97 | + Please note that this function is not a full GQL parser, it only handles CREATE queries that do not contain |
| 98 | + other clauses like MATCH, WHERE, RETURN, etc, or any Cypher function calls. |
| 99 | + It also does not handle all possible GQL syntax, but it should work for most common cases. |
| 100 | +
|
| 101 | + Parameters |
| 102 | + ---------- |
| 103 | + query : str |
| 104 | + The GQL CREATE query to parse |
| 105 | + """ |
| 106 | + |
| 107 | + query = query.strip() |
| 108 | + # Case-insensitive check that 'CREATE' is the first non-whitespace token |
| 109 | + if not re.match(r"(?i)^create\b", query): |
| 110 | + raise ValueError("Query must begin with 'CREATE' (case insensitive).") |
| 111 | + |
| 112 | + def parse_prop_str(prop_str: str, prop_start: int, props: dict[str, Any]) -> None: |
| 113 | + depth = 0 |
| 114 | + in_string = None |
| 115 | + start_idx = 0 |
| 116 | + for i, ch in enumerate(prop_str): |
| 117 | + if in_string is None: |
| 118 | + if ch in ["'", '"']: |
| 119 | + in_string = ch |
| 120 | + elif ch in ["{", "["]: |
| 121 | + depth += 1 |
| 122 | + elif ch in ["}", "]"]: |
| 123 | + depth -= 1 |
| 124 | + elif ch == "," and depth == 0: |
| 125 | + pair = prop_str[start_idx:i].strip() |
| 126 | + if ":" not in pair: |
| 127 | + snippet = _get_snippet(query, prop_start + start_idx) |
| 128 | + raise ValueError(f"Property syntax error near: `{snippet}`.") |
| 129 | + k, v = pair.split(":", 1) |
| 130 | + k = k.strip().strip("'\"") |
| 131 | + props[k] = _parse_value(v) |
| 132 | + start_idx = i + 1 |
| 133 | + else: |
| 134 | + if ch == in_string: |
| 135 | + in_string = None |
| 136 | + if prop_str[start_idx:]: |
| 137 | + pair = prop_str[start_idx:].strip() |
| 138 | + if ":" not in pair: |
| 139 | + snippet = _get_snippet(query, prop_start + start_idx) |
| 140 | + raise ValueError(f"Property syntax error near: `{snippet}`.") |
| 141 | + k, v = pair.split(":", 1) |
| 142 | + k = k.strip().strip("'\"") |
| 143 | + props[k] = _parse_value(v) |
| 144 | + |
| 145 | + def parse_labels_and_props(s: str) -> tuple[Optional[str], dict[str, Any]]: |
| 146 | + props = {} |
| 147 | + prop_match = re.search(r"\{(.*)\}", s) |
| 148 | + prop_str = "" |
| 149 | + if prop_match: |
| 150 | + prop_str = prop_match.group(1) |
| 151 | + prop_start = query.index(prop_str, query.index(s)) |
| 152 | + s = s[: prop_match.start()].strip() |
| 153 | + alias_labels = re.split(r"[:&]", s) |
| 154 | + raw_alias = alias_labels[0].strip() |
| 155 | + final_alias = raw_alias if raw_alias else None |
| 156 | + |
| 157 | + label_list = [lbl.strip() for lbl in alias_labels[1:]] |
| 158 | + props["__labels"] = sorted(label_list) |
| 159 | + |
| 160 | + if prop_str: |
| 161 | + parse_prop_str(prop_str, prop_start, props) |
| 162 | + return final_alias, props |
| 163 | + |
| 164 | + nodes = [] |
| 165 | + relationships = [] |
| 166 | + alias_to_id = {} |
| 167 | + anonymous_count = 0 |
| 168 | + |
| 169 | + query = re.sub(r"(?i)^create\s*", "", query, count=1).rstrip(";").strip() |
| 170 | + parts = [] |
| 171 | + bracket_level = 0 |
| 172 | + current: list[str] = [] |
| 173 | + for i, char in enumerate(query): |
| 174 | + if char == "(": |
| 175 | + bracket_level += 1 |
| 176 | + elif char == ")": |
| 177 | + bracket_level -= 1 |
| 178 | + if bracket_level < 0: |
| 179 | + snippet = _get_snippet(query, i) |
| 180 | + raise ValueError(f"Unbalanced parentheses near: `{snippet}`.") |
| 181 | + if char == "," and bracket_level == 0: |
| 182 | + parts.append("".join(current).strip()) |
| 183 | + current = [] |
| 184 | + else: |
| 185 | + current.append(char) |
| 186 | + parts.append("".join(current).strip()) |
| 187 | + if bracket_level != 0: |
| 188 | + snippet = _get_snippet(query, len(query) - 1) |
| 189 | + raise ValueError(f"Unbalanced parentheses near: `{snippet}`.") |
| 190 | + |
| 191 | + node_pattern = re.compile(r"^\(([^)]+)\)$") |
| 192 | + rel_pattern = re.compile(r"^\(([^)]+)\)-\s*\[\s*:(\w+)\s*(\{[^}]*\})?\s*\]->\(([^)]+)\)$") |
| 193 | + |
| 194 | + for part in parts: |
| 195 | + node_m = node_pattern.match(part) |
| 196 | + if node_m: |
| 197 | + alias_labels_props = node_m.group(1).strip() |
| 198 | + alias, props = parse_labels_and_props(alias_labels_props) |
| 199 | + if not alias: |
| 200 | + alias = f"_anon_{anonymous_count}" |
| 201 | + anonymous_count += 1 |
| 202 | + if alias not in alias_to_id: |
| 203 | + alias_to_id[alias] = str(uuid.uuid4()) |
| 204 | + nodes.append(Node(id=alias_to_id[alias], properties=props)) |
| 205 | + else: |
| 206 | + rel_m = rel_pattern.match(part) |
| 207 | + if rel_m: |
| 208 | + left_node = rel_m.group(1).strip() |
| 209 | + rel_type = rel_m.group(2).replace(":", "").strip() |
| 210 | + right_node = rel_m.group(4).strip() |
| 211 | + |
| 212 | + left_alias, left_props = parse_labels_and_props(left_node) |
| 213 | + if not left_alias or left_alias not in alias_to_id: |
| 214 | + snippet = _get_snippet(query, query.index(left_node)) |
| 215 | + raise ValueError(f"Relationship references unknown node alias: '{left_alias}' near: `{snippet}`.") |
| 216 | + |
| 217 | + right_alias, right_props = parse_labels_and_props(right_node) |
| 218 | + if not right_alias or right_alias not in alias_to_id: |
| 219 | + snippet = _get_snippet(query, query.index(right_node)) |
| 220 | + raise ValueError(f"Relationship references unknown node alias: '{right_alias}' near: `{snippet}`.") |
| 221 | + |
| 222 | + rel_id = str(uuid.uuid4()) |
| 223 | + rel_props = {"__type": rel_type} |
| 224 | + rel_props_str = rel_m.group(3) or "" |
| 225 | + if rel_props_str: |
| 226 | + inner_str = rel_props_str.strip("{}").strip() |
| 227 | + prop_start = query.index(inner_str, query.index(inner_str)) |
| 228 | + parse_prop_str(inner_str, prop_start, rel_props) |
| 229 | + |
| 230 | + relationships.append( |
| 231 | + Relationship( |
| 232 | + id=rel_id, |
| 233 | + source=alias_to_id[left_alias], |
| 234 | + target=alias_to_id[right_alias], |
| 235 | + properties=rel_props, |
| 236 | + ) |
| 237 | + ) |
| 238 | + else: |
| 239 | + snippet = part[:30] |
| 240 | + raise ValueError(f"Invalid element in CREATE near: `{snippet}`.") |
| 241 | + |
| 242 | + return VisualizationGraph(nodes=nodes, relationships=relationships) |
0 commit comments