
    4Ysh|                         d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZ dd	lmZ dd
lmZmZmZmZmZmZ dZdZdZ ej4                  d      Zedef   ZdefdZ G d dee      Z G d de      Z y)z
This is an RDFLib store around Ivan Herman et al.'s SPARQL service wrapper.
This was first done in layer-cake, and then ported to RDFLib

    N   )SPARQLConnector)NATIVE_REGEX)Store)VariableBNode)DATASET_DEFAULT_GRAPH_ID)Node)AnyCallableDictOptionalUnionTupleLIMITOFFSETzORDER BYz(?P<label>_\:[^\s]+).returnc                 X    t        | t              rt        d      | j                         S )Nz]SPARQLStore does not support BNodes! See http://www.w3.org/TR/sparql11-query/#BGPsparqlBNodes)
isinstancer   	Exceptionn3)nodes    /var/www/sten-cake5-migrate2.hellocrow.space/lexinfo-master/env/lib/python3.12/site-packages/rdflib/plugins/stores/sparqlstore.py_node_to_sparqlr      s-    $G
 	
 779    c                   8    e Zd ZdZdZdZdZeZddde	ddfde
deded	ed
e
deee
e
f      f fdZd*de
fdZd Zd Zd Zd Zd+dZd Zd Z fdZd Z	 d,dZd-dZd-dZd-dZd-dZd Zd Z d Z!d  Z"d! Z#d" Z$d# Z%d.d$Z&d.d%Z'd.d&Z(d-d'Z)d-d(Z*d-d)Z+ xZ,S )/SPARQLStorea  An RDFLib store around a SPARQL endpoint

    This is context-aware and should work as expected
    when a context is specified.

    For ConjunctiveGraphs, reading is done from the "default graph". Exactly
    what this means depends on your endpoint, because SPARQL does not offer a
    simple way to query the union of all graphs as it would be expected for a
    ConjuntiveGraph. This is why we recommend using Dataset instead, which is
    motivated by the SPARQL 1.1.

    Fuseki/TDB has a flag for specifying that the default graph
    is the union of all graphs (``tdb:unionDefaultGraph`` in the Fuseki config).

    .. warning:: By default the SPARQL Store does not support blank-nodes!

                 As blank-nodes act as variables in SPARQL queries,
                 there is no way to query for a particular blank node without
                 using non-standard SPARQL extensions.

                 See http://www.w3.org/TR/sparql11-query/#BGPsparqlBNodes

    You can make use of such extensions through the ``node_to_sparql``
    argument. For example if you want to transform BNode('0001') into
    "<bnode:b0001>", you can use a function like this:

    >>> def my_bnode_ext(node):
    ...    if isinstance(node, BNode):
    ...        return '<bnode:b%s>' % node
    ...    return _node_to_sparql(node)
    >>> store = SPARQLStore('http://dbpedia.org/sparql',
    ...                     node_to_sparql=my_bnode_ext)

    You can request a particular result serialization with the
    ``returnFormat`` parameter. This is a string that must have a
    matching plugin registered. Built in is support for ``xml``,
    ``json``, ``csv``, ``tsv`` and ``application/rdf+xml``.

    The underlying SPARQLConnector uses the urllib library.
    Any extra kwargs passed to the SPARQLStore connector are passed to
    urllib when doing HTTP calls. I.e. you have full control of
    cookies/auth/headers.

    Form example:

    >>> store = SPARQLStore('...my endpoint ...', auth=('user','pass'))

    will use HTTP basic auth.

    FTNxmlquery_endpointsparql11context_awarenode_to_sparqlreturnFormatauthc                     t        t        | 
  d|||d| || _        i | _        || _        || _        || _        d| _        y )N)r   r#   r$   r    )	superr   __init__r"   
nsBindingsr    r!   graph_aware_queries)	selfr   r    r!   r"   r#   r$   sparqlconnector_kwargs	__class__s	           r   r(   zSPARQLStore.__init__a   s[     	k4) 	
)%	
 %		
 -*, *(r   configurationc                 L    t        |      t        k(  r|| _        yt        d      )zThis method is included so that calls to this Store via Graph, e.g. Graph("SPARQLStore"),
        can set the required parameters
        z<configuration must be a string (a single query endpoint URI)N)typestrr   r   r,   r/   creates      r   openzSPARQLStore.openy   s)     #%"/DN r   c                     t        d      )NzDThe SPARQL Store is read only. Try SPARQLUpdateStore for read/write.	TypeErrorr,   r/   s     r   r4   zSPARQLStore.create   s    R
 	
