o
    hc                     @  s  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 dZ(dGddZ)dHdIddZ*dHdJddZ+dHdKd"d#Z,	dHdLd'd(Z-G d)d* d*Z.G d+d, d,e.Z/G d-d. d.e.Z0G d/d0 d0e.Z1G d1d2 d2e1Z2G d3d4 d4Z3G d5d6 d6e/Z4G d7d8 d8e/Z5G d9d: d:e5Z6G d;d< d<e5Z7G d=d> d>e1Z8G d?d@ d@e/Z9G dAdB dBe/Z:G dCdD dDe/Z;G dEdF dFe.Z<dS )Mz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                   @  s   e Zd ZdZd	ddZdS )
ExprzExpression wrapper.exprr   returnNonec                 C  
   || _ d S N)r   )selfr    r#   K/var/www/html/scripts/venv/lib/python3.10/site-packages/mysqlx/statement.py__init__?   s   
zExpr.__init__N)r   r   r   r   )__name__
__module____qualname____doc__r%   r#   r#   r#   r$   r   <   s    r   valuesr   r   Union[List, Tuple]c                  G  s*   t | dkrt| d ttfr| d S | S )zParse flexible parameters.r
   r   )len
isinstancelisttuple)r*   r#   r#   r$   flexible_paramsC   s   r0    
identifierstrsql_modeboolc                 C  sP   d|v r| d dkr| d dkp| d dko| d dkS | d dko'| 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#   )r2   r4   r#   r#   r$   is_quoted_identifierJ   s
   
r:   c                 C  sH   t | dkrdS d|v r| dd}d| dS | 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``r6   r9   z""r7   )r,   replace)r2   r4   quotedr#   r#   r$   quote_identifier[   s   r=   identifiersIterable[str]c                   s   d  fdd| D S )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.
    .c                   s   g | ]}t | qS r#   )r=   ).0r2   r4   r#   r$   
<listcomp>z   s    z.quote_multipart_identifier.<locals>.<listcomp>)join)r>   r4   r#   rB   r$   quote_multipart_identifiero   s   
rE   default_schema
table_nameTuple[str, str]c                 C  s^   d|v rdnd}||v rd| nd}| |d}t|dkr!| n|d ||d |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.
    r6   r9   r7   r@   r
   r   r8   )splitr,   strip)rF   rG   r4   quote	delimitertempr#   r#   r$   parse_table_name~   s   rN   c                   @  s   e Zd ZdZd,d-d	d
Zed.ddZed/ddZed0ddZej	d1ddZed0ddZ
ed2ddZej	d3ddZed2ddZej	d3ddZed2ddZed2dd Zej	d3d!d Zd2d"d#Zd4d$d%Zd4d&d'Zd5d)d*Zd+S )6	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.
    Ttargetr   	doc_basedr5   r   r   c                 C  s@   || _ || _|r| nd | _d | _d| _d| _d| _d| _d S )Nr   TF)	_target
_doc_basedget_connection_connection_stmt_id_exec_counter_changed	_prepared_deallocate_prepare_executer"   rP   rQ   r#   r#   r$   r%      s   
zStatement.__init__c                 C     | j S )z#object: The database object target.)rR   r"   r#   r#   r$   rP         zStatement.targetr   c                 C  s   | j jS )z*:class:`mysqlx.Schema`: The Schema object.)rR   schemar]   r#   r#   r$   r_      s   zStatement.schemaintc                 C  r\   )zXReturns this statement ID.

        Returns:
            int: The statement ID.
        rV   r]   r#   r#   r$   stmt_id   s   zStatement.stmt_idvaluec                 C  r    r!   ra   r"   rc   r#   r#   r$   rb         
c                 C  r\   )z5int: The number of times this statement was executed.rW   r]   r#   r#   r$   exec_counter   r^   zStatement.exec_counterc                 C  r\   )z+bool: `True` if this statement has changes.rX   r]   r#   r#   r$   changed   r^   zStatement.changedc                 C  r    r!   rh   rd   r#   r#   r$   ri      re   c                 C  r\   )z1bool: `True` if this statement has been prepared.rY   r]   r#   r#   r$   prepared   r^   zStatement.preparedc                 C  r    r!   rj   rd   r#   r#   r$   rk      re   c                 C  s
   | j dkS )z;bool: `True` if this statement was executed more than once.r
   rf   r]   r#   r#   r$   repeated   s   
