
    BR<ic                    r   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZmZ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 ddlmZmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& dZ' G d d      Z(d4dZ)d5d6dZ*d5d7dZ+d5d8dZ,	 d5	 	 	 	 	 	 	 d9dZ- G d d      Z. G d de.      Z/ G d de.      Z0 G d de.      Z1 G d de1      Z2 G d  d!      Z3 G d" d#e/      Z4 G d$ d%e/      Z5 G d& d'e5      Z6 G d( d)e5      Z7 G d* d+e1      Z8 G d, d-e/      Z9 G d. d/e/      Z: G d0 d1e/      Z; G d2 d3e.      Z<y):zImplementation of Statements.    )annotationsN)AnyDictIterableListOptionalTupleUnion   )LockContention)DbDoc)NotSupportedErrorProgrammingError)
ExprParser)
deprecated)mysqlxpb_enum)	DocResultResult	RowResult	SqlResult)ConnectionTypeDatabaseTargetTypeMessageTypeProtobufMessageCextTypeProtobufMessageType
SchemaTypez&The given index name "{}" is not validc                      e Zd ZdZddZy)ExprzExpression wrapper.c                    || _         y N)expr)selfr!   s     Q/var/www/html/delta-backend/venv/lib/python3.12/site-packages/mysqlx/statement.py__init__zExpr.__init__?   s	    	    N)r!   r   returnNone)__name__
__module____qualname____doc__r$    r%   r#   r   r   <   s
    r%   r   c                 ^    t        |       dk(  rt        | d   t        t        f      r| d   S | S )zParse flexible parameters.r   r   )len
isinstancelisttuple)valuess    r#   flexible_paramsr3   C   s.    
6{aJvay4-@ayMr%   c                z    d|v r&| d   dk(  xr | d   dk(  xs | d   dk(  xr | d   dk(  S | d   dk(  xr | d   dk(  S )zCheck if the given identifier is quoted.

    Args:
        identifier (string): Identifier to check.
        sql_mode (Optional[string]): SQL mode.

    Returns:
        `True` if the identifier has backtick quotes, and False otherwise.
    ANSI_QUOTESr   `"r,   )
identifiersql_modes     r#   is_quoted_identifierr;   J   si      1$>B3)> 
qMS :Z^s%:	
 a=C9JrNc$99r%   c                    t        |       dk(  ryd|v r| j                  dd      }d| dS | j                  dd      }d| dS )a@  Quote the given identifier with backticks, converting backticks (`) in
    the identifier name with the correct escape sequence (``).

    Args:
        identifier (string): Identifier to quote.
        sql_mode (Optional[string]): SQL mode.

    Returns:
        A string with the identifier quoted with backticks.
    r   z``r5   r8   z""r6   )r.   replace)r9   r:   quoteds      r#   quote_identifierr?   [   s[     :! ##C.6(!}T*Fvha=r%   c           	     ^    dj                  | D cg c]  }t        ||       c}      S c c}w )a  Quote the given multi-part identifier with backticks.

    Args:
        identifiers (iterable): List of identifiers to quote.
        sql_mode (Optional[string]): SQL mode.

    Returns:
        A string with the multi-part identifier quoted with backticks.
    .)joinr?   )identifiersr:   r9   s      r#   quote_multipart_identifierrD   o   s.     88BMNJ	*h	/N Ns   *c                    d|v rdnd}||v rd| nd}|j                  |d      }t        |      dk(  r| n|d   j                  |      |d   j                  |      fS )zParse table name.

    Args:
        default_schema (str): The default schema.
        table_name (str): The table name.
        sql_mode(Optional[str]): The SQL mode.

    Returns:
        str: The parsed table name.
    r5   r8   r6   rA   r   r   r7   )splitr.   strip)default_schema
table_namer:   quote	delimitertemps         r#   parse_table_namerM   ~   sn     !H,C#E$
2!E7IIq)Dd)q.d1gmmE.BRu r%   c                  b   e Zd ZdZdddZedd       Zedd       Zedd       Zej                  dd       Zedd       Z
edd       Zej                  dd	       Zedd
       Zej                  dd       Zedd       Zedd       Zej                  dd       ZddZddZddZddZy)	Statementa	  Provides base functionality for statement objects.

    Args:
        target (object): The target database object, it can be
                         :class:`mysqlx.Collection` or :class:`mysqlx.Table`.
        doc_based (bool): `True` if it is document based.
    c                    || _         || _        |r|j                         nd | _        d | _        d| _        d| _        d| _        d| _        y )Nr   TF)	_target
