a
    còf¯c  ã                   @   sô   d Z ddlZddl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 ddlmZmZmZ ddlmZmZmZmZmZmZmZmZmZ d	Zd
ZdZdZ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&dS )z,Implementation of the CRUD database objects.é    Né   )ÚDbDoc)ÚER_NO_SUCH_TABLEÚER_TABLE_EXISTS_ERRORÚER_X_CMD_NUM_ARGUMENTSÚER_X_INVALID_ADMIN_COMMAND)ÚNotSupportedErrorÚOperationalErrorÚProgrammingError)Ú
deprecatedÚescapeÚquote_identifier)	ÚFindStatementÚAddStatementÚRemoveStatementÚModifyStatementÚSelectStatementÚInsertStatementÚDeleteStatementÚUpdateStatementÚCreateCollectionIndexStatementz_SELECT COUNT(*) FROM information_schema.views WHERE table_schema = '{0}' AND table_name = '{1}'z`SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '{1}'zJSELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = '{0}'zSELECT COUNT(*) FROM {0}.{1}zDROP TABLE IF EXISTS {0}.{1}c                   @   sˆ   e Zd ZdZdd„ Zedd„ ƒZedd„ ƒZedd	„ ƒZd
d„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zeddƒdd„ ƒZeddƒdd„ ƒZdS )ÚDatabaseObjectz¢Provides base functionality for database objects.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The database object name.
    c                 C   s:   || _ t|tƒr| ¡ n|| _| j  ¡ | _| j ¡ | _d S ©N)	Ú_schemaÚ
isinstanceÚbytesÚdecodeÚ_nameÚget_sessionÚ_sessionÚget_connectionÚ_connection)ÚselfÚschemaÚname© r%   úH/home/httpd/docs/test/DocsMgr/lib/python3.9/site-packages/mysqlx/crud.pyÚ__init__>   s    zDatabaseObject.__init__c                 C   s   | j S )z5:class:`mysqlx.Session`: The Session object.
        ©r   ©r"   r%   r%   r&   ÚsessionD   s    zDatabaseObject.sessionc                 C   s   | j S )z3:class:`mysqlx.Schema`: The Schema object.
        ©r   r)   r%   r%   r&   r#   J   s    zDatabaseObject.schemac                 C   s   | j S )z/str: The name of this database object.
        ©r   r)   r%   r%   r&   r$   P   s    zDatabaseObject.namec                 C   s   | j S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r!   r)   r%   r%   r&   r    V   s    zDatabaseObject.get_connectionc                 C   s   | j S )zwReturns the session of this database object.

        Returns:
            mysqlx.Session: The Session object.
        r(   r)   r%   r%   r&   r   ^   s    zDatabaseObject.get_sessionc                 C   s   | j S )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r+   r)   r%   r%   r&   Ú
get_schemaf   s    zDatabaseObject.get_schemac                 C   s   | j S )zwReturns the name of this database object.

        Returns:
            str: The name of this database object.
        r,   r)   r%   r%   r&   Úget_namen   s    zDatabaseObject.get_namec                 C   s   t ‚dS )zÓVerifies if this object exists in the database.

        Returns:
            bool: `True` if object exists in database.

        Raises:
           NotImplementedError: This method must be implemented.
        N)ÚNotImplementedErrorr)   r%   r%   r&   Úexists_in_databasev   s    	z!DatabaseObject.exists_in_databasez8.0.12z)Use 'exists_in_database()' method insteadc                 C   s   |   ¡ S )a+  Verifies if this object exists in the database.

        Returns:
            bool: `True` if object exists in database.

        Raises:
           NotImplementedError: This method must be implemented.

        .. deprecated:: 8.0.12
           Use ``exists_in_database()`` method instead.
        )r0   r)   r%   r%   r&   Ú	am_i_real�   s    zDatabaseObject.am_i_realzUse 'get_name()' method insteadc                 C   s   |   ¡ S )zÅReturns the name of this database object.

        Returns:
            str: The name of this database object.

        .. deprecated:: 8.0.12
           Use ``get_name()`` method instead.
        )r.   r)   r%   r%   r&   Úwho_am_i�   s    
zDatabaseObject.who_am_iN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r'   Úpropertyr*   r#   r$   r    r   r-   r.   r0   r   r1   r2   r%   r%   r%   r&   r   7   s"   



r   c                       s|   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	d
„Zdd„ Zddd„Z	ddd„Z
ddd„Zdd„ Zddd„Zddd„Z‡  ZS ) ÚSchemazÆA client-side representation of a database schema. Provides access to
    the schema contents.

    Args:
        session (mysqlx.XSession): Session object.
        name (str): The Schema name.
    c                    s   || _ tt| ƒ | |¡ d S r   )r   Úsuperr8   r'   )r"   r*   r$   ©Ú	__class__r%   r&   r'   ¥   s    zSchema.__init__c                 C   s    t  t| jƒ¡}| j |¡dkS ©z�Verifies if this object exists in the database.

        Returns:
            bool: `True` if object exists in database.
        r   )Ú_COUNT_SCHEMAS_QUERYÚformatr   r   r!   Úexecute_sql_scalar©r"   Úsqlr%   r%   r&   r0   ©   s    zSchema.exists_in_databasec              	   C   sz   | j  dd| ji¡}| ¡  g }|D ]P}|d dkr6q$zt| |d ƒ}W n  tyh   t| |d ƒ}Y n0 | |¡ q$|S )zyReturns a list of collections for this schema.

        Returns:
            `list`: List of Collection objects.
        Úlist_objectsr#   ÚtypeZ
COLLECTIONÚ
TABLE_NAMEr$   )r!   Úget_row_resultr   Ú	fetch_allÚ
CollectionÚ
ValueErrorÚappend)r"   ÚrowsÚcollectionsÚrowÚ
collectionr%   r%   r&   Úget_collections²   s    ÿzSchema.get_collectionsFc                 C   s   |   ||¡S )zuReturns a a table object for the given collection

        Returns:
            mysqlx.Table: Table object.

        )Ú	get_table)r"   r$   Úcheck_existencer%   r%   r&   Úget_collection_as_tableÆ   s    zSchema.get_collection_as_tablec              	   C   s|   | j  dd| ji¡}| ¡  g }d}|D ]N}|d |v r(zt| |d ƒ}W n  tyj   t| |d ƒ}Y n0 | |¡ q(|S )zoReturns a list of tables for this schema.

        Returns:
            `list`: List of Table objects.
        rB   r#   )ZTABLEZVIEWrC   rD   r$   )r!   rE   r   rF   ÚTablerH   rI   )r"   rJ   ZtablesZobject_typesrL   Útabler%   r%   r&   Ú
get_tablesÏ   s    ÿzSchema.get_tablesc                 C   s"   t | |ƒ}|r| ¡ stdƒ‚|S )zwReturns the table of the given name for this schema.

        Returns:
            mysqlx.Table: Table object.
        zTable does not exist)rR   r0   r
   )r"   r$   rP   rS   r%   r%   r&   rO   ã   s
    
zSchema.get_tablec                 C   s"   t | |ƒ}|r| ¡ stdƒ‚|S )ztReturns the view of the given name for this schema.

        Returns:
            mysqlx.View: View object.
        zView does not exist)ÚViewr0   r
   )r"   r$   rP   Úviewr%   r%   r&   Úget_viewï   s
    
zSchema.get_viewc                 C   s"   t | |ƒ}|r| ¡ stdƒ‚|S )z†Returns the collection of the given name for this schema.

        Returns:
            mysqlx.Collection: Collection object.
        zCollection does not exist)rG   r0   r
   )r"   r$   rP   rM   r%   r%   r&   Úget_collectionû   s
    
zSchema.get_collectionc                 C   s&   | j  dt t| jƒt|ƒ¡d¡ dS )zmDrops a collection.

        Args:
            name (str): The name of the collection to be dropped.
        rA   FN)r!   Úexecute_nonqueryÚ_DROP_TABLE_QUERYr>   r   r   )r"   r$   r%   r%   r&   Údrop_collection  s    ÿþzSchema.drop_collectionNc              
   K   s�  |st dƒ‚d|v r(t dt¡ |d }t| |ƒ}| j|dœ}|du�r
t|tƒrV|s^t dƒ‚d}|D ]}||vrft d |¡ƒ‚qfg }	d	|v r¶|d	 }
t|
t	ƒs¨t d
ƒ‚|	 
d	|
f¡ d|v rþ|d }t|t	tfƒsÜt dƒ‚|	 
dt|tƒröt |¡n|f¡ d|	f|d< z| j ddd|¡ W nj t�yŠ } zP|jtk�rFtdƒ‚|jtk�rh|�svt d |¡ƒ‚nt |j|jƒ‚W Y d}~n
d}~0 0 |S )aJ  Creates in the current schema a new collection with the specified
        name and retrieves an object representing the new collection created.

        Args:
            name (str): The name of the collection.
            reuse_existing (bool): `True` to reuse an existing collection.
            validation (Optional[dict]): A dict, containing the keys `level`
                                         with the validation level and `schema`
                                         with a dict or a string representation
                                         of a JSON schema specification.

        Returns:
            mysqlx.Collection: Collection object.

        Raises:
            :class:`mysqlx.ProgrammingError`: If ``reuse_existing`` is False
                                              and collection exists or the
                                              collection name is invalid.
            :class:`mysqlx.NotSupportedError`: If schema validation is not
                                               supported by the server.

        .. versionchanged:: 8.0.21
        úCollection name is invalidZreusezG'reuse' is deprecated since 8.0.21. Please use 'reuse_existing' instead)r#   r$   NúInvalid value for 'validation'©Úlevelr#   ú"Invalid option in 'validation': {}r_   úInvalid value for 'level'r#   úInvalid value for 'schema'Ú
validationÚoptionsÚmysqlxÚcreate_collectionTúlYour MySQL server does not support the requested operation. Please update to MySQL 8.0.19 or a later versionzCollection '{}' already exists)r
   ÚwarningsÚwarnÚDeprecationWarningrG   r   r   Údictr>   ÚstrrI   ÚjsonÚdumpsr!   rY   r	   Úerrnor   r   r   Úmsg)r"   r$   Zreuse_existingrc   ÚkwargsrM   ÚfieldsÚvalid_optionsÚoptionrd   r_   r#   Úerrr%   r%   r&   rf     sh    þ

ÿ
ÿÿÿÿÿÿ$zSchema.create_collectionc           
   
   C   s8  |st dƒ‚t|tƒr|s"t dƒ‚d}|D ]}||vr*t d |¡ƒ‚q*g }d|v rz|d }t|tƒslt dƒ‚| d|f¡ d|v rÂ|d }t|ttfƒs t dƒ‚| dt|tƒrºt |¡n|f¡ | j|d	|fd
œ}z| j	 
ddd|¡ W nH t�y2 }	 z.|	jtk�rtdƒ‚t |	j|	jƒ‚W Y d}	~	n
d}	~	0 0 dS )a
  Modifies a collection using a JSON schema validation.

        Args:
            name (str): The name of the collection.
            validation (Optional[dict]): A dict, containing the keys `level`
                                         with the validation level and `schema`
                                         with a dict or a string representation
                                         of a JSON schema specification.

        Raises:
            :class:`mysqlx.ProgrammingError`: If the collection name or
                                              validation is invalid.
            :class:`mysqlx.NotSupportedError`: If schema validation is not
                                               supported by the server.

        .. versionadded:: 8.0.21
        r\   r]   r^   r`   r_   ra   r#   rb   rc   )r#   r$   rd   re   Zmodify_collection_optionsTrg   N)r
   r   rk   r>   rl   rI   rm   rn   r   r!   rY   r	   ro   r   r   rp   )
