o
    –¨ÊhK¨  ã                   @   sÀ  d Z ddlZddlZddlZddlmZ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 ddlmZ dZG dd„ deƒZdd„ Zd8dd„Zd8dd„Zd8dd„Zd8dd„ZG dd„ deƒZG dd„ deƒZ G dd„ deƒZ!G d d!„ d!eƒZ"G d"d#„ d#e"ƒZ#G d$d%„ d%eƒZ$G d&d'„ d'e ƒZ%G d(d)„ d)e ƒZ&G d*d+„ d+e&ƒZ'G d,d-„ d-e&ƒZ(G d.d/„ d/e"ƒZ)G d0d1„ d1e ƒZ*G d2d3„ d3e ƒZ+G d4d5„ d5e ƒZ,G d6d7„ d7eƒZ-dS )9zImplementation of Statements.é    Né   )ÚProgrammingErrorÚNotSupportedError)Ú
ExprParser)Ú	INT_TYPESÚSTRING_TYPES)ÚLockContention)ÚDbDoc)Ú
deprecated)Ú	SqlResultÚResult)Úmysqlxpb_enumz&The given index name "{}" is not validc                   @   s   e Zd ZdZdd„ ZdS )ÚExprzExpression wrapper.c                 C   s
   || _ d S ©N)Úexpr)Úselfr   © r   úB/var/www/html/env/lib/python3.10/site-packages/mysqlx/statement.pyÚ__init__1   s   
zExpr.__init__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   /   s    r   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)Úvaluesr   r   r   Úflexible_params5   s   r   Ú c                 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 )zòCheck 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_moder   r   r   Úis_quoted_identifier<   s
   
ÿr'   c                 C   s<   t | ƒdkrdS d|v rd |  dd¡¡S 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``r    z"{0}"r#   z""z`{0}`r!   )r   ÚformatÚreplacer$   r   r   r   Úquote_identifierL   s
   r*   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*   )Ú.0r%   ©r&   r   r   Ú
<listcomp>h   s    ÿz.quote_multipart_identifier.<locals>.<listcomp>)Újoin)Úidentifiersr&   r   r-   r   Úquote_multipart_identifier^   s   
ÿr1   c                 C   s^   d|v rdnd}||v rd  |¡nd}| |d¡}t|ƒdu r!| n|d  |¡|d  |¡fS )	zÞParse 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.
    r    r#   r!   z.{0}r+   r   r   r"   )r(   Úsplitr   Ústrip)Údefault_schemaÚ
table_namer&   ÚquoteÚ	delimiterÚtempr   r   r   Úparse_table_namel   s   ÿr9   c                   @   sB   e Zd ZdZddd„Zedd„ ƒZedd„ ƒZd	d
„ Zdd„ Z	dS )Ú	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.
    Tc                 C   s(   || _ || _|r| ¡ | _d S d | _d S r   )Ú_targetÚ
_doc_basedÚget_connectionÚ_connection©r   ÚtargetÚ	doc_basedr   r   r   r   †   s   zStatement.__init__c                 C   ó   | j S )z#object: The database object target.)r;   ©r   r   r   r   r@   ‹   ó   zStatement.targetc                 C   s   | j jS )z*:class:`mysqlx.Schema`: The Schema object.)r;   ÚschemarC   r   r   r   rE   �   s   zStatement.schemac                 C   rB   )zkCheck if it is document based.

        Returns:
            bool: `True` if it is document based.
        )r<   rC   r   r   r   Úis_doc_based•   ó   zStatement.is_doc_basedc                 C   ó   t ‚©zqExecute the statement.

        Raises:
           NotImplementedError: This method must be implemented.
        ©ÚNotImplementedErrorrC   r   r   r   Úexecute�   ó   zStatement.executeN©T)
r   r   r   r   r   Úpropertyr@   rE   rF   rL   r   r   r   r   r:   ~   s    


