
    BR<ig                    d   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rddl*m+Z+ dZ,dZ-dZ.dZ/dZ0 G d d      Z1 G d de1      Z2 G d de1      Z3 G d de1      Z4 G d de4      Z5y)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                      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y)DatabaseObjectzProvides base functionality for database objects.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The database object name.
    c                    || _         t        |t              r|j                         n|| _        | j                   j                         | _        | j                  j                         | _        y N)	_schema
isinstancebytesdecode_nameget_session_sessionget_connection_connection)selfschemanames      L/var/www/html/delta-backend/venv/lib/python3.12/site-packages/mysqlx/crud.py__init__zDatabaseObject.__init__V   sJ    #)+5dE+B$++-
%)\\%=%=%?+/==+G+G+I    c                    | j                   S )z,:class:`mysqlx.Session`: The Session object.r.   r1   s    r4   sessionzDatabaseObject.session\   s     }}r6   c                    | j                   S )z*:class:`mysqlx.Schema`: The Schema object.r(   r9   s    r4   r2   zDatabaseObject.schemaa   s     ||r6   c                    | j                   S )z&str: The name of this database object.r,   r9   s    r4   r3   zDatabaseObject.namef   s     zzr6   c                    | j                   S )z~Returns the underlying connection.

        Returns:
            mysqlx.connection.Connection: The connection object.
        )r0   r9   s    r4   r/   zDatabaseObject.get_connectionk   s     r6   c                    | j                   S )zwReturns the session of this database object.

        Returns:
            mysqlx.Session: The Session object.
        r8   r9   s    r4   r-   zDatabaseObject.get_sessions   s     }}r6   c                    | j                   S )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r<   r9   s    r4   
get_schemazDatabaseObject.get_schema{   s     ||r6   c                    | j                   S )zwReturns the name of this database object.

        Returns:
            str: The name of this database object.
        r>   r9   s    r4   get_namezDatabaseObject.get_name   s     zzr6   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.
        )NotImplementedErrorr9   s    r4   exists_in_databasez!DatabaseObject.exists_in_database   s
     "!r6   z8.0.12z)Use 'exists_in_database()' method insteadc                "    | j                         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.
        )rG   r9   s    r4   	am_i_realzDatabaseObject.am_i_real   s     &&((r6   zUse 'get_name()' method insteadc                "    | j                         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.
        )rD   r9   s    r4   who_am_izDatabaseObject.who_am_i   s     }}r6   N)r2   r    r3   r"   returnNone)rL   r!   )rL   r    )rL   str)rL   r   )rL   r   )__name__
__module____qualname____doc__r5   propertyr:   r2   r3   r/   r-   rB   rD   rG   r   rI   rK    r6   r4   r%   r%   N   s    J       	" EF) G) ;<	 =	r6   r%   c                       e Zd ZdZd f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 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                4    || _         t        | 	  | |       y r'   )r.   superr5   )r1   r:   r3   	__class__s      r4   r5   zSchema.__init__   s    %,t$r6   c                    t         j                  t        | j                              }| 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,   r0   execute_sql_scalarr1   sqls     r4   rG   zSchema.exists_in_database   s9     #))&*<=22371<<r6   c                   | j                   j                  dd| j                  i      }|j                          g }|D ],  }|d   dk7  r	 t	        | |d         }|j                  |       . |S # t
        $ r t	        | |d         }Y /w xY w)zyReturns a list of collections for this schema.

        Returns:
            `list`: List of Collection objects.
        list_objectsr2   type
