Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: add collection name validation

Tiberiu Sabău343168df7a1f
diff --git a/semantica/export/arango_aql_exporter.py b/semantica/export/arango_aql_exporter.py
index a0aec52e..712cb1d3 100644
--- a/semantica/export/arango_aql_exporter.py
+++ b/semantica/export/arango_aql_exporter.py
@@ -84,6 +84,10 @@ class ArangoAQLExporter:
self.config = config or {}
self.config.update(kwargs)
+ # Validate collection names
+ self._validate_collection_name(vertex_collection, "vertex_collection")
+ self._validate_collection_name(edge_collection, "edge_collection")
+
# AQL export configuration
self.vertex_collection = vertex_collection
self.edge_collection = edge_collection
@@ -143,6 +147,12 @@ class ArangoAQLExporter:
vertex_collection = options.pop("vertex_collection", self.vertex_collection)
edge_collection = options.pop("edge_collection", self.edge_collection)
+ # Validate overridden collection names
+ if vertex_collection != self.vertex_collection:
+ self._validate_collection_name(vertex_collection, "vertex_collection")
+ if edge_collection != self.edge_collection:
+ self._validate_collection_name(edge_collection, "edge_collection")
+
# Generate AQL statements
aql_statements = self._generate_aql_statements(
knowledge_graph, vertex_collection, edge_collection, **options
@@ -303,6 +313,12 @@ class ArangoAQLExporter:
"""
Convert a vertex/entity to an ArangoDB document.
+ Additional properties from the input entity are preserved as-is in the
+ document root (not flattened or merged). Nested dictionaries and lists
+ are preserved as JSON-serializable structures. The 'properties' field,
+ if present, is also preserved as-is rather than being flattened into
+ the document root.
+
Args:
vertex: Vertex/entity dictionary
idx: Index for generating fallback IDs
@@ -372,7 +388,9 @@ class ArangoAQLExporter:
statements = []
# Add header comment
- statements.append(f"// Inserting {len(edges)} edges into {collection}")
+ statements.append(
+ f"// Attempting to insert {len(edges)} edges into {collection}"
+ )
statements.append("")
# Process edges in batches
@@ -485,6 +503,45 @@ class ArangoAQLExporter:
return document
+ def _validate_collection_name(self, name: str, param_name: str) -> None:
+ """
+ Validate an ArangoDB collection name.
+
+ ArangoDB collection names must:
+ - Start with a letter or underscore
+ - Contain only alphanumeric characters, hyphens, and underscores
+ - Not exceed 256 characters
+
+ Args:
+ name: Collection name to validate
+ param_name: Parameter name for error messages
+
+ Raises:
+ ValueError: If the collection name is invalid
+ """
+ if not name:
+ raise ValueError(f"{param_name} cannot be empty")
+
+ if len(name) > 256:
+ raise ValueError(
+ f"{param_name} '{name}' exceeds maximum length of 256 characters"
+ )
+
+ # Check first character
+ if not (name[0].isalpha() or name[0] == "_"):
+ raise ValueError(
+ f"{param_name} '{name}' must start with a letter or underscore"
+ )
+
+ # Check remaining characters
+ for char in name:
+ if not (char.isalnum() or char in ("-", "_")):
+ raise ValueError(
+ f"{param_name} '{name}' contains invalid character "
+ f"'{char}'. Only alphanumeric characters, hyphens, and "
+ "underscores are allowed."
+ )
+
def _sanitize_key(self, key: str) -> str:
"""
Sanitize a key for use as ArangoDB _key.
diff --git a/tests/test_arango_aql_exporter.py b/tests/test_arango_aql_exporter.py
index c7f19034..36e2e000 100644
--- a/tests/test_arango_aql_exporter.py
+++ b/tests/test_arango_aql_exporter.py
@@ -12,7 +12,7 @@ import tempfile
import unittest
from pathlib import Path
-from semantica.export.arango_aql_exporter import ArangoAQLExporter
+from semantica.export import ArangoAQLExporter
class TestArangoAQLExporter(unittest.TestCase):
@@ -158,7 +158,7 @@ class TestArangoAQLExporter(unittest.TestCase):
self.assertIn("Acme Corp", content)
# Check that edges are NOT present (empty relationships)
- self.assertIn("Inserting 0 edges", content)
+ self.assertIn("Attempting to insert 0 edges", content)
def test_export_relationships_only(self):
"""Test exporting only relationships (edges)."""
@@ -256,7 +256,7 @@ class TestArangoAQLExporter(unittest.TestCase):
# Should have collection creation comments but no INSERT statements
self.assertIn("Inserting 0 vertices", content)
- self.assertIn("Inserting 0 edges", content)
+ self.assertIn("Attempting to insert 0 edges", content)
def test_missing_source_or_target(self):
"""Test handling of edges with missing source or target."""
@@ -286,10 +286,10 @@ class TestArangoAQLExporter(unittest.TestCase):
with open(output_path, "r", encoding="utf-8") as f:
content = f.read()
- # Should only contain the valid relationship
+ # The data section should only contain the valid relationship
self.assertIn("VALID", content)
- # Count should reflect only 1 valid edge
- self.assertIn("Inserting 3 edges", content) # Attempts all 3
+ # The header comment should count all input edges, including invalid ones
+ self.assertIn("Attempting to insert 3 edges", content)
def test_key_sanitization(self):
"""Test sanitization of keys with invalid characters."""
@@ -494,6 +494,45 @@ class TestArangoAQLExporter(unittest.TestCase):
self.assertIn("INSERT doc INTO override_e", content)
self.assertIn("override_v/e1", content)
+ def test_invalid_collection_name_on_init(self):
+ """Test that invalid collection names raise ValueError on initialization."""
+ # Test collection name starting with number
+ with self.assertRaises(ValueError) as context:
+ ArangoAQLExporter(vertex_collection="123invalid")
+ self.assertIn("must start with a letter or underscore", str(context.exception))
+
+ # Test collection name with invalid characters
+ with self.assertRaises(ValueError) as context:
+ ArangoAQLExporter(edge_collection="invalid@name")
+ self.assertIn("contains invalid character", str(context.exception))
+
+ # Test empty collection name
+ with self.assertRaises(ValueError) as context:
+ ArangoAQLExporter(vertex_collection="")
+ self.assertIn("cannot be empty", str(context.exception))
+
+ # Test too long collection name
+ with self.assertRaises(ValueError) as context:
+ ArangoAQLExporter(vertex_collection="a" * 257)
+ self.assertIn("exceeds maximum length", str(context.exception))
+
+ def test_invalid_collection_name_on_export(self):
+ """Test invalid collection names raise ValueError when overriding."""
+ exporter = ArangoAQLExporter()
+ output_path = Path(self.test_dir) / "test.aql"
+
+ kg = {"entities": self.entities, "relationships": self.relationships}
+
+ # Test invalid vertex collection override
+ with self.assertRaises(ValueError) as context:
+ exporter.export(kg, str(output_path), vertex_collection="123invalid")
+ self.assertIn("must start with a letter or underscore", str(context.exception))
+
+ # Test invalid edge collection override
+ with self.assertRaises(ValueError) as context:
+ exporter.export(kg, str(output_path), edge_collection="invalid@name")
+ self.assertIn("contains invalid character", str(context.exception))
+
if __name__ == "__main__":
unittest.main()