
    Pi                    b   d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	m
Z
mZ ddlZddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZm Z m!Z!m"Z" dd	l#m$Z$m%Z%m&Z& dd
l'm(Z( ddl)m*Z*m+Z+m,Z, ej-        e,df         Z.ej-        e,df         Z/ej-        e,e+df         Z0 ed           G d d                      Z1 G d d          Z2 G d d          Z3 ed           G d d                      Z4 G d d          Z5 G d d          Z6 G d d          Z7 G d d          Z8dS )zRDF4J client module.    )annotationsN)	dataclass)AnyBinaryIOIterable)BNode)RDF4JUnsupportedProtocolErrorRDFLibParserErrorRepositoryAlreadyExistsErrorRepositoryErrorRepositoryFormatErrorRepositoryNotFoundErrorRepositoryNotHealthyErrorTransactionClosedErrorTransactionCommitErrorTransactionPingErrorTransactionRollbackError)build_context_parambuild_infer_param build_sparql_query_accept_headerbuild_spo_paramrdf_payload_to_streamvalidate_graph_namevalidate_no_bnodes)DATASET_DEFAULT_GRAPH_IDDatasetGraph)Result)IdentifiedNodeLiteralURIRefT)frozenc                  (    e Zd ZU dZded<   ded<   dS )NamespaceListingResultz'RDF4J namespace and prefix name result.strprefix	namespaceN)__name__
__module____qualname____doc____annotations__     o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/rdflib/contrib/rdf4j/client.pyr$   r$   -   s(         11KKKNNNNNr.   r$   c                  l    e Zd ZdZddZed             Zed             ZddZd Z	ddZ
ddZddZdS )RDF4JNamespaceManagerzA namespace manager for RDF4J repositories.

    Parameters:
        identifier: The identifier of the repository.
        http_client: The httpx.Client instance.
    
identifierr%   http_clienthttpx.Clientc                "    || _         || _        d S N)_identifier_http_clientselfr2   r3   s      r/   __init__zRDF4JNamespaceManager.__init__=   s    %'r.   c                    | j         S r6   r8   r:   s    r/   r3   z!RDF4JNamespaceManager.http_clientA         r.   c                    | j         S zRepository identifier.r7   r>   s    r/   r2   z RDF4JNamespaceManager.identifierE        r.   returnlist[NamespaceListingResult]c                0   ddi}| j                             d| j         d|          }|                                 	 |                                }|d         d         }d |D             S # t
          t          f$ r}t          d	|           d
}~ww xY w)zList all namespace declarations in the repository.

        Returns:
            list[NamespaceListingResult]: List of namespace and prefix name results.

        Raises:
            RepositoryFormatError: If the response format is unrecognized.
        Acceptapplication/sparql-results+json/repositories//namespacesheadersresultsbindingsc                `    g | ]+}t          |d          d         |d         d                   ,S )r&   valuer'   )r&   r'   )r$   ).0rows     r/   
<listcomp>z.RDF4JNamespaceManager.list.<locals>.<listcomp>^   sR       
 	 'x=1!+.w7    r.   Unrecognised response format: N)r3   getr2   raise_for_statusjsonKeyError
ValueErrorr   r:   rL   responsedatarM   errs         r/   listzRDF4JNamespaceManager.listJ   s     7
 #''9T_9997 ( 
 
 	!!###	P==??D9oj1G 
 #    *% 	P 	P 	P'(N(N(NOOO	Ps   -A- -B>BBc                    ddi}| j                             d| j         d|          }|                                 dS )z3Clear all namespace declarations in the repository.rG   rH   rI   rJ   rK   N)r3   deleter2   rV   )r:   rL   r[   s      r/   clearzRDF4JNamespaceManager.clearh   s\     7
 #**9T_9997 + 
 
 	!!#####r.   r&   
str | Nonec                   |st          d          ddi}	 | j                            d| j         d| |          }|                                 |j        S # t          j        $ r}|j        j	        dk    rY d}~dS  d}~ww xY w)	zGet the namespace URI for a given prefix.

        Parameters:
            prefix: The prefix to lookup.

        Returns:
            The namespace URI or `None` if not found.
        Prefix cannot be empty.rG   