r:   c                       sÜ   e Zd ZdZd1‡ f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d"d#„ Zed$ƒd%d&„ ƒZed$ƒd'd(„ ƒZd2d)d*„Zd+d,„ Zd-d.„ Zd/d0„ Z‡  ZS )3Ú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.
    TNc                    s¢   t t| ƒj||d� i | _g | _d | _d| _d | _d| _d| _	d| _
d | _d| _d | _d| _d | _d| _d| _d| _d| _d| _d| _d| _|rO|  |¡ d S d S )N©r@   rA   r   r   F)ÚsuperrP   r   Ú_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   r@   rA   Ú	condition©Ú	__class__r   r   r   ±   s4   ÿÿzFilterableStatement.__init__c                 C   s„   t |tƒr|  t|ƒ¡ dS t |tƒr>zt |¡}t |tƒs t‚W n ty,   t	dƒ‚w | 
¡ D ]
}|  ||| ¡ q1d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 bindz%Invalid JSON string or object to bindN)r   r	   ÚbindÚstrr   ÚjsonÚloadsÚdictÚ
ValueErrorr   Úkeys)r   ÚobjÚresÚkeyr   r   r   Ú_bind_singleË   s   




ÿÿÿz FilterableStatement._bind_singlec                 G   s0   d| _ d t|Ž ¡| _t| j| j ƒ ¡ | _| S )zÑSets the sorting criteria.

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

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.
        Tú,)re   r/   r   r\   r   r<   Úparse_order_specr]   ©r   Úclausesr   r   r   Ú_sortã   s   	ÿÿzFilterableStatement._sortc                 C   sL   d| _ || _zt|| j ƒ}| ¡ | _W n ty   tdƒ‚w |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.
        TzInvalid condition)
rf   r^   r   r<   r   r_   rq   r   Úplaceholder_name_to_positionrS   )r   ri   r   r   r   r   rg   ò   s   
ÿzFilterableStatement._set_wherec                 G   s4   t |Ž }d| _d |¡| _t| j| j ƒ ¡ | _dS )zJSet group by.

        Args:
            *fields: List of fields.
        Trw   N)r   rb   r/   rV   r   r<   Úparse_expr_listrW   ©r   Úfieldsr   r   r   Ú_set_group_by  s   ÿÿz!FilterableStatement._set_group_byc                 C   s   d| _ t|| j ƒ ¡ | _dS )zOSet having.

        Args:
            condition (str): The condition.
        TN)rc   r   r<   r   rU   ©r   ri   r   r   r   Ú_set_having  s   zFilterableStatement._set_havingc                 G   s4   t |Ž }d| _d |¡| _t| j| j ƒ ¡ | _| S )z¡Set the projection.

        Args:
            *fields: List of fields.

        Returns:
            :class:`mysqlx.FilterableStatement`: Returns self.
        Trw   )r   rd   r/   rZ   r   r<   Úparse_table_select_projectionr[   r~   r   r   r   Ú_set_projection  s   	þþz#FilterableStatement._set_projectionc                 C   rB   )zlReturns the binding map dictionary.

        Returns:
            dict: The binding map dictionary.
        )rS   rC   r   r   r   Úget_binding_map,  rG   z#FilterableStatement.get_binding_mapc                 C   rB   )z\Returns the bindings list.

        Returns:
            `list`: The bindings list.
        )rT   rC   r   r   r   Úget_bindings4  rG   z FilterableStatement.get_bindingsc                 C   rB   )zrReturns the grouping expression list.

        Returns:
            `list`: The grouping expression list.
        )rW   rC   r   r   r   Úget_grouping<  rG   z FilterableStatement.get_groupingc                 C   rB   )zdReturns the having expression.

        Returns:
            object: The having expression.
        )rU   rC   r   r   r   Ú
