
    mBNje                         d dl mZmZmZmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dZd	Zd
ZdZdZdZdZdZdZ G d d      Zy)    )AnyDictListOptional   )SchemaVersionMismatchException)ExecutionPlan)GraphSchema)stringify_param_value)QueryResultz
DB.INDEXESzDB.CONSTRAINTSz
GRAPH.COPYzGRAPH.QUERYzGRAPH.DELETEzGRAPH.EXPLAINzGRAPH.SLOWLOGzGRAPH.PROFILEzGRAPH.RO_QUERYc                   J   e Zd ZdZdefdZedefd       Z	 	 	 dBdedee	ee
f      d	ee   d
edef
dZ	 	 dCdedee	ee
f      d	ee   defdZ	 	 dCdedee	ee
f      d	ee   defdZdefdZdDdZd Zd ZdEdedefdZdEdedefdZdee   defdZ	 	 	 dFded
edee   deee      def
dZdededededef
dZdededefd Zdededefd!Zdededefd"Zdededefd#Z dededefd$Z!dededefd%Z"defd&Z#dd'dededed(edef
d)Z$dedefd*Z%dedefd+Z&d,d-d.ded/ed0edefd1Z'd2edefd3Z(d2edefd4Z)d,d-d.d2ed/ed0edefd5Z*d6ededefd7Z+defd8Z,d2efd9Z-defd:Z.d2efd;Z/d6ededefd<Z0defd=Z1d2efd>Z2defd?Z3d2efd@Z4dee	ee
f      fdAZ5y)GGraphz/
    Graph, collection of nodes and edges.
    namec                 b    || _         || _        t        |       | _        |j                  | _        y)z}
        Create a new graph.

        Args:
            client: The client object.
            name (str): Graph ID

        N)_nameclientr
   schemaexecute_command)selfr   r   s      _/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/falkordb/graph.py__init__zGraph.__init__   s,     
!$'%55    returnc                     | j                   S )zY
        Get the graph name.

        Returns:
            str: The graph name.

        )r   r   s    r   r   z
Graph.name+   s     zzr   Nqparamstimeout	read_onlyc                 t   |}| j                  |      |z   }|rt        nt        }|| j                  |dg}t	        |t
              r|j                  d|g       n|t        d      	  | j                  | }t        | |      S # t        $ r,}	| j                  j                  |	j                         |	d}	~	ww xY w)a  
        Executes a query against the graph.
        See: https://docs.falkordb.com/commands/graph.query.html

        Args:
            q (str): The query.
            params (dict): Query parameters.
            timeout (int): Maximum query runtime in milliseconds.
            read_only (bool): Whether the query is read-only.

        Returns:
            QueryResult: query result set.

        z	--compactr   Nz+Timeout argument must be a positive integer)_build_params_headerRO_QUERY_CMD	QUERY_CMDr   