text/plainrI   /namespaces/rK     N)
rY   r3   rU   r2   rV   texthttpxHTTPStatusErrorr[   status_code)r:   r&   rL   r[   r]   s        r/   rU   zRDF4JNamespaceManager.getr   s      	86777l
		'++FFFfFFPW ,  H %%'''= $ 	 	 	|'3..ttttt	s   AA B(A?>A??Br'   c                    |st          d          |st          d          ddi}| j                            d| j         d| ||          }|                                 dS )	a!  Set the namespace URI for a given prefix.

        !!! note
            If the prefix was previously mapped to a different namespace, this will be
            overwritten.

        Parameters:
            prefix: The prefix to set.
            namespace: The namespace URI to set.
        rd   zNamespace cannot be empty.Content-Typere   rI   rf   rL   contentN)rY   r3   putr2   rV   )r:   r&   r'   rL   r[   s        r/   setzRDF4JNamespaceManager.set   s      	86777 	;9:::L
 #''BT_BB&BB ( 
 

 	!!#####r.   c                    |st          d          | j                            d| j         d|           }|                                 dS )z|Remove the namespace declaration for a given prefix.

        Parameters:
            prefix: The prefix to remove.
        rd   rI   rf   N)rY   r3   r`   r2   rV   )r:   r&   r[   s      r/   removezRDF4JNamespaceManager.remove   sb      	86777#**BT_BB&BB
 
 	!!#####r.   Nr2   r%   r3   r4   )rD   rE   )r&   r%   rD   rb   )r&   r%   r'   r%   )r&   r%   )r(   r)   r*   r+   r;   propertyr3   r2   r^   ra   rU   rq   rs   r-   r.   r/   r1   r1   5   s         ( ( ( ( ! ! X!     X P P P P<$ $ $   2$ $ $ $2$ $ $ $ $ $r.   r1   c                      e Zd ZdZddZed             Zed             Zedd            Z	ddZ
ddZddZddZddZdS )GraphStoreManagerzAn RDF4J Graph Store Protocol Client.

    Parameters:
        identifier: The identifier of the repository.
        http_client: The httpx.Client instance.
    r2   r%   r3   r4   c                0    || _         || _        d| _        d S )Napplication/n-triples)r7   r8   _content_typer9   s      r/   r;   zGraphStoreManager.__init__   s     %'4r.   c                    | j         S r6   r=   r>   s    r/   r3   zGraphStoreManager.http_client   r?   r.   c                    | j         S rA   rB   r>   s    r/   r2   zGraphStoreManager.identifier   rC   r.   
graph_nameURIRef | strc                    i }t          | t                    r| t          k    s-t          | t                    r| t          t                    k    rnt          |           |d<   |S )Ngraph)
isinstancer!   r   r%   )r}   paramss     r/   _build_graph_name_paramsz*GraphStoreManager._build_graph_name_params   sd    z6**	.666*c** 7c":;;;; !*ooF7Or.   c                f    d| j          d}t          |t                    r|t          k    r|dz  }|S )NrI   z/rdf-graphs/servicez?default)r2   r   r!   r   )r:   r}   urls      r/   
_build_urlzGraphStoreManager._build_url   s@    CtCCCj&)) 	j<T.T.T:C
r.   rD   r   c                h   |st          d          t          |           d| j        i}|                     |          pd}| j                            |                     |          ||          }|                                 t          |          	                    |j
        | j                  S )a}  Fetch all statements in the specified graph.

        Parameters:
            graph_name: The graph name of the graph.

                For the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

        Returns:
            A [`Graph`][rdflib.graph.Graph] object containing all statements in the
                graph.
        Graph name must be provided.rG   NrL   r   )r2   r\   format)rY   r   rz   r   r3   rU   r   rV   r   parserh   )r:   r}   rL   r   r[   s        r/   rU   zGraphStoreManager.get   s      	=;<<<J'''d(
 ..z::Bd#''OOJ'' ( 
 

 	!!###
+++11t'9 2 
 
 	
r.   r\   str | bytes | BinaryIO | Graphc                   |st          d          t          |           t          |          \  }}d| j        i}|                     |          pd}	 | j                            |                     |          |||          }|                                 |r|	                                 dS dS # |r|	                                 w w xY w)a"  Add statements to the specified graph.

        Parameters:
            graph_name: The graph name of the graph.

                For the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

            data: The RDF data to add.
        r   rm   NrL   r   ro   )
rY   r   r   rz   r   r3   postr   rV   closer:   r}   r\   streamshould_closerL   r   r[   s           r/   addzGraphStoreManager.add  s      	=;<<<J'''4T::D.
 ..z::Bd
	',,
++	 -  H %%'''  |    AB3 3Cc                   |st          d          t          |           t          |          \  }}d| j        i}|                     |          pd}	 | j                            |                     |          |||          }|                                 |r|	                                 dS dS # |r|	                                 w w xY w)a3  Overwrite statements in the specified graph.

        Parameters:
            graph_name: The graph name of the graph.

                For the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

            data: The RDF data to overwrite with.
        r   rm   Nr   )
rY   r   r   rz   r   r3   rp   r   rV   r   r   s           r/   	overwritezGraphStoreManager.overwrite"  s      	=;<<<J'''4T::D.
 ..z::Bd
	'++
++	 ,  H %%'''  | r   c                    |st          d          t          |           |                     |          pd}| j                            |                     |          |          }|                                 dS )a   Clear all statements in the specified graph.

        Parameters:
            graph_name: The graph name of the graph.

                For the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
        r   Nr   )rY   r   r   r3   r`   r   rV   r:   r}   r   r[   s       r/   ra   zGraphStoreManager.clearA  s      	=;<<<J'''..z::Bd#**4??:+F+Fv*VV!!#####r.   Nrt   )r}   r~   )r}   r~   rD   r   )r}   r~   r\   r   )r(   r)   r*   r+   r;   ru   r3   r2   staticmethodr   r   rU   r   r   ra   r-   r.   r/   rw   rw      s         5 5 5 5
 ! ! X!     X     \(   
 
 
 
@   >   >$ $ $ $ $ $r.   rw   c                  J    e Zd ZU dZded<   ded<   ded<   ded<   dZd	ed
<   dS )RepositoryListingResulta'  RDF4J repository listing result.

    Parameters:
        identifier: Repository identifier.
        uri: Repository URI.
        readable: Whether the repository is readable by the client.
        writable: Whether the repository is writable by the client.
        title: Repository title.
    r%   r2   uriboolreadablewritableNrb   title)r(   r)   r*   r+   r,   r   r-   r.   r/   r   r   R  sS           OOOHHHNNNNNNEr.   r   c                     e Zd ZdZd0dZed             Zed             Zed1d            Zed2d            Z	d3dZ
d4d5dZed6d            Zd7dZd7dZd8dZ	 	 	 	 	 	 d9d:d'Z	 	 d;d<d+Z	 	 	 d=d>d,Z	 	 	 	 d?d@d.Zej        d/             ZdS )A
RepositoryzRDF4J repository client.

    Parameters:
        identifier: The identifier of the repository.
        http_client: The httpx.Client instance.
    r2   r%   r3   r4   c                >    || _         || _        d | _        d | _        d S r6   )r7   r8   _namespace_manager_graph_store_managerr9   s      r/   r;   zRepository.__init__m  s(    %'@D>B!!!r.   c                    | j         S r6   r=   r>   s    r/   r3   zRepository.http_clients  r?   r.   c                    | j         S rA   rB   r>   s    r/   r2   zRepository.identifierw  rC   r.   rD   r1   c                \    | j         t          | j        | j                  | _         | j         S )z%Namespace manager for the repository.)r   r1   r2   r3   r>   s    r/   
namespaceszRepository.namespaces|  s4     "*&;!1' 'D# &&r.   rw   c                \    | j         t          | j        | j                  | _         | j         S )z'Graph store manager for the repository.)r   rw   r2   r3   r>   s    r/   graphszRepository.graphs  s4     $,(9!1) )D% ((r.   r   c           	     d   ddd}	 | j                             d| j         |d          }|                                 dS # t          j        $ r^}|j        j        dk    rt          d	| j         d
          t          d	| j         d|j        j         d|j        j
                   d}~ww xY w)a%  Repository health check.

        Returns:
            bool: True if the repository is healthy, otherwise an error is raised.

        Raises:
            RepositoryNotFoundError: If the repository is not found.
            RepositoryNotHealthyError: If the repository is not healthy.
        application/sparql-queryrH   )rm   rG   rI   zASK {}rn   Trg   Repository  not found.z is not healthy.  - N)r3   r   r7   rV   ri   rj   r[   rk   r   r   rh   )r:   rL   r[   r]   s       r/   healthzRepository.health  s     77
 
	',,3!133Wh -  H %%'''4$ 	 	 	|'3..-?$"2???   ,qd.qqAYqq^a^j^oqq  	s   9A B/AB**B/Nr}   &URIRef | Iterable[URIRef] | str | Noneintc                    t          |           i }t          ||           | j                            d| j         d|          }|                                 |                     |j                  S )  The number of statements in the repository or in the specified graph name.

        Parameters:
            graph_name: Graph name(s) to restrict to.

                The default value `None` queries all graphs.

                To query just the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

        Returns:
            The number of statements.

        Raises:
            RepositoryFormatError: Fails to parse the repository size.
        rI   z/sizer   )r   r   r3   rU   r2   rV   _to_sizerh   r   s       r/   sizezRepository.size  s~    " 	J'''!#FJ///#''3T_333F ( 
 
 	!!###}}X]+++r.   r   c                    	 t          |           }|dk    r|S t          d|           # t          $ r}t          d|           |d }~ww xY w)Nr   zInvalid repository size: z!Failed to parse repository size: )r   rY   r   )r   rP   r]   s      r/   r   zRepository._to_size  sv    	IIEzz@@@AAA 	 	 	'9C99 	s   + + 