get_havingD  rG   zFilterableStatement.get_havingc                 C   rB   )z]Returns the limit row count.

        Returns:
            int: The limit row count.
        )rY   rC   r   r   r   Úget_limit_row_countL  rG   z'FilterableStatement.get_limit_row_countc                 C   rB   )zWReturns the limit offset.

        Returns:
            int: The limit offset.
        )rX   rC   r   r   r   Úget_limit_offsetT  rG   z$FilterableStatement.get_limit_offsetc                 C   rB   )zbReturns the where expression.

        Returns:
            object: The where expression.
        )r_   rC   r   r   r   Úget_where_expr\  rG   z"FilterableStatement.get_where_exprc                 C   rB   )zlReturns the projection expression.

        Returns:
            object: The projection expression.
        )r[   rC   r   r   r   Úget_projection_exprd  rG   z'FilterableStatement.get_projection_exprc                 C   rB   )z`Returns the sort expression.

        Returns:
            object: The sort expression.
        )r]   rC   r   r   r   Úget_sort_exprl  rG   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
        ©rg   r�   r   r   r   Úwheret  s   
zFilterableStatement.wherec                 G   ó
   | j |Ž S )zñSets the sorting criteria.

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

        Returns:
            mysqlx.FilterableStatement: FilterableStatement object.

        .. deprecated:: 8.0.12
        ©r{   ry   r   r   r   Úsortƒ  s   
zFilterableStatement.sortc                 C   sF   t |tƒr	|dk rtdƒ‚d| _|| _|r!|  |¡ 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   rq   ra   rY   ÚoffsetÚwarningsÚwarnÚDeprecationWarning)r   Ú	row_countr–   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   rq   rX   )r   r–   r   r   r   r–   «  s   zFilterableStatement.offsetc                 G   sV   d| _ t|ƒ}|dkr|  |d ¡ | S |dkrtdƒ‚| j |d |d dœ¡ | S )a¤  Binds a value to a specific placeholder.

        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   é   z#Invalid number of arguments to bind)ÚnameÚvalue)r`   r   rv   r   rT   Úappend)r   ÚargsÚcountr   r   r   rl   ¾  s   üzFilterableStatement.bindc                 C   rH   rI   rJ   rC   r   r   r   rL   Ö  rM   zFilterableStatement.execute©TNr   )r   r   r   r   r   rv   r{   rg   r€   r‚   r„   r…   r†   r‡   rˆ   r‰   rŠ   r‹   rŒ   r�   r
   r‘   r”   r›   r–   rl   rL   Ú__classcell__r   r   rj   r   rP   ¦   s4    
	


rP   c                       ó(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚSqlStatementz¬A statement for SQL execution.

    Args:
        connection (mysqlx.connection.Connection): Connection object.
        sql (string): The sql statement to be executed.
    c                    s$   t t| ƒjd dd� || _|| _d S ©NFrQ   )rR   r¥   r   r>   Ú_sql)r   Ú
connectionÚsqlrj   r   r   r   æ  s   
zSqlStatement.__init__c                 C   s   | j  | j¡ t| j ƒS )zaExecute the statement.

        Returns:
            mysqlx.SqlResult: SqlResult object.
        )r>   Úsend_sqlr§   r   rC   r   r   r   rL   ë  s   
zSqlStatement.execute©r   r   r   r   r   rL   r£   r   r   rj   r   r¥   ß  s    r¥   c                       ó0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚWriteStatementz/Provide common write operation attributes.
    c                    s   t t| ƒ ||¡ g | _d S r   )rR   r­   r   Ú_valuesr?   rj   r   r   r   ø  s   
zWriteStatement.__init__c                 C   rB   )z^Returns the list of values.

        Returns:
            `list`: The list of values.
        )r®   rC   r   r   r   Ú
get_valuesü  rG   zWriteStatement.get_valuesc                 C   rH   rI   rJ   rC   r   r   r   rL     rM   zWriteStatement.execute)r   r   r   r   r   r¯   rL   r£   r   r   rj   r   r­   õ  s
    r­   c                       sB   e Zd ZdZ‡ fdd„Zdd„ Zddd„Zd	d