r"   r$   rc   rs   rt   rd   r_   r#   rr   ru   r%   r%   r&   Úmodify_collectiond  sR    ÿ
ÿÿÿýÿÿzSchema.modify_collection)F)F)F)F)FN)N)r3   r4   r5   r6   r'   r0   rN   rQ   rT   rO   rW   rX   r[   rf   rv   Ú__classcell__r%   r%   r:   r&   r8   �   s   	
	




Sr8   c                   @   sr   e Zd ZdZdd„ Zd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S )rG   z�Represents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    c                 C   s*   t  t| jjƒt| jƒ¡}| j |¡dkS r<   ©Ú_COUNT_TABLES_QUERYr>   r   r   r$   r   r!   r?   r@   r%   r%   r&   r0   «  s    ÿzCollection.exists_in_databaseNc                 C   s   t | |ƒ}| j ¡ |_|S )zÔRetrieves documents from a collection.

        Args:
            condition (Optional[str]): The string with the filter expression of
                                       the documents to be retrieved.
        )r   r!   Úget_next_statement_idÚstmt_id©r"   Ú	conditionÚstmtr%   r%   r&   Úfindµ  s    
zCollection.findc                 G   s   t | ƒj|Ž S )zÑAdds a list of documents to a collection.

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

        Returns:
            mysqlx.AddStatement: AddStatement object.
        )r   Úadd)r"   Úvaluesr%   r%   r&   r€   À  s    	zCollection.addc                 C   s   t | |ƒ}| j ¡ |_|S )ap  Removes documents based on the ``condition``.

        Args:
            condition (str): The string with the filter expression of the
                             documents to be removed.

        Returns:
            mysqlx.RemoveStatement: RemoveStatement object.

        .. versionchanged:: 8.0.12
           The ``condition`` parameter is now mandatory.
        )r   r!   rz   r{   r|   r%   r%   r&   ÚremoveË  s    
zCollection.removec                 C   s   t | |ƒ}| j ¡ |_|S )ar  Modifies documents based on the ``condition``.

        Args:
            condition (str): The string with the filter expression of the
                             documents to be modified.

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.

        .. versionchanged:: 8.0.12
           The ``condition`` parameter is now mandatory.
        )r   r!   rz   r{   r|   r%   r%   r&   ÚmodifyÜ  s    
zCollection.modifyc              
   C   sv   t  t| jjƒt| jƒ¡}z| j |¡}W nF typ } z.|j	t