AAAqueryc                   ddi}t          ||           |s&| j                            d| j         ||          }n)| j                            d| j         |d|i|          }|                                 	 t          j        t          j	        |j
                  |j        d                             d          d         	          S # t          $ r3}t          d
|j                            d           d|           |d}~ww xY w)a  Execute a SPARQL query against the repository.

        !!! note
            A POST request is used by default. If any keyword arguments are provided,
            a GET request is used instead, and the arguments are passed as query parameters.

        Parameters:
            query: The SPARQL query to execute.
            **kwargs: Additional keyword arguments to include as query parameters
                in the request. See
                [RDF4J REST API - Execute SPARQL query](https://rdf4j.org/documentation/reference/rest-api/#tag/SPARQL/paths/~1repositories~1%7BrepositoryID%7D/get)
                for the list of supported query parameters.
        rm   r   rI   rn   r   r   ;r   content_type$Failed to parse SPARQL query result : N)r   r3   r   r2   rU   rV   r   r   ioBytesIOro   rL   splitrX   r
   )r:   r   kwargsrL   r[   r]   s         r/   r   zRepository.query  sN    "#=>(888 		',,222GU -  HH '++2221&1 ,  H
 	!!###	<
8+,,%-n=CCCHHK     	 	 	#dx7G7K7KN7[7[dd_bdd 	s   ;AC 
D	.DD	c                    ddi}| j                             d| j         d||          }|                                 dS )zExecute a SPARQL update operation on the repository.

        Parameters:
            query: The SPARQL update query to execute.
        rm   zapplication/sparql-updaterI   /statementsrn   N)r3   r   r2   rV   )r:   r   rL   r[   s       r/   updatezRepository.update  s\     "#>?#((9T_999 ) 
 

 	!!#####r.   list[IdentifiedNode]c                   ddi}| j                             d| j         d|          }|                                 	 g }|                                d         d         D ]}|d         d	         }|d         d
         }|dk    r#|                    t          |                     G|dk    r#|                    t          |                     pt          d|           |S # t          $ r}t          d|           |d}~ww xY w)zGet a list of all graph names in the repository.

        Returns:
            A list of graph names.

        Raises:
            RepositoryFormatError: Fails to parse the repository graph names.
        rG   rH   rI   z	/contextsrK   rM   rN   	contextIDrP   typer   bnodezInvalid graph name type: z(Failed to parse repository graph names: N)r3   rU   r2   rV   rW   appendr!   r   rY   	Exceptionr   )r:   rL   r[   valuesrR   rP   
value_typer]   s           r/   graph_nameszRepository.graph_names  sH    7
 #''7T_777 ( 
 
 	!!###	+-F}}y1*= O OK(1 -f5