r   c                     t        d      NzThe SPARQL store is read onlyr7   r9   s     r   destroyzSPARQLStore.destroy       788r   c                     t        d      r;   r7   r,   s    r   commitzSPARQLStore.commit   r=   r   c                     t        d      r;   r7   r?   s    r   rollbackzSPARQLStore.rollback   r=   r   c                     t        d      r;   r7   )r,   _contextquoteds       r   addzSPARQLStore.add   r=   r   c                     t        d      r;   r7   )r,   quadss     r   addNzSPARQLStore.addN   r=   r   c                     t        d      r;   r7   r,   rD   rE   s      r   removezSPARQLStore.remove   r=   r   c                 T    | xj                   dz  c_         t        t        |   |i |S Nr   )r+   r'   r   query)r,   argskwargsr.   s      r   _queryzSPARQLStore._query   s(    [$-t>v>>r   c                    t        t        | j                  j                               t        |j                               z         }|s|S dj	                  dj	                  |D cg c]  \  }}d|d|d c}}      d|g      S c c}}w )N
zPREFIX z: <> )setlistr)   itemsjoin)r,   rP   extra_bindingsbindingskvs         r   _inject_prefixeszSPARQLStore._inject_prefixes   sx    tDOO1134tN<P<P<R7SSTLyy		(K$!Q15KL
 	
Ks   &Bc                     | _         t        |t              sJ | t        |      dkD  r j	                  ||      }r] j
                  st        d      t              }|ddj                  d |D              ddj                   fd|D              dz  } j                  | j                  |      r|	      S d 	      S )
Nr   z4initBindings not supported for SPARQL 1.0 Endpoints.