isinstanceintextend	Exceptionr   r   r   r   refreshversion)
r   r   r   r   r   querycmdcommandresponsees
             r   _queryzGraph._query7   s    .  ))&1E9
 (lY!499e[A gs#NNIw/0 IJJ	+t++W5HtX..- 	 KK		*G		s   'B 	B7'B22B7c                 ,    | j                  |||d      S )aR  
        Executes a query against the graph.
        See: https://docs.falkordb.com/commands/graph.query.html

        Args:
            q (str): The query.
            params (dict): Query parameters.
            timeout (int): Maximum query runtime in milliseconds.

        Returns:
            QueryResult: query result set.

        Fr   r   r   r/   r   r   r   r   s       r   r*   zGraph.queryi   s    ( {{1VW{NNr   c                 ,    | j                  |||d      S )a_  
        Executes a read-only query against the graph.
        See: https://docs.falkordb.com/commands/graph.ro_query.html

        Args:
            q (str): The query.
            params (dict): Query parameters.
            timeout (int): Maximum query runtime in milliseconds.

        Returns:
            QueryResult: query result set.

        Tr1   r2   r3   s       r   ro_queryzGraph.ro_query   s    ( {{1VW{MMr   clonec                 p    | j                  t        | j                  |       t        | j                  |      S )z
        Creates a copy of graph

        Args:
            clone (str): Name of cloned graph

        Returns:
            Graph: the cloned graph
        )r   COPY_CMDr   r   r   )r   r6   s     r   copyz
Graph.copy   s+     	Xtyy%8T[[%((r   c                 v    | j                   j                          | j                  t        | j                        S )z
        Deletes the graph.
        See: https://docs.falkordb.com/commands/graph.delete.html

        Returns:
            None

        )r   clearr   
DELETE_CMDr   r   s    r   deletezGraph.delete   s+     	##J

;;r   c                 B    | j                  t        | j                        S )a  
        Get a list containing up to 10 of the slowest queries issued
        against the graph.

        Each item in the list has the following structure:
        1. a unix timestamp at which the log entry was processed
        2. the issued command
        3. the issued query
        4. the amount of time needed for its execution, in milliseconds.

        See: https://docs.falkordb.com/commands/graph.slowlog.html

        Returns:
            List: List of slow log entries.

        r   SLOWLOG_CMDr   r   s    r   slowlogzGraph.slowlog   s    $ ##K<<r   c                 F    | j                  t        | j                  d       y)z
        Reset the slowlog.
        See: https://docs.falkordb.com/commands/graph.slowlog.html

        Returns:
            None

        RESETNr?   r   s    r   slowlog_resetzGraph.slowlog_reset   s     	[$**g>r   r*   c                     | j                  |      |z   }| j                  t        | j                  |      }t	        |      S )a  
        Execute a query and produce an execution plan augmented with metrics
        for each operation's execution. Return an execution plan,
        with details on results produced by and time spent in each operation.
        See: https://docs.falkordb.com/commands/graph.profile.html

        Args:
            query (str): The query to profile.
            params (dict): Query parameters.

        Returns:
            ExecutionPlan: The profile information.

        )r!   r   PROFILE_CMDr   r	   r   r*   r   plans       r   profilezGraph.profile   s<      ))&1E9##KUCT""r   c                     | j                  |      |z   }| j                  t        | j                  |      }t	        |      S )a{  
        Get the execution plan for a given query.
        GRAPH.EXPLAIN returns an ExecutionPlan object.
        See: https://docs.falkordb.com/commands/graph.explain.html

        Args:
            query (str): The query for which to get the execution plan.
            params (dict): Query parameters.

        Returns:
            ExecutionPlan: The execution plan.

        )r!   r   EXPLAIN_CMDr   r	   rG   s       r   explainzGraph.explain   s<     ))&1E9##KUCT""r   c                 <   |yt        |t              st        d      d}|j                         D ]h  \  }}t        |t              r|j                         n
t        |      }|dk(  rt        d      d|v rt        d|d      |d| dt        |       d	z  }j |S )
z
        Build parameters header.

        Args:
            params (dict): The parameters.

        Returns:
            str: The parameters header.

         z'params' must be a dictzCYPHER z%Cypher parameter name cannot be empty`z1Cypher parameter name cannot contain a backtick: z= (FalkorDB does not support escaped backticks in identifiers)z`= )	r$   dict	TypeErroritemsbytesdecodestr
ValueErrorr   )r   r   params_headerkeyvaluekey_strs         r   r!   zGraph._build_params_header   s     >&$'566! ,,.JC&0e&<cjjl#c(G"} !HIIg~ Gk "00 
 q	,A%,H+IKKM ) r   	procedureargsemitc                 "   |xs g }d}t        |      dkD  r'i }t        |      D ]  \  }}d| }|||<   d|z   ||<    d| ddj                  |       d}	|%t        |      dkD  r|	d	dj                  |       z  }	| j                  |	||
      S )a@  
        Call a procedure.

        Args:
            procedure (str): The procedure to call.
            read_only (bool): Whether the procedure is read-only.
            args: Procedure arguments.
            emit: Procedure yield.

        Returns:
            QueryResult: The result of the procedure call.

        Nr   param$zCALL (,)zYIELD )r   r   )len	enumeratejoinr/   )