&&MM&--00007**MM%,,////$%M%M%MNNNM 	 	 	'@3@@ 	s   B%C% %
D/DDTsubjSubjectTypepredPredicateTypeobj
ObjectTypeinferr   rb   Graph | Datasetc                   t          ||||           |d}d|i}i }t          ||           t          ||||           t          ||           | j                            d| j         d||          }	|	                                 g d}
	 ||
v r)t                      	                    |	j
        |	          }n(t                      	                    |	j
        |	          }| j                                        D ]$}|                    |j        |j        d
           %|S # t"          $ r}t%          d|           |d}~ww xY w)  Get RDF statements from the repository matching the filtering parameters.

        !!! Note
            The terms for `subj`, `pred`, `obj` or `graph_name` cannot be
            [`BNodes`][rdflib.term.BNode].

        Parameters:
            subj: Subject of the statement to filter by, or `None` to match all.
            pred: Predicate of the statement to filter by, or `None` to match all.
            obj: Object of the statement to filter by, or `None` to match all.
            graph_name: Graph name(s) to restrict to.

                The default value `None` queries all graphs.

                To query just the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

            infer: Specifies whether inferred statements should be included in the
                result.
            content_type: The content type of the response.
                A triple-based format returns a [Graph][rdflib.graph.Graph], while a
                quad-based format returns a [`Dataset`][rdflib.graph.Dataset].

        Returns:
            A [`Graph`][rdflib.graph.Graph] or [`Dataset`][rdflib.graph.Dataset] object
                with the repository namespace prefixes bound to it.
        Napplication/n-quadsrG   r   rI   r   r   ry   text/turtlezapplication/rdf+xmlr   TreplaceError parsing RDF: )r   r   r   r   r3   rU   r2   rV   r   r   rh   r   r   r^   bindr&   r'   r   r
   r:   r   r   r   r}   r   r   rL   r   r[   triple_formatsretvalresultr]   s                 r/   rU   zRepository.get&  s   H 	4sJ7770L\*!#FJ///dC000&....#''9T_999 ( 
 

 	!!###
 
 

		J~--HM,OO hmLQQ/..00 K KFM6+;TJJJJM 	J 	J 	J#$?#$?$?@@cI	Js   BD$ $
