Source code

Download source archive ↓

src/rdflib/contrib/rdf4j/client.py

1"""RDF4J client module."""
2
3from __future__ import annotations
4
5import contextlib
6import io
7import typing as t
8from dataclasses import dataclass
9from typing import Any, BinaryIO, Iterable
10
11import httpx
12
13from rdflib import BNode
14from rdflib.contrib.rdf4j.exceptions import (
15    RDF4JUnsupportedProtocolError,
16    RDFLibParserError,
17    RepositoryAlreadyExistsError,
18    RepositoryError,
19    RepositoryNotFoundError,
20    RepositoryNotHealthyError,
21    RepositoryResponseFormatError,
22    TransactionClosedError,
23    TransactionCommitError,
24    TransactionPingError,
25    TransactionRollbackError,
26)
27from rdflib.contrib.rdf4j.util import (
28    build_context_param,
29    build_infer_param,
30    build_sparql_query_accept_header,
31    build_spo_param,
32    rdf_payload_to_stream,
33    validate_graph_name,
34    validate_no_bnodes,
35)
36from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, Dataset, Graph
37from rdflib.query import Result
38from rdflib.term import IdentifiedNode, Literal, URIRef
39
40SubjectType = t.Union[URIRef, None]
41PredicateType = t.Union[URIRef, None]
42ObjectType = t.Union[URIRef, Literal, None]
43
44
45@dataclass(frozen=True)
46class NamespaceListingResult:
47    """RDF4J namespace and prefix name result."""
48
49    prefix: str
50    namespace: str
51
52
53class RDF4JNamespaceManager:
54    """A namespace manager for RDF4J repositories.
55
56    Parameters:
57        identifier: The identifier of the repository.
58        http_client: The httpx.Client instance.
59    """
60
61    def __init__(self, identifier: str, http_client: httpx.Client):
62        self._identifier = identifier
63        self._http_client = http_client
64
65    @property
66    def http_client(self):
67        return self._http_client
68
69    @property
70    def identifier(self):
71        """Repository identifier."""
72        return self._identifier
73
74    def list(self) -> list[NamespaceListingResult]:
75        """List all namespace declarations in the repository.
76
77        Returns:
78            list[NamespaceListingResult]: List of namespace and prefix name results.
79
80        Raises:
81            RepositoryResponseFormatError: If the response format is unrecognized.
82        """
83        headers = {
84            "Accept": "application/sparql-results+json",
85        }
86        response = self.http_client.get(
87            f"/repositories/{self.identifier}/namespaces", headers=headers
88        )
89        response.raise_for_status()
90
91        try:
92            data = response.json()
93            results = data["results"]["bindings"]
94            return [
95                NamespaceListingResult(
96                    prefix=row["prefix"]["value"],
97                    namespace=row["namespace"]["value"],
98                )
99                for row in results
100            ]
101        except (KeyError, ValueError) as err:
102            raise RepositoryResponseFormatError(f"Unrecognised response format: {err}")
103
104    def clear(self):
105        """Clear all namespace declarations in the repository."""
106        headers = {
107            "Accept": "application/sparql-results+json",
108        }
109        response = self.http_client.delete(
110            f"/repositories/{self.identifier}/namespaces", headers=headers
111        )
112        response.raise_for_status()
113
114    def get(self, prefix: str) -> str | None:
115        """Get the namespace URI for a given prefix.
116
117        Parameters:
118            prefix: The prefix to lookup.
119
120        Returns:
121            The namespace URI or `None` if not found.
122        """
123        if not prefix:
124            raise ValueError("Prefix cannot be empty.")
125        headers = {
126            "Accept": "text/plain",
127        }
128        try:
129            response = self.http_client.get(
130                f"/repositories/{self.identifier}/namespaces/{prefix}", headers=headers
131            )
132            response.raise_for_status()
133            return response.text
134        except httpx.HTTPStatusError as err:
135            if err.response.status_code == 404:
136                return None
137            raise
138
139    def set(self, prefix: str, namespace: str):
140        """Set the namespace URI for a given prefix.
141
142        !!! note
143            If the prefix was previously mapped to a different namespace, this will be
144            overwritten.
145
146        Parameters:
147            prefix: The prefix to set.
148            namespace: The namespace URI to set.
149        """
150        if not prefix:
151            raise ValueError("Prefix cannot be empty.")
152        if not namespace:
153            raise ValueError("Namespace cannot be empty.")
154        headers = {
155            "Content-Type": "text/plain",
156        }
157        response = self.http_client.put(
158            f"/repositories/{self.identifier}/namespaces/{prefix}",
159            headers=headers,
160            content=namespace,
161        )
162        response.raise_for_status()
163
164    def remove(self, prefix: str):
165        """Remove the namespace declaration for a given prefix.
166
167        Parameters:
168            prefix: The prefix to remove.
169        """
170        if not prefix:
171            raise ValueError("Prefix cannot be empty.")
172        response = self.http_client.delete(
173            f"/repositories/{self.identifier}/namespaces/{prefix}"
174        )
175        response.raise_for_status()
176
177
178class GraphStoreManager:
179    """An RDF4J Graph Store Protocol Client.
180
181    Parameters:
182        identifier: The identifier of the repository.
183        http_client: The httpx.Client instance.
184    """
185
186    def __init__(self, identifier: str, http_client: httpx.Client):
187        self._identifier = identifier
188        self._http_client = http_client
189        self._content_type = "application/n-triples"
190
191    @property
192    def http_client(self):
193        return self._http_client
194
195    @property
196    def identifier(self):
197        """Repository identifier."""
198        return self._identifier
199
200    @staticmethod
201    def _build_graph_name_params(graph_name: URIRef | str):
202        params = {}
203        if (
204            isinstance(graph_name, URIRef)
205            and graph_name == DATASET_DEFAULT_GRAPH_ID
206            or isinstance(graph_name, str)
207            and graph_name == str(DATASET_DEFAULT_GRAPH_ID)
208        ):
209            # Do nothing; GraphDB does not work with `?default=`
210            # (note the trailing equal character), which is the default
211            # behavior of httpx when setting the param value to an empty string.
212            # httpx completely omits query parameters whose values are `None`, so that's
213            # not an option either.
214            # The workaround is to construct our own query parameter URL when we target
215            # the default graph.
216            pass
217        else:
218            params["graph"] = str(graph_name)
219        return params
220
221    def _build_url(self, graph_name: URIRef | str):
222        url = f"/repositories/{self.identifier}/rdf-graphs/service"
223        if isinstance(graph_name, URIRef) and graph_name == DATASET_DEFAULT_GRAPH_ID:
224            url += "?default"
225        return url
226
227    def get(self, graph_name: URIRef | str) -> Graph:
228        """Fetch all statements in the specified graph.
229
230        Parameters:
231            graph_name: The graph name of the graph.
232
233                For the default graph, use
234                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
235
236        Returns:
237            A [`Graph`][rdflib.graph.Graph] object containing all statements in the
238                graph.
239        """
240        if not graph_name:
241            raise ValueError("Graph name must be provided.")
242        validate_graph_name(graph_name)
243        headers = {
244            "Accept": self._content_type,
245        }
246        params = self._build_graph_name_params(graph_name) or None
247
248        response = self.http_client.get(
249            self._build_url(graph_name),
250            headers=headers,
251            params=params,
252        )
253        response.raise_for_status()
254
255        return Graph(identifier=graph_name).parse(
256            data=response.text, format=self._content_type
257        )
258
259    def add(self, graph_name: URIRef | str, data: str | bytes | BinaryIO | Graph):
260        """Add statements to the specified graph.
261
262        Parameters:
263            graph_name: The graph name of the graph.
264
265                For the default graph, use
266                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
267
268            data: The RDF data to add.
269        """
270        if not graph_name:
271            raise ValueError("Graph name must be provided.")
272        validate_graph_name(graph_name)
273        stream, should_close = rdf_payload_to_stream(data)
274        headers = {
275            "Content-Type": self._content_type,
276        }
277        params = self._build_graph_name_params(graph_name) or None
278        try:
279            response = self.http_client.post(
280                self._build_url(graph_name),
281                headers=headers,
282                params=params,
283                content=stream,
284            )
285            response.raise_for_status()
286        finally:
287            if should_close:
288                stream.close()
289
290    def overwrite(self, graph_name: URIRef | str, data: str | bytes | BinaryIO | Graph):
291        """Overwrite statements in the specified graph.
292
293        Parameters:
294            graph_name: The graph name of the graph.
295
296                For the default graph, use
297                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
298
299            data: The RDF data to overwrite with.
300        """
301        if not graph_name:
302            raise ValueError("Graph name must be provided.")
303        validate_graph_name(graph_name)
304        stream, should_close = rdf_payload_to_stream(data)
305        headers = {
306            "Content-Type": self._content_type,
307        }
308        params = self._build_graph_name_params(graph_name) or None
309        try:
310            response = self.http_client.put(
311                self._build_url(graph_name),
312                headers=headers,
313                params=params,
314                content=stream,
315            )
316            response.raise_for_status()
317        finally:
318            if should_close:
319                stream.close()
320
321    def clear(self, graph_name: URIRef | str):
322        """Clear all statements in the specified graph.
323
324        Parameters:
325            graph_name: The graph name of the graph.
326
327                For the default graph, use
328                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
329        """
330        if not graph_name:
331            raise ValueError("Graph name must be provided.")
332        validate_graph_name(graph_name)
333        params = self._build_graph_name_params(graph_name) or None
334        response = self.http_client.delete(self._build_url(graph_name), params=params)
335        response.raise_for_status()
336
337
338@dataclass(frozen=True)
339class RepositoryListingResult:
340    """RDF4J repository listing result.
341
342    Parameters:
343        identifier: Repository identifier.
344        uri: Repository URI.
345        readable: Whether the repository is readable by the client.
346        writable: Whether the repository is writable by the client.
347        title: Repository title.
348    """
349
350    identifier: str
351    uri: str
352    readable: bool
353    writable: bool
354    title: str | None = None
355
356
357class Repository:
358    """RDF4J repository client.
359
360    Parameters:
361        identifier: The identifier of the repository.
362        http_client: The httpx.Client instance.
363    """
364
365    def __init__(self, identifier: str, http_client: httpx.Client):
366        self._identifier = identifier
367        self._http_client = http_client
368        self._namespace_manager: RDF4JNamespaceManager | None = None
369        self._graph_store_manager: GraphStoreManager | None = None
370
371    @property
372    def http_client(self):
373        return self._http_client
374
375    @property
376    def identifier(self):
377        """Repository identifier."""
378        return self._identifier
379
380    @property
381    def namespaces(self) -> RDF4JNamespaceManager:
382        """Namespace manager for the repository."""
383        if self._namespace_manager is None:
384            self._namespace_manager = RDF4JNamespaceManager(
385                self.identifier, self.http_client
386            )
387        return self._namespace_manager
388
389    @property
390    def graphs(self) -> GraphStoreManager:
391        """Graph store manager for the repository."""
392        if self._graph_store_manager is None:
393            self._graph_store_manager = GraphStoreManager(
394                self.identifier, self.http_client
395            )
396        return self._graph_store_manager
397
398    def health(self) -> bool:
399        """Repository health check.
400
401        Returns:
402            bool: True if the repository is healthy, otherwise an error is raised.
403
404        Raises:
405            RepositoryNotFoundError: If the repository is not found.
406            RepositoryNotHealthyError: If the repository is not healthy.
407        """
408        headers = {
409            "Content-Type": "application/sparql-query",
410            "Accept": "application/sparql-results+json",
411        }
412        try:
413            response = self.http_client.post(
414                f"/repositories/{self._identifier}", headers=headers, content="ASK {}"
415            )
416            response.raise_for_status()
417            return True
418        except httpx.HTTPStatusError as err:
419            if err.response.status_code == 404:
420                raise RepositoryNotFoundError(
421                    f"Repository {self._identifier} not found."
422                )
423            raise RepositoryNotHealthyError(
424                f"Repository {self._identifier} is not healthy. {err.response.status_code} - {err.response.text}"
425            )
426
427    def size(self, graph_name: URIRef | Iterable[URIRef] | str | None = None) -> int:
428        """The number of statements in the repository or in the specified graph name.
429
430        Parameters:
431            graph_name: Graph name(s) to restrict to.
432
433                The default value `None` queries all graphs.
434
435                To query just the default graph, use
436                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
437
438        Returns:
439            The number of statements.
440
441        Raises:
442            RepositoryResponseFormatError: Fails to parse the repository size.
443        """
444        validate_graph_name(graph_name)
445        params: dict[str, str] = {}
446        build_context_param(params, graph_name)
447        response = self.http_client.get(
448            f"/repositories/{self.identifier}/size", params=params
449        )
450        response.raise_for_status()
451        return self._to_size(response.text)
452
453    @staticmethod
454    def _to_size(size: str):
455        try:
456            value = int(size)
457            if value >= 0:
458                return value
459            raise ValueError(f"Invalid repository size: {value}")
460        except ValueError as err:
461            raise RepositoryResponseFormatError(
462                f"Failed to parse repository size: {err}"
463            ) from err
464
465    def query(self, query: str, **kwargs):
466        """Execute a SPARQL query against the repository.
467
468        !!! note
469            A POST request is used by default. If any keyword arguments are provided,
470            a GET request is used instead, and the arguments are passed as query parameters.
471
472        Parameters:
473            query: The SPARQL query to execute.
474            **kwargs: Additional keyword arguments to include as query parameters
475                in the request. See
476                [RDF4J REST API - Execute SPARQL query](https://rdf4j.org/documentation/reference/rest-api/#tag/SPARQL/paths/~1repositories~1%7BrepositoryID%7D/get)
477                for the list of supported query parameters.
478        """
479        headers = {"Content-Type": "application/sparql-query"}
480        build_sparql_query_accept_header(query, headers)
481
482        if not kwargs:
483            response = self.http_client.post(
484                f"/repositories/{self.identifier}", headers=headers, content=query
485            )
486        else:
487            response = self.http_client.get(
488                f"/repositories/{self.identifier}",
489                headers=headers,
490                params={"query": query, **kwargs},
491            )
492        response.raise_for_status()
493        try:
494            return Result.parse(
495                io.BytesIO(response.content),
496                content_type=response.headers["Content-Type"].split(";")[0],
497            )
498        except KeyError as err:
499            raise RDFLibParserError(
500                f"Failed to parse SPARQL query result {response.headers.get('Content-Type')}: {err}"
501            ) from err
502
503    def update(self, query: str):
504        """Execute a SPARQL update operation on the repository.
505
506        Parameters:
507            query: The SPARQL update query to execute.
508        """
509        headers = {"Content-Type": "application/sparql-update"}
510        response = self.http_client.post(
511            f"/repositories/{self.identifier}/statements",
512            headers=headers,
513            content=query,
514        )
515        response.raise_for_status()
516
517    def graph_names(self) -> list[IdentifiedNode]:
518        """Get a list of all graph names in the repository.
519
520        Returns:
521            A list of graph names.
522
523        Raises:
524            RepositoryResponseFormatError: Fails to parse the repository graph names.
525        """
526        headers = {
527            "Accept": "application/sparql-results+json",
528        }
529        response = self.http_client.get(
530            f"/repositories/{self.identifier}/contexts", headers=headers
531        )
532        response.raise_for_status()
533        try:
534            values: list[IdentifiedNode] = []
535            for row in response.json()["results"]["bindings"]:
536                value = row["contextID"]["value"]
537                value_type = row["contextID"]["type"]
538                if value_type == "uri":
539                    values.append(URIRef(value))
540                elif value_type == "bnode":
541                    values.append(BNode(value))
542                else:
543                    raise ValueError(f"Invalid graph name type: {value_type}")
544            return values
545        except Exception as err:
546            raise RepositoryResponseFormatError(
547                f"Failed to parse repository graph names: {err}"
548            ) from err
549
550    def get(
551        self,
552        subj: SubjectType = None,
553        pred: PredicateType = None,
554        obj: ObjectType = None,
555        graph_name: URIRef | Iterable[URIRef] | str | None = None,
556        infer: bool = True,
557        content_type: str | None = None,
558    ) -> Graph | Dataset:
559        """Get RDF statements from the repository matching the filtering parameters.
560
561        !!! Note
562            The terms for `subj`, `pred`, `obj` or `graph_name` cannot be
563            [`BNodes`][rdflib.term.BNode].
564
565        Parameters:
566            subj: Subject of the statement to filter by, or `None` to match all.
567            pred: Predicate of the statement to filter by, or `None` to match all.
568            obj: Object of the statement to filter by, or `None` to match all.
569            graph_name: Graph name(s) to restrict to.
570
571                The default value `None` queries all graphs.
572
573                To query just the default graph, use
574                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
575
576            infer: Specifies whether inferred statements should be included in the
577                result.
578            content_type: The content type of the response.
579                A triple-based format returns a [Graph][rdflib.graph.Graph], while a
580                quad-based format returns a [`Dataset`][rdflib.graph.Dataset].
581
582        Returns:
583            A [`Graph`][rdflib.graph.Graph] or [`Dataset`][rdflib.graph.Dataset] object
584                with the repository namespace prefixes bound to it.
585        """
586        validate_no_bnodes(subj, pred, obj, graph_name)
587        if content_type is None:
588            content_type = "application/n-quads"
589        headers = {"Accept": content_type}
590        params: dict[str, str] = {}
591        build_context_param(params, graph_name)
592        build_spo_param(params, subj, pred, obj)
593        build_infer_param(params, infer=infer)
594
595        response = self.http_client.get(
596            f"/repositories/{self.identifier}/statements",
597            headers=headers,
598            params=params,
599        )
600        response.raise_for_status()
601        triple_formats = [
602            "application/n-triples",
603            "text/turtle",
604            "application/rdf+xml",
605        ]
606        try:
607            if content_type in triple_formats:
608                retval = Graph().parse(data=response.text, format=content_type)
609            else:
610                retval = Dataset().parse(data=response.text, format=content_type)
611            for result in self.namespaces.list():
612                retval.bind(result.prefix, result.namespace, replace=True)
613            return retval
614        except Exception as err:
615            raise RDFLibParserError(f"Error parsing RDF: {err}") from err
616
617    def upload(
618        self,
619        data: str | bytes | BinaryIO | Graph | Dataset,
620        base_uri: str | None = None,
621        content_type: str | None = None,
622    ):
623        """Upload and append statements to the repository.
624
625        Parameters:
626            data: The RDF data to upload.
627            base_uri: The base URI to resolve against for any relative URIs in the data.
628            content_type: The content type of the data. Defaults to
629                `application/n-quads` when the value is `None`.
630        """
631        stream, should_close = rdf_payload_to_stream(data)
632        try:
633            headers = {"Content-Type": content_type or "application/n-quads"}
634            params = {}
635            if base_uri is not None:
636                params["baseURI"] = base_uri
637            response = self.http_client.post(
638                f"/repositories/{self.identifier}/statements",
639                headers=headers,
640                params=params,
641                content=stream,
642            )
643            response.raise_for_status()
644        finally:
645            if should_close:
646                stream.close()
647
648    def overwrite(
649        self,
650        data: str | bytes | BinaryIO | Graph | Dataset,
651        graph_name: URIRef | Iterable[URIRef] | str | None = None,
652        base_uri: str | None = None,
653        content_type: str | None = None,
654    ):
655        """Upload and overwrite statements in the repository.
656
657        Parameters:
658            data: The RDF data to upload.
659            graph_name: Graph name(s) to restrict to.
660
661                The default value `None` applies to all graphs.
662
663                To apply to just the default graph, use
664                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
665
666            base_uri: The base URI to resolve against for any relative URIs in the data.
667            content_type: The content type of the data. Defaults to
668                `application/n-quads` when the value is `None`.
669        """
670        stream, should_close = rdf_payload_to_stream(data)
671        validate_graph_name(graph_name)
672        try:
673            headers = {"Content-Type": content_type or "application/n-quads"}
674            params: dict[str, str] = {}
675            build_context_param(params, graph_name)
676            if base_uri is not None:
677                params["baseURI"] = base_uri
678            response = self.http_client.put(
679                f"/repositories/{self.identifier}/statements",
680                headers=headers,
681                params=params,
682                content=stream,
683            )
684            response.raise_for_status()
685        finally:
686            if should_close:
687                stream.close()
688
689    def delete(
690        self,
691        subj: SubjectType = None,
692        pred: PredicateType = None,
693        obj: ObjectType = None,
694        graph_name: URIRef | Iterable[URIRef] | str | None = None,
695    ) -> None:
696        """Deletes statements from the repository matching the filtering parameters.
697
698        !!! Note
699            The terms for `subj`, `pred`, `obj` or `graph_name` cannot be
700            [`BNodes`][rdflib.term.BNode].
701
702        Parameters:
703            subj: Subject of the statement to filter by, or `None` to match all.
704            pred: Predicate of the statement to filter by, or `None` to match all.
705            obj: Object of the statement to filter by, or `None` to match all.
706            graph_name: Graph name(s) to restrict to.
707
708                The default value `None` queries all graphs.
709
710                To query just the default graph, use
711                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
712        """
713        validate_no_bnodes(subj, pred, obj, graph_name)
714        params: dict[str, str] = {}
715        build_context_param(params, graph_name)
716        build_spo_param(params, subj, pred, obj)
717
718        response = self.http_client.delete(
719            f"/repositories/{self.identifier}/statements",
720            params=params,
721        )
722        response.raise_for_status()
723
724    @contextlib.contextmanager
725    def transaction(self):
726        """Create a new transaction for the repository.
727
728        !!! warning
729
730        Transaction instances are not thread-safe. Do not share a single
731        Transaction instance across multiple threads. Each thread should create
732        its own transaction, or use appropriate synchronization if sharing is
733        required.
734        """
735        with Transaction.create(self) as txn:
736            yield txn
737
738
739class Transaction:
740    """An RDF4J transaction.
741
742    !!! warning
743
744        Transaction instances are not thread-safe. Do not share a single
745        Transaction instance across multiple threads. Each thread should create
746        its own transaction, or use appropriate synchronization if sharing is
747        required.
748
749    Parameters:
750        repo: The repository instance.
751    """
752
753    def __init__(self, repo: Repository, url: str):
754        self._repo = repo
755        self._url: str = url
756        self._closed: bool = False
757
758    def __enter__(self):
759        return self
760
761    def __exit__(self, exc_type, exc_val, exc_tb):
762        if not self.is_closed:
763            if exc_type is None:
764                self.commit()
765            else:
766                try:
767                    self.rollback()
768                except Exception:
769                    pass
770
771        # Propagate errors.
772        return False
773
774    @property
775    def repo(self):
776        """The repository instance."""
777        return self._repo
778
779    @property
780    def url(self):
781        """The transaction URL."""
782        return self._url
783
784    @property
785    def is_closed(self) -> bool:
786        """Whether the transaction is closed."""
787        return self._closed
788
789    def _raise_for_closed(self):
790        if self.is_closed:
791            raise TransactionClosedError("The transaction has been closed.")
792
793    @classmethod
794    def create(cls, repo: Repository) -> Transaction:
795        """Create a new transaction for the repository.
796
797        Parameters:
798            repo: The repository instance.
799
800        Returns:
801            A new Transaction instance.
802        """
803        response = repo.http_client.post(
804            f"/repositories/{repo.identifier}/transactions"
805        )
806        response.raise_for_status()
807        url = response.headers["Location"]
808        return cls(repo, url)
809
810    def commit(self):
811        """Commit the transaction.
812
813        Raises:
814            TransactionCommitError: If the transaction commit fails.
815            TransactionClosedError: If the transaction is closed.
816        """
817        self._raise_for_closed()
818        params = {"action": "COMMIT"}
819        response = self.repo.http_client.put(self.url, params=params)
820        if response.status_code != 200:
821            raise TransactionCommitError(
822                f"Transaction commit failed: {response.status_code} - {response.text}"
823            )
824        self._closed = True
825
826    def rollback(self):
827        """Roll back the transaction.
828
829        Raises:
830            TransactionRollbackError: If the transaction rollback fails.
831            TransactionClosedError: If the transaction is closed.
832        """
833        self._raise_for_closed()
834        response = self.repo.http_client.delete(self.url)
835        if response.status_code != 204:
836            raise TransactionRollbackError(
837                f"Transaction rollback failed: {response.status_code} - {response.text}"
838            )
839        self._closed = True
840
841    def ping(self):
842        """Ping the transaction.
843
844        Raises:
845            RepositoryTransactionPingError: If the transaction ping fails.
846            TransactionClosedError: If the transaction is closed.
847        """
848        self._raise_for_closed()
849        params = {"action": "PING"}
850        response = self.repo.http_client.put(self.url, params=params)
851        if response.status_code != 200:
852            raise TransactionPingError(
853                f"Transaction ping failed: {response.status_code} - {response.text}"
854            )
855
856    def size(self, graph_name: URIRef | Iterable[URIRef] | str | None = None):
857        """The number of statements in the repository or in the specified graph name.
858
859        Parameters:
860            graph_name: Graph name(s) to restrict to.
861
862                The default value `None` queries all graphs.
863
864                To query just the default graph, use
865                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
866
867        Returns:
868            The number of statements.
869
870        Raises:
871            RepositoryResponseFormatError: Fails to parse the repository size.
872        """
873        self._raise_for_closed()
874        validate_graph_name(graph_name)
875        params = {"action": "SIZE"}
876        build_context_param(params, graph_name)
877        response = self.repo.http_client.put(self.url, params=params)
878        response.raise_for_status()
879        return self.repo._to_size(response.text)
880
881    def query(self, query: str, **kwargs):
882        """Execute a SPARQL query against the repository.
883
884        Parameters:
885            query: The SPARQL query to execute.
886            **kwargs: Additional keyword arguments to include as query parameters
887                in the request. See
888                [RDF4J REST API - Execute SPARQL query](https://rdf4j.org/documentation/reference/rest-api/#tag/SPARQL/paths/~1repositories~1%7BrepositoryID%7D/get)
889                for the list of supported query parameters.
890        """
891        self._raise_for_closed()
892        headers: dict[str, str] = {}
893        build_sparql_query_accept_header(query, headers)
894        params = {"action": "QUERY", "query": query}
895        response = self.repo.http_client.put(
896            self.url, headers=headers, params={**params, **kwargs}
897        )
898        response.raise_for_status()
899        try:
900            return Result.parse(
901                io.BytesIO(response.content),
902                content_type=response.headers["Content-Type"].split(";")[0],
903            )
904        except KeyError as err:
905            raise RDFLibParserError(
906                f"Failed to parse SPARQL query result {response.headers.get('Content-Type')}: {err}"
907            ) from err
908
909    def update(self, query: str, **kwargs):
910        """Execute a SPARQL update operation on the repository.
911
912        Parameters:
913            query: The SPARQL update query to execute.
914            **kwargs: Additional keyword arguments to include as query parameters
915                See [RDF4J REST API - Execute a transaction action](https://rdf4j.org/documentation/reference/rest-api/#tag/Transactions/paths/~1repositories~1%7BrepositoryID%7D~1transactions~1%7BtransactionID%7D/put)
916                for the list of supported query parameters.
917        """
918        self._raise_for_closed()
919        params = {"action": "UPDATE", "update": query}
920        response = self.repo.http_client.put(
921            self.url,
922            params={**params, **kwargs},
923        )
924        response.raise_for_status()
925
926    def upload(
927        self,
928        data: str | bytes | BinaryIO | Graph | Dataset,
929        base_uri: str | None = None,
930        content_type: str | None = None,
931    ):
932        """Upload and append statements to the repository.
933
934        Parameters:
935            data: The RDF data to upload.
936            base_uri: The base URI to resolve against for any relative URIs in the data.
937            content_type: The content type of the data. Defaults to
938                `application/n-quads` when the value is `None`.
939        """
940        self._raise_for_closed()
941        stream, should_close = rdf_payload_to_stream(data)
942        headers = {"Content-Type": content_type or "application/n-quads"}
943        params = {"action": "ADD"}
944        if base_uri is not None:
945            params["baseURI"] = base_uri
946        try:
947            response = self.repo.http_client.put(
948                self.url,
949                headers=headers,
950                params=params,
951                content=stream,
952            )
953            response.raise_for_status()
954        finally:
955            if should_close:
956                stream.close()
957
958    def get(
959        self,
960        subj: SubjectType = None,
961        pred: PredicateType = None,
962        obj: ObjectType = None,
963        graph_name: URIRef | Iterable[URIRef] | str | None = None,
964        infer: bool = True,
965        content_type: str | None = None,
966    ) -> Graph | Dataset:
967        """Get RDF statements from the repository matching the filtering parameters.
968
969        !!! Note
970            The terms for `subj`, `pred`, `obj` or `graph_name` cannot be
971            [`BNodes`][rdflib.term.BNode].
972
973        Parameters:
974            subj: Subject of the statement to filter by, or `None` to match all.
975            pred: Predicate of the statement to filter by, or `None` to match all.
976            obj: Object of the statement to filter by, or `None` to match all.
977            graph_name: Graph name(s) to restrict to.
978
979                The default value `None` queries all graphs.
980
981                To query just the default graph, use
982                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
983
984            infer: Specifies whether inferred statements should be included in the
985                result.
986            content_type: The content type of the response.
987                A triple-based format returns a [Graph][rdflib.graph.Graph], while a
988                quad-based format returns a [`Dataset`][rdflib.graph.Dataset].
989
990        Returns:
991            A [`Graph`][rdflib.graph.Graph] or [`Dataset`][rdflib.graph.Dataset] object
992                with the repository namespace prefixes bound to it.
993        """
994        self._raise_for_closed()
995        validate_no_bnodes(subj, pred, obj, graph_name)
996        if content_type is None:
997            content_type = "application/n-quads"
998        headers = {"Accept": content_type}
999        params: dict[str, str] = {"action": "GET"}
1000        build_context_param(params, graph_name)
1001        build_spo_param(params, subj, pred, obj)
1002        build_infer_param(params, infer=infer)
1003
1004        response = self.repo.http_client.put(
1005            self.url,
1006            headers=headers,
1007            params=params,
1008        )
1009        response.raise_for_status()
1010        triple_formats = [
1011            "application/n-triples",
1012            "text/turtle",
1013            "application/rdf+xml",
1014        ]
1015        try:
1016            if content_type in triple_formats:
1017                retval = Graph().parse(data=response.text, format=content_type)
1018            else:
1019                retval = Dataset().parse(data=response.text, format=content_type)
1020            for result in self.repo.namespaces.list():
1021                retval.bind(result.prefix, result.namespace, replace=True)
1022            return retval
1023        except Exception as err:
1024            raise RDFLibParserError(f"Error parsing RDF: {err}") from err
1025
1026    def delete(
1027        self,
1028        data: str | bytes | BinaryIO | Graph | Dataset,
1029        base_uri: str | None = None,
1030        content_type: str | None = None,
1031    ) -> None:
1032        """Delete statements from the repository.
1033
1034        !!! Note
1035            This function operates differently to
1036            [`Repository.delete`][rdflib.contrib.rdf4j.client.Repository.delete]
1037            as it does not use filter parameters. Instead, it expects a data payload.
1038            See the notes from
1039            [graphdb.js#Deleting](https://github.com/Ontotext-AD/graphdb.js?tab=readme-ov-file#deleting-1)
1040            for more information.
1041
1042        Parameters:
1043            data: The RDF data to upload.
1044            base_uri: The base URI to resolve against for any relative URIs in the data.
1045            content_type: The content type of the data. Defaults to
1046                `application/n-quads` when the value is `None`.
1047        """
1048        self._raise_for_closed()
1049        params: dict[str, str] = {"action": "DELETE"}
1050        stream, should_close = rdf_payload_to_stream(data)
1051        headers = {"Content-Type": content_type or "application/n-quads"}
1052        if base_uri is not None:
1053            params["baseURI"] = base_uri
1054        try:
1055            response = self.repo.http_client.put(
1056                self.url,
1057                headers=headers,
1058                params=params,
1059                content=stream,
1060            )
1061            response.raise_for_status()
1062        finally:
1063            if should_close:
1064                stream.close()
1065
1066
1067class RepositoryManager:
1068    """A client to manage server-level repository operations.
1069
1070    Parameters:
1071        http_client: The httpx.Client instance.
1072    """
1073
1074    def __init__(self, http_client: httpx.Client):
1075        self._http_client = http_client
1076
1077    @property
1078    def http_client(self):
1079        return self._http_client
1080
1081    def list(self) -> list[RepositoryListingResult]:
1082        """List all available repositories.
1083
1084        Returns:
1085            list[RepositoryListingResult]: List of repository results.
1086
1087        Raises:
1088            RepositoryResponseFormatError: If the response format is unrecognized.
1089        """
1090        headers = {
1091            "Accept": "application/sparql-results+json",
1092        }
1093        response = self.http_client.get("/repositories", headers=headers)
1094        response.raise_for_status()
1095
1096        try:
1097            data = response.json()
1098            results = data["results"]["bindings"]
1099            return [
1100                RepositoryListingResult(
1101                    identifier=repo["id"]["value"],
1102                    uri=repo["uri"]["value"],
1103                    readable=repo["readable"]["value"],
1104                    writable=repo["writable"]["value"],
1105                    title=repo.get("title", {}).get("value"),
1106                )
1107                for repo in results
1108            ]
1109        except (KeyError, ValueError) as err:
1110            raise RepositoryResponseFormatError(f"Unrecognised response format: {err}")
1111
1112    def get(self, repository_id: str) -> Repository:
1113        """Get a repository by ID.
1114
1115        !!! Note
1116            This performs a health check before returning the repository object.
1117
1118        Parameters:
1119            repository_id: The identifier of the repository.
1120
1121        Returns:
1122            Repository: The repository instance.
1123
1124        Raises:
1125            RepositoryNotFoundError: If the repository is not found.
1126            RepositoryNotHealthyError: If the repository is not healthy.
1127        """
1128        repo = Repository(repository_id, self.http_client)
1129        repo.health()
1130        return repo
1131
1132    def create(
1133        self, repository_id: str, data: str, content_type: str = "text/turtle"
1134    ) -> Repository:
1135        """Create a new repository.
1136
1137        Parameters:
1138            repository_id: The identifier of the repository.
1139            data: The repository configuration in RDF.
1140            content_type: The repository configuration content type.
1141
1142        Raises:
1143            RepositoryAlreadyExistsError: If the repository already exists.
1144            RepositoryNotHealthyError: If the repository is not healthy.
1145        """
1146        try:
1147            headers = {"Content-Type": content_type}
1148            response = self.http_client.put(
1149                f"/repositories/{repository_id}", headers=headers, content=data
1150            )
1151            response.raise_for_status()
1152            return self.get(repository_id)
1153        except httpx.HTTPStatusError as err:
1154            if err.response.status_code == 409:
1155                raise RepositoryAlreadyExistsError(
1156                    f"Repository {repository_id} already exists."
1157                )
1158            raise
1159
1160    def delete(self, repository_id: str) -> None:
1161        """Delete a repository.
1162
1163        Parameters:
1164            repository_id: The identifier of the repository.
1165
1166        Raises:
1167            RepositoryNotFoundError: If the repository is not found.
1168            RepositoryError: If the repository is not deleted successfully.
1169        """
1170        try:
1171            response = self.http_client.delete(f"/repositories/{repository_id}")
1172            response.raise_for_status()
1173            if response.status_code != 204:
1174                raise RepositoryError(
1175                    f"Unexpected response status code when deleting repository {repository_id}: {response.status_code} - {response.text.strip()}"
1176                )
1177        except httpx.HTTPStatusError as err:
1178            if err.response.status_code == 404:
1179                raise RepositoryNotFoundError(f"Repository {repository_id} not found.")
1180            raise
1181
1182
1183class RDF4JClient:
1184    """RDF4J client.
1185
1186    This client and its inner management objects perform HTTP requests via
1187    httpx and may raise httpx-specific exceptions. Errors documented by RDF4J
1188    in its protocol specification are mapped to specific exceptions in this
1189    library where applicable. Error mappings are documented on each management
1190    method. The underlying httpx client is reused across requests, and
1191    connection pooling is handled automatically by httpx.
1192
1193    Parameters:
1194        base_url: The base URL of the RDF4J server.
1195        auth: Authentication credentials. Can be a tuple (username, password) for
1196            basic auth, or a string for token-based auth (e.g., "GDB <token>")
1197            which is added as the Authorization header.
1198        timeout: Request timeout in seconds or an httpx.Timeout for fine-grained control (default: 30.0).
1199        kwargs: Additional keyword arguments to pass to the httpx.Client.
1200    """
1201
1202    def __init__(
1203        self,
1204        base_url: str,
1205        auth: tuple[str, str] | str | None = None,
1206        timeout: float | httpx.Timeout = 30.0,
1207        **kwargs: Any,
1208    ):
1209        if not base_url.endswith("/"):
1210            base_url += "/"
1211
1212        httpx_auth: tuple[str, str] | None = None
1213        if isinstance(auth, tuple):
1214            httpx_auth = auth
1215        elif isinstance(auth, str):
1216            headers = kwargs.get("headers", {})
1217            headers["Authorization"] = auth
1218            kwargs["headers"] = headers
1219
1220        self._http_client = httpx.Client(
1221            base_url=base_url, auth=httpx_auth, timeout=timeout, **kwargs
1222        )
1223        self._repository_manager = RepositoryManager(self.http_client)
1224        try:
1225            protocol_version = self.protocol
1226        except httpx.RequestError as err:
1227            self.close()
1228            raise RDF4JUnsupportedProtocolError(
1229                f"Failed to check protocol version: {err}"
1230            ) from err
1231        if protocol_version < 12:
1232            self.close()
1233            raise RDF4JUnsupportedProtocolError(
1234                f"RDF4J server protocol version {protocol_version} is not supported. Minimum required version is 12."
1235            )
1236
1237    def __enter__(self):
1238        return self
1239
1240    def __exit__(self, exc_type, exc_val, exc_tb):
1241        self.close()
1242
1243    @property
1244    def http_client(self):
1245        return self._http_client
1246
1247    @property
1248    def repositories(self) -> RepositoryManager:
1249        """Server-level repository management operations."""
1250        return self._repository_manager
1251
1252    @property
1253    def protocol(self) -> float:
1254        """The RDF4J REST API protocol version.
1255
1256        Returns:
1257            The protocol version number.
1258        """
1259        response = self.http_client.get("/protocol", headers={"Accept": "text/plain"})
1260        response.raise_for_status()
1261        return float(response.text.strip())
1262
1263    def close(self):
1264        """Close the underlying httpx.Client."""
1265        self.http_client.close()