„ Zdd„ Z‡  Z	S )ÚAddStatementz�A statement for document addition on a collection.

    Args:
        collection (mysqlx.Collection): The Collection object.
    c                    s"   t t| ƒ |d¡ d| _g | _d S )NTF)rR   r°   r   Ú_upsertÚids)r   Ú
collectionrj   r   r   r     s   
zAddStatement.__init__c                 C   rB   )zhReturns `True` if it's an upsert.

        Returns:
            bool: `True` if it's an upsert.
        ©r±   rC   r   r   r   Ú	is_upsert  rG   zAddStatement.is_upsertTc                 C   s
   || _ | S )zÿSets 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´   )r   rž   r   r   r   Úupsert   s   zAddStatement.upsertc                 G   s:   t |Ž D ]}t|tƒr| j |¡ q| j t|ƒ¡ q| S )zÏAdds a list of documents into a collection.

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

        Returns:
            mysqlx.AddStatement: AddStatement object.
        )r   r   r	   r®   rŸ   )r   r   Úvalr   r   r   Úadd+  s
   	
zAddStatement.addc                 C   s    t | jƒdkr
tƒ S | j | ¡S )ú[Execute the statement.

        Returns:
            mysqlx.Result: Result object.
        r   )r   r®   r   r>   Úsend_insertrC   r   r   r   rL   ;  s   zAddStatement.executerN   )
r   r   r   r   r   rµ   r¶   r¸   rL   r£   r   r   rj   r   r°     s    
r°   c                   @   s"   e Zd ZdZddd„Zdd„ ZdS )Ú
UpdateSpecz²Update specification class implementation.

    Args:
        update_type (int): The update type.
        source (str): The source.
        value (Optional[str]): The value.
    Nc                 C   sl   |t dƒkr|  ||¡ d S || _|| _t|ƒdkr'|d dkr'|dd … | _t| jdƒ ¡ j| _|| _d S )Nú*Mysqlx.Crud.UpdateOperation.UpdateType.SETr   ú$r   F)	r   Ú
_table_setÚupdate_typeÚsourcer   r   Údocument_fieldr%   rž   )r   r¿   rÀ   rž   r   r   r   r   O  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À   rž   )r   rÀ   rž   r   r   r   r¾   \  s
   ÿ
zUpdateSpec._table_setr   )r   r   r   r   r   r¾   r   r   r   r   r»   G  s    
r»   c                       sp   e Zd ZdZ‡ fd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‡  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                    s   t t| ƒj||d� g | _d S ©N)r@   ri   )rR   rÃ   r   Ú_update_ops©r   r³   ri   rj   r   r   r   t  s   ÿ
zModifyStatement.__init__c                 G   r’   )zÉSets the sorting criteria.

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

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        r“   ry   r   r   r   r”   y  ó   
	zModifyStatement.sortc                 C   rB   ©ztReturns the list of update operations.

        Returns:
            `list`: The list of update operations.
        ©rÅ   rC   r   r   r   Úget_update_ops„  rG   zModifyStatement.get_update_opsc                 C   ó   | j  tt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_SET©rÅ   rŸ   r»   r   ©r   Údoc_pathrž   r   r   r   ÚsetŒ  s   

ÿþ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_REPLACErÌ   rÍ   r   r   r   Úchange›  s   
ÿþzModifyStatement.changec                 G   s   | j  dd„ t|Ž D ƒ¡ | S )a  Removes attributes from documents in a collection.

        Args:
            doc_path (string): The document path of the attribute to be
                               removed.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        c                 S   s   g | ]	}t td ƒ|ƒ‘qS )z2Mysqlx.Crud.UpdateOperation.UpdateType.ITEM_REMOVE)r»   r   )r,   Úitemr   r   r   r.   ¸  s    þÿÿÿz)ModifyStatement.unset.<locals>.<listcomp>)rÅ   Úextendr   )r   Ú	doc_pathsr   r   r   Úunset®  s   