COLLECTION
TABLE_NAMEr3   )r0   get_row_resultr,   	fetch_all
Collection
ValueErrorappend)r1   rowscollectionsrow
collections        r4   get_collectionszSchema.get_collections   s     ..~$**?UV 	+C6{l*;'c,.?@
 z*	+   ;'c&k:
;s   
A..B	B	c                &    | j                  ||      S )zuReturns a a table object for the given collection

        Returns:
            mysqlx.Table: Table object.

        )	get_table)r1   r3   check_existences      r4   get_collection_as_tablezSchema.get_collection_as_table   s     ~~dO44r6   c                   | j                   j                  dd| j                  i      }|j                          g }d}|D ]+  }|d   |v s	 t	        | |d         }|j                  |       - |S # t
        $ r t	        | |d         }Y /w xY w)zoReturns a list of tables for this schema.

        Returns:
            `list`: List of Table objects.
        rb   r2   )TABLEVIEWrc   re   r3   )r0   rf   r,   rg   Tableri   rj   )r1   rk   tablesobject_typesrm   tables         r4   
get_tableszSchema.get_tables   s     ..~$**?UV
  	%C6{l*5!$L(9:E e$	%  " 5!$F4E5s   A//B
	B
c                X    t        | |      }|r|j                         st        d      |S )zwReturns the table of the given name for this schema.

        Returns:
            mysqlx.Table: Table object.
        zTable does not exist)rw   rG   r   )r1   r3   rr   rz   s       r4   rq   zSchema.get_table   s0     dD!++-&'=>>r6   c                X    t        | |      }|r|j                         st        d      |S )ztReturns the view of the given name for this schema.

        Returns:
            mysqlx.View: View object.
        zView does not exist)ViewrG   r   )r1   r3   rr   views       r4   get_viewzSchema.get_view  s0     D$**,&'<==r6   c                X    t        | |      }|r|j                         st        d      |S )zReturns the collection of the given name for this schema.

        Returns:
            mysqlx.Collection: Collection object.
        zCollection does not exist)rh   rG   r   )r1   r3   rr   rn   s       r4   get_collectionzSchema.get_collection  s1      d+
