o
    –¨Êh5I  ã                   @   sÔ   d Z ddlmZ ddlmZ ddl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.é   )ÚDbDoc)ÚER_NO_SUCH_TABLE)Ú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(   || _ || _| j  ¡ | _| j ¡ | _d S ©N)Ú_schemaÚ_nameÚget_sessionÚ_sessionÚget_connectionÚ_connection)ÚselfÚschemaÚname© r   ú=/var/www/html/env/lib/python3.10/site-packages/mysqlx/crud.pyÚ__init__:   s   zDatabaseObject.__init__c                 C   ó   | j S )z5:class:`mysqlx.Session`: The Session object.
        ©r   ©r   r   r   r   Úsession@   ó   zDatabaseObject.sessionc                 C   r    )z3:class:`mysqlx.Schema`: The Schema object.
        ©r   r"   r   r   r   r   F   r$   zDatabaseObject.schemac                 C   r    )z/str: The name of this database object.
        ©r   r"   r   r   r   r   L   r$   zDatabaseObject.namec                 C   r    )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r   r"   r   r   r   r   R   ó   zDatabaseObject.get_connectionc                 C   r    )zwReturns the session of this database object.

        Returns:
            mysqlx.Session: The Session object.
        r!   r"   r   r   r   r   Z   r'   zDatabaseObject.get_sessionc                 C   r    )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r%   r"   r   r   r   Ú
get_schemab   r'   zDatabaseObject.get_schemac                 C   r    )zwReturns the name of this database object.

        Returns:
            str: The name of this database object.
        r&   r"   r   r   r   Úget_namej   r'   zDatabaseObject.get_namec                 C   s   t ‚)zÓVerifies if this object exists in the database.

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

        Raises:
           NotImplementedError: This method must be implemented.
        )ÚNotImplementedErrorr"   r   r   r   Úexists_in_databaser   s   	z!DatabaseObject.exists_in_databasez8.0.12z)Use 'exists_in_database()' method insteadc                 C   ó   |   ¡ 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.
        )r+   r"   r   r   r   Ú	am_i_real}   s   zDatabaseObject.am_i_realzUse 'get_name()' method insteadc                 C   r,   )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)   r+   r   r-   r.   r   r   r   r   r   3   s$    



r   c                       sr   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‡  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   Úsuperr4   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   r+   ¥   s   zSchema.exists_in_databasec              	   C   sv   | j  d| j¡}| ¡  g }|D ](}|d dkrqz	t| |d ƒ}W n ty2   t| |d ƒ}Y nw | |¡ q|S )zyReturns a list of collections for this schema.

        Returns:
            `list`: List of Collection objects.
        Úlist_objectsÚtypeÚ
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   sx   | j  d| j¡}| ¡  g }d}|D ]'}|d |v r9z	t| |d ƒ}W n ty3   t| |d ƒ}Y nw | |¡ q|S )zoReturns a list of tables for this schema.

        Returns:
            `list`: List of Table objects.
        r>   )ÚTABLEÚVIEWr?   rA   r   )r   rB   r   rC   ÚTablerE   rF   )r   rG   ÚtablesÚobject_typesrI   Útabler   r   r   Ú
get_tablesÊ   s   ÿ
€zSchema.get_tablesc                 C   ó"   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)rQ   r+   r   )r   r   rM   rT   r   r   r   rL   Ý   ó
   
zSchema.get_tablec                 C   rV   )ztReturns the view of the given name for this schema.

        Returns:
            mysqlx.View: View object.
        zView does not exist)ÚViewr+   r   )r   r   rM   Úviewr   r   r   Úget_viewé   rW   zSchema.get_viewc                 C   rV   )z†Returns the collection of the given name for this schema.

        Returns:
            mysqlx.Collection: Collection object.
        zCollection does not exist)rD   r+   r   )r   r   rM   rJ   r   r   r   Úget_collectionõ   rW   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.
        r=   FN)r   Úexecute_nonqueryÚ_DROP_TABLE_QUERYr:   r   r   )r   r   r   r   r   Údrop_collection  s   ÿþzSchema.drop_collectionc                 C   sH   |st dƒ‚t| |ƒ}| ¡ s| j ddd| j|¡ |S |s"t dƒ‚|S )aû  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 (bool): `True` to reuse an existing collection.

        Returns:
            mysqlx.Collection: Collection object.

        Raises:
            :class:`mysqlx.ProgrammingError`: If ``reuse`` is False and
                                              collection exists.
        zCollection name is invalidÚxpluginÚcreate_collectionTzCollection already exists)r   rD   r+   r   r\   r   )r   r   ÚreuserJ   r   r   r   r`     s   

ÿþzSchema.create_collection)F)r/   r0   r1   r2   r   r+   rK   rN   rU   rL   rZ   r[   r^   r`   Ú__classcell__r   r   r6   r   r4   ™   s    	
	



