o
    hg                     @  sF  d Z ddlmZ ddlZddlZddlmZmZmZm	Z	m
Z
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 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dl%m&Z&m'Z'm(Z(m)Z) erpddl*m+Z+ dZ,dZ-dZ.dZ/dZ0G dd dZ1G dd de1Z2G dd de1Z3G dd de1Z4G dd de4Z5dS )z,Implementation of the CRUD database objects.    )annotationsN)TYPE_CHECKINGAnyDictListOptionalUnion   )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)	AddStatementCreateCollectionIndexStatementDeleteStatementFindStatementInsertStatementModifyStatementRemoveStatementSelectStatementUpdateStatement)ConnectionType
SchemaTypeSessionType
StrOrBytes)Resultz_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d	Zed'ddZed(ddZed)ddZd*ddZ	d'ddZ
d(ddZd)ddZd+ddZeddd+d d!Zedd"d)d#d$Zd%S ),DatabaseObjectzProvides base functionality for database objects.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The database object name.
    schemar   namer!   returnNonec                 C  s:   || _ t|tr| n|| _| j  | _| j | _d S N)	_schema
isinstancebytesdecode_nameget_session_sessionget_connection_connection)selfr$   r%    r3   F/var/www/html/scripts/venv/lib/python3.10/site-packages/mysqlx/crud.py__init__V   s   zDatabaseObject.__init__r    c                 C     | j S )z,:class:`mysqlx.Session`: The Session object.r/   r2   r3   r3   r4   session\      zDatabaseObject.sessionc                 C  r6   )z*:class:`mysqlx.Schema`: The Schema object.r)   r8   r3   r3   r4   r$   a   r:   zDatabaseObject.schemastrc                 C  r6   )z&str: The name of this database object.r-   r8   r3   r3   r4   r%   f   r:   zDatabaseObject.namer   c                 C  r6   )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r1   r8   r3   r3   r4   r0   k      zDatabaseObject.get_connectionc                 C  r6   )zwReturns the session of this database object.

        Returns:
            mysqlx.Session: The Session object.
        r7   r8   r3   r3   r4   r.   s   r>   zDatabaseObject.get_sessionc                 C  r6   )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r;   r8   r3   r3   r4   
get_schema{   r>   zDatabaseObject.get_schemac                 C  r6   )zwReturns the name of this database object.

        Returns:
            str: The name of this database object.
        r=   r8   r3   r3   r4   get_name   r>   zDatabaseObject.get_namer   c                 C  s   t )zVerifies if this object exists in the database.

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

        Raises:
           NotImplementedError: This method must be implemented.
        )NotImplementedErrorr8   r3   r3   r4   exists_in_database   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.
        )rB   r8   r3   r3   r4   	am_i_real   s   zDatabaseObject.am_i_realzUse 'get_name()' method insteadc                 C  rC   )zReturns the name of this database object.

        Returns:
            str: The name of this database object.

        .. deprecated:: 8.0.12
           Use ``get_name()`` method instead.
        )r@   r8   r3   r3   r4   who_am_i   s   
zDatabaseObject.who_am_iN)r$   r   r%   r!   r&   r'   )r&   r    )r&   r   )r&   r<   )r&   r   )r&   r   )__name__
__module____qualname____doc__r5   propertyr9   r$   r%   r0   r.   r?   r@   rB   r   rD   rE   r3   r3   r3   r4   r#   N   s$    





r#   c                      s   e Zd ZdZd, fdd	Zd-ddZd.ddZ	d/d0ddZd1ddZd/d0ddZ	d/d2ddZ
d/d3ddZd4d d!Z		"d5d6d(d)Z	"d7d8d*d+Z  ZS )9SchemazA client-side representation of a database schema. Provides access to
    the schema contents.

    Args:
        session (mysqlx.XSession): Session object.
        name (str): The Schema name.
    r9   r    r%   r<   r&   r'   c                   s   || _ t | | d S r(   )r/   superr5   )r2   r9   r%   	__class__r3   r4   r5      s   zSchema.__init__boolc                 C  s    t t| j}| j|dkS zVerifies if this object exists in the database.

        Returns:
            bool: `True` if object exists in database.
        r	   )_COUNT_SCHEMAS_QUERYformatr   r-   r1   execute_sql_scalarr2   sqlr3   r3   r4   rB      s   zSchema.exists_in_databaseList[Collection]c              	   C  sz   | j dd| ji}|  g }|D ](}|d dkrqz	t| |d }W n ty4   t| |d }Y nw || q|S )zyReturns a list of collections for this schema.

        Returns:
            `list`: List of Collection objects.
        list_objectsr$   type