_doc_basedget_connection_connection_stmt_id_exec_counter_changed	_prepared_deallocate_prepare_execute)r"   target	doc_baseds      r#   r$   zStatement.__init__   sO    +1 )'-F!!#4 	 (,"#"$16(r%   c                    | j                   S )z#object: The database object target.)rQ   r"   s    r#   rZ   zStatement.target   s     ||r%   c                .    | j                   j                  S )z*:class:`mysqlx.Schema`: The Schema object.)rQ   schemar]   s    r#   r_   zStatement.schema   s     ||"""r%   c                    | j                   S )zXReturns this statement ID.

        Returns:
            int: The statement ID.
        rU   r]   s    r#   stmt_idzStatement.stmt_id   s     }}r%   c                    || _         y r    ra   r"   values     r#   rb   zStatement.stmt_id   	    r%   c                    | j                   S )z5int: The number of times this statement was executed.rV   r]   s    r#   exec_counterzStatement.exec_counter   s     !!!r%   c                    | j                   S )z+bool: `True` if this statement has changes.rW   r]   s    r#   changedzStatement.changed   s     }}r%   c                    || _         y r    rk   rd   s     r#   rl   zStatement.changed   rf   r%   c                    | j                   S )z1bool: `True` if this statement has been prepared.rX   r]   s    r#   preparedzStatement.prepared   s     ~~r%   c                    || _         y r    ro   rd   s     r#   rp   zStatement.prepared   s	    r%   c                     | j                   dkD  S )z;bool: `True` if this statement was executed more than once.r   rh   r]   s    r#   repeatedzStatement.repeated   s     !!A%%r%   c                    | j                   S )z9bool: `True` to deallocate + prepare + execute statement.rY   r]   s    r#   deallocate_prepare_executez$Statement.deallocate_prepare_execute   s     ///r%   c                    || _         y r    ru   rd   s     r#   rv   z$Statement.deallocate_prepare_execute   s
    +0(r%   c                    | j                   S )zkCheck if it is document based.

        Returns:
            bool: `True` if it is document based.
        )rR   r]   s    r#   is_doc_basedzStatement.is_doc_based   s     r%   c                .    | xj                   dz  c_         y)z@Increments the number of times this statement has been executed.r   Nrh   r]   s    r#   increment_exec_counterz Statement.increment_exec_counter   s    ar%   c                    d| _         y)z<Resets the number of times this statement has been executed.r   Nrh   r]   s    r#   reset_exec_counterzStatement.reset_exec_counter   s
    r%   c                    t         zqExecute the statement.

        Raises:
           NotImplementedError: This method must be implemented.
        NotImplementedErrorr]   s    r#   executezStatement.execute   
     "!r%   NTrZ   r   r[   boolr&   r'   )r&   r   )r&   r   r&   int)re   r   r&   r'   r&   r   )re   r   r&   r'   )r&   r'   r&   r   )r(   r)   r*   r+   r$   propertyrZ   r_   rb   setterri   rl   rp   rs   rv   ry   r{   r}   r   r,   r%   r#   rO   rO      s"   
7   # #   ^^  " "   ^^    __  & & 0 0  &&1 '1 "r%   rO   c                  "    e Zd ZdZ	 	 d	 	 	 	 	 	 	 d fdZddZddZddZddZddZ	d dZ
d!d	Zd"d
Zd#dZd$dZd%dZd%dZd$dZ	 	 d#dZ	 	 d#dZ ed      dd       Z ed      dd       Z	 d&	 	 	 	 	 d'dZd(dZd)dZd*dZ xZS )+FilterableStatementa  A statement to be used with filterable statements.

    Args:
        target (object): The target database object, it can be
                         :class:`mysqlx.Collection` or :class:`mysqlx.Table`.
        doc_based (Optional[bool]): `True` if it is document based
                                    (default: `True`).
        condition (Optional[str]): Sets the search condition to filter
                                   documents or records.
    c                h   t         |   ||       i | _        i | _        d | _        d| _        d | _        d| _        d | _        d| _	        d | _
        d| _        d | _        d| _        d | _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        |r| j-                  |       y y )NrZ   r[    r   F)superr$   _binding_map	_bindings_having_grouping_str	_grouping_limit_offset_limit_row_count_projection_str_projection_expr	_sort_str
_sort_expr
_where_str_where_exprhas_bindings	has_limithas_group_by
has_havinghas_projectionhas_sort	has_where
_set_wherer"   rZ   r[   	condition	__class__s       r#   r$   zFilterableStatement.__init__
  s     	)<,.68.2"$  	 #$%)$&  	 !  	  "(,"'$"' %$)#$OOI& r%   c                   t        |t              r)| j                  t        |      j	                                yt        |t              r | j                  |j	                                yt        |t
              rX	 t        j                  |      }t        |t              st        	 |j                         D ]  }| j                  |||           yt        d      # t        $ r}t        d      |d}~ww xY w)a  Bind single object.

        Args:
            obj (:class:`mysqlx.DbDoc` or str): DbDoc or JSON string object.

        Raises:
            :class:`mysqlx.ProgrammingError`: If invalid JSON string to bind.
            ValueError: If JSON loaded is not a dictionary.
        zInvalid JSON string to bindNz%Invalid JSON string or object to bind)r/   dictbindr   as_strstrjsonloads
ValueErrorr   keys)r"   objreserrkeys        r#   _bind_singlez FilterableStatement._bind_single.  s     c4 IIeCj'')*U#IIcjjl#S!Ojjo!#t,$$ - xxz )		#s3x() ##JKK  O&'DE3NOs   ;+C 	C7&C22C7c                    d| _         dj                  t        |       | _        t	        | j                  | j
                         j                         | _        d| _        | S )zSets the sorting criteria.

        Args:
            *clauses: The expression strings defining the sort criteria.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.
        T,)	r   rB   r3   r   r   rR   parse_order_specr   rW   r"   clausess     r#   _sortzFilterableStatement._sortH  sV     /7";<$NN/



 	 r%   c                    d| _         || _        	 t        || j                         }|j	                         | _        |j                  | _	        d| _
        | S # t        $ r}t        d      |d}~ww xY w)a  Sets the search condition to filter.

        Args:
            condition (str): Sets the search condition to filter documents or
                             records.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.
        TzInvalid conditionN)r   r   r   rR   r!   r   r   r   placeholder_name_to_positionr   rW   )r"   r   r!   r   s       r#   r   zFilterableStatement._set_whereY  sw     #	AiT__)<=D#yy{D !==	  	A"#67S@	As   ,A 	A0A++A0c                    t        | }d| _        dj                  |      | _        t	        | j                  | j
                         j                         | _        d| _        y)zJSet group by.

        Args:
            *fields: List of fields.
        Tr   N)	r3   r   rB   r   r   rR   parse_expr_listr   rW   r"   fieldss     r#   _set_group_byz!FilterableStatement._set_group_byn  sY     !&)  XXf-#DOO 3

