
    "ic                     2   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e!          Z" G d de"          Z# G d de"          Z$ G d de"          Z% G 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                       e Zd ZdZd Zed             Zed             Zed             Zd Z	d Z
d Zd	 Zd
 Z edd          d             Z e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.
    c                     || _         t          |t                    r|                                n|| _        | j                                         | _        | j                                        | _        d S N)	_schema
isinstancebytesdecode_nameget_session_sessionget_connection_connection)selfschemanames      C/srv/django_bis/venv311/lib/python3.11/site-packages/mysqlx/crud.py__init__zDatabaseObject.__init__>   s\    &0u&=&=GT[[]]]4
0022=7799    c                     | j         S )z5:class:`mysqlx.Session`: The Session object.
        r"   r%   s    r(   sessionzDatabaseObject.sessionD   s     }r*   c                     | j         S )z3:class:`mysqlx.Schema`: The Schema object.
        r   r-   s    r(   r&   zDatabaseObject.schemaJ   s     |r*   c                     | j         S )z/str: The name of this database object.
        r    r-   s    r(   r'   zDatabaseObject.nameP   s     zr*   c                     | j         S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r$   r-   s    r(   r#   zDatabaseObject.get_connectionV   s     r*   c                     | j         S )zwReturns the session of this database object.

        Returns:
            mysqlx.Session: The Session object.
        r,   r-   s    r(   r!   zDatabaseObject.get_session^   s     }r*   c                     | j         S )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r0   r-   s    r(   
get_schemazDatabaseObject.get_schemaf   s     |r*   c                     | j         S )zwReturns the name of this database object.

        Returns:
            str: The name of this database object.
        r2   r-   s    r(   get_namezDatabaseObject.get_namen   s     zr*   c                     t           )zVerifies if this object exists in the database.

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

        Raises:
           NotImplementedError: This method must be implemented.
        )NotImplementedErrorr-   s    r(   exists_in_databasez!DatabaseObject.exists_in_databasev   s
     "!r*   z8.0.12z)Use 'exists_in_database()' method insteadc                 *    |                                  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-   s    r(   	am_i_realzDatabaseObject.am_i_real   s     &&(((r*   zUse 'get_name()' method insteadc                 *    |                                  S )zReturns the name of this database object.

        Returns:
            str: The name of this database object.

        .. deprecated:: 8.0.12
           Use ``get_name()`` method instead.
        )r8   r-   s    r(   who_am_izDatabaseObject.who_am_i   s     }}r*   N)__name__
__module____qualname____doc__r)   propertyr.   r&   r'   r#   r!   r6   r8   r;   r   r=   r?    r*   r(   r   r   7   s        : : :   X
   X
   X
           	" 	" 	" ZEFF) ) GF) Z;<<	 	 =<	 	 	r*   r   c                   j     e Zd ZdZ fdZd Zd ZddZd ZddZ	dd	Z
dd
Zd ZddZddZ xZS )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.
    c                 h    || _         t          t          |                               | |           d S r   )r"   superrG   r)   )r%   r.   r'   	__class__s      r(   r)   zSchema.__init__   s0    fd$$T400000r*   c                     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    r$   execute_sql_scalarr%   sqls     r(   r;   zSchema.exists_in_database   s=     #))&*<*<==223771<<r*   c                 @   | j                             dd| j        i          }|                                 g }|D ]b}|d         dk    r	 t	          | |d                   }n&# t
          $ r t	          | |d                   }Y nw xY w|                    |           c|S )zyReturns a list of collections for this schema.

        Returns:
            `list`: List of Collection objects.
        list_objectsr&   type