zStatement.repeatedc                 C  r\   )z9bool: `True` to deallocate + prepare + execute statement.rZ   r]   r#   r#   r$   deallocate_prepare_execute   r^   z$Statement.deallocate_prepare_executec                 C  r    r!   rm   rd   r#   r#   r$   rn      re   c                 C  r\   )zkCheck if it is document based.

        Returns:
            bool: `True` if it is document based.
        )rS   r]   r#   r#   r$   is_doc_based      zStatement.is_doc_basedc                 C  s   |  j d7  _ dS )z@Increments the number of times this statement has been executed.r
   Nrf   r]   r#   r#   r$   increment_exec_counter   s   z Statement.increment_exec_counterc                 C  s
   d| _ dS )z<Resets the number of times this statement has been executed.r   Nrf   r]   r#   r#   r$   reset_exec_counter   re   zStatement.reset_exec_counterr   c                 C     t zqExecute the statement.

        Raises:
           NotImplementedError: This method must be implemented.
        NotImplementedErrorr]   r#   r#   r$   execute      zStatement.executeNTrP   r   rQ   r5   r   r   )r   r   )r   r   r   r`   )rc   r`   r   r   r   r5   )rc   r5   r   r   )r   r   r   r   )r&   r'   r(   r)   r%   propertyrP   r_   rb   setterrg   ri   rk   rl   rn   ro   rq   rr   rw   r#   r#   r#   r$   rO      s>    


rO   c                      s  e Zd ZdZ		dHdI fddZdJddZdKddZdLddZdMddZdNddZ	dOddZ
dPd d!ZdQd#d$ZdRd&d'ZdSd)d*ZdTd,d-ZdTd.d/ZdSd0d1ZdRd2d3ZdRd4d5Zed6dLd7d8Zed6dKd9d:Z	dUdVd>d?ZdWd@dAZdXdDdEZdYdFdGZ  ZS )Z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.
    TNrP   r   rQ   r5   	conditionOptional[str]r   r   c                   s   t  j||d i | _i | _d | _d| _d | _d| _d | _d| _	d | _
d| _d | _d| _d | _d| _d| _d| _d| _d| _d| _d| _|rM| | d S d S )NrP   rQ   r1   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"   rP   rQ   r   	__class__r#   r$   r%   
  s6   zFilterableStatement.__init__obj!Union[DbDoc, Dict[str, Any], str]c              
   C  s   t |tr| t|  dS t |tr| |  dS t |trTzt|}t |ts0tW n tyB } zt	d|d}~ww |
 D ]
}| |||  qGdS t	d)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_strr3   jsonloads
ValueErrorr   keys)r"   r   reserrkeyr#   r#   r$   _bind_single.  s$   






z FilterableStatement._bind_singleclausesr3   c                 G  s6   d| _ dt| | _t| j| j  | _d| _| S )zSets the sorting criteria.

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

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.
        T,)	r   rD   r0   r   r   rS   parse_order_specr   rX   r"   r   r#   r#   r$   _sortH  s   	
zFilterableStatement._sortc              
   C  s^   d| _ || _zt|| j }| | _W n ty% } ztd|d}~ww |j| _	d| _
| 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.
        TzInvalid conditionN)r   r   r   rS   r   r   r   r   placeholder_name_to_positionr   rX   )r"   r   r   r   r#   r#   r$   r   Y  s   

zFilterableStatement._set_wherefieldsc                 G  s:   t | }d| _d|| _t| j| j  | _d| _dS )zJSet group by.

        Args:
            *fields: List of fields.
        Tr   N)	r0   r   rD   r   r   rS   parse_expr_listr   rX   r"   r   r#   r#   r$   _set_group_byn  s   

z!FilterableStatement._set_group_byc                 C  s$   d| _ t|| j  | _d| _dS )zOSet having.

        Args:
            condition (str): The condition.
        TN)r   r   rS   r   r   rX   r"   r   r#   r#   r$   _set_having|  s   
zFilterableStatement._set_havingc                 G  s:   t | }d| _d|| _t| j| j  | _d| _| S )zSet the projection.

        Args:
            *fields: List of fields.

        Returns:
            :class:`mysqlx.FilterableStatement`: Returns self.
        Tr   )	r0   r   rD   r   r   rS   parse_table_select_projectionr   rX   r   r#   r#   r$   _set_projection  s   	