/
 	 r%   c                t    d| _         t        || j                         j                         | _        d| _        y)zOSet having.

        Args:
            condition (str): The condition.
        TN)r   r   rR   r!   r   rW   r"   r   s     r#   _set_havingzFilterableStatement._set_having|  s0     !)-@AFFHr%   c                    t        | }d| _        dj                  |      | _        t	        | j                  | j
                         j                         | _        d| _        | S )zSet the projection.

        Args:
            *fields: List of fields.

        Returns:
            :class:`mysqlx.FilterableStatement`: Returns self.
        Tr   )	r3   r   rB   r   r   rR   parse_table_select_projectionr   rW   r   s     r#   _set_projectionz#FilterableStatement._set_projection  s`     !&)""xx/ *  doo"5!

'
'
) 	 r%   c                    | j                   S zlReturns the binding map dictionary.

        Returns:
            dict: The binding map dictionary.
        r   r]   s    r#   get_binding_mapz#FilterableStatement.get_binding_map          r%   c                    | j                   S z\Returns the bindings list.

        Returns:
            `list`: The bindings list.
        r   r]   s    r#   get_bindingsz FilterableStatement.get_bindings       ~~r%   c                    | j                   S )zrReturns the grouping expression list.

        Returns:
            `list`: The grouping expression list.
        )r   r]   s    r#   get_groupingz FilterableStatement.get_grouping  r   r%   c                    | j                   S )zdReturns the having expression.

        Returns:
            object: The having expression.
        )r   r]   s    r#   
get_havingzFilterableStatement.get_having       ||r%   c                    | j                   S )z]Returns the limit row count.

        Returns:
            int: The limit row count.
        )r   r]   s    r#   get_limit_row_countz'FilterableStatement.get_limit_row_count  s     $$$r%   c                    | j                   S )zWReturns the limit offset.

        Returns:
            int: The limit offset.
        )r   r]   s    r#   get_limit_offsetz$FilterableStatement.get_limit_offset  s     !!!r%   c                    | j                   S )zbReturns the where expression.

        Returns:
            object: The where expression.
        )r   r]   s    r#   get_where_exprz"FilterableStatement.get_where_expr       r%   c                    | j                   S )zlReturns the projection expression.

        Returns:
            object: The projection expression.
        )r   r]   s    r#   get_projection_exprz'FilterableStatement.get_projection_expr  s     $$$r%   c                    | j                   S )z`Returns the sort expression.

        Returns:
            object: The sort expression.
        )r   r]   s    r#   get_sort_exprz!FilterableStatement.get_sort_expr  s     r%   8.0.12c                $    | j                  |      S )a&  Sets the search condition to filter.

        Args:
            condition (str): Sets the search condition to filter documents or
                             records.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        .. deprecated:: 8.0.12
        r   r   s     r#   wherezFilterableStatement.where  s     y))r%   c                      | j                   | S )zSets the sorting criteria.

        Args:
            *clauses: The expression strings defining the sort criteria.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        .. deprecated:: 8.0.12
        r   r   s     r#   sortzFilterableStatement.sort  s     tzz7##r%   c                L   t        |t              r|dk  rt        d      | j                  s;t	        | j
                  dk(        | _        t	        | j
                  dk(         | _        || _        d| _        |r,| j                  |       t        j                  dt               | S )a  Sets the maximum number of items to be returned.

        Args:
            row_count (int): The maximum number of items.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        Raises:
            ValueError: If ``row_count`` is not a positive integer.

        .. versionchanged:: 8.0.12
           The usage of ``offset`` was deprecated.
        r   z0The 'row_count' value must be a positive integerTzh'limit(row_count, offset)' is deprecated, please use 'offset(offset)' to set the number of items to skip)category)r/   r   r   r   r   rV   rW   rY   r   offsetwarningswarnDeprecationWarning)r"   	row_countr   s      r#   limitzFilterableStatement.limit  s    " )S)Y]OPP~~ !3!3q!89DM/38J8Ja8O4O/PD, )KKMM ,	 r%   c                T    t        |t              r|dk  rt        d      || _        | S )a:  Sets the number of items to skip.

        Args:
            offset (int): The number of items to skip.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        Raises:
            ValueError: If ``offset`` is not a positive integer.

        .. versionadded:: 8.0.12
        r   z-The 'offset' value must be a positive integer)r/   r   r   r   )r"   r   s     r#   r   zFilterableStatement.offset$  s-     &#&&1*LMM#r%   c                    d| _         t        |      }|dk(  r| j                  |d          | S |dk(  r|d   | j                  |d   <   | S t	        d      )a  Binds value(s) to a specific placeholder(s).

        Args:
            *args: The name of the placeholder and the value to bind.
                   A :class:`mysqlx.DbDoc` object or a JSON string
                   representation can be used.

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        Raises:
            ProgrammingError: If the number of arguments is invalid.
        Tr   r      #Invalid number of arguments to bind)r   r.   r   r   r   )r"   argscounts      r#   r   zFilterableStatement.bind7  si     !D	A:d1g&
 	 aZ&*1gDNN47#  ##HIIr%   c                    t         r   r   r]   s    r#   r   zFilterableStatement.executeO  r   r%   TNrZ   r   r[   r   r   Optional[str]r&   r'   )r   z!Union[DbDoc, Dict[str, Any], str]r&   r'   )r   r   r&   r   )r   r   r&   r   )r   r   r&   r'   )r   r   r&   r'   )r   r   r&   r   r&   Dict[str, Any])r&   zUnion[Dict[str, Any], List])r&   z9List[Union[ProtobufMessageType, ProtobufMessageCextType]])r&   r   r   r    )r   r   r   zOptional[int]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   r   r   r   r   r   r   r   r   __classcell__r   s   @r#   r   r      s    	 #'	"'""' "' !	"'
 
