Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Add SPARQL CONSTRUCT template support to RDF4J backend (#754)

Sameer6305a0462269dbee
diff --git a/semantica/triplet_store/blazegraph_store.py b/semantica/triplet_store/blazegraph_store.py
index b657b8e8..73ebf0da 100644
--- a/semantica/triplet_store/blazegraph_store.py
+++ b/semantica/triplet_store/blazegraph_store.py
@@ -40,27 +40,9 @@ from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from . import sparql_escaping
-# Matches CONSTRUCT only as the actual SPARQL query-form keyword: anchored
-# from the start of the string, optionally preceded by PREFIX/BASE
-# declarations, then requires CONSTRUCT as the first non-whitespace keyword.
-# This prevents false-positives from SELECT/ASK queries that merely contain
-# the word "CONSTRUCT" inside a string literal or comment (e.g. a literal
-# value of '"please CONSTRUCT this"' or a comment line).
-_CONSTRUCT_QUERY_RE = re.compile(
- r"""
- \A # anchor to start of string
- (?: # skip zero or more of:
- \s+ # whitespace
- | \#[^\n]* # comments (until newline)
- | PREFIX\s+[\w\-]*:\s*<[^>]*> # PREFIX declaration
- | BASE\s+<[^>]*> # BASE declaration
- )*
- \s* # any remaining whitespace before the query form
- CONSTRUCT # the actual query-form keyword
- \b # must be followed by a non-word character
- """,
- re.IGNORECASE | re.VERBOSE,
-)
+# _CONSTRUCT_QUERY_RE was moved to sparql_escaping.CONSTRUCT_QUERY_RE so both
+# BlazegraphStore and RDF4JStore share a single canonical implementation.
+# _is_construct_query below delegates to sparql_escaping.CONSTRUCT_QUERY_RE.
class BlazegraphStore:
@@ -145,8 +127,11 @@ class BlazegraphStore:
queries already pass validation today). This helper only decides
which HTTP Accept header and response parser execute_sparql uses; it
does not gate query validity.
+
+ Delegates to sparql_escaping.CONSTRUCT_QUERY_RE, which is the single
+ canonical CONSTRUCT-detection regex shared with RDF4JStore.
"""
- return _CONSTRUCT_QUERY_RE.search(query) is not None
+ return sparql_escaping.CONSTRUCT_QUERY_RE.search(query) is not None
def execute_sparql(self, query: str, **options) -> Dict[str, Any]:
"""
diff --git a/semantica/triplet_store/rdf4j_store.py b/semantica/triplet_store/rdf4j_store.py
index 3e26d719..4a24b7fc 100644
--- a/semantica/triplet_store/rdf4j_store.py
+++ b/semantica/triplet_store/rdf4j_store.py
@@ -29,11 +29,13 @@ License: MIT
from typing import Any, Dict, List, Optional
import requests
+from rdflib import Graph, Literal
from ..semantic_extract.triplet_extractor import Triplet
from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+from . import sparql_escaping
class RDF4JStore:
@@ -102,6 +104,15 @@ class RDF4JStore:
"""Get SPARQL Update endpoint."""
return f"{self.endpoint}/repositories/{self.repository_id}/statements"
+ def _is_construct_query(self, query: str) -> bool:
+ """
+ Detect whether `query` is a SPARQL CONSTRUCT query.
+
+ Delegates to sparql_escaping.CONSTRUCT_QUERY_RE, the single canonical
+ CONSTRUCT-detection regex shared with BlazegraphStore.
+ """
+ return sparql_escaping.CONSTRUCT_QUERY_RE.search(query) is not None
+
def create_repository(
self, repository_config: Dict[str, Any], **options
) -> Dict[str, Any]:
@@ -176,10 +187,29 @@ class RDF4JStore:
Args:
query: SPARQL query string
- **options: Additional options
+ **options: Additional options:
+ - result_format: Optional[Literal["bindings", "construct"]].
+ If omitted, auto-detected via _is_construct_query(query).
Returns:
- Query results
+ Query results. For non-CONSTRUCT queries (or when result_format
+ resolves to "bindings"), the existing shape is unchanged:
+ {"success": bool, "bindings": [...], "variables": [...], "metadata": {...}}
+ For CONSTRUCT queries (or result_format="construct"), the shape is:
+ {"success": bool, "bindings": [], "variables": [], "triples": [...],
+ "metadata": {...}}
+ where "triples" is a list of (subject, predicate, object, metadata)
+ 4-tuples parsed from the Turtle response via rdflib. subject and
+ predicate are always plain strings. object is the literal's
+ lexical value or the IRI string. metadata is a dict that is empty
+ ({}) for URIs and plain untyped/unlang-tagged literals, and
+ otherwise contains "datatype" (the datatype IRI as a string) and/
+ or "language" (the RFC 5646 language tag) for literals that carry
+ that information.
+
+ Raises:
+ ProcessingError: if not connected, the HTTP request fails, or (for
+ CONSTRUCT queries) the response body fails to parse as Turtle.
"""
tracking_id = self.progress_tracker.start_tracking(
module="triplet_store",
@@ -196,6 +226,78 @@ class RDF4JStore:
sparql_endpoint = self._get_sparql_endpoint()
+ result_format = options.get("result_format")
+ if result_format is None:
+ result_format = "construct" if self._is_construct_query(query) else "bindings"
+
+ if result_format == "construct":
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Sending CONSTRUCT query to RDF4J endpoint..."
+ )
+ # result_format is a load-bearing internal detail of this
+ # function; pop it from a local copy so a caller-supplied
+ # result_format in **options cannot crash with
+ # "got multiple values for keyword argument".
+ execute_options = dict(options)
+ execute_options.pop("result_format", None)
+
+ response = requests.post(
+ sparql_endpoint,
+ data={"query": query},
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Accept": "text/turtle",
+ },
+ timeout=self.timeout,
+ auth=(self.username, self.password)
+ if self.username and self.password
+ else None,
+ )
+
+ response.raise_for_status()
+
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Parsing CONSTRUCT response as Turtle..."
+ )
+ graph = Graph()
+ try:
+ graph.parse(data=response.content, format="turtle")
+ except Exception as parse_error:
+ raise ProcessingError(
+ f"Failed to parse CONSTRUCT response as Turtle: {parse_error}"
+ ) from parse_error
+
+ triples = []
+ for s, p, o in graph:
+ obj_metadata: Dict[str, Any] = {}
+ if isinstance(o, Literal):
+ if o.datatype is not None:
+ obj_metadata["datatype"] = str(o.datatype)
+ if o.language is not None:
+ obj_metadata["language"] = str(o.language)
+ triples.append((str(s), str(p), str(o), obj_metadata))
+
+ result = {
+ "success": True,
+ "bindings": [],
+ "variables": [],
+ "triples": triples,
+ "metadata": {
+ "query": query,
+ "endpoint": sparql_endpoint,
+ "result_format": "construct",
+ },
+ }
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"CONSTRUCT query executed: {len(triples)} triples",
+ )
+ return result
+
+ # Non-CONSTRUCT path — unchanged from prior behavior, including the
+ # explicit Accept: application/sparql-results+json header.
self.progress_tracker.update_tracking(
tracking_id, message="Sending query to RDF4J endpoint..."
)
@@ -242,7 +344,15 @@ class RDF4JStore:
Args:
triplets: List of triplets
- **options: Additional options
+ **options: Additional options:
+ - graph: Optional[str] — named graph URI. When provided, the
+ request appends a ``context`` query parameter to the
+ /statements endpoint, formatted as an N-Triples-encoded IRI
+ (angle-bracket-wrapped, e.g. ``<http://example.org/g>``).
+ The ``requests`` library URL-encodes this automatically, so
+ the wire value is ``?context=%3Chttp%3A%2F%2F...%3E``.
+ When graph is None or omitted, no context parameter is sent
+ and writes go to the default/all graphs as before.
Returns:
Operation status
@@ -268,6 +378,17 @@ class RDF4JStore:
)
rdf_data = self._triplets_to_ntriples(triplets)
+ # Build the context (named graph) query parameter if requested.
+ # RDF4J REST API requires the value to be N-Triples-encoded:
+ # the IRI must be wrapped in angle brackets, e.g. <http://...>.
+ # requests.post with params= URL-encodes the value automatically,
+ # so the wire value becomes ?context=%3Chttp%3A...%3E.
+ # When graph is None, send no context parameter at all — do NOT
+ # default to context=null, which would change "all graphs" semantics
+ # to "default graph only" and is a behavior change from today.
+ graph = options.get("graph")
+ context_params = {"context": f"<{graph}>"} if graph is not None else None
+
self.progress_tracker.update_tracking(
tracking_id, message="Sending triplets to RDF4J repository..."
)
@@ -275,6 +396,7 @@ class RDF4JStore:
update_endpoint,
data=rdf_data,
headers={"Content-Type": "application/n-triples"},
+ params=context_params,
timeout=self.timeout * 2,
auth=(self.username, self.password)
if self.username and self.password
diff --git a/semantica/triplet_store/sparql_escaping.py b/semantica/triplet_store/sparql_escaping.py
index 1863168a..311fdb41 100644
--- a/semantica/triplet_store/sparql_escaping.py
+++ b/semantica/triplet_store/sparql_escaping.py
@@ -41,6 +41,31 @@ LANG_TAG_RE = re.compile(r"^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$")
# identical to the character class used throughout BlazegraphStore.
_DISALLOWED_URI_CHARS_RE = re.compile(r"[\s<>\"{}|\\^`]")
+# Matches CONSTRUCT only as the actual SPARQL query-form keyword: anchored
+# from the start of the string, optionally preceded by PREFIX/BASE
+# declarations, then requires CONSTRUCT as the first non-whitespace keyword.
+# This prevents false-positives from SELECT/ASK queries that merely contain
+# the word "CONSTRUCT" inside a string literal or comment (e.g. a literal
+# value of '"please CONSTRUCT this"' or a comment line).
+#
+# Shared by BlazegraphStore and RDF4JStore so the detection logic has one
+# canonical implementation rather than being duplicated per-backend.
+CONSTRUCT_QUERY_RE = re.compile(
+ r"""
+ \A # anchor to start of string
+ (?: # skip zero or more of:
+ \s+ # whitespace
+ | \#[^\n]* # comments (until newline)
+ | PREFIX\s+[\w\-]*:\s*<[^>]*> # PREFIX declaration
+ | BASE\s+<[^>]*> # BASE declaration
+ )*
+ \s* # any remaining whitespace before the query form
+ CONSTRUCT # the actual query-form keyword
+ \b # must be followed by a non-word character
+ """,
+ re.IGNORECASE | re.VERBOSE,
+)
+
def escape_literal(value: str) -> str:
"""
diff --git a/tests/triplet_store/test_rdf4j_store.py b/tests/triplet_store/test_rdf4j_store.py
new file mode 100644
index 00000000..b7acf746
--- /dev/null
+++ b/tests/triplet_store/test_rdf4j_store.py
@@ -0,0 +1,378 @@
+import os, sys, unittest
+from unittest.mock import MagicMock, patch
+
+PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
+if PROJECT_ROOT not in sys.path:
+ sys.path.insert(0, PROJECT_ROOT)
+
+from semantica.semantic_extract.triplet_extractor import Triplet
+from semantica.triplet_store.rdf4j_store import RDF4JStore
+from semantica.utils.exceptions import ProcessingError
+
+
+def _make_connected_store():
+ with patch.object(RDF4JStore, "_connect", autospec=True):
+ store = RDF4JStore(
+ endpoint="http://localhost:8080/rdf4j-server", repository_id="repo1"
+ )
+ store.connected = True
+ return store
+
+
+CONSTRUCT_QUERY = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"
+
+
+class TestRDF4JStoreIsConstructQuery(unittest.TestCase):
+ def test_detects_uppercase(self):
+ self.assertTrue(_make_connected_store()._is_construct_query(
+ "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"))
+ def test_detects_lowercase(self):
+ self.assertTrue(_make_connected_store()._is_construct_query(
+ "construct { ?s ?p ?o } where { ?s ?p ?o }"))
+ def test_detects_mixed_case(self):
+ self.assertTrue(_make_connected_store()._is_construct_query(
+ "Construct { ?s ?p ?o } Where { ?s ?p ?o }"))
+ def test_detects_with_prefix_preamble(self):
+ q = "PREFIX ex: <http://ex.org/>\nCONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"
+ self.assertTrue(_make_connected_store()._is_construct_query(q))
+ def test_detects_complex_preambles(self):
+ s = _make_connected_store()
+ cases = {
+ "multiline_prefix": "PREFIX foaf:\n <http://xmlns.com/foaf/0.1/>\nCONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }",
+ "empty_prefix": "PREFIX : <http://ex.org/> CONSTRUCT { ?s ?p ?o }",
+ "inline_comment": "PREFIX ex: <http://ex.org/>\n# comment\nCONSTRUCT { ?s ?p ?o }",
+ "base_declaration": "BASE <http://ex.org/>\nCONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }",
+ }
+ for name, q in cases.items():
+ with self.subTest(case=name):
+ self.assertTrue(s._is_construct_query(q))
+ def test_false_for_select(self):
+ self.assertFalse(_make_connected_store()._is_construct_query(
+ "SELECT ?s WHERE { ?s ?p ?o }"))
+ def test_false_for_ask(self):
+ self.assertFalse(_make_connected_store()._is_construct_query(
+ "ASK { ?s ?p ?o }"))
+ def test_no_false_positive_on_constructor_substring(self):
+ self.assertFalse(_make_connected_store()._is_construct_query(
+ 'SELECT ?s WHERE { ?s <urn:p> "CONSTRUCTOR" }'))
+ def test_no_false_positive_on_construct_in_string(self):
+ self.assertFalse(_make_connected_store()._is_construct_query(
+ 'SELECT ?s WHERE { ?s <urn:p> "please CONSTRUCT this" }'))
+
+
+class TestRDF4JStoreExecuteSparqlConstructPath(unittest.TestCase):
+ def test_construct_sends_turtle_accept_header(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.content = b'@prefix ex: <http://ex.org/> .\nex:s1 ex:p1 "v" .\n'
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.execute_sparql(CONSTRUCT_QUERY)
+ _, kw = mp.call_args
+ self.assertEqual(kw["headers"]["Accept"], "text/turtle")
+ self.assertEqual(kw["headers"]["Content-Type"], "application/x-www-form-urlencoded")
+
+ def test_construct_parses_triples_from_turtle_fixture(self):
+ store = _make_connected_store()
+ fixture = (
+ b'@prefix ex: <http://ex.org/> .\n'
+ b'ex:s1 ex:p1 "value1" .\n'
+ b'ex:s1 ex:p2 ex:o2 .\n'
+ )
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ result = store.execute_sparql(CONSTRUCT_QUERY)
+ self.assertTrue(result["success"])
+ self.assertEqual(result["bindings"], [])
+ self.assertEqual(result["variables"], [])
+ self.assertEqual(result["metadata"]["result_format"], "construct")
+ triples = {(s, p, o) for s, p, o, _m in result["triples"]}
+ self.assertIn(("http://ex.org/s1", "http://ex.org/p1", "value1"), triples)
+ self.assertIn(("http://ex.org/s1", "http://ex.org/p2", "http://ex.org/o2"), triples)
+ self.assertEqual(len(result["triples"]), 2)
+ for _s, _p, _o, meta in result["triples"]:
+ self.assertEqual(meta, {})
+
+ def test_result_format_construct_forces_construct_path(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.content = b'@prefix ex: <http://ex.org/> .\nex:s1 ex:p1 "v" .\n'
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ result = store.execute_sparql("SELECT ?s WHERE { ?s ?p ?o }", result_format="construct")
+ _, kw = mp.call_args
+ self.assertEqual(kw["headers"]["Accept"], "text/turtle")
+ self.assertIn("triples", result)
+
+ def test_malformed_turtle_raises_processing_error(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.content = b"this is { not [ valid turtle at all !!!"
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ with self.assertRaises(ProcessingError) as ctx:
+ store.execute_sparql(CONSTRUCT_QUERY)
+ self.assertIsInstance(ctx.exception, ProcessingError)
+ self.assertNotIsInstance(ctx.exception, (SyntaxError, ValueError))
+
+ def test_typed_literal_datatype_preserved_in_metadata(self):
+ store = _make_connected_store()
+ fixture = (
+ b'@prefix ex: <http://ex.org/> .\n'
+ b'@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n'
+ b'ex:s1 ex:p_age 42 .\n'
+ )
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ result = store.execute_sparql(CONSTRUCT_QUERY)
+ self.assertEqual(len(result["triples"]), 1)
+ _s, _p, o, meta = result["triples"][0]
+ self.assertEqual(o, "42")
+ self.assertEqual(meta.get("datatype"), "http://www.w3.org/2001/XMLSchema#integer")
+ self.assertNotIn("language", meta)
+
+ def test_language_tagged_literal_preserved_in_metadata(self):
+ store = _make_connected_store()
+ fixture = b'@prefix ex: <http://ex.org/> .\nex:s2 ex:p_label "hello"@en .\n'
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ result = store.execute_sparql(CONSTRUCT_QUERY)
+ self.assertEqual(len(result["triples"]), 1)
+ _s, _p, o, meta = result["triples"][0]
+ self.assertEqual(o, "hello")
+ self.assertEqual(meta.get("language"), "en")
+ self.assertNotIn("datatype", meta)
+
+ def test_literal_with_braces_parsed_correctly(self):
+ store = _make_connected_store()
+ fixture = b'@prefix ex: <http://ex.org/> .\nex:s1 ex:p1 "text with { and } braces inside" .\n'
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ result = store.execute_sparql(CONSTRUCT_QUERY)
+ self.assertEqual(len(result["triples"]), 1)
+ _s, _p, obj, meta = result["triples"][0]
+ self.assertEqual(obj, "text with { and } braces inside")
+ self.assertEqual(meta, {})
+
+
+class TestRDF4JStoreProperty9NonConstructUnchanged(unittest.TestCase):
+ # RDF4J had Accept: application/sparql-results+json on non-CONSTRUCT before feat/754.
+ # That header is preserved exactly. NOT aligned with Blazegraph headerless path.
+
+ def test_select_response_shape_unchanged(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {
+ "head": {"vars": ["s", "p", "o"]},
+ "results": {"bindings": [
+ {"s": {"type": "uri", "value": "http://ex.org/s1"},
+ "p": {"type": "uri", "value": "http://ex.org/p1"},
+ "o": {"type": "literal", "value": "v1"}}]},
+ }
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ result = store.execute_sparql("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")
+ _, kw = mp.call_args
+ self.assertEqual(kw["headers"], {"Accept": "application/sparql-results+json"})
+ self.assertNotIn("Content-Type", kw["headers"])
+ self.assertEqual(result, {
+ "success": True,
+ "bindings": mock_resp.json.return_value["results"]["bindings"],
+ "variables": ["s", "p", "o"],
+ "metadata": {"query": "SELECT ?s ?p ?o WHERE { ?s ?p ?o }",
+ "endpoint": store._get_sparql_endpoint()},
+ })
+ self.assertNotIn("triples", result)
+
+ def test_select_does_not_send_turtle_accept(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"head": {"vars": []}, "results": {"bindings": []}}
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.execute_sparql("SELECT ?s WHERE { ?s ?p ?o }")
+ _, kw = mp.call_args
+ self.assertNotEqual(kw["headers"].get("Accept"), "text/turtle")
+
+ def test_ask_uses_json_not_turtle_path(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"head": {}, "boolean": True}
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.execute_sparql("ASK { ?s ?p ?o }")
+ _, kw = mp.call_args
+ self.assertEqual(kw["headers"].get("Accept"), "application/sparql-results+json")
+
+ def test_non_construct_result_has_no_triples_key(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"head": {"vars": []}, "results": {"bindings": []}}
+ mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post", return_value=mock_resp):
+ result = store.execute_sparql("SELECT ?s WHERE { ?s ?p ?o }")
+ self.assertNotIn("triples", result)
+
+
+class TestRDF4JStoreAddTripletsContextParameter(unittest.TestCase):
+ def _t(self):
+ return Triplet(subject="http://ex.org/s1", predicate="http://ex.org/p", object="http://ex.org/o1")
+
+ def test_graph_present_sends_context_param(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph="http://ex.org/mygraph")
+ _, kw = mp.call_args
+ self.assertIsNotNone(kw.get("params"))
+ self.assertIn("context", kw["params"])
+
+ def test_graph_present_encodes_as_angle_bracket_wrapped_iri(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph="http://ex.org/mygraph")
+ _, kw = mp.call_args
+ self.assertEqual(kw["params"]["context"], "<http://ex.org/mygraph>")
+ self.assertNotEqual(kw["params"]["context"], "http://ex.org/mygraph")
+
+ def test_graph_none_sends_no_context_param(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph=None)
+ _, kw = mp.call_args
+ self.assertIsNone(kw.get("params"))
+
+ def test_graph_omitted_sends_no_context_param(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()])
+ _, kw = mp.call_args
+ self.assertIsNone(kw.get("params"))
+
+ def test_graph_none_does_not_send_context_null(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph=None)
+ _, kw = mp.call_args
+ params = kw.get("params")
+ if params is not None:
+ self.assertNotIn("context", params)
+
+ def test_context_encoding_matches_confirmed_rdf4j_protocol(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ graph_uri = "http://ex.org/mygraph"
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph=graph_uri)
+ _, kw = mp.call_args
+ ctx = kw["params"]["context"]
+ self.assertEqual(ctx, f"<{graph_uri}>")
+ self.assertTrue(ctx.startswith("<"))
+ self.assertTrue(ctx.endswith(">"))
+
+ def test_graph_present_posts_to_statements_endpoint_not_modified_url(self):
+ store = _make_connected_store()
+ mock_resp = MagicMock(); mock_resp.raise_for_status = MagicMock()
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp) as mp:
+ store.add_triplets([self._t()], graph="http://ex.org/g")
+ call_url = mp.call_args[0][0]
+ self.assertEqual(call_url, store._get_update_endpoint())
+ self.assertNotIn("context", call_url)
+
+
+class TestExecuteConstructTemplateWithRDF4JBackend(unittest.TestCase):
+
+ def test_end_to_end_with_rdf4j_backend(self):
+ from semantica.triplet_store.construct_templates import (
+ ConstructTemplate, ParameterDescriptor, execute_construct_template,
+ )
+ fixture = b'@prefix ex: <http://ex.org/> .\nex:s1 ex:p1 "Alice" .\n'
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ store = _make_connected_store()
+ calls = []
+ store.add_triplets = (
+ lambda triplets, **opts:
+ (calls.append((triplets, opts)) or None) or {"success": True}
+ )
+ template = ConstructTemplate(
+ name="rdf4j_e2e",
+ description="e2e test",
+ construct_query=(
+ "CONSTRUCT { <http://ex.org/s1> <http://ex.org/p1> {{value}} } "
+ "WHERE { <http://ex.org/s1> <http://ex.org/p1> {{value}} }"
+ ),
+ parameters=[ParameterDescriptor(name="value", type="literal", required=True)],
+ target_graph="http://ex.org/rdf4j_graph",
+ )
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp):
+ result = execute_construct_template(
+ template, params={"value": "Alice"}, store_backend=store)
+ self.assertGreater(len(result), 0)
+ self.assertEqual(len(calls), 1)
+ _, opts = calls[0]
+ self.assertEqual(opts.get("graph"), "http://ex.org/rdf4j_graph")
+
+ def test_literal_metadata_round_trips_through_rdf4j_backend(self):
+ from semantica.triplet_store.construct_templates import (
+ ConstructTemplate, ParameterDescriptor, execute_construct_template,
+ )
+ fixture = (
+ b'@prefix ex: <http://ex.org/> .\n'
+ b'@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n'
+ b'ex:s1 ex:p_age 42 .\n'
+ b'ex:s2 ex:p_label "hello"@en .\n'
+ )
+ mock_resp = MagicMock()
+ mock_resp.content = fixture
+ mock_resp.raise_for_status = MagicMock()
+ store = _make_connected_store()
+ store.add_triplets = lambda triplets, **opts: {"success": True}
+ template = ConstructTemplate(
+ name="rdf4j_roundtrip",
+ description="round-trip test",
+ construct_query="CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }",
+ parameters=[ParameterDescriptor(name="value", type="literal", required=True)],
+ )
+ with patch("semantica.triplet_store.rdf4j_store.requests.post",
+ return_value=mock_resp):
+ result = execute_construct_template(
+ template, params={"value": "x"}, store_backend=store)
+ by_subject = {t.subject: t for t in result}
+ age_t = by_subject["http://ex.org/s1"]
+ self.assertEqual(age_t.object, "42")
+ self.assertEqual(age_t.metadata.get("datatype"),
+ "http://www.w3.org/2001/XMLSchema#integer")
+ label_t = by_subject["http://ex.org/s2"]
+ self.assertEqual(label_t.object, "hello")
+ self.assertEqual(label_t.metadata.get("lang"), "en")
+
+
+if __name__ == "__main__":
+ unittest.main()