r   r\   r   r]   r^   r   iarg
param_namer   s
             r   call_procedurezGraph.call_procedure  s    , zr t9q=F $D/3$QC[
%(z"
*Q *
 I;a/q1D	A6#((4.)**A{{1Vy{AAr   idx_typeentity_typelabel	attributec                     |dk(  rd| d}n|dk(  rd| d}nt        d      |dk(  r
d	| d
| d}n)|dk(  r
d| d
| d}n|dk(  r
d| d
| d}nt        d      | j                  |      S )a  Drop a graph index.

        Args:
            idx_type (str): The type of index ("RANGE", "FULLTEXT", "VECTOR").
            entity_type (str): The type of entity ("NODE" or "EDGE").
            label (str): The label of the node or edge.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        NODE(e:rd   EDGE()-[e:]->()Invalid entity typeRANGEzDROP INDEX FOR z ON (e.VECTORzDROP VECTOR INDEX FOR FULLTEXTzDROP FULLTEXT INDEX FOR zInvalid index type)rW   r*   )r   rl   rm   rn   ro   patternr   s          r   _drop_indexzGraph._drop_indexC  s     & E7!nGF"ugU+G233 w!'')A>A!(	1EA#*7)79+QGA122zz!}r   c                 *    | j                  dd||      S )aV  Drop a range index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-node-label

        Args:
            label (str): The label of the node.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        rw   rq   r{   r   rn   ro   s      r   drop_node_range_indexzGraph.drop_node_range_indexe       	BBr   c                 *    | j                  dd||      S )aZ  Drop a full-text index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-node-label

        Args:
            label (str): The label of the node.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        ry   rq   r}   r~   s      r   drop_node_fulltext_indexzGraph.drop_node_fulltext_indexr       
FE9EEr   c                 *    | j                  dd||      S )aW  Drop a vector index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-node-label

        Args:
            label (str): The label of the node.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        rx   rq   r}   r~   s      r   drop_node_vector_indexzGraph.drop_node_vector_index       &%CCr   c                 *    | j                  dd||      S )a^  Drop a range index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-relationship-type

        Args:
            label (str): The label of the edge.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        rw   rs   r}   r~   s      r   drop_edge_range_indexzGraph.drop_edge_range_index  r   r   c                 *    | j                  dd||      S )ab  Drop a full-text index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-relationship-type

        Args:
            label (str): The label of the edge.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        ry   rs   r}   r~   s      r   drop_edge_fulltext_indexzGraph.drop_edge_fulltext_index  r   r   c                 *    | j                  dd||      S )a_  Drop a vector index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#deleting-an-index-for-a-relationship-type

        Args:
            label (str): The label of the edge.
            attribute (str): The attribute to drop the index on.

        Returns:
            Any: The result of the index dropping query.
        rx   rs   r}   r~   s      r   drop_edge_vector_indexzGraph.drop_edge_vector_index  r   r   c                 ,    | j                  t              S )zRetrieve a list of graph indices.
        See: https://docs.falkordb.com/commands/graph.query.html#procedures

        Returns:
            list: List of graph indices.
        )rk   GRAPH_INDEXESr   s    r   list_indiceszGraph.list_indices  s     ""=11r   )options
propertiesc                   |dk(  rd| d}n|dk(  rd| d}nt        d      |dk(  rd	}d
| d| d}|dj                  t        dj                  |            z  }|dz  }|`d}|j	                         D ];  \  }	}
t        |
t              r||	dz   |
z   dz   z  }%||	dz   t        |
      z   dz   z  }= |dd dz   }|d| z  }| j                  |      S )a  Create a typed index for nodes or edges.

        Args:
            idx_type (str): The type of index ("RANGE", "FULLTEXT", "VECTOR").
            entity_type (str): The type of entity ("NODE" or "EDGE").
            label (str): The label of the node or edge.
            properties: Variable number of property names to be indexed.
            options (dict, optional): Additional options for the index.

        Returns:
            Any: The result of the index creation query.
        rq   rr   rd   rs   rt   ru   rv   rw   rN   zCREATE z INDEX FOR z ON (rc   ze.{0}N{z:'z',:}z	 OPTIONS )rW   rg   mapformatrS   r$   rV   r*   )r   rl   rm   rn   r   r   rz   r   options_maprY   rZ   s              r   _create_typed_indexzGraph._create_typed_index  s   ( & E7!nGF"ugU+G233wHhZ{7)59	SXXc'..*566	SK%mmo
UeS)3:#5#<<K39s5z#9C#??K	 .
 &cr*S0K9[M**Azz!}r   c                 ,     | j                   dd|g| S )a`  Create a range index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#creating-an-index-for-a-node-label

        Args:
            label (str): The label of the node.
            properties: Variable number of property names to be indexed.

        Returns:
            Any: The result of the index creation query.
        rw   rq   r   r   rn   r   s      r   create_node_range_indexzGraph.create_node_range_index  s      (t''LLLr   c                 ,     | j                   dd|g| S )am  Create a full-text index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#creating-a-full-text-index-for-a-node-label

        Args:
            label (str): The label of the node.
            properties: Variable number of property names to be indexed.

        Returns:
            Any: The result of the index creation query.
        ry   rq   r   r   s      r   create_node_fulltext_indexz Graph.create_node_fulltext_index  s      (t''
FEOJOOr   r   	euclidean)dimsimilarity_functionr   r   c                <    ||d} | j                   dd|g|d|iS )a  Create a vector index for a node.
        See: https://docs.falkordb.com/commands/graph.query.html#vector-indexing

        Args:
            label (str): The label of the node.
            properties: Variable number of property names to be indexed.
            dim (int, optional): The dimension of the vector.
            similarity_function (str, optional): The similarity function for the vector.

        Returns:
            Any: The result of the index creation query.
        	dimensionsimilarityFunctionrx   rq   r   r   )r   rn   r   r   r   r   s         r   create_node_vector_indexzGraph.create_node_vector_index  s;    & !$;NO't''fe