"'HL4"*$!%" %	B%	B * * $ $ 7;!!&3!	!F&0"r%   r   c                  V     e Zd ZdZd fdZed	d       Zd
dZddZddZ	ddZ
 xZS )SqlStatementzA statement for SQL execution.

    Args:
        connection (mysqlx.connection.Connection): Connection object.
        sql (string): The sql statement to be executed.
    c                |    t         |   d d       || _        || _        d | _        g | _        d| _        d| _        y NFr   )r   r$   rT   _sqlr   r   r   r   )r"   
connectionsqlr   s      r#   r$   zSqlStatement.__init__`  sB    6+5	6:-/"'$r%   c                    | j                   S )zstring: The SQL text statement.)r  r]   s    r#   r	  zSqlStatement.sqli  s     yyr%   c                    | j                   S r   r   r]   s    r#   r   zSqlStatement.get_binding_mapn  r   r%   c                    | j                   S r   r   r]   s    r#   r   zSqlStatement.get_bindingsv  r   r%   c                    t        |      dk(  rt        d      d| _        t        | }t	        |t
        t        f      r	|| _        | S | j                  j                  |       | S )zBinds value(s) to a specific placeholder(s).

        Args:
            *args: The value(s) to bind.

        Returns:
            mysqlx.SqlStatement: SqlStatement object.
        r   r   T)	r.   r   r   r3   r/   r0   r1   r   append)r"   r   bindingss      r#   r   zSqlStatement.bind~  sb     t9>"#HII "D)hu.%DN  NN!!(+r%   c                8    | j                   j                  |       S )zaExecute the statement.

        Returns:
            mysqlx.SqlResult: SqlResult object.
        )rT   send_sqlr]   s    r#   r   zSqlStatement.execute  s     ((..r%   )r  r   r	  r   r&   r'   r&   r   r   )r&   zUnion[Tuple, List])r   r   r&   r  )r&   r   )r(   r)   r*   r+   r$   r   r	  r   r   r   r   r  r  s   @r#   r  r  X  s5    %  !&/r%   r  c                  8     e Zd ZdZd fdZ	 	 ddZddZ xZS )WriteStatementz*Provide common write operation attributes.c                4    t         |   ||       g | _        y r    )r   r$   _values)r"   rZ   r[   r   s      r#   r$   zWriteStatement.__init__  s    +  	r%   c                    | j                   S )z^Returns the list of values.

        Returns:
            `list`: The list of values.
        )r  r]   s    r#   
get_valueszWriteStatement.get_values  s      ||r%   c                    t         r   r   r]   s    r#   r   zWriteStatement.execute  r   r%   r   )r&   zpList[Union[int, str, DbDoc, Dict[str, Any], List[Optional[Union[str, int, float, ExprParser, Dict[str, Any]]]]]]r   )r(   r)   r*   r+   r$   r  r   r  r  s   @r#   r  r    s    4

$"r%   r  c                  F     e Zd ZdZd fdZddZd	d
dZddZddZ xZ	S )AddStatementzA statement for document addition on a collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
    c                B    t         |   |d       d| _        g | _        y )NTF)r   r$   _upsertids)r"   
collectionr   s     r#   r$   zAddStatement.__init__  s     T*"r%   c                    | j                   S )zhReturns `True` if it's an upsert.

        Returns:
            bool: `True` if it's an upsert.
        r  r]   s    r#   	is_upsertzAddStatement.is_upsert  r   r%   c                    || _         | S )zSets the upset flag to the boolean of the value provided.
        Setting of this flag allows updating of the matched rows/documents
        with the provided value.

        Args:
            value (optional[bool]): Set or unset the upsert flag.
        r!  rd   s     r#   upsertzAddStatement.upsert  s     r%   c                    t        | D ]R  }t        |t              r| j                  j	                  |       /| j                  j	                  t        |             T | S )zAdds a list of documents into a collection.

        Args:
            *values: The documents to be added into the collection.

        Returns:
            mysqlx.AddStatement: AddStatement object.
        )r3   r/   r   r  r  )r"   r2   vals      r#   addzAddStatement.add  sQ     #F+ 	0C#u%##C(##E#J/		0
 r%   c                |    t        | j                        dk(  r
t               S | j                  j	                  |       S )[Execute the statement.

        Returns:
            mysqlx.Result: Result object.
        r   )r.   r  r   rT   send_insertr]   s    r#   r   zAddStatement.execute  s3     t||!8O++D11r%   )r  r   r&   r'   r   r   )re   r   r&   r  )r2   r   r&   r  r&   r   )
r(   r)   r*   r+   r$   r"  r$  r'  r   r  r  s   @r#   r  r    s!    
	 	2r%   r  c                  "    e Zd ZdZdddZddZy)
UpdateSpeczUpdate specification class implementation.

    Args:
        update_type (int): The update type.
        source (str): The source.
        value (Optional[str]): The value.

    Raises:
        ProgrammingError: If `source` is invalid.
    Nc                    |t        d      k(  r| j                  ||       y || _        	 t        |d      j	                         j
                  | _        || _	        y # t        $ r}t        |       |d }~ww xY w)N*Mysqlx.Crud.UpdateOperation.UpdateType.SETF)
r   
_table_setupdate_typer   document_fieldr9   sourcer   r   re   )r"   r1  r3  re   r   s        r#   r$   zUpdateSpec.__init__  sr    -(TUUOOFE*$/D:#-fe#<#K#K#M#X#X $DJ  :&#0c9:s   )A 	A6$A11A6c                p    t        d      | _        t        |d      j                         | _        || _        y)zlTable set.

        Args:
            source (str): The source.
            value (str): The value.
        r/  TN)r   r1  r   parse_table_update_fieldr3  re   )r"   r3  re   s      r#   r0  zUpdateSpec._table_set  s0     ))UV .GGI