krZtd | j| jj¡ƒ‚‚ W Y d}~n
d}~0 0 |S )z}Counts the documents in the collection.

        Returns:
            int: The total of documents in the collection.
        z-Collection '{}' does not exist in schema '{}'N©Ú_COUNT_QUERYr>   r   r   r$   r   r!   r?   r	   ro   r   ©r"   rA   Úresru   r%   r%   r&   Úcountí  s    ÿ

ÿÿzCollection.countc                 C   s   t | ||ƒS )ab  Creates a collection index.

        Args:
            index_name (str): Index name.
            fields_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,
                                                "array": array,
                                                "collation": collation,
                                                "options": options,
                                                "srid": srid},
                                                # {... more members,
                                                #      repeated as many times
                                                #      as needed}
                                                ],
                                    "type": type}
        )r   )r"   Ú
index_nameZfields_descr%   r%   r&   Úcreate_indexÿ  s    zCollection.create_indexc              	   C   s$   | j  ddd| jj| j|dœ¡ dS )z[Drops a collection index.

        Args:
            index_name (str): Index name.
        re   Zdrop_collection_indexF)r#   rM   r$   N)r!   rY   r   r$   r   )r"   r‰   r%   r%   r&   Ú
drop_index  s    
þÿzCollection.drop_indexc                 C   s:   d|v r|d |krt dƒ‚|  d¡ d|¡ d|¡ ¡ S )zÒReplaces the Document matching the document ID with a new document
        provided.

        Args:
            doc_id (str): Document ID
            doc (:class:`mysqlx.DbDoc` or `dict`): New Document
        Ú_idúKReplacement document has an _id that is different than the matched documentú	_id = :idú$Úid)r
   rƒ   ÚsetÚbindÚexecute©r"   Údoc_idÚdocr%   r%   r&   Úreplace_one"  s    ÿÿzCollection.replace_onec                 C   sH   d|v r|d |krt dƒ‚t|tƒs.t|ƒ}|  | |¡¡ d¡ ¡ S )zÏUpserts the Document matching the document ID with a new document
        provided.

        Args:
            doc_id (str): Document ID
            doc (:class:`mysqlx.DbDoc` or dict): New Document
        rŒ   r�   T)r
   r   r   r€   ÚcopyZupsertr“   r”   r%   r%   r&   Úadd_or_replace_one2  s    ÿ