COLLECTION
TABLE_NAMEr%   )r1   get_row_resultr-   	fetch_all
Collection
ValueErrorappend)r2   rowscollectionsrow
collectionr3   r3   r4   get_collections   s   zSchema.get_collectionsFcheck_existenceTablec                 C  s   |  ||S )zuReturns a a table object for the given collection

        Returns:
            mysqlx.Table: Table object.

        )	get_table)r2   r%   re   r3   r3   r4   get_collection_as_table   s   	zSchema.get_collection_as_tableList[Table]c              	   C  s|   | j dd| ji}|  g }d}|D ]'}|d |v r;z	t| |d }W n ty5   t| |d }Y nw || q|S )zoReturns a list of tables for this schema.

        Returns:
            `list`: List of Table objects.
        rW   r$   )TABLEVIEWrX   rZ   r%   )r1   r[   r-   r\   rf   r^   r_   )r2   r`   tablesobject_typesrb   tabler3   r3   r4   
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)rf   rB   r   )r2   r%   re   rn   r3   r3   r4   rg      
   
zSchema.get_tableViewc                 C  rp   )ztReturns the view of the given name for this schema.

        Returns:
            mysqlx.View: View object.
        zView does not exist)rr   rB   r   )r2   r%   re   viewr3   r3   r4   get_view  rq   zSchema.get_viewr]   c                 C  rp   )zReturns the collection of the given name for this schema.

        Returns:
            mysqlx.Collection: Collection object.
        zCollection does not exist)r]   rB   r   )r2   r%   re   rc   r3   r3   r4   get_collection  rq   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.
        rU   FN)r1   execute_nonquery_DROP_TABLE_QUERYrR   r   r-   )r2   r%   r3   r3   r4   drop_collection   s   zSchema.drop_collectionNreuse_existing
validation%Optional[Dict[str, Union[str, Dict]]]kwargsr   c              
   K  s  |st dd|v rtdt |d }t| |}| j|d}|durt|tr*|s.t dd}|D ]}||vr?t d| q2g }	d	|v rZ|d	 }
t|
tsSt d
|		d	|
f d|v r~|d }t|ttfsmt d|		dt|trzt
|n|f d|	f|d< z| jddd| W |S  ty } z*|jtkrtd||jtkr|st d| d|nt |j|j|W Y d}~|S d}~ww )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 invalid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'rz   optionsmysqlxcreate_collectionTlYour MySQL server does not support the requested operation. Please update to MySQL 8.0.19 or a later versionCollection 'z' already exists)r   warningswarnDeprecationWarningr]   r-   r*   dictr<   r_   jsondumpsr1   rv   r   errnor   r   r   msg)r2   r%   ry   rz   r|   rc   fieldsvalid_optionsoptionr   r   r$   errr3   r3   r4   r   .  sv   





zSchema.create_collectionc           
   
   C  s*  |st dt|tr|st dd}|D ]}||vr"t d| qg }d|v r=|d }t|ts6t d|d|f d|v ra|d }t|ttfsPt d|dt|tr]t|n|f | j|d	|fd
}z| j	ddd| W dS  t
y }	 z|	jtkrtd|	t |	j|	j|	d}	~	ww )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   r   r$   r   rz   )r$   r%   r   r   modify_collection_optionsTr   N)r   r*   r   r<   r_   r   r   r-   r1   rv   r   r   r   r   r   )
r2   r%   rz   r   r   r   r   r$   r   r   r3   r3   r4   modify_collection  sT   


zSchema.modify_collection)r9   r    r%   r<   r&   r'   r&   rO   )r&   rV   )F)r%   r<   re   rO   r&   rf   )r&   ri   )r%   r<   re   rO   r&   rr   )r%   r<   re   rO   r&   r]   )r%   r<   r&   r'   )FN)
r%   r<   ry   rO   rz   r{   r|   r   r&   r]   r(   )r%   r<   rz   r{   r&   r'   )rF   rG   rH   rI   r5   rB   rd   rh   ro   rg   rt   ru   rx   r   r   __classcell__r3   r3   rM   r4   rK      s"    

	

`rK   c                   @  s   e Zd ZdZd0ddZd1d2d
dZd3ddZd4ddZd5ddZd6ddZ	d7dd Z
d8d"d#Zd9d(d)Zd9d*d+Zd:d,d-Zd;d.d/ZdS )<r]   zRepresents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    r&   rO   c                 C  *   t t| jjt| j}| j|dkS rP   _COUNT_TABLES_QUERYrR   r   r)   r%   r-   r1   rS   rT   r3   r3   r4   rB        zCollection.exists_in_databaseN	conditionOptional[str]r   c                 C     t | |}| j |_|S )zRetrieves documents from a collection.

        Args:
            condition (Optional[str]): The string with the filter expression of
                                       the documents to be retrieved.
        )r   r1   get_next_statement_idstmt_idr2   r   stmtr3   r3   r4   find  s   
zCollection.findvaluesr
   r   c                 G  s   t | j| S )zAdds 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)r2   r   r3   r3   r4   r     s   	zCollection.addr<   r   c                 C  r   )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   r1   r   r   r   r3   r3   r4   remove     