&0
:A
 	
r   relationc                 ,     | j                   dd|g| S )an  Create a range index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#creating-an-index-for-a-relationship-type

        Args:
            relation (str): The relation of the edge.
            properties: Variable number of property names to be indexed.

        Returns:
            Any: The result of the index creation query.
        rw   rs   r   r   r   r   s      r   create_edge_range_indexzGraph.create_edge_range_index  s      (t''OJOOr   c                 ,     | j                   dd|g| S )a[  Create a full-text index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#full-text-indexing

        Args:
            relation (str): The relation of the edge.
            properties: Variable number of property names to be indexed.

        Returns:
            Any: The result of the index creation query.
        ry   rs   r   r   s      r   create_edge_fulltext_indexz Graph.create_edge_fulltext_index*  s      (t''
FHRzRRr   c                <    ||d} | j                   dd|g|d|iS )a  Create a vector index for an edge.
        See: https://docs.falkordb.com/commands/graph.query.html#vector-indexing

        Args:
            relation (str): The relation of the edge.
            properties: Variable number of property names to be indexed.
            dim (int, optional): The dimension of the vector.
            similarity_function (str, optional): The similarity function for the vector.

        Returns:
            Any: The result of the index creation query.
        r   rx   rs   r   r   )r   r   r   r   r   r   s         r   create_edge_vector_indexzGraph.create_edge_vector_index7  s;    & !$;NO't''fh
)3
=D
 	
r   constraint_typec                 \     | j                   dd| j                  |||dt        |      g| S )z%
        Create a constraint
        GRAPH.CONSTRAINTCREATE
PROPERTIESr   r   re   r   r   rm   rn   r   s        r   _create_constraintzGraph._create_constraintO  sC     $t##II
O

 

 
	
r   c                 r    	  | j                   |g|   | j                  dd|g| S # t        $ r Y  w xY w)a0  
        Create node unique constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        The constraint is created asynchronously, use list constraints to pull on
        constraint creation status

        Note: unique constraints require the existence of a range
        index over the constraint properties, this function will
        create any missing range indices

        Args:
            label (str): Node label to apply constraint to
            properties: Variable number of property names to constrain
        UNIQUErq   )r   r'   r   r   s      r   create_node_unique_constraintz#Graph.create_node_unique_constrainte  sN    $	(D((<<
 't&&xLLL	  		   * 	66c                 r    	  | j                   |g|   | j                  dd|g| S # t        $ r Y  w xY w)a?  
        Create edge unique constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        The constraint is created asynchronously, use list constraints to pull on
        constraint creation status

        Note: unique constraints require the existence of a range
        index over the constraint properties, this function will
        create any missing range indices

        Args:
            relation (str): Edge relationship-type to apply constraint to
            properties: Variable number of property names to constrain
        r   RELATIONSHIP)r   r'   r   r   s      r   create_edge_unique_constraintz#Graph.create_edge_unique_constraint  sN    $	(D((?J? 't&&xWJWW  		r   c                 ,     | j                   dd|g| S )a  
        Create node mandatory constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        The constraint is created asynchronously, use list constraints to pull on
        constraint creation status

        Args:
            label (str): Node label to apply constraint to
            properties: Variable number of property names to constrain
        	MANDATORYrq   r   r   s      r    create_node_mandatory_constraintz&Graph.create_node_mandatory_constraint  s      't&&{FEOJOOr   c                 ,     | j                   dd|g| S )a  
        Create edge mandatory constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        The constraint is created asynchronously, use list constraints to pull on
        constraint creation status

        Args:
            relation (str): Edge relationship-type to apply constraint to
            properties: Variable number of property names to constrain
        r   r   r   r   s      r    create_edge_mandatory_constraintz&Graph.create_edge_mandatory_constraint  s(     't&&
4>
 	
r   c                 \     | j                   dd| j                  |||dt        |      g| S )a)  
        Drops a constraint

        Args:
        constraint_type (str): Type of constraint to drop
        entity_type (str): Type of entity to drop constraint from
        label (str): entity's label / relationship-type
        properties: entity's properties to remove constraint from
        r   DROPr   r   r   s        r   _drop_constraintzGraph._drop_constraint  sC     $t##II