z#FilterableStatement._set_projectionDict[str, Any]c                 C  r\   zlReturns the binding map dictionary.

        Returns:
            dict: The binding map dictionary.
        r   r]   r#   r#   r$   get_binding_map  rp   z#FilterableStatement.get_binding_mapUnion[Dict[str, Any], List]c                 C  r\   z\Returns the bindings list.

        Returns:
            `list`: The bindings list.
        r   r]   r#   r#   r$   get_bindings  rp   z FilterableStatement.get_bindings9List[Union[ProtobufMessageType, ProtobufMessageCextType]]c                 C  r\   )zrReturns the grouping expression list.

        Returns:
            `list`: The grouping expression list.
        )r   r]   r#   r#   r$   get_grouping  rp   z FilterableStatement.get_groupingr   c                 C  r\   )zdReturns the having expression.

        Returns:
            object: The having expression.
        )r   r]   r#   r#   r$   
get_having  rp   zFilterableStatement.get_havingr`   c                 C  r\   )z]Returns the limit row count.

        Returns:
            int: The limit row count.
        )r   r]   r#   r#   r$   get_limit_row_count  rp   z'FilterableStatement.get_limit_row_countc                 C  r\   )zWReturns the limit offset.

        Returns:
            int: The limit offset.
        )r   r]   r#   r#   r$   get_limit_offset  rp   z$FilterableStatement.get_limit_offsetc                 C  r\   )zbReturns the where expression.

        Returns:
            object: The where expression.
        )r   r]   r#   r#   r$   get_where_expr  rp   z"FilterableStatement.get_where_exprc                 C  r\   )zlReturns the projection expression.

        Returns:
            object: The projection expression.
        )r   r]   r#   r#   r$   get_projection_expr     z'FilterableStatement.get_projection_exprc                 C  r\   )z`Returns the sort expression.

        Returns:
            object: The sort expression.
        )r   r]   r#   r#   r$   get_sort_expr  r   z!FilterableStatement.get_sort_expr8.0.12c                 C  
   |  |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   r#   r#   r$   where  s   
zFilterableStatement.wherec                 G  
   | 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   r#   r#   r$   sort  s   
zFilterableStatement.sort	row_countoffsetOptional[int]c                 C  sn   t |tr	|dk rtd| js!t| jdk| _t| jdk | _|| _d| _|r5| 	| t
jdtd | 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   r5   rW   rX   rZ   r   r   warningswarnDeprecationWarning)r"   r   r   r#   r#   r$   limit  s   
zFilterableStatement.limitc                 C  s$   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   r#   r#   r$   r   $  s   zFilterableStatement.offsetargsr   c                 G  sN   d| _ t|}|dkr| |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"   r   countr#   r#   r$   r   7  s   zFilterableStatement.bindc                 C  rs   rt   ru   r]   r#   r#   r$   rw   O  rx   zFilterableStatement.executeTNrP   r   rQ   r5   r   r   r   r   )r   r   r   r   )r   r3   r   r   )r   r3   r   r   )r   r3   r   r   )r   r3   r   r   )r   r3   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   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   __classcell__r#   r#   r   r$   r      s:    
$

















#
r   c                      sX   e Zd ZdZd fdd	Zedd
dZdddZdddZdddZ	dddZ
  ZS )SqlStatementzA statement for SQL execution.

    Args:
        connection (mysqlx.connection.Connection): Connection object.
        sql (string): The sql statement to be executed.
    
connectionr   sqlr3   r   r   c                   s8   t  jd dd || _|| _d | _g | _d| _d| _d S NFr   )r   r%   rU   _sqlr   r   r   r   )r"   r   r   r   r#   r$   r%   `  s   
zSqlStatement.__init__c                 C  r\   )zstring: The SQL text statement.)r   r]   r#   r#   r$   r   i  r^   zSqlStatement.sqlr   c                 C  r\   r   r   r]   r#   r#   r$   r   n  rp   zSqlStatement.get_binding_mapUnion[Tuple, List]c                 C  r\   r   r   r]   r#   r#   r$   r   v  rp   zSqlStatement.get_bindingsr   r   c                 G  sJ   t |dkr
tdd| _t| }t|ttfr|| _| S | 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   r0   r-   r.   r/   r   append)r"   r   bindingsr#   r#   r$   r   ~  s   	zSqlStatement.bindr   c                 C     | j | S )zaExecute the statement.

        Returns:
            mysqlx.SqlResult: SqlResult object.
        )rU   send_sqlr]   r#   r#   r$   rw        zSqlStatement.execute)r   r   r   r3   r   r   r   r3   r   )r   r   )r   r   r   r   )r   r   )r&   r'   r(   r)   r%   r~   r   r   r   r   rw   r   r#   r#   r   r$   r   X  s    	