VALUES (  c              3   8   K   | ]  }d t        |      z     yw?Nr2   .0xs     r   	<genexpr>z$SPARQLStore.query.<locals>.<genexpr>        1!s1v1    )
{ ( c              3   F   K   | ]  }j                  |           y wNr"   ri   rj   initBindingsr,   s     r   rk   z$SPARQLStore.query.<locals>.<genexpr>         I!,,\!_=I   ! ) }
default_graph)debugr   r2   lenr`   r    r   rY   r[   rS   _is_contextual)r,   rP   initNsrs   
queryGraphDEBUGr_   s   `  `   r   rP   zSPARQLStore.query   s     
%%%%#f+/))%8E== VWW\"A 1q11IqII E
 {{t/B/B:/N  
 	
TX  
 	
r   c           	   #   p  K   |\  }}}g }|st        d      }|j                  |       |st        d      }|j                  |       |st        d      }|j                  |       |r3dj                  |D cg c]  }|j                          c}      }d|z  }	nd}	| j                  }
|	d |
|      d |
|      d |
|      d}t        |t              s t        |t              st        |t              rd	}t        |t               r|}ndt        |t               r|}nQt        |t               r|}n>t        |t              r.t        t        |t              t               rt        |t              }|dt        d|j                         z   }	 |d
t        t        |t                    z  z   }	 |dt        t        |t                    z  z   }| j                  || j!                  |      r|j"                  nd	      }|rft%        |      t&        k(  r|d   dk(  rt        d      |D ];  }|j)                  ||      |j)                  ||      |j)                  ||      fd	f = y	|j*                  r
|||fd	f y	y	c c}w # t        t        t        f$ r Y w xY w# t        t        t        f$ r Y w xY ww)a0  
        - tuple **(s, o, p)**
          the triple used as filter for the SPARQL select.
          (None, None, None) means anything.
        - context **context**
          the graph effectively calling this method.

        Returns a tuple of triples executing essentially a SPARQL like
        SELECT ?subj ?pred ?obj WHERE { ?subj ?pred ?obj }

        **context** may include three parameter
        to refine the underlying query:
        * LIMIT: an integer to limit the number of results
        * OFFSET: an integer to enable paging of results
        * ORDERBY: an instance of Variable('s'), Variable('o') or Variable('p') or, by default, the first 'None' from the given triple

        .. warning::

            - Using LIMIT or OFFSET automatically include ORDERBY otherwise this is
              because the results are retrieved in a not deterministic way (depends on
              the walking path on the graph)
            - Using OFFSET without defining LIMIT will discard the first OFFSET - 1 results

        ``
        a_graph.LIMIT = limit
        a_graph.OFFSET = offset
        triple_generator = a_graph.triples(mytriple):
          # do something
          # Removes LIMIT and OFFSET if not required for the next triple() calls
        del a_graph.LIMIT
        del a_graph.OFFSET
        ``


        sporc   z
SELECT %s ASK { z }Nz	 LIMIT %sz
 OFFSET %srw   r   i  zPIt looks like you need to authenticate with this SPARQL Store. HTTP unauthorized)r   appendr[   r   r"   hasattrr   r   ORDERBYr   getattrint
ValueErrorr8   AttributeErrorrS   r{   
identifierr1   tupleget	askAnswer)r,   sporE   r   r   r   varstermr_   verbntsrP   varresultrows                  r   tripleszSPARQLStore.triples   s    J 1aAKKNAKKNAKKN5$'')56A!#DD!!%)3q63q63q6B GU#w'w(C!X&Ax(Ax('*z)80 gw/::E	K#ggu.E*FFFE	L3ww/G+HHHE 040C0CG0L',,RV  

 F|u$!9#$j   GGAqMGGAqMGGAqM 	  !Qio%  m 6: I~6 		 I~6 		sV   A4J66I=DJ6J /J B4J6JJ6JJ6J30J62J33J6c                     t        d      )a=  
        A variant of triples that can take a list of terms instead of a
        single term in any slot.  Stores can implement this to optimize
        the response time from the import default 'fallback' implementation,
        which will iterate over each term in the list and dispatch to
        triples.
        z'Triples choices currently not supported)NotImplementedErrorrL   s      r   triples_choiceszSPARQLStore.triples_choices3  s     ""KLLr   c                     | j                   st        d      d}| j                  || j                  |      r|j                  nd       }t        t        t        |            j                        S )NzEFor performance reasons, this is notsupported for sparql1.0 endpointsz*SELECT (count(*) as ?c) WHERE {?s ?p ?o .}rw   )	r    r   rS   r{   r   r   nextiterc)r,   rE   qr   s       r   __len__zSPARQLStore.__len__=  sp    }}%6 
 =A[[&&w/ &00	 ! F tDL)++,,r   c                     |rV| j                   }|\  }}} ||r|n
t        d             ||r|n
t        d             ||r|n
t        d            f}d|z  }nd}| j                  |      }d |D        S )a  
        Iterates over results to "SELECT ?NAME { GRAPH ?NAME { ?s ?p ?o } }"
        or "SELECT ?NAME { GRAPH ?NAME {} }" if triple is `None`.

        Returns instances of this store with the SPARQL wrapper
        object updated via addNamedGraph(?NAME).

        This causes a named-graph-uri key / value  pair to be sent over
        the protocol.

        Please note that some SPARQL endpoints are not able to find empty named
        graphs.
        r   r   r   z.SELECT ?name WHERE { GRAPH ?name { %s %s %s }}z%SELECT ?name WHERE { GRAPH ?name {} }c              3   4   K   | ]  }|j                     y wrp   )name)ri   r   s     r   rk   z'SPARQLStore.contexts.<locals>.<genexpr>l  s     +S+s   )r"   r   rS   )	r,   tripler   r   r   r   paramsr   r   s	            r   contextszSPARQLStore.contextsO  s~     %%CGAq!A.A.A.F
 A6IA7AQ+F++r   c                 "    || j                   |<   y rp   )r)   )r,   prefix	namespaces      r   bindzSPARQLStore.bindo  s    "+r   c                     t        | j                  j                         D cg c]	  \  }}||f c}}      j                  |      S c c}}w )rc   )dictr)   rZ   r   )r,   r   r^   r_   s       r   r   zSPARQLStore.prefixr  s;    (=(=(?@1aV@AEEiPP@s   A
c                 8    | j                   j                  |      S rp   )r)   r   )r,   r   s     r   r   zSPARQLStore.namespacev  s    ""6**r   c              #   \   K   | j                   j                         D ]  \  }}||f  y wrp   )r)   rZ   )r,   r   nss      r   
namespaceszSPARQLStore.namespacesy  s0     ////1 	JFB"*	   *,c                     t        d      r;   r7   r,   graphs     r   	add_graphzSPARQLStore.add_graph}  r=   r   c                     t        d      r;   r7   r   s     r   remove_graphzSPARQLStore.remove_graph  r=   r   c                 p    | j                   r|yt        |t              r|dk7  S |j                  t        k7  S )zrReturns `True` if the "GRAPH" keyword must appear
        in the final SPARQL query sent to the endpoint.
        F	__UNION__)r!   r   r2   r   r	   r   s     r   r{   zSPARQLStore._is_contextual  s;     ""eS!K''##'???r   c              #   R   K   | j                  d||f      D ]  \  }}|d     ywz;A generator of subjects with the given predicate and objectNr   r   r,   	predicateobjecttr   s        r   subjectszSPARQLStore.subjects  2     LL$	6!:; 	DAqA$J	   %'c              #   R   K   | j                  |d|f      D ]  \  }}|d     ywz;A generator of predicates with the given subject and objectNr   r   r,   subjectr   r   r   s        r   
predicateszSPARQLStore.predicates  2     LL'4!89 	DAqA$J	r   c              #   R   K   | j                  ||df      D ]  \  }}|d     ywz;A generator of objects with the given subject and predicateN   r   r,   r   r   r   r   s        r   objectszSPARQLStore.objects  2     LL'9d!;< 	DAqA$J	r   c              #   \   K   | j                  dd|f      D ]  \  }}|d   |d   f  ywz?A generator of (subject, predicate) tuples for the given objectNr   r   r   r,   r   r   r   s       r   subject_predicateszSPARQLStore.subject_predicates  ;     LL$f!56 	DAqA$!*	r   c              #   \   K   | j                  d|df      D ]  \  }}|d   |d   f  ywz?A generator of (subject, object) tuples for the given predicateNr   r   r   r,   r   r   r   s       r   subject_objectszSPARQLStore.subject_objects  ;     LL$	4!89 	DAqA$!*	r   c              #   \   K   | j                  |ddf      D ]  \  }}|d   |d   f  ywz?A generator of (predicate, object) tuples for the given subjectNr   r   r   r,   r   r   r   s       r   predicate_objectszSPARQLStore.predicate_objects  ;     LL'4!67 	DAqA$!*	r   FNF)NNNFrp   NN)-__name__
__module____qualname____doc__formula_awaretransaction_awarer*   r   regex_matchingr   r2   boolNodeToSparqlr   r   r(   r5   r4   r<   r@   rB   rG   rJ   rM   rS   r`   rP   r   r   r   r   r   r   r   r   r   r   r{   r   r   r   r   r   r   __classcell__)r.   s   @r   r   r   (   s    1f MK!N #"'6!*.  	
 %  uS#X'0	# 	

999999?


 MR
0k&ZM-$,@,Q+99	@




r   r   c                      e Zd ZdZ ej
                  dej                        ZdZdZ	dZ
dZdede	de
ded		Zd
ZdZdZdZdZdedededed		Zdededed	Z ej
                  e      Z	 	 	 	 	 	 	 d5dee   dee   dededededefdZd6deeeeef   f   fdZd Zd Zd  Zd! Zd6d"Zd# Z d$ Z!d% Z"d7d&Z#d' Z$d( Z%d) Z&d* Z'i i ddfd+Z(d, Z)d- Z*d. Z+d8d/Z,d8d0Z-d8d1Z.d9d2Z/d9d3Z0d9d4Z1y):SPARQLUpdateStorea  A store using SPARQL queries for reading and SPARQL Update for changes.

    This can be context-aware, if so, any changes will be to the given named
    graph only.

    In favor of the SPARQL 1.1 motivated Dataset, we advise against using this
    with ConjunctiveGraphs, as it reads and writes from and to the
    "default graph". Exactly what this means depends on the endpoint and can
    result in confusion.

    For Graph objects, everything works as expected.

    See the :class:`SPARQLStore` base class for more information.

    z(?P<where>WHERE\s*\{)z'([^'\\]|\\.)*'z"([^"\\]|\\.)*"z'''(('|'')?([^'\\]|\\.))*'''z"""(("|"")?([^"\\]|\\.))*"""(z)|()z<([^<>"{}|^`\]\\[\x00-\x20])*>z#[^\x0D\x0A]*([\x0D\x0A]|\Z){}z\\.z(?P<block_start>z)|(?P<block_end>z)|(?P<block_content>NFr   update_endpointr    r!   postAsEncoded
autocommitdirty_readsc                     t        j                  | |||fd|i| || _        || _        || _        d| _        d| _        y)aE  
        :param autocommit if set, the store will commit after every
        writing operations. If False, we only make queries on the
        server once commit is called.

        :param dirty_reads if set, we do not commit before reading. So you
        cannot read what you wrote before manually calling commit.

        r   Nr   )r   r(   r   r   r   _edits_updates)	r,   r   r   r    r!   r   r   r   kwdss	            r   r(   zSPARQLUpdateStore.__init__  sY    * 			

 ,	
 	
 +$&r   r/   c                     t        |      t        k(  r|| _        yt        |      t        k(  r|d   | _        |d   | _        yt        d      )zThis method is included so that calls to this Store via Graph, e.g.
        Graph("SPARQLStore"), can set the required parameters

        r   r   zqconfiguration must be either a string (a single query endpoint URI) or a tuple (a query/update endpoint URI pair)N)r1   r2   r   r   r   r   r3   s      r   r5   zSPARQLUpdateStore.open  sS    
 #%"/D- E)"/"2D#0#3D @ r   c                     | j                   s| j                  s| j                          t        j                  | g|i |S rp   )r   r   r@   r   rP   r,   rQ   rR   s      r   rP   zSPARQLUpdateStore.query*  s5    t'7'7KKM  7777r   c                     | j                   s| j                  s| j                          t        j                  | g|i |S rp   )r   r   r@   r   r   r   s      r   r   zSPARQLUpdateStore.triples/  5    t'7'7KKM""49$9&99r   c                     | j                   s| j                  s| j                          t        j                  | g|i |S rp   )r   r   r@   r   r   r   s      r   r   zSPARQLUpdateStore.contexts4  s5    t'7'7KKM##D:4:6::r   c                     | j                   s| j                  s| j                          t        j                  | g|i |S rp   )r   r   r@   r   r   r   s      r   r   zSPARQLUpdateStore.__len__9  r   r   c                     |rt        d      t        |t              r$|d   | _        t	        |      dkD  r|d   | _        yy|| _        || _        y)a"  
        sets the endpoint URLs for this SPARQLStore
        :param configuration: either a tuple of (query_endpoint, update_endpoint),
            or a string with the endpoint which is configured as query and update endpoint
        :param create: if True an exception is thrown.
        zCannot create a SPARQL Endpointr   r   N)r   r   r   r   rz   r   r3   s      r   r5   zSPARQLUpdateStore.open?  s[     =>>mU+"/"2D=!A%'4Q'7$ & #0D#0D r   c                 @    | j                   g | _         | j                   S rp   r   r?   s    r   _transactionzSPARQLUpdateStore._transactionR  s    ;;DK{{r   c                     | j                   rKt        | j                         dkD  r2| j                  dj                  | j                                d| _         yyy)ak  add(), addN(), and remove() are transactional to reduce overhead of many small edits.
        Read and update() calls will automatically commit any outstanding edits.
        This should behave as expected most of the time, except that alternating writes
        and reads can degenerate to the original call-per-triple situation that originally existed.
        r   z
;
N)r   rz   _updater[   r?   s    r   r@   zSPARQLUpdateStore.commitX  sB     ;;3t{{+a/LLdkk23DK 0;r   c                     d | _         y rp   r  r?   s    r   rB   zSPARQLUpdateStore.rollbackb  s	    r   c                 p   | j                   st        d      |rJ |\  }}}| j                  } ||      d ||      d ||      d}| j                  |      rd ||j                        d|d}	nd|z  }	| j                         j                  |	       | j                  r| j                          yy)	z%Add a triple to the store of triples.zUpdateEndpoint is not setrc    .INSERT DATA { GRAPH r   z } }zINSERT DATA { %s }N)	r   r   r"   r{   r   r  r   r   r@   )
r,   r   rE   rF   r   r   objr   r   r   s
             r   rG   zSPARQLUpdateStore.adde  s     ##788z$'!)S!!!$Ws9~s3xHw'589K9K5LfUA$v-A""1%??KKM r   c                 2   | j                   st        d      t        j                  t              }|D ]  \  }}}}||   j                  |||f         g }| j                  }|D ]n  }||   D cg c]#  \  }}} ||      d ||      d ||      d% }	}}}|j                  d ||j                        ddj                  |	      d       p | j                         j                  |       | j                  r| j                          yyc c}}}w )	z!Add a list of quads to the store.'UpdateEndpoint is not set - call 'open'rc   r
  r  r   rU   z } }
N)r   r   collectionsdefaultdictrY   r   r"   r   r[   r  extendr   r@   )
r,   rI   r   r   r   r  rE   datar   r   s
             r   rJ   zSPARQLUpdateStore.addNx  s   ##EFF**4005 	@,GYWW$$gy#%>?	@!! 	G 08/@ +GY !$Gc)nc#hGG  KKw))*DIIg,>@	 	""4(??KKM s   0(D
c                    | j                   st        d      |\  }}}|st        d      }|st        d      }|st        d      }| j                  } ||      d ||      d ||      d}| j	                  |      r ||j
                        }d||dz  }	n	d	|d
|d}	| j                         j                  |	       | j                  r| j                          yy)zRemove a triple from the storer  SPOrc   r
  z9WITH %(graph)s DELETE { %(triple)s } WHERE { %(triple)s })r   r   z	DELETE { z } WHERE { z } N)
r   r   r   r"   r{   r   r  r   r   r@   )
r,   r   rE   r   r   r  r   r   cidr   s
             r   rM   zSPARQLUpdateStore.remove  s    ##EFF$'!)SsmG I3-C!!!$Ws9~s3xHw'g(()CK O A ( 28@A""1%??KKM r   c                 $    t        |      | _        y rp   )r   _timeout)r,   timeouts     r   
setTimeoutzSPARQLUpdateStore.setTimeout  s    Gr   c                 Z    | xj                   dz  c_         t        j                  | |       y rO   )r   r   update)r,   r  s     r   r  zSPARQLUpdateStore._update  s     tV,r   c                      j                   st        d      | _        t        |t              sJ  j                  ||      } j                  |      r j                  ||      }rbt              }ddj                  d |D              ddj                   fd|D              d} j                  j                  d|z   |      } j                         j                  |        j                  r j                          y	y	)
a  
        Perform a SPARQL Update Query against the endpoint,
        INSERT, LOAD, DELETE etc.
        Setting initNs adds PREFIX declarations to the beginning of
        the update. Setting initBindings adds inline VALUEs to the
        beginning of every WHERE clause. By the SPARQL grammar, all
        operations that support variables (namely INSERT and DELETE)
        require a WHERE clause.
        Important: initBindings fails if the update contains the
        substring 'WHERE {' which does not denote a WHERE clause, e.g.
        if it is part of a literal.

        .. admonition:: Context-aware query rewriting

            - **When:**  If context-awareness is enabled and the graph is not the default graph of the store.
            - **Why:** To ensure consistency with the :class:`~rdflib.plugins.stores.memory.Memory` store.
              The graph must accept "local" SPARQL requests (requests with no GRAPH keyword)
              as if it was the default graph.
            - **What is done:** These "local" queries are rewritten by this store.
              The content of each block of a SPARQL Update operation is wrapped in a GRAPH block
              except if the block is empty.
              This basically causes INSERT, INSERT DATA, DELETE, DELETE DATA and WHERE to operate
              only on the context.
            - **Example:** `"INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }"` is converted into
              `"INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> } }"`.
            - **Warning:** Queries are presumed to be "local" but this assumption is **not checked**.
              For instance, if the query already contains GRAPH blocks, the latter will be wrapped in new GRAPH blocks.
            - **Warning:** A simplified grammar is used that should tolerate
              extensions of the SPARQL grammar. Still, the process may fail in
              uncommon situations and produce invalid output.

        zUpdate endpoint is not set!rb   rc   c              3   8   K   | ]  }d t        |      z     ywre   rg   rh   s     r   rk   z+SPARQLUpdateStore.update.<locals>.<genexpr>  rl   rm   rn   c              3   F   K   | ]  }j                  |           y wrp   rq   rr   s     r   rk   z+SPARQLUpdateStore.update.<locals>.<genexpr>  rt   ru   rv   zWHERE { N)r   r   ry   r   r2   r`   r{   _insert_named_graphrY   r[   where_patternsubr  r   r   r@   )r,   rP   r|   rs   r}   r~   r_   valuess   `  `    r   r  zSPARQLUpdateStore.update  s    B ##9::
%%%%%%eV4z*,,UJ?E \"A1q11IqIIF
 &&**:+>FE""5)??KKM r   c                    t        |t              r| j                  |      }nd|z  }d|z  }d}d}g }d}| j                  j	                  |      D ]  }|j                  d      O|dz  }|dk(  s |j                  |||j                                 |j                  |       |j                         }d|j                  d      v|dk(  r|||j                          }	|d	   |u r7|	d
k(  s|	j                         r"|j                          |j                  |	       n"|j                  |	       |j                  |       |j                         }|dz  } |j                  ||d        d
j                  |      S )a  
        Inserts GRAPH <query_graph> {} into blocks of SPARQL Update operations

        For instance,  "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }"
        is converted into
        "INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> } }"
        z<%s>z GRAPH %s {z} r   block_startNr   	block_endrW   )r   r
   r"   BLOCK_FINDING_PATTERNfinditergroupr   endstartisspacepopr[   )
r,   rP   query_graphgraph_block_opengraph_block_closelevelmodified_queryposmatchsince_previous_poss
             r   r!  z%SPARQLUpdateStore._insert_named_graph  s}    k4(--k:K ;.K(;6  //88? 	E{{=)5
A:"))%eiik*BC"))*:;))+C[)5A:).sU[[])C&%b)-==*b04F4N4N4P '**,&--.@A&--.@A&--.?@++-C
/	0 	eCDk*ww~&&r   c                     | j                   st        j                  | |       y |j                  t        k7  r.| j                  d| j                  |j                        z         y y )NzCREATE GRAPH %s)r*   r   r   r   r	   r  r"   r   s     r   r   zSPARQLUpdateStore.add_graph)  sP    OOD%(!99KK)D,?,?@P@P,QQR :r   c                     | j                   st        j                  | |       y |j                  t        k(  r| j                  d       y | j                  d| j                  |j                        z         y )NzDROP DEFAULTzDROP GRAPH %s)r*   r   r   r   r	   r  r"   r   s     r   r   zSPARQLUpdateStore.remove_graph/  sX    tU+!99KK'KK$*=*=e>N>N*OOPr   c              #   R   K   | j                  d||f      D ]  \  }}|d     ywr   r   r   s        r   r   zSPARQLUpdateStore.subjects7  r   r   c              #   R   K   | j                  |d|f      D ]  \  }}|d     ywr   r   r   s        r   r   zSPARQLUpdateStore.predicates<  r   r   c              #   R   K   | j                  ||df      D ]  \  }}|d     ywr   r   r   s        r   r   zSPARQLUpdateStore.objectsA  r   r   c              #   \   K   | j                  dd|f      D ]  \  }}|d   |d   f  ywr   r   r   s       r   r   z$SPARQLUpdateStore.subject_predicatesF  r   r   c              #   \   K   | j                  d|df      D ]  \  }}|d   |d   f  ywr   r   r   s       r   r   z!SPARQLUpdateStore.subject_objectsK  r   r   c              #   \   K   | j                  |ddf      D ]  \  }}|d   |d   f  ywr   r   r   s       r   r   z#SPARQLUpdateStore.predicate_objectsP  r   r   )NNTTTTFr   r   r   rp   )2r   r   r   r   recompile
IGNORECASEr"  STRING_LITERAL1STRING_LITERAL2STRING_LITERAL_LONG1STRING_LITERAL_LONG2StringIRIREFCOMMENTBLOCK_START	BLOCK_ENDESCAPEDBlockContentBlockFindingr)  r   r2   r   r(   r   r   r5   rP   r   r   r   r  r@   rB   rG   rJ   rM   r  r  r  r!  r   r   r   r   r   r   r   r   r&   r   r   r   r     s     BJJ;R]]KM. ,O+O==	F 3F1G KIG -3FGWMLL
 'BJJ|4 )-)-""!" " "#" 	"
 " " " "H%U38_(<"=  8
:
;
:1&&.6%- $&B4u ;z7'rSQ




r   r   )!r   r@  r  sparqlconnectorr   #rdflib.plugins.stores.regexmatchingr   rdflib.storer   rdflibr   r   rdflib.graphr	   rdflib.termr
   typingr   r   r   r   r   r   r   r   r   rA  BNODE_IDENT_PATTERNr2   r   r   r   r   r&   r   r   <module>rW     s   
 
  , <  " 1  > > 		
 bjj!89 S!S B/5 BJf fr   