From f9e30304d75b6306cce094f012758993d3cb5530 Mon Sep 17 00:00:00 2001 From: lamost423 <117018962+lamost423@users.noreply.github.com> Date: Wed, 25 Mar 2026 22:28:27 +0800 Subject: [PATCH] fix: sanitize hyphens in Neo4j Cypher relationship names (#4154) --- mem0/memory/utils.py | 1 + tests/memory/test_neo4j_cypher_syntax.py | 26 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/mem0/memory/utils.py b/mem0/memory/utils.py index 0d2cb6749..e0581a09c 100644 --- a/mem0/memory/utils.py +++ b/mem0/memory/utils.py @@ -249,6 +249,7 @@ def sanitize_relationship_for_cypher(relationship) -> str: "}": "_rbrace_", "<": "_langle_", ">": "_rangle_", + "-": "_", } # Apply replacements and clean up diff --git a/tests/memory/test_neo4j_cypher_syntax.py b/tests/memory/test_neo4j_cypher_syntax.py index 45eab377a..53fe0a0de 100644 --- a/tests/memory/test_neo4j_cypher_syntax.py +++ b/tests/memory/test_neo4j_cypher_syntax.py @@ -1,6 +1,32 @@ import os from unittest.mock import Mock, patch +from mem0.memory.utils import sanitize_relationship_for_cypher + + +class TestSanitizeRelationshipForCypher: + """Test that relationship names are properly sanitized for Neo4j Cypher queries.""" + + def test_hyphen_replaced_with_underscore(self): + """Hyphens in relationship names cause Neo4j CypherSyntaxError and must be replaced.""" + assert sanitize_relationship_for_cypher("manages_via_low-cost_models") == "manages_via_low_cost_models" + + def test_multiple_hyphens(self): + assert sanitize_relationship_for_cypher("co-owns-with") == "co_owns_with" + + def test_no_special_chars_unchanged(self): + assert sanitize_relationship_for_cypher("works_at") == "works_at" + + def test_spaces_not_handled_here(self): + """Spaces are replaced upstream before this function is called.""" + # sanitize only handles special chars, spaces are handled by the caller + result = sanitize_relationship_for_cypher("has relationship") + assert result == "has relationship" + + def test_existing_chars_still_sanitized(self): + assert "_slash_" in sanitize_relationship_for_cypher("read/write") + assert "_at_" in sanitize_relationship_for_cypher("user@company") + class TestNeo4jCypherSyntaxFix: """Test that Neo4j Cypher syntax fixes work correctly"""