r%   r    )r1  r   r3  r   re   r   r&   r'   )r3  r   re   r   r&   r'   )r(   r)   r*   r+   r$   r0  r,   r%   r#   r-  r-    s    		$	r%   r-  c                       e Zd ZdZd fdZddZddZddZ ed      dd       Z	ddZ
dd	Zdd
ZddZddZ xZS )ModifyStatementaU  A statement for document update operations on a Collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
        condition (str): Sets the search condition to identify the documents
                         to be modified.

    .. versionchanged:: 8.0.12
       The ``condition`` parameter is now mandatory.
    c                6    t         |   ||       i | _        y N)rZ   r   r   r$   _update_opsr"   r  r   r   s      r#   r$   zModifyStatement.__init__.  s    
i@+-r%   c                      | j                   | S )zSets the sorting criteria.

        Args:
            *clauses: The expression strings defining the sort criteria.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        r   r   s     r#   r   zModifyStatement.sort2       tzz7##r%   c                    | j                   S ztReturns the list of update operations.

        Returns:
            `list`: The list of update operations.
        r;  r]   s    r#   get_update_opszModifyStatement.get_update_ops=  r   r%   c                Z    t        t        d      ||      | j                  |<   d| _        | S )a2  Sets or updates attributes on documents in a collection.

        Args:
            doc_path (string): The document path of the item to be set.
            value (string): The value to be set on the specified attribute.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        z/Mysqlx.Crud.UpdateOperation.UpdateType.ITEM_SETTr-  r   r;  rW   r"   doc_pathre   s      r#   setzModifyStatement.setE  s6     &0KL&
"
 r%   r   c                Z    t        t        d      ||      | j                  |<   d| _        | S )a  Add an update to the statement setting the field, if it exists at
        the document path, to the given value.

        Args:
            doc_path (string): The document path of the item to be set.
            value (object): The value to be set on the specified attribute.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.

        .. deprecated:: 8.0.12
        z3Mysqlx.Crud.UpdateOperation.UpdateType.ITEM_REPLACETrD  rE  s      r#   changezModifyStatement.changeW  s6     &0OP&
"
 r%   c                r    t        | D ]$  }t        t        d      |      | j                  |<   & d| _        | S )a  Removes attributes from documents in a collection.

        Args:
            doc_paths (list): The list of document paths of the attributes to be
                              removed.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        z2Mysqlx.Crud.UpdateOperation.UpdateType.ITEM_REMOVET)r3   r-  r   r;  rW   )r"   	doc_pathsitems      r#   unsetzModifyStatement.unsetm  sG     $Y/ 	D%/RS&DT"	
 r%   c                Z    t        t        d      ||      | j                  |<   d| _        | S )a  Insert a value into the specified array in documents of a
        collection.

        Args:
            field (string): A document path that identifies the array attribute
                            and position where the value will be inserted.
            value (object): The value to be inserted.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        z3Mysqlx.Crud.UpdateOperation.UpdateType.ARRAY_INSERTTrD  r"   fieldre   s      r#   array_insertzModifyStatement.array_insert  s6     #-OP#

 r%   c                Z    t        t        d      ||      | j                  |<   d| _        | S )a  Inserts a value into a specific position in an array attribute in
        documents of a collection.

        Args:
            doc_path (string): A document path that identifies the array
                               attribute and position where the value will be
                               inserted.
            value (object): The value to be inserted.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        z3Mysqlx.Crud.UpdateOperation.UpdateType.ARRAY_APPENDTrD  rE  s      r#   array_appendzModifyStatement.array_append  s6     &0OP&
"
 r%   c                    |d}t        |t        t        t        t        f      st        d      t        t        d      dt        |t              r|j                         n|      | j                  d<   d| _
        | S )a  Takes a :class:`mysqlx.DbDoc`, string JSON format or a dict with the
        changes and applies it on all matching documents.

        Args:
            doc (object): A generic document (DbDoc), string in JSON format or
                          dict, with the changes to apply to the matching
                          documents.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        r   z>Invalid data for update operation on document collection tablez2Mysqlx.Crud.UpdateOperation.UpdateType.MERGE_PATCH$patchT)r/   r   r   r   r   r   r-  r   r!   r;  rW   )r"   docs     r#   rV  zModifyStatement.patch  sv     ;C#
D%=>"P  %/NO$S*5CHHJ3%
!
 r%   c                f    | j                   st        d      | j                  j                  |       S )Execute the statement.

        Returns:
            mysqlx.Result: Result object.

        Raises:
            ProgrammingError: If condition was not set.
        z!No condition was found for modifyr   r   rT   send_updater]   s    r#   r   zModifyStatement.execute  .     ~~"#FGG++D11r%   r  r   r   r   r&   r'   )r   r   r&   r7  r   )rF  r   re   r   r&   r7  )rK  r   r&   r7  )rP  r   re   r   r&   r7  )rW  z#Union[Dict, DbDoc, ExprParser, str]r&   r7  r+  )r(   r)   r*   r+   r$   r   rB  rG  r   rI  rM  rQ  rS  rV  r   r  r  s   @r#   r7  r7  "  sN    	.	$ $  *$(*42r%   r7  c                       e Zd ZdZ	 	 d	 	 	 	 	 	 	 d fdZedd       ZddZddZddZ	e