E.EEr\   (str | bytes | BinaryIO | Graph | Datasetbase_uric                (   t          |          \  }}	 d|pdi}i }|||d<   | j                            d| j         d|||          }|                                 |r|                                 dS dS # |r|                                 w w xY w)T  Upload and append statements to the repository.

        Parameters:
            data: The RDF data to upload.
            base_uri: The base URI to resolve against for any relative URIs in the data.
            content_type: The content type of the data. Defaults to
                `application/n-quads` when the value is `None`.
        rm   r   NbaseURIrI   r   r   )r   r3   r   r2   rV   r   	r:   r\   r   r   r   r   rL   r   r[   s	            r/   uploadzRepository.uploadi  s      5T::	%|'L7LMGF#$,y!',,====	 -  H %%'''  | s   A
A8 8Bc                f   t          |          \  }}t          |           	 d|pdi}i }t          ||           |||d<   | j                            d| j         d|||          }	|	                                 |r|                                 dS dS # |r|                                 w w xY w)a]  Upload and overwrite statements in the repository.

        Parameters:
            data: The RDF data to upload.
            graph_name: Graph name(s) to restrict to.

                The default value `None` applies to all graphs.

                To apply to just the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].

            base_uri: The base URI to resolve against for any relative URIs in the data.
            content_type: The content type of the data. Defaults to
                `application/n-quads` when the value is `None`.
        rm   r   Nr   rI   r   r   )r   r   r   r3   rp   r2   rV   r   )
r:   r\   r}   r   r   r   r   rL   r   r[   s
             r/   r   zRepository.overwrite  s    ,  5T::J'''	%|'L7LMG%'F
333#$,y!'++====	 ,  H %%'''  | s   AB B0Nonec                    t          ||||           i }t          ||           t          ||||           | j                            d| j         d|          }|                                 dS )a  Deletes statements from the repository matching the filtering parameters.

        !!! Note
            The terms for `subj`, `pred`, `obj` or `graph_name` cannot be
            [`BNodes`][rdflib.term.BNode].

        Parameters:
            subj: Subject of the statement to filter by, or `None` to match all.
            pred: Predicate of the statement to filter by, or `None` to match all.
            obj: Object of the statement to filter by, or `None` to match all.
            graph_name: Graph name(s) to restrict to.

                The default value `None` queries all graphs.

                To query just the default graph, use
                [`DATASET_DEFAULT_GRAPH_ID`][rdflib.graph.DATASET_DEFAULT_GRAPH_ID].
        rI   r   r   N)r   r   r   r3   r`   r2   rV   )r:   r   r   r   r}   r   r[   s          r/   r`   zRepository.delete  s    0 	4sJ777!#FJ///dC000#**9T_999 + 
 
 	!!#####r.   c              #  b   K   t          |           5 }|V  ddd           dS # 1 swxY w Y   dS )z,Create a new transaction for the repository.N)Transaction)r:   txns     r/   transactionzRepository.transaction  s        	#III	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   $((rt   )rD   r1   )rD   rw   rD   r   r6   )r}   r   rD   r   )r   r%   r   r%   )rD   r   NNNNTNr   r   r   r   r   r   r}   r   r   r   r   rb   rD   r   NNr\   r   r   rb   r   rb   )NNN)r\   r   r}   r   r   rb   r   rb   )NNNN)
r   r   r   r   r   r   r}   r   rD   r   )r(   r)   r*   r+   r;   ru   r3   r2   r   r   r   r   r   r   r   r   r   rU   r   r   r`   
contextlibcontextmanagerr   r-   r.   r/   r   r   e  s        C C C C ! ! X!     X  ' ' ' X' ) ) ) X)   :, , , , ,4 	 	 	 \	$ $ $ $L$ $ $ $   F !"=A#'AJ AJ AJ AJ AJL  $#'	    D >B##'' ' ' ' 'V !"=A!$ !$ !$ !$ !$F     r.   r   c                      e Zd ZdZd-dZd Zd Zed             Zed             Z	ed.d            Z
d Zd/dZd Zd Zd Zd Zd Zd0d1dZd2dZd2dZ	 	 d3d4d Z	 	 	 	 	 	 d5d6d*Z	 	 d3d7d,ZdS )8r   zRAn RDF4J transaction.

    Parameters:
        repo: The repository instance.
    repor   c                "    || _         d | _        d S r6   )_repo_url)r:   r  s     r/   r;   zTransaction.__init__  s    
 $			r.   c                8    |                                  | _        | S r6   _start_transactionr  r>   s    r/   	__enter__zTransaction.__enter__  s    ++--	r.   c                    | j         s=||                                  n&	 |                                  n# t          $ r Y nw xY wdS )NF)	is_closedcommitrollbackr   r:   exc_typeexc_valexc_tbs       r/   __exit__zTransaction.__exit__  s\    ~ 	MMOOOO    D us   5 
AAc                    | j         S )zThe repository instance.)r  r>   s    r/   r  zTransaction.repo  s     zr.   c                    | j         S )zThe transaction URL.r  r>   s    r/   r   zTransaction.url  s     yr.   rD   r   c                    | j         du S )z"Whether the transaction is closed.Nr  r>   s    r/   r
  zTransaction.is_closed  s     yD  r.   c                2    | j         rt          d          d S )Nz The transaction has been closed.)r
  r   r>   s    r/   _raise_for_closedzTransaction._raise_for_closed  s(    > 	M()KLLL	M 	Mr.   r%   c                    | j         j                            d| j         j         d          }|                                 |j        d         S )NrI   z/transactionsLocation)r  r3   r   r2   rV   rL   r:   r[   s     r/   r  zTransaction._start_transaction
  sQ    9(--@TY1@@@
 
 	!!###
++r.   c                    d | _         d S r6   r  r>   s    r/   _close_transactionzTransaction._close_transaction  s    			r.   c                8    |                                  | _        dS )zOpens a transaction.Nr  r>   s    r/   openzTransaction.open  s    ++--			r.   c                    |                                   ddi}| j        j                            | j        |          }|j        dk    rt          d|j         d|j                   |                                  dS )zCommit the transaction.

        Raises:
            TransactionCommitError: If the transaction commit fails.
            TransactionClosedError: If the transaction is closed.
        actionCOMMITr      zTransaction commit failed: r   N)	r  r  r3   rp   r   rk   r   rh   r  r:   r   r[   s      r/   r  zTransaction.commit  s     	   H%9(,,TXf,EE3&&(Vh.BVVx}VV   	!!!!!r.   c                    | j         j                            | j                  }|j        dk    rt          d|j         d|j                   |                                  dS )zRoll back the transaction.   zTransaction rollback failed: r   N)r  r3   r`   r   rk   r   rh   r  r  s     r/   r  zTransaction.rollback(  sn    9(//993&&*X0DXXXX   	!!!!!r.   c                    |                                   ddi}| j        j                            | j        |          }|j        dk    rt          d|j         d|j                   dS )zPing the transaction.

        Raises:
            RepositoryTransactionPingError: If the transaction ping fails.
            TransactionClosedError: If the transaction is closed.
        r   PINGr   r"  zTransaction ping failed: r   N)r  r  r3   rp   r   rk   r   rh   r#  s      r/   pingzTransaction.ping1  s     	   F#9(,,TXf,EE3&&&TH,@TTX]TT   '&r.   Nr}   r   c                "   |                                   t          |           ddi}t          ||           | j        j                            | j        |          }|                                 | j                            |j	                  S )r   r   SIZEr   )
