Skip to content

Commit c753a74

Browse files
feat: graph_name validation on graph store construction (#162)
* chore: adding graph_name validation on graph store construction * test: add tests for invalid graph name * chore: format fix --------- Co-authored-by: rahul2393 <irahul@google.com>
1 parent a517e6e commit c753a74

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/langchain_google_spanner/graph_store.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ def client_with_user_agent(
132132
class GraphDocumentUtility:
133133
"""Utilities to process graph documents."""
134134

135+
@staticmethod
136+
def is_valid_identifier(s: str) -> bool:
137+
return re.match(r"^[a-z][a-z0-9_]{0,127}$", s, re.IGNORECASE) is not None
138+
135139
@staticmethod
136140
def to_identifier(s: str) -> str:
137141
return "`" + s + "`"
@@ -780,7 +784,15 @@ def __init__(
780784
properties as static;
781785
static_edge_properties: in flexible schema, treat these edge
782786
properties as static.
787+
788+
Raises:
789+
ValueError: An error occured initializing graph schema.
783790
"""
791+
if not GraphDocumentUtility.is_valid_identifier(graph_name):
792+
raise ValueError(
793+
"Graph name `{}` is not a valid identifier".format(graph_name)
794+
)
795+
784796
self.graph_name: str = graph_name
785797
self.nodes: CaseInsensitiveDict[ElementSchema] = CaseInsensitiveDict({})
786798
self.edges: CaseInsensitiveDict[ElementSchema] = CaseInsensitiveDict({})

tests/integration/test_spanner_graph_store.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,3 +400,36 @@ def test_spanner_graph_avoid_unnecessary_overwrite(self, use_flexible_schema):
400400
print("Clean up graph with name `{}`".format(graph_name))
401401
graph.cleanup()
402402
print("Actual results:", results)
403+
404+
@pytest.mark.parametrize(
405+
"graph_name, raises_exception",
406+
[
407+
("test_graph", False),
408+
("123test_graph", True),
409+
("test_graph2", False),
410+
("test-graph", True),
411+
],
412+
)
413+
def test_spanner_graph_invalid_graph_name(self, graph_name, raises_exception):
414+
suffix = random_string(num_char=5, exclude_whitespaces=True)
415+
graph_name += suffix
416+
if raises_exception:
417+
with pytest.raises(Exception) as excinfo:
418+
SpannerGraphStore(
419+
instance_id,
420+
google_database,
421+
graph_name,
422+
client=Client(project=project_id),
423+
static_node_properties=["a", "b"],
424+
static_edge_properties=["a", "b"],
425+
)
426+
assert "not a valid identifier" in str(excinfo.value)
427+
else:
428+
SpannerGraphStore(
429+
instance_id,
430+
google_database,
431+
graph_name,
432+
client=Client(project=project_id),
433+
static_node_properties=["a", "b"],
434+
static_edge_properties=["a", "b"],
435+
)

0 commit comments

Comments
 (0)