j                  f	 	 	 ddZe
j                  f	 	 	 ddZdd	Zdd
ZddZ xZS )ReadStatementa  Provide base functionality for Read operations

    Args:
        target (object): The target database object, it can be
                         :class:`mysqlx.Collection` or :class:`mysqlx.Table`.
        doc_based (Optional[bool]): `True` if it is document based
                                    (default: `True`).
        condition (Optional[str]): Sets the search condition to filter
                                   documents or records.
    c                n    t         |   |||       d| _        d| _        t        j
                  | _        y NF)r   r$   _lock_exclusive_lock_sharedr   DEFAULT_lock_contentionr   s       r#   r$   zReadStatement.__init__  s4     	I6%*"'0>0F0Fr%   c                    | j                   S )z::class:`mysqlx.LockContention`: The lock contention value.)re  r]   s    r#   lock_contentionzReadStatement.lock_contention  s     $$$r%   c                x    	 t        |j                        }|| _        y# t        $ r}t        d      |d}~ww xY w)zSet the lock contention.

        Args:
            lock_contention (:class:`mysqlx.LockContention`): Lock contention.

        Raises:
            ProgrammingError: If is an invalid lock contention value.
        z;Invalid lock contention mode. Use 'NOWAIT' or 'SKIP_LOCKED'N)r   re   r   r   re  )r"   rg  _r   s       r#   _set_lock_contentionz"ReadStatement._set_lock_contention  sF    	445A
 !0	  	"M	s    	949c                    | j                   S )zrReturns `True` if is `EXCLUSIVE LOCK`.

        Returns:
            bool: `True` if is `EXCLUSIVE LOCK`.
        )rb  r]   s    r#   is_lock_exclusivezReadStatement.is_lock_exclusive  s     ###r%   c                    | j                   S )zlReturns `True` if is `SHARED LOCK`.

        Returns:
            bool: `True` if is `SHARED LOCK`.
        )rc  r]   s    r#   is_lock_sharedzReadStatement.is_lock_shared  r   r%   c                D    d| _         d| _        | j                  |       | S )zExecute a read operation with `SHARED LOCK`. Only one lock can be
           active at a time.

        Args:
            lock_contention (:class:`mysqlx.LockContention`): Lock contention.
        FTrb  rc  rj  r"   rg  s     r#   lock_sharedzReadStatement.lock_shared  s'      % !!/2r%   c                D    d| _         d| _        | j                  |       | S )zExecute a read operation with `EXCLUSIVE LOCK`. Only one lock can be
           active at a time.

        Args:
            lock_contention (:class:`mysqlx.LockContention`): Lock contention.
        TFrp  rq  s     r#   lock_exclusivezReadStatement.lock_exclusive  s'      $!!!/2r%   c                $     | j                   |  | S )zSets a grouping criteria for the resultset.

        Args:
            *fields: The string expressions identifying the grouping criteria.

        Returns:
            mysqlx.ReadStatement: ReadStatement object.
        )r   r   s     r#   group_byzReadStatement.group_by*  s     	F#r%   c                (    | j                  |       | S )a=  Sets a condition for records to be considered in agregate function
        operations.

        Args:
            condition (string): A condition on the agregate functions used on
                                the grouping criteria.

        Returns:
            mysqlx.ReadStatement: ReadStatement object.
        )r   r   s     r#   havingzReadStatement.having6  s     	#r%   c                8    | j                   j                  |       S r)  )rT   	send_findr]   s    r#   r   zReadStatement.executeD  s     ))$//r%   r   r   )r&   r   )rg  r   r&   r'   r   )rg  r   r&   r_  )r   r   r&   r_  )r   r   r&   r_  )r&   zUnion[DocResult, RowResult])r(   r)   r*   r+   r$   r   rg  rj  rl  rn  r   rd  rr  rt  rv  rx  r   r  r  s   @r#   r_  r_    s    	 #'		G"	G 	G !		G
 
	G % %0$$! 1?0F0F-	 1?0F0F-	
0r%   r_  c                  B     e Zd ZdZ	 d	 	 	 	 	 d fdZddZddZ xZS )	FindStatementa  A statement document selection on a Collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
        condition (Optional[str]): An optional expression to identify the
                                   documents to be retrieved. If not specified
                                   all the documents will be included on the
                                   result unless a limit is set.
    c                (    t         |   |d|       y )NTr   r$   r<  s      r#   r$   zFindStatement.__init__X  s     	T95r%   c                      | j                   | S )zSets a document field filter.

        Args:
            *fields: The string expressions identifying the fields to be
                     extracted.

        Returns:
            mysqlx.FindStatement: FindStatement object.
        )r   r   s     r#   r   zFindStatement.fields]  s     $t##V,,r%   c                      | j                   | S zSets the sorting criteria.

        Args:
            *clauses: The expression strings defining the sort criteria.

        Returns:
            mysqlx.FindStatement: FindStatement object.
        r   r   s     r#   r   zFindStatement.sorti  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   @r#   r}  r}  M  s6     JN6,69F6	6

-	$r%   r}  c                  <     e Zd ZdZd fdZddZddZd	dZ xZS )
SelectStatementzA statement for record retrieval operations on a Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be retrieved.
    c                D    t         |   |d        | j                  |  y ra  )r   r$   r   r"   tabler   r   s      r#   r$   zSelectStatement.__init__}  s"    &f%r%   c                $    | j                  |      S )zSets the search condition to filter.

        Args:
            condition (str): Sets the search condition to filter records.

        Returns:
            mysqlx.SelectStatement: SelectStatement object.
        r   r   s     r#   r   zSelectStatement.where       y))r%   c                      | j                   | S )zSets the order by criteria.

        Args:
            *clauses: The expression strings defining the order by criteria.

        Returns:
            mysqlx.SelectStatement: SelectStatement object.
        r   r   s     r#   order_byzSelectStatement.order_by  r>  r%   c                   | j                   rd| j                   nd}| j                  rd| j                   nd}| j                  rd| j
                   nd}| j                  rd| j                   nd}| j                  rd| j                   d| j                   nd}d| j                  xs d	 d