002&'BCCr6   c           	         | j                   j                  dt        j                  t	        | j
                        t	        |            d       y)zmDrops a collection.

        Args:
            name (str): The name of the collection to be dropped.
        r`   FN)r0   execute_nonquery_DROP_TABLE_QUERYr]   r   r,   )r1   r3   s     r4   drop_collectionzSchema.drop_collection   sB     	))$$ ,.>t.D 	
r6   c                   |st        d      d|v rt        j                  dt               |d   }t	        | |      }| j
                  |d}|t        |t              r|st        d      d}|D ]  }||vst        d|        g }	d	|v r3|d	   }
t        |
t              st        d
      |	j                  d	|
f       d|v r^|d   }t        |t        t        f      st        d      |	j                  dt        |t              rt        j                  |      n|f       d|	f|d<   	 | j                  j                  ddd|       |S # t        $ rp}|j                  t         k(  rt#        d      ||j                  t$        k(  r|s1t        d| d      |t        |j&                  |j                        |Y d}~|S d}~ww xY 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)r2   r3   NInvalid value for 'validation'levelr2    Invalid option in 'validation': r   Invalid value for 'level'r2   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 versionCollection 'z' already exists)r   warningswarnDeprecationWarningrh   r,   r)   dictrN   rj   jsondumpsr0   r   r   errnor   r   r   msg)r1   r3   reuse_existingr   kwargsrn   fieldsvalid_optionsoptionr   r   r2   errs                r4   r   zSchema.create_collection.  s   < "#?@@fMM6"
 $G_Nd+
,0JJ!E!j$/z&'GHH/M$ X.*-MfX+VWWX G*$"7+!%-*+FGG/0:%#H-!&3+6*+GHH .8.F

6*F ".w 7F9	D---tV$    	Dyy22' 	
 yy11%*&tf,<= 'sww		:C & 	Ds   )E	 		GA%F==Gc                   |st        d      t        |t              r|st        d      d}|D ]  }||vst        d|        g }d|v r3|d   }t        |t              st        d      |j	                  d|f       d|v r^|d   }t        |t        t        f      st        d      |j	                  dt        |t              rt        j                  |      n|f       | j                  |d	|fd
}	 | j                  j                  ddd|       y# t        $ rE}	|	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
        r   r   r   r   r   r   r2   r   r   )r2   r3   r   r   modify_collection_optionsTr   N)r   r)   r   rN   rj   r   r   r,   r0   r   r   r   r   r   r   )
r1   r3   r   r   r   r   r   r2   r   r   s
             r4   modify_collectionzSchema.modify_collection  s   ( "#?@@*d+:"#CDD+  	TF]*&)I&'RSS	T j w'EeS)&'BCCNNGU+,z!)FfsDk2&'CDDNN*4VT*BDJJv& jj$g.
	@--5tV   	@yy66' 	
 #377CII6C?	@s   4D 	E!A EE!)r:   r!   r3   rN   rL   rM   rL   bool)rL   zList[Collection])F)r3   rN   rr   r   rL   rw   )rL   zList[Table])r3   rN   rr   r   rL   r~   )r3   rN   rr   r   rL   rh   )r3   rN   rL   rM   )FN)
r3   rN   r   r   r   %Optional[Dict[str, Union[str, Dict]]]r   r   rL   rh   r'   )r3   rN   r   r   rL   rM   )rO   rP   rQ   rR   r5   rG   ro   rs   r{   rq   r   r   r   r   r   __classcell__)rY   s   @r4   rV   rV      s    %=( 27	5	5*.	5		5,



"  %<@	]] ] :	]
 ] 
]@ NRB@B@%JB@	B@r6   rV   c                  ~    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y)rh   zRepresents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    c                    t         j                  t        | j                  j                        t        | j
                              }| j                  j                  |      dk(  S r[   _COUNT_TABLES_QUERYr]   r   r(   r3   r,   r0   r^   r_   s     r4   rG   zCollection.exists_in_database  J     "((0A0A)BF4::DVW22371<<r6   Nc                \    t        | |      }| j                  j                         |_        |S )zRetrieves documents from a collection.

        Args:
            condition (Optional[str]): The string with the filter expression of
                                       the documents to be retrieved.
        )r   r0   get_next_statement_idstmt_idr1   	conditionstmts      r4   findzCollection.find  s+     T9-''==?r6   c                2     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)r1   valuess     r4   r   zCollection.add  s     &|D!%%v..r6   c                \    t        | |      }| j                  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   r0   r   r   r   s      r4   removezCollection.remove  +     tY/''==?r6   c                \    t        | |      }| j                  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   r0   r   r   r   s      r4   modifyzCollection.modify
  r   r6   c                v   t         j                  t        | j                  j                        t        | j
                              }	 | j                  j                  |      }|S # t        $ rJ}|j                  t        k(  r1t        d| j
                   d| j                  j                   d      | d}~ww xY 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_QUERYr]   r   r(   r3   r,   r0   r^   r   r   r   r1   r`   resr   s       r4   countzCollection.count  s     !!T\\../1A$**1M
	""55c:C 
   	yy,,&"4::, /))*!-  	   A% %	B8.AB33B8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   )r1   
index_namefields_descs      r4   create_indexzCollection.create_index/  s    0 .dJLLr6   c           	         | j                   j                  ddd| j                  j                  | j                  |d       y)z[Drops a collection index.

        Args:
            index_name (str): Index name.
        r   drop_collection_indexF)r2   rn   r3   N)r0   r   r(   r3   r,   )r1   r   s     r4   