O

 

 
	
r   c                 ,     | j                   dd|g| S )aL  
        Drop node unique constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        Note: the constraint supporting range index is not removed

        Args:
            label (str): Node label to remove the constraint from
            properties: properties to remove constraint from
        r   rq   r   r   s      r   drop_node_unique_constraintz!Graph.drop_node_unique_constraint  s      %t$$XvuJzJJr   c                 ,     | j                   dd|g| S )aX  
        Drop edge unique constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        Note: the constraint supporting range index is not removed

        Args:
            label (str): Edge relationship-type to remove the constraint from
            properties: properties to remove constraint from
        r   r   r   r   s      r   drop_edge_unique_constraintz!Graph.drop_edge_unique_constraint  s      %t$$X~xU*UUr   c                 ,     | j                   dd|g| S )a  
        Drop node mandatory constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        Args:
            label (str): Node label to remove the constraint from
            properties: properties to remove constraint from
        r   rq   r   r   s      r   drop_node_mandatory_constraintz$Graph.drop_node_mandatory_constraint  s      %t$$[&%M*MMr   c                 ,     | j                   dd|g| S )a  
        Drop edge mandatory constraint
        See: https://docs.falkordb.com/commands/graph.constraint-create.html

        Args:
            label (str): Edge relationship-type to remove the constraint from
            properties: properties to remove constraint from
        r   r   r   r   s      r   drop_edge_mandatory_constraintz$Graph.drop_edge_mandatory_constraint  s      %t$$[.(XZXXr   c           	          | j                  t              j                  }g }|D ](  }|j                  |d   |d   |d   |d   |d   d       * |S )z
        Lists graph's constraints

        See: https://docs.falkordb.com/commands/graph.constraint-create.html#listing-constraints

        Returns:
            [Dict[str, object]]: list of constraints
        r   r            )typern   r   
entitytypestatus)rk   GRAPH_LIST_CONSTRAINTS
result_setappend)r   resultconstraintsrows       r   list_constraintszGraph.list_constraints  sh     $$%;<GGCF V"%a&"%a&!!f  r   )NNF)NN)r   N)N)TNN)6__name__
__module____qualname____doc__rV   r   propertyr   r   r   objectr%   boolr   r/   r*   r5   r9   r=   rA   rD   r	   rI   rL   rQ   r!   r   rk   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   r   r      sk   6S 6 	c 	 	 /3!%00 c6k*+0 #	0
 0 
0j /3!%	OO c6k*+O #	O
 
O2 /3!%	NN c6k*+N #	N
 
N,)# )<=(	?#S #- #(#S #- #(8D> c F #$((B(B (B tn	(B
 tCy!(B 
(BX  *- 69 FI 	 DC3 C3 C; CFc Fc Fk FDC DC DK DC3 C3 C; CFc Fc Fk FDC DC DK D2k 2 -- - 	-
 - 
-^MS M+ MP P[ P" #.

 	

 !
 

0P P[ PS3 S S" #.

 	

 !
 

0
"
14
=@
,M3 M4Xc X2Pc P
 
 
"
14
=@
2K KVC V
NC 
N	Ys 	Y$tCK'8"9 r   r   N)typingr   r   r   r   
exceptionsr   execution_planr	   graph_schemar
   helpersr   query_resultr   r   r   r8   r#   r<   rK   r@   rF   r"   r   r   r   r   <module>r      sX    , , 6 ) % * % )  	
D Dr   