| j                  j                   d| j                  j                   | | | | | }|S )zYReturns the generated SQL.

        Returns:
            str: The generated SQL.
        z WHERE r   z
 GROUP BY z HAVING z
 ORDER BY z LIMIT z OFFSET zSELECT *z FROM rA   )r   r   r   r   r   r   r   r   r   r   r   r   r_   namerZ   )r"   r   rv  rx  r  r   stmts          r#   get_sqlzSelectStatement.get_sql  s     04~~'$//*+28<8I8IZ 2 234r.2oo8DLL>*248MMZ/0r ~~ d++,HT5G5G4HI 	 d**1c2 3KK$$%Qt{{'7'7&8ghZxz%: 	
 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   @r#   r  r  u  s    &	*	$r%   r  c                  4     e Zd ZdZd fdZddZddZ xZS )InsertStatementzA statement for insert operations on Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be inserted.
    c                @    t         |   |d       t        | | _        y ra  )r   r$   r3   _fieldsr  s      r#   r$   zInsertStatement.__init__  s    &+:F+Cr%   c                Z    | j                   j                  t        t        |              | S )zSet the values to be inserted.

        Args:
            *values: The values of the columns to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object.
        )r  r  r0   r3   )r"   r2   s     r#   r2   zInsertStatement.values  s%     	D&!9:;r%   c                8    | j                   j                  |       S rz  )rT   r*  r]   s    r#   r   zInsertStatement.execute  s     ++D11r%   )r  r   r   r   r&   r'   )r2   r   r&   r  r+  )r(   r)   r*   r+   r$   r2   r   r  r  s   @r#   r  r    s    D
2r%   r  c                  L     e Zd ZdZd fdZd	dZd
dZddZddZddZ	 xZ
S )UpdateStatementzA statement for record update operations on a Table.

    Args:
        table (mysqlx.Table): The Table object.

    .. versionchanged:: 8.0.12
       The ``fields`` parameters were removed.
    c                6    t         |   |d       i | _        y r  r:  r"   r  r   s     r#   r$   zUpdateStatement.__init__  s    7+-r%   c                $    | j                  |      S )zSets the search condition to filter.

        Args:
            condition (str): Sets the search condition to filter records.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r   r   s     r#   r   zUpdateStatement.where  r  r%   c                      | j                   | S )zSets the order by criteria.

        Args:
            *clauses: The expression strings defining the order by criteria.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r   r   s     r#   r  zUpdateStatement.order_by  r>  r%   c                    | j                   S r@  rA  r]   s    r#   rB  zUpdateStatement.get_update_ops  r   r%   c                Z    t        t        d      ||      | j                  |<   d| _        | S )a  Updates the column value on records in a table.

        Args:
            field (string): The column name to be updated.
            value (object): The value to be set on the specified column.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r/  TrD  rO  s      r#   rG  zUpdateStatement.set  s6     #-FG#

 r%   c                f    | j                   st        d      | j                  j                  |       S )zExecute the statement.

        Returns:
            mysqlx.Result: Result object

        Raises:
            ProgrammingError: If condition was not set.
        z!No condition was found for updaterZ  r]   s    r#   r   zUpdateStatement.execute  r\  r%   r  r   r&   r'   )r   r   r&   r  )r   r   r&   r  r   )rP  r   re   r   r&   r  r+  )r(   r)   r*   r+   r$   r   r  rB  rG  r   r  r  s   @r#   r  r    s&    .	*	$ $2r%   r  c                  4     e Zd ZdZd fdZddZddZ xZS )RemoveStatementaE  A statement for document removal from a collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
        condition (str): Sets the search condition to identify the documents
                         to be removed.

    .. versionchanged:: 8.0.12
       The ``condition`` parameter was added.
    c                (    t         |   ||       y r9  r  r<  s      r#   r$   zRemoveStatement.__init__'  s    
i@r%   c                      | j                   | S r  r   r   s     r#   r   zRemoveStatement.sort*  r>  r%   c                f    | j                   st        d      | j                  j                  |       S )rY  z!No condition was found for remover   r   rT   send_deleter]   s    r#   r   zRemoveStatement.execute5  r\  r%   r]  )r   r   r&   r  r+  )r(   r)   r*   r+   r$   r   r   r  r  s   @r#   r  r    s    	A	$2r%   r  c                  <     e Zd ZdZd fdZddZddZd	dZ xZS )
DeleteStatementzA statement that drops a table.

    Args:
        table (mysqlx.Table): The Table object.

    .. versionchanged:: 8.0.12
       The ``condition`` parameter was removed.
    c                (    t         |   |d       y r  r  r  s     r#   r$   zDeleteStatement.__init__M  s    7r%   c                $    | j                  |      S )zSets the search condition to filter.

        Args:
            condition (str): Sets the search condition to filter records.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object.
        r   r   s     r#   r   zDeleteStatement.whereP  r  r%   c                      | j                   | S )zSets the order by criteria.

        Args:
            *clauses: The expression strings defining the order by criteria.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object.
        r   r   s     r#   r  zDeleteStatement.order_by[  r>  r%   c                f    | j                   st        d      | j                  j                  |       S )rY  z!No condition was found for deleter  r]   s    r#   r   zDeleteStatement.executef  r\  r%   r  )r   r   r&   r  )r   r   r&   r  r+  )	r(   r)   r*   r+   r$   r   r  r   r  r  s   @r#   r  r  C  s    8	*	$2r%   r  c                  <     e Zd ZdZ	 	 	 	 	 	 	 	 d fdZddZ xZS )CreateCollectionIndexStatementa)  A statement that creates an index on a collection.

    Args:
        collection (mysqlx.Collection): Collection.
        index_name (string): Index name.
        index_desc (dict): A dictionary containing the fields members that
                           constraints the index to be created. It must have
                           the form as shown in the following::

                               {"fields": [{"field": member_path,
                                            "type": member_type,
                                            "required": member_required,
                                            "collation": collation,
                                            "options": options,
                                            "srid": srid},
                                            # {... more members,
                                            #      repeated as many times
                                            #      as needed}
                                            ],
                                "type": type}
    c                    t         |   |       t        j                  |      | _        || _        | j                  j                  dg       | _        y )N)rZ   r   )r   r$   copydeepcopy_index_desc_index_namepop_fields_desc)r"   r  