r  r   r   r  r3   rp   r   rV   r   rh   r   s       r/   r   zTransaction.size@  s    " 	   J'''F#FJ///9(,,TXf,EE!!###y!!(-000r.   r   c                   i }t          ||           d|d}| j        j                            | j        |i ||          }|                                 	 t          j        t          j	        |j
                  |j        d                             d          d                   S # t          $ r3}t          d|j                            d           d	|           |d
}~ww xY w)a  Execute a SPARQL query against the repository.

        Parameters:
            query: The SPARQL query to execute.
            **kwargs: Additional keyword arguments to include as query parameters
                in the request. See
                [RDF4J REST API - Execute SPARQL query](https://rdf4j.org/documentation/reference/rest-api/#tag/SPARQL/paths/~1repositories~1%7BrepositoryID%7D/get)
                for the list of supported query parameters.
        QUERY)r   r   r   rm   r   r   r   r   r   N)r   r  r3   rp   r   rV   r   r   r   r   ro   rL   r   rX   r
   rU   )r:   r   r   rL   r   r[   r]   s          r/   r   zTransaction.queryY  s    #%(888#e449(,,Hg.B.B6.B - 
 
 	!!###	<
8+,,%-n=CCCHHK     	 	 	#dx7G7K7KN7[7[dd_bdd 	s   AB) )
C&3.C!!C&c                    d|d}| j         j                            | j        i ||          }|                                 dS )a  Execute a SPARQL update operation on the repository.

        Parameters:
            query: The SPARQL update query to execute.
            **kwargs: Additional keyword arguments to include as query parameters
                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)
                for the list of supported query parameters.
        UPDATE)r   r   r   N)r  r3   rp   r   rV   )r:   r   r   r   r[   s        r/   r   zTransaction.updatet  s\     %669(,,H'f'' - 
 
 	!!#####r.   r\   r   r   rb   r   c                .   t          |          \  }}d|pdi}ddi}|||d<   	 | j        j                            | j        |||          }|                                 |r|                                 dS dS # |r|                                 w w xY w)r   rm   r   r   ADDNr   r   r   r  r3   rp   r   rV   r   r   s	            r/   r   zTransaction.upload  s      5T::!<#H3HIE" (F9
	y,00	 1  H %%'''  |    <A; ;BTr   r   r   r   r   r   r   r   c                   t          ||||           |d}d|i}ddi}t          ||           t          ||||           t          ||           | j        j                            | j        ||          }	|	                                 g d}
	 ||
v r)t                      
                    |	j        |	          }n(t                      
                    |	j        |	          }| j        j                                        D ]$}|                    |j        |j        d
           %|S # t$          $ r}t'          d|           |d}~ww xY w)r   Nr   rG   r   GETr   r   r   r   Tr   r   )r   r   r   r   r  r3   rp   r   rV   r   r   rh   r   r   r^   r   r&   r'   r   r
   r   s                 r/   rU   zTransaction.get  s   H 	4sJ7770L\*"*E!2FJ///dC000&....9(,,H - 
 

 	!!###
 
 

		J~--HM,OO hmLQQ).3355 K KFM6+;TJJJJM 	J 	J 	J#$?#$?$?@@cI	Js   BD, ,
E6E		Er   c                .   ddi}t          |          \  }}d|pdi}|||d<   	 | j        j                            | j        |||          }|                                 |r|                                 dS dS # |r|                                 w w xY w)a  Delete statements from the repository.

        !!! Note
            This function operates differently to
            [`Repository.delete`][rdflib.contrib.rdf4j.client.Repository.delete]
            as it does not use filter parameters. Instead, it expects a data payload.
            See the notes from
            [graphdb.js#Deleting](https://github.com/Ontotext-AD/graphdb.js?tab=readme-ov-file#deleting-1)
            for more information.

        Parameters:
            data: The RDF data to upload.
            base_uri: The base URI to resolve against for any relative URIs in the data.
            content_type: The content type of the data. Defaults to
                `application/n-quads` when the value is `None`.
        r   DELETErm   r   Nr   r   r1  )	r:   r\   r   r   r   r   r   rL   r[   s	            r/   r`   zTransaction.delete  s    , #+H!54T::!<#H3HI (F9
	y,00	 1  H %%'''  | r2  )r  r   r   )rD   r%   r6   )r}   r   r   r   r   r   r   )r\   r   r   rb   r   rb   rD   r   )r(   r)   r*   r+   r;   r  r  ru   r  r   r
  r  r  r  r  r  r  r(  r   r   r   r   rU   r`   r-   r.   r/   r   r     s        % % % %       X   X ! ! ! X!M M M, , , ,  . . ." " " " " "  1 1 1 1 12   6$ $ $ $&  $#'	    B !"=A#'AJ AJ AJ AJ AJL  $#'	% % % % % % %r.   r   c                  T    e Zd ZdZddZed             ZddZddZ	 dddZ	ddZ
dS )RepositoryManagerz|A client to manage server-level repository operations.

    Parameters:
        http_client: The httpx.Client instance.
    r3   r4   c                    || _         d S r6   r=   )r:   r3   s     r/   r;   zRepositoryManager.__init__  s    'r.   c                    | j         S r6   r=   r>   s    r/   r3   zRepositoryManager.http_client  r?   r.   rD   list[RepositoryListingResult]c                   ddi}| j                             d|          }|                                 	 |                                }|d         d         }d |D             S # t          t
          f$ r}t          d|           d	}~ww xY w)
zList all available repositories.

        Returns:
            list[RepositoryListingResult]: List of repository results.

        Raises:
            RepositoryFormatError: If the response format is unrecognized.
        rG   rH   z/repositoriesrK   rM   rN   c                    g | ]m}t          |d          d         |d         d         |d         d         |d         d         |                    di                               d                    nS )idrP   r   r   r   r   )r2   r   r   r   r   )r   rU   )rQ   r  s     r/   rS   z*RepositoryManager.list.<locals>.<listcomp>.  s     	 	 	  (#Dz'2UG,!*-g6!*-g6((7B//33G<<  	 	 	r.   rT   N)r3   rU   rV   rW   rX   rY   r   rZ   s         r/   r^   zRepositoryManager.list  s     7
 #'''II!!###	P==??D9oj1G	 	 $	 	 	 	 *% 	P 	P 	P'(N(N(NOOO	Ps   -A$ $B5BBrepository_idr%   r   c                X    t          || j                  }|                                 |S )a  Get a repository by ID.

        !!! Note
            This performs a health check before returning the repository object.

        Parameters:
            repository_id: The identifier of the repository.

        Returns:
            Repository: The repository instance.

        Raises:
            RepositoryNotFoundError: If the repository is not found.
            RepositoryNotHealthyError: If the repository is not healthy.
        )r   r3   r   )r:   r?  r  s      r/   rU   zRepositoryManager.get;  s(      -)9::r.   r   r\   r   c                   	 d|i}| j                             d| ||          }|                                 |                     |          S # t          j        $ r)}|j        j        dk    rt          d| d           d}~ww xY w)a  Create a new repository.

        Parameters:
            repository_id: The identifier of the repository.
            data: The repository configuration in RDF.
            content_type: The repository configuration content type.

        Raises:
            RepositoryAlreadyExistsError: If the repository already exists.
            RepositoryNotHealthyError: If the repository is not healthy.
        rm   rI   rn   i  r   z already exists.N)	r3   rp   rV   rU   ri   rj   r[   rk   r   )r:   r?  r\   r   rL   r[   r]   s          r/   createzRepositoryManager.createO  s    	%|4G'++000'4 ,  H %%'''88M***$ 	 	 	|'3..2A-AAA   	s   AA B$BBr   c           	     ^   	 | j                             d|           }|                                 |j        dk    r4t	          d| d|j         d|j                                                   d	S # t          j        $ r)}|j	        j        dk    rt          d| d           d	}~ww xY w)
a  Delete a repository.

        Parameters:
            repository_id: The identifier of the repository.

        Raises:
            RepositoryNotFoundError: If the repository is not found.
            RepositoryError: If the repository is not deleted successfully.
        rI   r%  z9Unexpected response status code when deleting repository r   r   rg   r   r   N)r3   r`   rV   rk   r   rh   stripri   rj   r[   r   )r:   r?  r[   r]   s       r/   r`   zRepositoryManager.deletek  s   
	'../O/O/OPPH%%'''#s**% RP]  R  Raiau  R  R  {C  {H  {N  {N  {P  {P  R  R   +* $ 	 	 	|'3..-.VM.V.V.VWWW	s   A0A4 4B,$B''B,N)r3   r4   )rD   r;  )r?  r%   rD   r   )r   )r?  r%   r\   r%   r   r%   rD   r   )r?  r%   rD   r   )r(   r)   r*   r+   r;   ru   r3   r^   rU   rB  r`   r-   r.   r/   r8  r8    s         ( ( ( ( ! ! X!P P P P>   * BO    8     r.   r8  c                  x    e Zd ZdZ	 	 dddZd Zd Zed             Zedd            Z	edd            Z
d ZdS )RDF4JClienta  RDF4J client.

    Parameters:
        base_url: The base URL of the RDF4J server.
        auth: Authentication tuple (username, password).
        timeout: Request timeout in seconds (default: 30.0).
        kwargs: Additional keyword arguments to pass to the httpx.Client.
    N      >@base_urlr%   authtuple[str, str] | Nonetimeoutfloatr   r   c                d   |                     d          s|dz  }t          j        d|||d|| _        d | _        	 | j        }n># t          j        $ r,}|                                  t          d|           |d }~ww xY w|dk     r'|                                  t          d| d          d S )N/)rH  rI  rK  z"Failed to check protocol version:    zRDF4J server protocol version z2 is not supported. Minimum required version is 12.r-   )	endswithri   Clientr8   _repository_managerprotocolRequestErrorr   r	   )r:   rH  rI  rK  r   protocol_versionr]   s          r/   r;   zRDF4JClient.__init__  s       %% 	OH!L 
D'
 
=C
 
 >B 	#}! 	 	 	JJLLL/:S:: 	
 b  JJLLL/u1Auuu   ! s   A B 'A;;B c                    | S r6   r-   r>   s    r/   r  zRDF4JClient.__enter__  s    r.   c                .    |                                   d S r6   )r   r  s       r/   r  zRDF4JClient.__exit__  s    

r.   c                    | j         S r6   r=   r>   s    r/   r3   zRDF4JClient.http_client  r?   r.   rD   r8  c                P    | j         t          | j                  | _         | j         S )z.Server-level repository management operations.)rR  r8  r3   r>   s    r/   repositorieszRDF4JClient.repositories  s)     #+'89I'J'JD$''r.   c                    | j                             dddi          }|                                 t          |j                                                  S )zhThe RDF4J REST API protocol version.

        Returns:
            The protocol version number.
        z	/protocolrG   re   rK   )r3   rU   rV   rL  rh   rD  r  s     r/   rS  zRDF4JClient.protocol  sR     #''h=U'VV!!###X]((**+++r.   c                8    | j                                          dS )z"Close the underlying httpx.Client.N)r3   r   r>   s    r/   r   zRDF4JClient.close  s         r.   )NrG  )rH  r%   rI  rJ  rK  rL  r   r   )rD   r8  )rD   rL  )r(   r)   r*   r+   r;   r  r  ru   r3   rZ  rS  r   r-   r.   r/   rF  rF    s          (,	    4     ! ! X! ( ( ( X( , , , X,! ! ! ! !r.   rF  )9r+   
__future__r   r   r   typingtdataclassesr   r   r   r   ri   rdflibr   rdflib.contrib.rdf4j.exceptionsr	   r
   r   r   r   r   r   r   r   r   r   rdflib.contrib.rdf4j.utilr   r   r   r   r   r   r   rdflib.graphr   r   r   rdflib.queryr   rdflib.termr   r    r!   Unionr   r   r   r$   r1   rw   r   r   r   r8  rF  r-   r.   r/   <module>rh     s     " " " " " "     				     ! ! ! ! ! ! * * * * * * * * * *                                                  B A A A A A A A A A       7 7 7 7 7 7 7 7 7 7gfdl#%WVWd*+
 $       z$ z$ z$ z$ z$ z$ z$ z$z]$ ]$ ]$ ]$ ]$ ]$ ]$ ]$@ $       $s s s s s s s slp p p p p p p pf	q q q q q q q qhB! B! B! B! B! B! B! B! B! B!r.   