r   c                      6   e Zd ZdZd fdd	ZdddZdddZ  ZS )WriteStatementz*Provide common write operation attributes.rP   r   rQ   r5   r   r   c                   s   t  || g | _d S r!   )r   r%   _valuesr[   r   r#   r$   r%     s   	zWriteStatement.__init__pList[Union[int, str, DbDoc, Dict[str, Any], List[Optional[Union[str, int, float, ExprParser, Dict[str, Any]]]]]]c                 C  r\   )z^Returns the list of values.

        Returns:
            `list`: The list of values.
        )r   r]   r#   r#   r$   
get_values  s   zWriteStatement.get_valuesr   c                 C  rs   rt   ru   r]   r#   r#   r$   rw     rx   zWriteStatement.executerz   )r   r   r}   )r&   r'   r(   r)   r%   r   rw   r   r#   r#   r   r$   r     s
    
r   c                      sL   e Zd ZdZd fddZdd	d
ZddddZdddZdddZ  Z	S )AddStatementzA statement for document addition on a collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
    
collectionr   r   r   c                   s   t  |d d| _g | _d S )NTF)r   r%   _upsertids)r"   r   r   r#   r$   r%     s   
zAddStatement.__init__r5   c                 C  r\   )zhReturns `True` if it's an upsert.

        Returns:
            bool: `True` if it's an upsert.
        r   r]   r#   r#   r$   	is_upsert  rp   zAddStatement.is_upsertTrc   c                 C  s
   || _ | 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   r#   r#   r$   upsert  s   zAddStatement.upsertr*   r   c                 G  s:   t | D ]}t|tr| j| q| jt| q| S )zAdds a list of documents into a collection.

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

        Returns:
            mysqlx.AddStatement: AddStatement object.
        )r0   r-   r   r   r   )r"   r*   valr#   r#   r$   add  s
   	
zAddStatement.addr   c                 C  s    t | jdkr
t S | j| S )[Execute the statement.

        Returns:
            mysqlx.Result: Result object.
        r   )r,   r   r   rU   send_insertr]   r#   r#   r$   rw     s   zAddStatement.execute)r   r   r   r   r|   ry   )rc   r5   r   r   )r*   r   r   r   r   r   )
r&   r'   r(   r)   r%   r   r   r   rw   r   r#   r#   r   r$   r     s    

r   c                   @  s&   e Zd ZdZddddZdddZdS )
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.
    Nupdate_typer`   sourcer3   rc   r   r   r   c              
   C  sh   |t dkr| || d S || _zt|d j| _W n ty. } zt| |d }~ww || _	d S )N*Mysqlx.Crud.UpdateOperation.UpdateType.SETF)
r   
_table_setr   r   document_fieldr2   r   r   r   rc   )r"   r   r   rc   r   r#   r#   r$   r%     s   
zUpdateSpec.__init__c                 C  s$   t d| _t|d | _|| _dS )zlTable set.

        Args:
            source (str): The source.
            value (str): The value.
        r   TN)r   r   r   parse_table_update_fieldr   rc   )r"   r   rc   r#   r#   r$   r    s   

zUpdateSpec._table_setr!   )r   r`   r   r3   rc   r   r   r   )r   r3   rc   r   r   r   )r&   r'   r(   r)   r%   r  r#   r#   r#   r$   r     s    r   c                      s   e Zd ZdZd' fdd	Zd(ddZd)ddZd*ddZedd*ddZ	d+ddZ
d,ddZd*ddZd-d"d#Zd.d%d&Z  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.
    r   r   r   r3   r   r   c                   s   t  j||d i | _d S N)rP   r   r   r%   _update_opsr"   r   r   r   r#   r$   r%   .     