r4   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 )rD   z�Represents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    c                 C   ó*   t  t| jjƒt| jƒ¡}| j |¡dkS r8   ©Ú_COUNT_TABLES_QUERYr:   r   r   r   r   r   r;   r<   r   r   r   r+   -  ó   ÿzCollection.exists_in_databaseNc                 C   ó
   t | |ƒ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   Ú	conditionr   r   r   Úfind7  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   rk   @  s   	zCollection.addc                 C   rg   )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   rh   r   r   r   ÚremoveL  ó   
zCollection.removec                 C   rg   )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   rh   r   r   r   Úmodify[  rn   zCollection.modifyc              
   C   óh   t  t| jjƒt| jƒ¡}z	| j |¡}W |S  ty3 } z|j	t
kr.td | j| jj¡ƒ‚‚ d}~ww )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   Úerrnor   ©r   r=   ÚresÚerrr   r   r   Úcountj  ó   ÿú
þ€ûzCollection.countc                 C   s   t | ||ƒS )a"  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,
                                                "collation": collation,
                                                "options": options,
                                                "srid": srid},
                                                # {... more members,
                                                #      repeated as many times
                                                #      as needed}
                                                ],
                                    "type": type}
        )r   )r   Ú
index_nameÚfields_descr   r   r   Úcreate_index|  s   zCollection.create_indexc                 C   s    | j  ddd| jj| j|¡ dS )z[Drops a collection index.

        Args:
            index_name (str): Index name.
        r_   Údrop_collection_indexFN)r   r\   r   r   r   )r   ry   r   r   r   Ú
drop_index“  s   
þzCollection.drop_indexc                 C   s   |   d¡ d|¡ d|¡ ¡ S )z½Replaces the Document matching the document ID with a new document
        provided.

        Args:
            doc_id (str): Document ID
            doc (DbDoc/dict): New Document
        ú	_id = :idú$Úid)ro   ÚsetÚbindÚexecute©r   Údoc_idÚdocr   r   r   Úreplace_one�  s   ÿzCollection.replace_onec                 C   s,   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 (DbDoc/dict): New Document
        T)Ú
isinstancer   rk   ÚcopyÚupsertrƒ   r„   r   r   r   Úadd_or_replace_one¨  s   
zCollection.add_or_replace_onec                 C   s   |   d¡ d|¡ ¡  ¡ S )zjReturns a Document matching the Document ID.

        Args:
            doc_id (str): Document ID
        r~   r€   )rj   r‚   rƒ   Ú	fetch_one©r   r…   r   r   r   Úget_one´  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€   )rm   r‚   rƒ   r�   r   r   r   Ú
remove_one¼  s   	zCollection.remove_oner   )r/   r0   r1   r2   r+   rj   rk   rm   ro   rw   r{   r}   r‡   r‹   rŽ   r�   r   r   r   r   rD   %  s    

	
rD   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 )rQ   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   rc   r8   rd   r<   r   r   r   r+   Ó  rf   zTable.exists_in_databasec                 G   ó   t | g|¢R Ž S )zËCreates a new :class:`mysqlx.SelectStatement` object.

        Args:
            *fields: The fields to be retrieved.

        Returns:
            mysqlx.SelectStatement: SelectStatement object
        )r   ©r   Úfieldsr   r   r   ÚselectÝ  ó   	zTable.selectc                 G   r�   )zÊCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r   r‘   r   r   r   Úinsertè  r”   zTable.insertc                 C   ó   t | ƒS )z‹Creates a new :class:`mysqlx.UpdateStatement` object.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r"   r   r   r   Úupdateó  s   zTable.updatec                 C   r–   )zãCreates a new :class:`mysqlx.DeleteStatement` object.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object

        .. versionchanged:: 8.0.12
           The ``condition`` parameter was removed.
        )r   r"   r   r   r   Údeleteû  s   	zTable.deletec              
   C   rp   )ziCounts the rows in the table.

        Returns:
            int: The total of rows in the table.
        z(Table '{}' does not exist in schema '{}'Nrq   rt   r   r   r   rw     rx   zTable.countc                 C   rc   )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  rf   zTable.is_viewN)r/   r0   r1   r2   r+   r“   r•   r—   r˜   rw   r›   r   r   r   r   rQ   È  s    

rQ   c                   @   s   e Zd ZdZdd„ ZdS )rX   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   rc   r8   r™   r<   r   r   r   r+   -  rf   zView.exists_in_databaseN)r/   r0   r1   r2   r+   r   r   r   r   rX   #  s    	rX   N)!r2   Údbdocr   Ú	errorcoder   Úerrorsr   r   Úhelpersr   r   r   Ú	statementr	   r
   r   r   r   r   r   r   r   rš   re   r9   rr   r]   Úobjectr   r4   rD   rQ   rX   r   r   r   r   Ú<module>   s$   ,f  $[