ýzModifyStatement.unsetc                 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_INSERTrÌ   ©r   Úfieldrž   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_APPENDrÌ   rÍ   r   r   r   Úarray_appendÐ  s   ÿþÿzModifyStatement.array_appendc                 C   sT   |du rd}t |ttttfƒstdƒ‚| j tt	dƒdt |tƒr$| 
¡ n|ƒ¡ | 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.
        Nr   z>Invalid data for update operation on document collection tablez2Mysqlx.Crud.UpdateOperation.UpdateType.MERGE_PATCH)r   r   rp   r	   rm   r   rÅ   rŸ   r»   r   r   )r   Údocr   r   r   Úpatchã  s   ÿÿþÿzModifyStatement.patchc                 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©rf   r   r>   ÚupdaterC   r   r   r   rL   û  ó   	zModifyStatement.execute)r   r   r   r   r   r”   rÊ   rÏ   r
   rÐ   rÔ   r×   rØ   rÚ   rL   r£   r   r   rj   r   rÃ   i  s    

rÃ   c                       sz   e Zd ZdZd‡ fd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‡  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.
    TNc                    s,   t t| ƒ |||¡ d| _d| _tj| _d S ©NF)rR   rà   r   Ú_lock_exclusiveÚ_lock_sharedr   ÚDEFAULTÚ_lock_contentionrh   rj   r   r   r     s   zReadStatement.__init__c                 C   rB   )z::class:`mysqlx.LockContention`: The lock contention value.)rå   rC   r   r   r   Úlock_contention  rD   zReadStatement.lock_contentionc                 C   s0   zt  |¡}W n ty   tdƒ‚w || _dS )zÖSet 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   Úindexrq   r   rå   )r   ræ   Ú_r   r   r   Ú_set_lock_contention  s   	ÿ
z"ReadStatement._set_lock_contentionc                 C   rB   )zrReturns `True` if is `EXCLUSIVE LOCK`.

        Returns:
            bool: `True` if is `EXCLUSIVE LOCK`.
        )râ   rC   r   r   r   Úis_lock_exclusive0  rG   zReadStatement.is_lock_exclusivec                 C   rB   )zlReturns `True` if is `SHARED LOCK`.

        Returns:
            bool: `True` if is `SHARED LOCK`.
        )rã   rC   r   r   r   Úis_lock_shared8  rG   zReadStatement.is_lock_sharedc                 C   ó   d| _ d| _|  |¡ | S )zÅExecute 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   rì   )zÈExecute a read operation with `EXCLUSIVE LOCK`. Only one lock can be
           active at a time.

        Args:
            lock_contention (:class:`mysqlx.LockContention`): Lock contention.
        TFrí   rî   r   r   r   Úlock_exclusiveL  rð   zReadStatement.lock_exclusivec                 G   s   | j |Ž  | S )zÜSets 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_byX  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   Úhavingd  s   
zReadStatement.havingc                 C   ó   | j  | ¡S ©r¹   )r>   ÚfindrC   r   r   r   rL   r  ó   zReadStatement.executer¢   )r   r   r   r   r   rO   ræ   ré   rê   rë   r   rä   rï   rñ   rò   ró   rL   r£   r   r   rj   r   rà   	  s    

rà   c                       s2   e Zd ZdZd	‡ fdd„	Zdd„ Z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.
    Nc                    s   t t| ƒ |d|¡ d S )NT)rR   rø   r   rÆ   rj   r   r   r   …  ó   zFindStatement.__init__c                 G   r’   )zèSets 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.fieldsc                 G   r’   ©zÅSets the sorting criteria.

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

        Returns:
            mysqlx.FindStatement: FindStatement object.
        r“   ry   r   r   r   r”   ”  rÇ   zFindStatement.sortr   )r   r   r   r   r   r   r”   r£   r   r   rj   r   rø   {  s
    	rø   c                       ó8   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Z‡  ZS )