zModifyStatement.__init__r   c                 G  r   )zSets the sorting criteria.

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

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        r   r   r#   r#   r$   r   2     
	zModifyStatement.sortr   c                 C  r\   ztReturns the list of update operations.

        Returns:
            `list`: The list of update operations.
        r  r]   r#   r#   r$   get_update_ops=  rp   zModifyStatement.get_update_opsdoc_pathrc   r   c                 C      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  rX   r"   r  rc   r#   r#   r$   setE     

zModifyStatement.setr   c                 C  r  )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_REPLACETr  r  r#   r#   r$   changeW  s   
zModifyStatement.change	doc_pathsc                 G  s,   t | D ]}ttd|| j|< q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)r0   r   r   r  rX   )r"   r  itemr#   r#   r$   unsetm  s   
zModifyStatement.unsetfieldc                 C  r  )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_INSERTTr  r"   r  rc   r#   r#   r$   array_insert  s   
zModifyStatement.array_insertc                 C  r  )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_APPENDTr  r  r#   r#   r$   array_append  s   
zModifyStatement.array_appenddoc#Union[Dict, DbDoc, ExprParser, str]c                 C  sX   |du rd}t |ttttfstdttddt |tr!| 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.
        Nr1   z>Invalid data for update operation on document collection tablez2Mysqlx.Crud.UpdateOperation.UpdateType.MERGE_PATCH$patchT)r-   r   r   r   r3   r   r   r   r   r  rX   )r"   r  r#   r#   r$   r    s   
zModifyStatement.patchr   c                 C     | j std| 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   rU   send_updater]   r#   r#   r$   rw        	zModifyStatement.executer   r   r   r3   r   r   )r   r3   r   r  r   )r  r3   rc   r   r   r  )r  r3   r   r  )r  r3   rc   r   r   r  )r  r  r   r  r   )r&   r'   r(   r)   r%   r   r  r  r   r  r  r  r  r  rw   r   r#   r#   r   r$   r  "  s    






r  c                      s   e Zd ZdZ		d%d& fddZed'ddZd(ddZd)ddZd)ddZ	e
jfd*ddZe
jfd*ddZd+ddZd,d d!Zd-d#d$Z  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.
    TNrP   r   rQ   r5   r   r   r   r   c                   s(   t  ||| d| _d| _tj| _d S NF)r   r%   _lock_exclusive_lock_sharedr   DEFAULT_lock_contentionr   r   r#   r$   r%     s   zReadStatement.__init__r   c                 C  r\   )z::class:`mysqlx.LockContention`: The lock contention value.)r+  r]   r#   r#   r$   lock_contention  r^   zReadStatement.lock_contentionr,  c              
   C  s<   zt |j}W n ty } ztd|d}~ww || _dS )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   rc   r   r   r+  )r"   r,  _r   r#   r#   r$   _set_lock_contention  s   	
z"ReadStatement._set_lock_contentionc                 C  r\   )zrReturns `True` if is `EXCLUSIVE LOCK`.

        Returns:
            bool: `True` if is `EXCLUSIVE LOCK`.
        )r(  r]   r#   r#   r$   is_lock_exclusive  rp   zReadStatement.is_lock_exclusivec                 C  r\   )zlReturns `True` if is `SHARED LOCK`.

        Returns:
            bool: `True` if is `SHARED LOCK`.
        )r)  r]   r#   r#   r$   is_lock_shared  rp   zReadStatement.is_lock_sharedc                 C     d| _ d| _| | | 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r(  r)  r.  r"   r,  r#   r#   r$   lock_shared     	
zReadStatement.lock_sharedc                 C  r1  )zExecute a read operation with `EXCLUSIVE LOCK`. Only one lock can be
           active at a time.

        Args:
            lock_contention (:class:`mysqlx.LockContention`): Lock contention.
        TFr2  r3  r#   r#   r$   lock_exclusive  r5  zReadStatement.lock_exclusiver   r3   c                 G  s   | 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   r#   r#   r$   group_by*  s   
	zReadStatement.group_byc                 C  s   |  | | 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   r#   r#   r$   having6  s   
zReadStatement.havingUnion[DocResult, RowResult]c                 C  r   r   )rU   	send_findr]   r#   r#   r$   rw   D  r   zReadStatement.executer   r   )r   r   )r,  r   r   r   r|   )r,  r   r   r&  )r   r3   r   r&  )r   r3   r   r&  )r   r9  )r&   r'   r(   r)   r%   r~   r,  r.  r/  r0  r   r*  r4  r6  r7  r8  rw   r   r#   r#   r   r$   r&    s"    


	