zCollection.remover   c                 C  r   )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   r1   r   r   r   r3   r3   r4   modify
  r   zCollection.modifyintc              
   C  p   t t| jjt| j}z	| j|}W |S  ty7 } z|j	t
kr2td| j d| jj d| d}~ww )z}Counts the documents in the collection.

        Returns:
            int: The total of documents in the collection.
        r   ' does not exist in schema ''N_COUNT_QUERYrR   r   r)   r%   r-   r1   rS   r   r   r   r2   rU   resr   r3   r3   r4   count  $   

zCollection.count
index_namefields_descDict[str, Any]r   c                 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   )r2   r   r   r3   r3   r4   create_index/  s   zCollection.create_indexr'   c              	   C  s$   | j ddd| jj| j|d dS )z[Drops a collection index.

        Args:
            index_name (str): Index name.
        r   drop_collection_indexF)r$   rc   r%   N)r1   rv   r)   r%   r-   )r2   r   r3   r3   r4   
drop_indexI  s   zCollection.drop_indexdoc_iddocUnion[Dict, DbDoc]'Result'c                 C  s:   d|v r|d |krt d| dd|d| S )zReplaces 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
        _idKReplacement document has an _id that is different than the matched document	_id = :id$id)r   r   setbindexecuter2   r   r   r3   r3   r4   replace_oneZ  s
   zCollection.replace_onec                 C  sH   d|v r|d |krt dt|tst|}| ||d S )zUpserts 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   copyupsertr   r   r3   r3   r4   add_or_replace_onei  s   
zCollection.add_or_replace_onec                 C  s,   |  dd| }| }| j  |S )zReturns 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   	fetch_oner1   fetch_active_result)r2   r   resultr   r3   r3   r4   get_onez  s   	
zCollection.get_onec                 C  s   |  dd| S )zRemoves a Document matching the Document ID.

        Args:
            doc_id (str): Document ID

        Returns:
            mysqlx.Result: Result object.
        r   r   )r   r   r   )r2   r   r3   r3   r4   
remove_one  s   	zCollection.remove_oner   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   )rF   rG   rH   rI   rB   r   r   r   r   r   r   r   r   r   r   r   r3   r3   r3   r4   r]     s    
	








r]   c                   @  sV   e Zd ZdZdddZdd	d
ZdddZdddZdddZd ddZ	dddZ
dS )!rf   zRepresents 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.
    r&   rO   c                 C  r   rP   r   rT   r3   r3   r4   rB     r   zTable.exists_in_databaser   r<   r   c                 G      t | g|R  }| j |_|S )zCreates a new :class:`mysqlx.SelectStatement` object.

        Args:
            *fields: The fields to be retrieved.

        Returns:
            mysqlx.SelectStatement: SelectStatement object
        )r   r1   r   r   r2   r   r   r3   r3   r4   select     	zTable.selectr   r   c                 G  r   )zCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r   r1   r   r   r   r3   r3   r4   insert  r   zTable.insertr   c                 C     t | }| j |_|S )zCreates a new :class:`mysqlx.UpdateStatement` object.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r1   r   r   r2   r   r3   r3   r4   update  s   zTable.updater   c                 C  r   )zCreates a new :class:`mysqlx.DeleteStatement` object.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object

        .. versionchanged:: 8.0.12
           The ``condition`` parameter was removed.
        )r   r1   r   r   r   r3   r3   r4   delete  s   	zTable.deleter   c              
   C  r   )ziCounts the rows in the table.

        Returns:
            int: The total of rows in the table.
        zTable 'r   r   Nr   r   r3   r3   r4   r     r   zTable.countc                 C  r   )zDetermine if the underlying object is a view or not.

        Returns:
            bool: `True` if the underlying object is a view.
        r	   _COUNT_VIEWS_QUERYrR   r   r)   r%   r-   r1   rS   rT   r3   r3   r4   is_view  r   zTable.is_viewNr   )r   r<   r&   r   )r   r   r&   r   )r&   r   )r&   r   r   )rF   rG   rH   rI   rB   r   r   r   r   r   r   r3   r3   r3   r4   rf     s    


	




rf   c                   @  s   e Zd ZdZdddZdS )rr   zRepresents 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.
    r&   rO   c                 C  r   rP   r   rT   r3   r3   r4   rB     r   zView.exists_in_databaseNr   )rF   rG   rH   rI   rB   r3   r3   r3   r4   rr     s    	rr   )6rI   
__future__r   r   r   typingr   r   r   r   r   r   dbdocr
   	errorcoder   r   r   r   errorsr   r   r   helpersr   r   r   	statementr   r   r   r   r   r   r   r   r   typesr   r   r    r!   r   r"   r   r   rQ   r   rw   r#   rK   r]   rf   rr   r3   r3   r3   r4   <module>   s:    ,d  " Cc