COLLECTION
TABLE_NAMEr'   )r$   get_row_resultr    	fetch_all
Collection
ValueErrorappend)r%   rowscollectionsrow
collections        r(   get_collectionszSchema.get_collections   s     ..~08$*/EG G 	+ 	+C6{l**;'c,.?@@

 ; ; ;'c&k::


;z****s   A"" BBFc                 .    |                      ||          S )zuReturns a a table object for the given collection

        Returns:
            mysqlx.Table: Table object.

        )	get_table)r%   r'   check_existences      r(   get_collection_as_tablezSchema.get_collection_as_table   s     ~~dO444r*   c                 >   | j                             dd| j        i          }|                                 g }d}|D ]_}|d         |v rS	 t	          | |d                   }n&# t
          $ r t	          | |d                   }Y nw xY w|                    |           `|S )zoReturns a list of tables for this schema.

        Returns:
            `list`: List of Table objects.
        rS   r&   )TABLEVIEWrT   rV   r'   )r$   rW   r    rX   TablerZ   r[   )r%   r\   tablesobject_typesr^   tables         r(   
get_tableszSchema.get_tables   s     ..~08$*/EG G) 	% 	%C6{l**5!$L(9::EE! 5 5 5!$F44EEE5e$$$s   
A!! BBc                 p    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)rh   r;   r   )r%   r'   rc   rk   s       r(   rb   zSchema.get_table   sC     dD!! 	?++-- ?&'=>>>r*   c                 p    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)Viewr;   r   )r%   r'   rc   views       r(   get_viewzSchema.get_view   sC     D$ 	>**,, >&'<===r*   c                 p    t          | |          }|r#|                                st          d          |S )zReturns the collection of the given name for this schema.

        Returns:
            mysqlx.Collection: Collection object.
        zCollection does not exist)rY   r;   r   )r%   r'   rc   r_   s       r(   get_collectionzSchema.get_collection   sF      d++
 	D0022 D&'BCCCr*   c           	          | j                             dt                              t	          | j                  t	          |                    d           dS )zmDrops a collection.

        Args:
            name (str): The name of the collection to be dropped.
        rQ   FN)r$   execute_nonquery_DROP_TABLE_QUERYrN   r   r    )r%   r'   s     r(   drop_collectionzSchema.drop_collection  sa     	))$++,<TZ,H,H,<T,B,BD DEJ	L 	L 	L 	L 	Lr*   Nc                 *   |st          d          d|v r"t          j        dt                     |d         }t	          | |          }| j        |d}|t          |t                    r|st          d          d}|D ](}||vr"t          d                    |                    )g }	d	|v rC|d	         }
t          |
t                    st          d
          |	
                    d	|
f           d|v rs|d         }t          |t          t          f          st          d          |	
                    dt          |t                    rt          j        |          n|f           d|	f|d<   	 | j                            ddd|           n# t          $ rx}|j        t"          k    rt%          d          |j        t&          k    r%|s"t          d                    |                    nt          |j        |j                  Y d}~nd}~ww xY w|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 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'
validationoptionsmysqlxcreate_collectionTlYour 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DeprecationWarningrY   r    r   dictrN   strr[   jsondumpsr$   ru   r
   errnor   r	   r   msg)r%   r'   reuse_existingr   kwargsr_   fieldsvalid_optionsoptionr   r}   r&   errs                r(   r   zSchema.create_collection  s   2  	A"#?@@@fM @,. . . $G_Nd++
 J55!j$// Iz I&'GHHH/M$ > >..* ,..4fVnn> > > / G*$$"7+!%-- H*+FGGG/000:%%#H-!&3+66 I*+GHHH",VT":": Gtz&111@FHI I I ".w 7F9	;---tV= = = = 	; 	; 	;y222'   y111% G*8??EEG G GG 'sw	:::	G G G G G	; s   0F 
HA.HHc                 :   |st          d          t          |t                    r|st          d          d}|D ](}||vr"t          d                    |                    )g }d|v rC|d         }t          |t                    st          d          |                    d|f           d|v rs|d         }t          |t          t          f          st          d          |                    dt          |t                    rt          j        |          n|f           | j        |d	|fd
}	 | j	        
                    ddd|           dS # t          $ r>}	|	j        t          k    rt          d          t          |	j        |	j                  d}	~	ww xY 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
        ry   r{   r|   r~   r}   r   r&   r   r   )r&   r'   r   r   modify_collection_optionsTr   N)r   r   r   rN   r   r[   r   r   r    r$   ru   r
   r   r   r	   r   )
r%   r'   r   r   r   r   r}   r&   r   r   s
             r(   modify_collectionzSchema.modify_collectiond  s   $  	A"#?@@@*d++ 	E: 	E"#CDDD+  	: 	:F]**& (**0&..: : : + j  w'EeS)) D&'BCCCNNGU+,,,z!!)FfsDk22 E&'CDDDNN(66C4:f---<BDE E E
 j$g.
 
		7--5tVE E E E E 	7 	7 	7y666'   #37CI666	7s   3E 
F9FF)F)FNr   )r@   rA   rB   rC   r)   r;   r`   rd   rl   rb   rq   rs   rw   r   r   __classcell__)rJ   s   @r(   rG   rG      s         1 1 1 1 1= = =  (5 5 5 5  (
 
 
 

 
 
 

 
 
 
L L LQ Q Q Qf<7 <7 <7 <7 <7 <7 <7 <7r*   rG   c                   \    e Zd ZdZd ZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd ZdS )rY   zRepresents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    c                     t                               t          | j        j                  t          | j                            }| j                            |          dk    S rL   _COUNT_TABLES_QUERYrN   r   r   r'   r    r$   rO   rP   s     r(   r;   zCollection.exists_in_database  Q     "((0A)B)B)/
););= =223771<<r*   Nc                 b    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   r$   get_next_statement_idstmt_idr%   	conditionstmts      r(   findzCollection.find  s.     T9--'==??r*   c                 0     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)r%   valuess     r(   r   zCollection.add  s     &|D!!%v..r*   c                 b    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$   r   r   r   s      r(   removezCollection.remove  .     tY//'==??r*   c                 b    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$   r   r   r   s      r(   modifyzCollection.modify  r   r*   c                 p   t                               t          | j        j                  t          | j                            }	 | j                            |          }nU# t          $ rH}|j	        t          k    r2t          d                    | j        | j        j                             d}~ww xY w|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_QUERYrN   r   r   r'   r    r$   rO   r
   r   r   r%   rQ   resr   s       r(   countzCollection.count       !!"24<3D"E"E"24:">">@ @	"55c::CC 	 	 	y,,,&vdj$,*;<<> > > 	 
   A! !
B3+AB..B3c                 $    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_namefields_descs      r(   create_indexzCollection.create_index  s    , .dJLLLr*   c           	      f    | 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&   r_   r'   N)r$   ru   r   r'   r    )r%   r   s     r(   
drop_indexzCollection.drop_index  sQ     	))(4K*/DL<M@D
:D2F 2F	G 	G 	G 	G 	Gr*   c                     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r%   doc_iddocs      r(   replace_onezCollection.replace_one"  so     C<<CJ&00"#   {{;''++C55Dv&&wwyy	1r*   c                 "   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   s      r(   add_or_replace_onezCollection.add_or_replace_one2  s     C<<CJ&00"#   #u%% 	**Cxx(())0066>>@@@r*   c                     |                      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_oner$   fetch_active_result)r%   r   resultr   s       r(   get_onezCollection.get_oneC  s\     ;'',,T6::BBDD  ,,...
r*   c                 x    |                      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   )r%   r   s     r(   
remove_onezCollection.remove_oneQ  s2     {{;'',,T6::BBDDDr*   r   )r@   rA   rB   rC   r;   r   r   r   r   r   r   r   r   r   r   r   rE   r*   r(   rY   rY     s         = = =	 	 	 		/ 	/ 	/  "  "  $M M M0	G 	G 	G1 1 1 A A A"  	E 	E 	E 	E 	Er*   rY   c                   <    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	S )
rh   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.
    c                     t                               t          | j        j                  t          | j                            }| j                            |          dk    S rL   r   rP   s     r(   r;   zTable.exists_in_databaseh  r   r*   c                 \    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   r$   r   r   r%   r   r   s      r(   selectzTable.selectr  4     t-f---'==??r*   c                 \    t          | g|R  }| j                                        |_        |S )zCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r   r$   r   r   r   s      r(   insertzTable.insert  r   r*   c                 `    t          |           }| j                                        |_        |S )zCreates a new :class:`mysqlx.UpdateStatement` object.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r$   r   r   r%   r   s     r(   updatezTable.update  s,     t$$'==??r*   c                 `    t          |           }| j                                        |_        |S )zCreates 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   s     r(   deletezTable.delete  s,     t$$'==??r*   c                 p   t                               t          | j        j                  t          | j                            }	 | j                            |          }nU# t          $ rH}|j	        t          k    r2t          d                    | j        | j        j                             d}~ww xY w|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   s       r(   r   zTable.count  r   r   c                     t                               t          | j        j                  t          | j                            }| j                            |          dk    S )zDetermine if the underlying object is a view or not.

        Returns:
            bool: `True` if the underlying object is a view.
        r   _COUNT_VIEWS_QUERYrN   r   r   r'   r    r$   rO   rP   s     r(   is_viewzTable.is_view  Q     !''t|/@(A(A(.tz(:(:< <223771<<r*   N)r@   rA   rB   rC   r;   r   r   r   r   r   r   rE   r*   r(   rh   rh   ]  s         = = =          $= = = = =r*   rh   c                       e Zd ZdZd ZdS )ro   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.
    c                     t                               t          | j        j                  t          | j                            }| j                            |          dk    S rL   r   rP   s     r(   r;   zView.exists_in_database  r   r*   N)r@   rA   rB   rC   r;   rE   r*   r(   ro   ro     s-         = = = = =r*   ro   )'rC   r   r   dbdocr   	errorcoder   r   r   r   errorsr	   r
   r   helpersr   r   r   	statementr   r   r   r   r   r   r   r   r   r   r   rM   r   rv   objectr   rG   rY   rh   ro   rE   r*   r(   <module>r      sP  : 3 2        L L L L L L L L L L L L I I I I I I I I I I 9 9 9 9 9 9 9 9 9 98 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8J K 4 -2 c c c c cV c c cLC7 C7 C7 C7 C7^ C7 C7 C7LwE wE wE wE wE wE wE wEt`= `= `= `= `=N `= `= `=F= = = = =5 = = = = =r*   