r&  c                      s:   e Zd ZdZ	dd fd	d
ZdddZdddZ  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.
    Nr   r   r   r   r   r   c                   s   t  |d| d S )NTr   r%   r  r   r#   r$   r%   X  s   zFindStatement.__init__r   r3   c                 G  r   )zSets a document field filter.

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

        Returns:
            mysqlx.FindStatement: FindStatement object.
        )r   r   r#   r#   r$   r   ]  s   

zFindStatement.fieldsr   c                 G  r   zSets the sorting criteria.

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

        Returns:
            mysqlx.FindStatement: FindStatement object.
        r   r   r#   r#   r$   r   i  r
  zFindStatement.sortr!   )r   r   r   r   r   r   )r   r3   r   r<  )r   r3   r   r<  )r&   r'   r(   r)   r%   r   r   r   r#   r#   r   r$   r<  M  s    
r<  c                      s@   e Zd ZdZd fdd	ZdddZdddZdddZ  ZS )SelectStatementzA statement for record retrieval operations on a Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be retrieved.
    tabler   r   r3   r   r   c                   s   t  |d | j|  d S r'  )r   r%   r   r"   r@  r   r   r#   r$   r%   }     zSelectStatement.__init__r   c                 C  r   )zSets the search condition to filter.

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

        Returns:
            mysqlx.SelectStatement: SelectStatement object.
        r   r   r#   r#   r$   r     r
  zSelectStatement.wherer   c                 G  r   )zSets the order by criteria.

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

        Returns:
            mysqlx.SelectStatement: SelectStatement object.
        r   r   r#   r#   r$   order_by  r
  zSelectStatement.order_byc                 C  s   | 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r9d| j	 d| j
 nd}d| jp@d	 d
| jj d| jj | | | | | }|S )zYReturns the generated SQL.

        Returns:
            str: The generated SQL.
        z WHERE r1   z
 GROUP BY z HAVING z
 ORDER BY z LIMIT z OFFSET zSELECT *z FROM r@   )r   r   r   r   r   r   r   r   r   r   r   r   r_   namerP   )r"   r   r7  r8  rC  r   stmtr#   r#   r$   get_sql  s2   zSelectStatement.get_sql)r@  r   r   r3   r   r   )r   r3   r   r?  )r   r3   r   r?  r   )	r&   r'   r(   r)   r%   r   rC  rG  r   r#   r#   r   r$   r?  u  s    

r?  c                      r   )InsertStatementzA statement for insert operations on Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be inserted.
    r@  r   r   r   r   r   c                   s   t  |d t| | _d S r'  )r   r%   r0   _fieldsrA  r   r#   r$   r%     rB  zInsertStatement.__init__r*   c                 G  s   | 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   r.   r0   )r"   r*   r#   r#   r$   r*     s   	zInsertStatement.valuesr   c                 C  r   r:  )rU   r   r]   r#   r#   r$   rw     r   zInsertStatement.execute)r@  r   r   r   r   r   )r*   r   r   rH  r   )r&   r'   r(   r)   r%   r*   rw   r   r#   r#   r   r$   rH    s
    
rH  c                      sT   e Zd ZdZd fddZdd
dZdddZdddZdddZdddZ	  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.
    r@  r   r   r   c                   s   t  j|dd i | _d S r   r  r"   r@  r   r#   r$   r%     r	  zUpdateStatement.__init__r   r3   c                 C  r   )zSets the search condition to filter.

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

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r   r   r#   r#   r$   r     r
  zUpdateStatement.wherer   c                 G  r   )zSets the order by criteria.

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

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r   r   r#   r#   r$   rC    r
  zUpdateStatement.order_byr   c                 C  r\   r  r  r]   r#   r#   r$   r    rp   zUpdateStatement.get_update_opsr  rc   r   c                 C  r  )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   Tr  r  r#   r#   r$   r    r  zUpdateStatement.setr   c                 C  r   )zExecute the statement.

        Returns:
            mysqlx.Result: Result object

        Raises:
            ProgrammingError: If condition was not set.
        z!No condition was found for updater"  r]   r#   r#   r$   rw     r$  zUpdateStatement.executer@  r   r   r   )r   r3   r   rJ  )r   r3   r   rJ  r   )r  r3   rc   r   r   rJ  r   )r&   r'   r(   r)   r%   r   rC  r  r  rw   r   r#   r#   r   r$   rJ    s    	