ÚSelectStatementz¤A statement for record retrieval operations on a Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be retrieved.
    c                    s    t t| ƒ |d¡ | j|Ž  d S rá   )rR   rü   r   r„   ©r   Útabler   rj   r   r   r   §  ó   zSelectStatement.__init__c                 C   r�   )zÔSets 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.wherec                 G   r’   )zÎSets the order by criteria.

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

        Returns:
            mysqlx.SelectStatement: SelectStatement object.
        r“   ry   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	r7d | j
| j¡nd}dj| jp?d| jj| jj|||||d	�}|S )
zYReturns the generated SQL.

        Returns:
            str: The generated SQL.
        z
 WHERE {0}r   z GROUP BY {0}z HAVING {0}z ORDER BY {0}z LIMIT {0} OFFSET {1}zISELECT {select} FROM {schema}.{table}{where}{group}{having}{order}{limit}Ú*)ÚselectrE   rþ   r›   r‘   Úgroupró   Úorder)rf   r(   r^   rb   rV   rc   rU   re   r\   ra   rY   rX   rZ   rE   r�   r@   )r   r‘   rò   ró   r   r›   Ústmtr   r   r   Úget_sqlÂ  s.   ÿÿÿ
þÿþ
ûzSelectStatement.get_sql)	r   r   r   r   r   r‘   r   r  r£   r   r   rj   r   rü      s    rü   c                       r¬   )ÚInsertStatementz—A statement for insert operations on Table.

    Args:
        table (mysqlx.Table): The Table object.
        *fields: The fields to be inserted.
    c                    s    t t| ƒ |d¡ t|Ž | _d S rá   )rR   r  r   r   Ú_fieldsrý   rj   r   r   r   á  rÿ   zInsertStatement.__init__c                 G   s   | j  tt|Ž ƒ¡ | S )zÃSet the values to be inserted.

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

        Returns:
            mysqlx.InsertStatement: InsertStatement object.
        )r®   rŸ   r   r   )r   r   r   r   r   r   å  s   	zInsertStatement.valuesc                 C   rô   rõ   )r>   rº   rC   r   r   r   rL   ñ  r÷   zInsertStatement.execute)r   r   r   r   r   r   rL   r£   r   r   rj   r   r  Ú  s
    r  c                       sH   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	‡  Z
S )ÚUpdateStatementzÃA 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                    s   t t| ƒj|dd� g | _d S r¦   )rR   r	  r   rÅ   ©r   rþ   rj   r   r   r     s   
zUpdateStatement.__init__c                 C   r�   )zÔSets 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.wherec                 G   r’   )zÎSets the order by criteria.

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

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object.
        r“   ry   r   r   r   r     rÇ   zUpdateStatement.order_byc                 C   rB   rÈ   rÉ   rC   r   r   r   rÊ     rG   zUpdateStatement.get_update_opsc                 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¼   rÌ   rÕ   r   r   r   rÏ   %  s   
ÿÿÿzUpdateStatement.setc                 C   rÛ   )z£Execute the statement.

        Returns:
            mysqlx.Result: Result object

        Raises:
            ProgrammingError: If condition was not set.
        z!No condition was found for updaterÝ   rC   r   r   r   rL   4  rß   zUpdateStatement.execute)r   r   r   r   r   r‘   r   rÊ   rÏ   rL   r£   r   r   rj   r   r	  ú  s    r	  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.
    c                    s   t t| ƒj||d� d S rÄ   )rR   r  r   rÆ   rj   r   r   r   M  s   
ÿzRemoveStatement.__init__c                 G   r’   rú   r“   ry   r   r   r   r”   Q  rÇ   zRemoveStatement.sortc                 C   rÛ   )rÜ   z!No condition was found for remove©rf   r   r>   ÚdeleterC   r   r   r   rL   \  rß   zRemoveStatement.execute)r   r   r   r   r   r”   rL   r£   r   r   rj   r   r  B  s
    