zCollection.add_or_replace_onec                 C   s,   |   d¡ d|¡ ¡ }| ¡ }| j ¡  |S )z½Returns a Document matching the Document ID.

        Args:
            doc_id (str): Document ID

        Returns:
            mysqlx.DbDoc: The Document matching the Document ID.
        rŽ   r�   )r   r’   r“   Z	fetch_oner!   Zfetch_active_result)r"   r•   Úresultr–   r%   r%   r&   Úget_oneC  s    	
zCollection.get_onec                 C   s   |   d¡ d|¡ ¡ S )z¦Removes a Document matching the Document ID.

        Args:
            doc_id (str): Document ID

        Returns:
            mysqlx.Result: Result object.
        rŽ   r�   )r‚   r’   r“   )r"   r•   r%   r%   r&   Ú
remove_oneQ  s    	zCollection.remove_one)N)r3   r4   r5   r6   r0   r   r€   r‚   rƒ   rˆ   rŠ   r‹   r—   r™   r›   rœ   r%   r%   r%   r&   rG   £  s   

rG   c                   @   sH   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dS )rR   zîRepresents a database table on a schema.

    Provides access to the table through standard INSERT/SELECT/UPDATE/DELETE
    statements.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The table name.
    c                 C   s*   t  t| jjƒt| jƒ¡}| j |¡dkS r<   rx   r@   r%   r%   r&   r0   h  s    ÿzTable.exists_in_databasec                 G   s    t | g|¢R Ž }| j ¡ |_|S )zËCreates a new :class:`mysqlx.SelectStatement` object.

        Args:
            *fields: The fields to be retrieved.

        Returns:
            mysqlx.SelectStatement: SelectStatement object
        )r   r!   rz   r{   ©r"   rr   r~   r%   r%   r&   Úselectr  s    	zTable.selectc                 G   s    t | g|¢R Ž }| j ¡ |_|S )zÊCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r   r!   rz   r{   r�   r%   r%   r&   Úinsert  s    	zTable.insertc                 C   s   t | ƒ}| j ¡ |_|S )z‹Creates a new :class:`mysqlx.UpdateStatement` object.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r!   rz   r{   ©r"   r~   r%   r%   r&   ÚupdateŒ  s    zTable.updatec                 C   s   t | ƒ}| j ¡ |_|S )zãCreates a new :class:`mysqlx.DeleteStatement` object.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object

        .. versionchanged:: 8.0.12
           The ``condition`` parameter was removed.
        )r   r!   rz   r{   r    r%   r%   r&   Údelete–  s    	zTable.deletec              
   C   sv   t  t| jjƒt| jƒ¡}z| j |¡}W nF typ } z.|j	t