index_name
index_descr   s       r#   r$   z'CreateCollectionIndexStatement.__init__  sJ     	
++/==+D *262B2B2F2FxQS2Tr%   c                	   | j                   (t        t        j                  | j                               	 t	        | j                         j                         j                         }t        |t              r9|d   t        d      k7  rht        t        j                  | j                               |j                  t        d      k7  r(t        t        j                  | j                               | j                  st        d| j                         t        | j                  t              st        d      i }| j                   |d<   | j                   j"                  |d<   | j                   j$                  j"                  |d<   d| j                  v r| j                  j'                  d      |d<   nd	|d<   | j                  j'                  d
d      |d
<   |d
   rt)        d      g |d<   | j                  rt        d| j                         	 | j                  D ]  }i }|j'                  d      |d<   |j'                  d      |d<   |j'                  dd      |d<   |j'                  dd      |d<   t        |d   t*              st-        d      t        |d   t*              st-        d      |d   j/                         dk(  r|d   st        d      |d   j/                         d	k(  r|d   dk(  rt        d      d|v rV|d   j/                         j1                  d      s t        d|d   j/                          d      |j'                  d      |d<   d|v r5|d   j/                         dk7  rt        d      |j'                  d      |d<   d|v r5|d   j/                         dk7  rt        d       |j'                  d      |d<   |d   j3                  |        	 | j                  D ]  }|st        d#|        | j6                  j9                  d$d%d&|      S # t        t        f$ r.}t        t        j                  | j                               |d}~ww xY w# t4        $ r}t        d!| d"       |d}~ww xY w)'r)  NtypezMysqlx.Expr.Expr.Type.IDENTzCRequired member 'fields' not found in the given index description: z,Required member 'fields' must contain a listr  r  r_   INDEXuniqueFz!Unique indexes are not supported.
constraintzUnidentified fields: rP  memberrequiredarrayz'Field member 'required' must be Booleanz$Field member 'array' must be BooleanSPATIALzQField member 'required' must be set to 'True' when index type is set to 'SPATIAL'GEOJSONzIIndex 'type' must be set to 'SPATIAL' when field type is set to 'GEOJSON'	collationTEXTzCThe 'collation' member can only be used when field type is set to ''optionszIThe 'options' member can only be used when index type is set to 'GEOJSON'sridzFThe 'srid' member can only be used when index type is set to 'GEOJSON'zRequired inner member z not found in constraint: zUnidentified inner fields: mysqlxcreate_collection_indexT)r  r   ERR_INVALID_INDEX_NAMEformatr   r!   get_messager/   r   r   r  r   AttributeErrorr  r  r0   rQ   r  r_   r  r   r   	TypeErrorupper
startswithr  KeyErrorrT   execute_nonquery)r"   parsed_identr   r   
field_descr  s         r#   r   z&CreateCollectionIndexStatement.execute  s    #"#9#@#@AQAQ#RSS	%d&6&67<<>JJLL ,-'=9V+WW*.55d6F6FG   $$6S(TT*.55d6F6FG    "  $ 0 013 
 $++T2"#QRR!''V!\\..\,,11XT%%%++//7DL"DL))--h>X>#$GHH\"%:4;K;K:L#MNN1	"// ,6

'1~~g'>
8$%/^^F%;
6")3
E)J
:&&0nnWe&D
7#!*Z"8$?#$MNN!*W"5t<#$JKK<%%'94Z
=S*9  <%%'72z&7IY7V*3  *,%f-335@@H.  *6 2 8 8 :;1> 
 /9nn[.IJ{+ 
*!&)//1Y>.=  -7NN9,EJy)Z'!&)//1Y>.7  *4)?Jv&\"))*5Y,6d ++ 	SJ&)DZL'QRR	S 00/t
 	
m N+ 	"&--d.>.>?	Z  	"(-G
|T	s1   B:P# GQ# #Q 2)QQ #	R,Q>>R)r  r   r  r   r  r   r&   r'   r+  )r(   r)   r*   r+   r$   r   r  r  s   @r#   r  r  t  s>    ,	U&	U 	U #		U
 
	Up
r%   r  )r2   r   r&   zUnion[List, Tuple])r   )r9   r   r:   r   r&   r   )r9   r   r:   r   r&   r   )rC   zIterable[str]r:   r   r&   r   )rH   r   rI   r   r:   r   r&   zTuple[str, str])=r+   
__future__r   r  r   r   typingr   r   r   r   r   r	   r
   	constantsr   dbdocr   errorsr   r   r!   r   helpersr   protobufr   resultr   r   r   r   typesr   r   r   r   r   r   r  r   r3   r;   r?   rD   rM   rO   r   r  r  r  r-  r7  r_  r}  r  r  r  r  r  r  r,   r%   r#   <module>r     sa  > $ "    D D D %  7   # ; ;  B  :"(  ;=%(47,g" g"TW") W"t
?/9 ?/D'"Y '"T82> 82v   Fk2) k2\z0' z0z%$M %$P6m 6r2n 2BI2) I2X%2) %2P.2) .2bR
Y R
r%   