r  c                       rû   )
ÚDeleteStatementz¯A statement that drops a table.

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

    .. versionchanged:: 8.0.12
       The ``condition`` parameter was removed.
    c                    s   t t| ƒj|dd� d S r¦   )rR   r  r   r
  rj   r   r   r   s  rù   zDeleteStatement.__init__c                 C   r�   )zÔSets 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‘   v  rÇ   zDeleteStatement.wherec                 G   r’   )zÎSets the order by criteria.

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

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object.
        r“   ry   r   r   r   r   �  rÇ   zDeleteStatement.order_byc                 C   rÛ   )rÜ   z!No condition was found for deleter  rC   r   r   r   rL   Œ  rß   zDeleteStatement.execute)	r   r   r   r   r   r‘   r   rL   r£   r   r   rj   r   r  j  s    r  c                       r¤   )Ú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                    s8   t t| ƒj|d� t |¡| _|| _| j dg ¡| _d S )N)r@   r   )	rR   r  r   ÚcopyÚdeepcopyÚ_index_descÚ_index_nameÚpopÚ_fields_desc)r   r³   Ú
index_nameÚ
index_descrj   r   r   r   °  s   z'CreateCollectionIndexStatement.__init__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yN   tt | j ¡ƒ‚w | jsZtd | j¡ƒ‚t| jtƒsdt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
 r›tdƒ‚g |d< | jrªtd | j¡ƒ‚z”| jD ]Ž}i }| d¡|d< | d¡|d< | dd¡|d< |d  ¡ dkrØ|d sØtdƒ‚|d  ¡ d	krê|d dkrêtdƒ‚d|v �r|d  ¡  d¡sütdƒ‚| d¡|d< d|v �r|d  ¡ dk�rtdƒ‚| d¡|d< d|v �r5|d  ¡ dk�r.tdƒ‚| d¡|d< |d  |¡ q®W n t�yS } ztd ||¡ƒ‚d}~ww | jD ]}|�rctd |¡ƒ‚�qW| j dd d!|¡S )"r¹   NÚtypezMysqlx.Expr.Expr.Type.IDENTzERequired member "fields" not found in the given index description: {}z-Required member "fields" must contain a list.r�   r³   rE   ÚINDEXÚuniqueFz!Unique indexes are not supported.Ú
constraintzUnidentified fields: {}rÖ   ÚmemberÚrequiredÚ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ÚTEXTzLThe "collation" member can only be used when field  type is set to "GEOJSON"Ú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"z4Required inner member {} not found in constraint: {}zUnidentified inner fields:{}ÚmysqlxÚcreate_collection_indexT)r  r   ÚERR_INVALID_INDEX_NAMEr(   r   r   Úget_messager   rp   r   r  rq   ÚAttributeErrorr  r  r   r;   r�   rE   r  r   ÚupperÚ
startswithrŸ   ÚKeyErrorr>   Úexecute_nonquery)r   Úparsed_identr    Ú
field_descr  Úerrr   r   r   rL   ¶  s¾   

ÿ
ÿ
ÿþÿ
ÿ€
ÿÿþ

ÿ
ÿ
ÿ
ÿ
ÿÚ'ÿ€ÿ
ÿÿÿz&CreateCollectionIndexStatement.executer«   r   r   rj   r   r  š  s    r  )r   ).r   r  rn   r—   Úerrorsr   r   r   r   Úcompatr   r   Ú	constantsr   Údbdocr	   Úhelpersr
   Úresultr   r   Úprotobufr   r&  Úobjectr   r   r'   r*   r1   r9   r:   rP   r¥   r­   r°   r»   rÃ   rà   rø   rü   r  r	  r  r  r  r   r   r   r   Ú<module>   sJ   



(  ;:" !r%: H(0