
    2ib                         d dl 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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)    )ListDictOptional   )GraphSchema)QueryResult)ExecutionPlan)SchemaVersionMismatchException)quote_stringstringify_param_valuez
DB.INDEXESzDB.CONSTRAINTSz
GRAPH.COPYzGRAPH.QUERYzGRAPH.DELETEzGRAPH.EXPLAINzGRAPH.SLOWLOGzGRAPH.PROFILEzGRAPH.RO_QUERYc                   D   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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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
f   g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      X/mnt/e/genesis-system/.venvs/voice-bridge/lib/python3.12/site-packages/falkordb/graph.py__init__zGraph.__init__   s,      $
%*40%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._query6   s    $  ))&1E9
 (lY		5+6 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.queryc   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_queryu   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 ]%  \  }}|t	        |      dz   t        |      z   dz   z  }' |S )z
        Build parameters header.

        Args:
            params (dict): The parameters.

        Returns:
            str: The parameters header.

         z'params' must be a dictzCYPHER = )r$   dict	TypeErroritemsstrr   )r   r   params_headerkeyvalues        r   r!   zGraph._build_params_header   sj     >&$'566! ,,. 	QJCSX^.CE.JJSPPM	Q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   rX   r   rY   rZ   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:r`   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)
ValueErrorr*   )r   rh   ri   rj   rk   patternr   s          r   _drop_indexzGraph._drop_index(  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.
        rs   rm   rx   r   rj   rk   s      r   drop_node_range_indexzGraph.drop_node_range_indexI       	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.
        ru   rm   rz   r{   s      r   drop_node_fulltext_indexzGraph.drop_node_fulltext_indexV       
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.
        rt   rm   rz   r{   s      r   drop_node_vector_indexzGraph.drop_node_vector_indexc       &%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.
        rs   ro   rz   r{   s      r   drop_edge_range_indexzGraph.drop_edge_range_indexp  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.
        ru   ro   rz   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.
        rt   ro   rz   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.
        )rg   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.
        rm   rn   r`   ro   rp   rq   rr   rs   rN   zCREATE z INDEX FOR z ON (r_   ze.{0}N{z:'z',:}z	 OPTIONS )rv   rc   mapformatrS   r$   rT   r*   )r   rh   ri   rj   r   r   rw   r   options_maprV   rW   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.
        rs   rm   r   r   rj   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.
        ru   rm   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similarityFunctionrt   rm   r   r   )r   rj   r   r   r   r   s         r   create_node_vector_indexzGraph.create_node_vector_index  s1     !$;NO't''&%^*^V]^^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.
        rs   ro   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.
        ru   ro   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   rt   ro   r   r   )r   r   r   r   r   r   s         r   create_edge_vector_indexzGraph.create_edge_vector_index  s1     !$;NO't''&(aZaY`aar   constraint_typec                 \     | j                   dd| j                  |||dt        |      g| S )z%
        Create a constraint
        GRAPH.CONSTRAINTCREATE
PROPERTIESr   r   ra   r   r   ri   rj   r   s        r   _create_constraintzGraph._create_constraint  s?     $t##$6$))$3[%$0#j/PDNP 	Pr   c                 r    	  | j                   |g|   | j                  dd|g| S # t        $ r Y  w xY w)a*  
        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 a the existance 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
        UNIQUErm   )r   r'   r   r   s      r   create_node_unique_constraintz#Graph.create_node_unique_constraint)  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)a9  
        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 a the existance 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_constraintB  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
        	MANDATORYrm   r   r   s      r    create_node_mandatory_constraintz&Graph.create_node_mandatory_constraintZ  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_constrainti  s      't&&{NHZzZZr   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_constraintw  s?     $t##$6		$3[%$0#j/PDNP 	P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   rm   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   rm   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            )typerj   r   
entitytypestatus)rg   GRAPH_LIST_CONSTRAINTS
result_setappend)r   resultconstraintsrows       r   list_constraintszGraph.list_constraints  sl     $$%;<GG 	7Cc!f.1!f.1!f.1!f.1!f	 6 7	7 r   )NNF)NN)r   N)N)TNN)6__name__
__module____qualname____doc__rT   r   propertyr   r   r   objectr%   boolr   r/   r*   r5   r9   r=   rA   rD   r	   rI   rL   rQ   r!   r   rg   rx   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      s?   6S 6 	c 	 	 DH?D+ +Xd3;.?%@ +}+8<+IT+Z CG'+Os OHT#v+->$? O}O0;O$ FJ'+N# NxS&[0A'B N}N0;N$)# )<=(	?#S #- #(#S #- #(4 C . @D.237$B $B $B%d^$B%d3i0$B<G$BPC c # "'2B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 =A'C 'c '# ')-c'EP'RMS M+ MP P[ P LM<G_c _S _69_LW_"P P[ PS3 S S OP<Gb b b69bLWb"P# PC PPS PM3 M2Xc X0Pc P[ [P P# Pc PK KVC V
NC 
N	Ys 	Y4V#4"5 r   r   N)typingr   r   r   graph_schemar   query_resultr   execution_planr	   
exceptionsr
   helpersr   r   r   r   r8   r#   r<   rK   r@   rF   r"   r   r   r   r   <module>r      sX    ' ' % % ) 6 8 &)  	
 w
 w
r   