drop_indexzCollection.drop_indexI  s=     	))#,,++"jj"			
r6   c                    d|v r|d   |k7  rt        d      | j                  d      j                  d|      j                  d|      j	                         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r1   doc_iddocs      r4   replace_onezCollection.replace_oneZ  s\     C<CJ&0"#  {{;'++C5::4HPPRRr6   c                    d|v r|d   |k7  rt        d      t        |t              st        |      }| j                  |j	                  |            j                  d      j                         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      r4   add_or_replace_onezCollection.add_or_replace_onei  si     C<CJ&0"#  #u%*Cxx()006>>@@r6   c                    | j                  d      j                  d|      j                         }|j                         }| j                  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_oner0   fetch_active_result)r1   r   resultr   s       r4   get_onezCollection.get_onez  sM     ;',,T6:BBD ,,.
r6   c                `    | j                  d      j                  d|      j                         S )zRemoves a Document matching the Document ID.

        Args:
            doc_id (str): Document ID

        Returns:
            mysqlx.Result: Result object.
        r   r   )r   r   r   )r1   r   s     r4   
remove_onezCollection.remove_one  s)     {{;',,T6:BBDDr6   r   r'   )r   zOptional[str]rL   r   )r   r   rL   r   )r   rN   rL   r   )r   rN   rL   r   rL   int)r   rN   r   zDict[str, Any]rL   r   )r   rN   rL   rM   )r   rN   r   zUnion[Dict, DbDoc]rL   'Result')r   rN   rL   r   )r   rN   rL   r   )rO   rP   rQ   rR   rG   r   r   r   r   r   r   r   r   r   r   r   rT   r6   r4   rh   rh     sb    =		/""(MM,:M	'M4
"SA"	Er6   rh   c                  H    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
y	)rw   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         j                  t        | j                  j                        t        | j
                              }| j                  j                  |      dk(  S r[   r   r_   s     r4   rG   zTable.exists_in_database  r   r6   c                \    t        | g| }| j                  j                         |_        |S )zCreates a new :class:`mysqlx.SelectStatement` object.

        Args:
            *fields: The fields to be retrieved.

        Returns:
            mysqlx.SelectStatement: SelectStatement object
        )r   r0   r   r   r1   r   r   s      r4   selectzTable.select  .     t-f-''==?r6   c                \    t        | g| }| j                  j                         |_        |S )zCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r   r0   r   r   r   s      r4   insertzTable.insert  r   r6   c                Z    t        |       }| j                  j                         |_        |S )zCreates a new :class:`mysqlx.UpdateStatement` object.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r0   r   r   r1   r   s     r4   updatezTable.update  s)     t$''==?r6   c                Z    t        |       }| j                  j                         |_        |S )zCreates a new :class:`mysqlx.DeleteStatement` object.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object

        .. versionchanged:: 8.0.12
           The ``condition`` parameter was removed.
        )r   r0   r   r   r   s     r4   deletezTable.delete  s)     t$''==?r6   c                v   t         j                  t        | j                  j                        t        | j
                              }	 | j                  j                  |      }|S # t        $ rJ}|j                  t        k(  r1t        d| j
                   d| j                  j                   d      | d}~ww xY w)ziCounts the rows in the table.

        Returns:
            int: The total of rows in the table.
        zTable 'r   r   Nr   r   s       r4   r   zTable.count  s     !!T\\../1A$**1M
	""55c:C 
   	yy,,&djj\ *))*!-  	r   c                    t         j                  t        | j                  j                        t        | j
                              }| 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_QUERYr]   r   r(   r3   r,   r0   r^   r_   s     r4   is_viewzTable.is_view  J     !''t||/@/@(A6$**CUV22371<<r6   Nr   )r   rN   rL   r   )r   r   rL   r   )rL   r   )rL   r   r   )rO   rP   rQ   rR   rG   r   r   r   r   r   r   rT   r6   r4   rw   rw     s*    =(=r6   rw   c                      e Zd ZdZddZy)r~   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         j                  t        | j                  j                        t        | j
                              }| j                  j                  |      dk(  S r[   r   r_   s     r4   rG   zView.exists_in_database  r   r6   Nr   )rO   rP   rQ   rR   rG   rT   r6   r4   r~   r~     s    =r6   r~   )6rR   
__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   r\   r   r   r%   rV   rh   rw   r~   rT   r6   r4   <module>r     s   : 3 "   B B   J I 9 9
 
 
 G F8 
8 
 Q  .2 a aH]@^ ]@@	E ED`=N `=F=5 =r6   