krZtd | j| jj¡ƒ‚‚ W Y d}~n
d}~0 0 |S )ziCounts the rows in the table.

        Returns:
            int: The total of rows in the table.
        z(Table '{}' does not exist in schema '{}'Nr„   r†   r%   r%   r&   rˆ   £  s    ÿ

ÿÿzTable.countc                 C   s*   t  t| jjƒt| jƒ¡}| j |¡dkS )zŒDetermine if the underlying object is a view or not.

        Returns:
            bool: `True` if the underlying object is a view.
        r   ©Ú_COUNT_VIEWS_QUERYr>   r   r   r$   r   r!   r?   r@   r%   r%   r&   Úis_viewµ  s    ÿzTable.is_viewN)r3   r4   r5   r6   r0   rž   rŸ   r¡   r¢   rˆ   r¥   r%   r%   r%   r&   rR   ]  s   


rR   c                   @   s   e Zd ZdZdd„ ZdS )rU   zÌRepresents a database view on a schema.

    Provides a mechanism for creating, alter and drop views.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The table name.
    c                 C   s*   t  t| jjƒt| jƒ¡}| j |¡dkS r<   r£   r@   r%   r%   r&   r0   Ê  s    ÿzView.exists_in_databaseN)r3   r4   r5   r6   r0   r%   r%   r%   r&   rU   À  s   	rU   )'r6   rm   rh   Zdbdocr   Ú	errorcoder   r   r   r   Úerrorsr   r	   r
   Úhelpersr   r   r   Z	statementr   r   r   r   r   r   r   r   r   r¤   ry   r=   r…   rZ   Úobjectr   r8   rG   rR   rU   r%   r%   r%   r&   Ú<module>   s(   ,f   ;c