rJ  c                      r   )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.
    r   r   r   r3   r   r   c                   s   t  j||d d S r  r=  r  r   r#   r$   r%   '     zRemoveStatement.__init__r   c                 G  r   r>  r   r   r#   r#   r$   r   *  r
  zRemoveStatement.sortr   c                 C  r   )r!  z!No condition was found for remover   r   rU   send_deleter]   r#   r#   r$   rw   5  r$  zRemoveStatement.executer%  )r   r3   r   rM  r   )r&   r'   r(   r)   r%   r   rw   r   r#   r#   r   r$   rM    s
    
rM  c                      s@   e Zd ZdZd fddZdd
dZdddZdddZ  ZS )DeleteStatementzA statement that drops a table.

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

    .. versionchanged:: 8.0.12
       The ``condition`` parameter was removed.
    r@  r   r   r   c                   s   t  j|dd d S r   r=  rK  r   r#   r$   r%   M  rN  zDeleteStatement.__init__r   r3   c                 C  r   )zSets the search condition to filter.

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

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object.
        r   r   r#   r#   r$   r   P  r
  zDeleteStatement.wherer   c                 G  r   )zSets the order by criteria.

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

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object.
        r   r   r#   r#   r$   rC  [  r
  zDeleteStatement.order_byr   c                 C  r   )r!  z!No condition was found for deleterO  r]   r#   r#   r$   rw   f  r$  zDeleteStatement.executerL  )r   r3   r   rQ  )r   r3   r   rQ  r   )	r&   r'   r(   r)   r%   r   rC  rw   r   r#   r#   r   r$   rQ  C  s    	

rQ  c                      s,   e Zd ZdZd fd
dZdddZ  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}
    r   r   
index_namer3   
index_descr   r   r   c                   s4   t  j|d t|| _|| _| jdg | _d S )N)rP   r   )r   r%   copydeepcopy_index_desc_index_namepop_fields_desc)r"   r   rS  rT  r   r#   r$   r%     s   z'CreateCollectionIndexStatement.__init__r   c              
   C  s@  | j du rtt| j z0t| j   }t|tr-|d t	dkr,tt| j n|j
t	dkr<tt| j W n ttfyT } z	tt| j |d}~ww | js`td| j t| jtsjtdi }| j |d< | jj|d< | jjj|d< d| jv r| jd|d< nd	|d< | jd
d|d
< |d
 rtdg |d< | jrtd| j z| jD ]}i }|d|d< |d|d< |dd|d< |dd|d< t|d tstdt|d tstd|d  dkr|d std|d  d	kr|d dkrtdd|v r2|d  ds+td|d   d|d|d< d|v rK|d  dkrDtd|d|d< d|v rd|d  dkr]td |d|d< |d | qW n ty } ztd!| d"| |d}~ww | jD ]}|rtd#| q| jd$d%d&|S )'r   NtypezMysqlx.Expr.Expr.Type.IDENTzCRequired member 'fields' not found in the given index description: z,Required member 'fields' must contain a listrE  r   r_   INDEXuniqueFz!Unique indexes are not supported.
constraintzUnidentified fields: r  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)rX  r   ERR_INVALID_INDEX_NAMEformatr   r   get_messager-   r   r   r[  r   AttributeErrorrZ  rW  r.   rR   rE  r_   rY  r   r5   	TypeErrorupper
startswithr   KeyErrorrU   execute_nonquery)r"   parsed_identr   r   
field_descr^  r#   r#   r$   rw     s   







 



-
z&CreateCollectionIndexStatement.execute)r   r   rS  r3   rT  r   r   r   r   )r&   r'   r(   r)   r%   rw   r   r#   r#   r   r$   rR  t  s    rR  )r*   r   r   r+   )r1   )r2   r3   r4   r3   r   r5   )r2   r3   r4   r3   r   r3   )r>   r?   r4   r3   r   r3   )rF   r3   rG   r3   r4   r3   r   rH   )=r)   
__future__r   rU  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   rk  r   r0   r:   r=   rE   rN   rO   r   r   r   r   r   r  r&  r<  r?  rH  rJ  rM  rQ  rR  r#   r#   r#   r$   <module>   sP   $ 	
j  \B*;# /}(9!L(1