
    DhB                         d Z ddlmZ ddlmZmZmZmZ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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y)z,Implementation of the CRUD database objects.   )ProgrammingError)FindStatementAddStatementRemoveStatementModifyStatementSelectStatementInsertStatementDeleteStatementUpdateStatementCreateCollectionIndexStatementDropCollectionIndexStatementCreateViewStatementAlterViewStatementCreateTableStatementz_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}'zMSELECT COUNT(*) FROM information_schema.schemata WHERE schema_name like '{0}'z SELECT COUNT(*) FROM `{0}`.`{1}`z DROP TABLE IF EXISTS `{0}`.`{1}`zDROP VIEW IF EXISTS `{0}`.`{1}`c                   T    e Zd ZdZd Zed        Zed        Zd Zd Z	d Z
d Zd	 Zy
)DatabaseObjectzProvides base functionality for database objects.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The database object name.
    c                 r    || _         || _        | j                   j                         j                  | _        y N)_schema_nameget_session_connection)selfschemanames      K/var/www/html/civilisation/venv/lib/python3.12/site-packages/mysqlx/crud.py__init__zDatabaseObject.__init__5   s+    
<<335AA    c                     | j                   S )z3:class:`mysqlx.Schema`: The Schema object.
        r   r   s    r   r   zDatabaseObject.schema:   s     ||r   c                     | j                   S )z/str: The name of this database object.
        r   r!   s    r   r   zDatabaseObject.name@   s     zzr   c                     | j                   S )z{Returns the Schema object of this database object.

        Returns:
            mysqlx.Schema: The Schema object.
        r    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.
        r#   r!   s    r   get_namezDatabaseObject.get_nameN   s     zz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   c                 "    | j                         S r   )r*   r!   s    r   	am_i_realzDatabaseObject.am_i_reala   s    &&((r   c                 "    | j                         S r   )r'   r!   s    r   who_am_izDatabaseObject.who_am_id   s    }}r   N)__name__
__module____qualname____doc__r   propertyr   r   r%   r'   r*   r,   r.    r   r   r   r   .   sN    B
  
  
	")r   r   c                        e Zd ZdZ fdZd Zd Zd ZddZd Z	ddZ
dd	Zdd
Zd Zd Zd ZddZddZ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                 <    || _         t        t        |   | |       y r   )_sessionsuperr6   r   )r   sessionr   	__class__s      r   r   zSchema.__init__p   s    fd$T40r   c                 |    t         j                  | 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   execute_sql_scalarr   sqls     r   r*   zSchema.exists_in_databaset   s4     #))$**522371<<r   c                     | j                   S )zuReturns the session of this Schema object.

        Returns:
            mysqlx.Session: The Session object.
        )r8   r!   s    r   r   zSchema.get_session}   s     }}r   c                 \   | j                   j                  d| j                        }|j                          g }|D ]D  }|j	                  d      dk7  r	 t        | |j	                  d            }|j                  |       F |S # t        $ r t        | |j	                  d            }Y ;w xY w)zwReturns 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
get_string
Collection
ValueErrorappend)r   rowscollectionsrow
collections        r   get_collectionszSchema.get_collections   s     ..~tzzJ 	+C~~f%5F'cnn\.JK
 z*	+   F'cnnV.DE
Fs   B$B+*B+c                 &    | j                  ||      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4r   c                 ^   | j                   j                  d| j                        }|j                          g }d}|D ]C  }|j	                  d      |v s	 t        | |j	                  d            }|j                  |       E |S # t        $ r t        | |j	                  d            }Y ;w xY w)zmReturns a list of tables for this schema.

        Returns:
            list: List of Table objects.
        rE   )TABLEVIEWrF   rH   r   )r   rI   r   rJ   rK   TablerM   rN   )r   rO   tablesobject_typesrQ   tables         r   
get_tableszSchema.get_tables   s     ..~tzzJ) 	%C~~f%5@!$|(DEE e$	%  " @!$v(>?E@s   B$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)r[   r*   r   )r   r   rV   r^   s       r   rU   zSchema.get_table   s0     dD!++-&'=>>r   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)Viewr*   r   )r   r   rV   views       r   get_viewzSchema.get_view   s0     D$**,&'<==r   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)rL   r*   r   )r   r   rV   rR   s       r   get_collectionzSchema.get_collection   s1      d+
002&'BCCr   c                 z    | j                   j                  dt        j                  | j                  |      d       y)zmDrops a collection.

        Args:
            name (str): The name of the collection to be dropped.
        rB   FN)r   execute_nonquery_DROP_TABLE_QUERYr?   r   r   r   s     r   drop_collectionzSchema.drop_collection   s2     	))$++DJJ=u	Fr   c                     t        | |      }|j                         r| j                  |       y| j                  j	                  dt
        j                  | j                  |      d       y)zcDrops a table.

        Args:
            name (str): The name of the table to be dropped.
        rB   FN)r[   is_view	drop_viewr   rh   ri   r?   r   )r   r   r^   s      r   
drop_tablezSchema.drop_table   sS     dD!==?NN4 --(//

DA5Jr   c                 z    | j                   j                  dt        j                  | j                  |      d       y)zaDrops a view.

        Args:
            name (str): The name of the view to be dropped.
        rB   FN)r   rh   _DROP_VIEW_QUERYr?   r   rj   s     r   rn   zSchema.drop_view   s2     	))#**4::t<e	Er   c                     |st        d      t        | |      }|j                         s+| j                  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:
            ProgrammingError: If ``reuse`` is False and collection exists.
        zCollection name is invalidxplugincreate_collectionTzCollection already exists)r   rL   r*   r   rh   r   )r   r   reuserR   s       r   rt   zSchema.create_collection   so     "#?@@d+
,,.--i9L.2DJJF  "#>??r   c                 <    t        | |      }|j                  |      S )aA  Creates in the current schema a new view with the specified name
        and retrieves an object representing the new view created.

        Args:
            name (string): The name of the view.
            replace (Optional[bool]): `True` to add replace.

        Returns:
            mysqlx.View: View object.
        )rb   get_create_statement)r   r   replacerc   s       r   create_viewzSchema.create_view  s!     D$((11r   c                 :    t        | |      }|j                         S )zAlters a view in the current schema with the specified name and
        retrieves an object representing the view.

        Args:
            name (string): The name of the view.

        Returns:
            mysqlx.View: View object.
        )rb   get_alter_statement)r   r   rc   s      r   
alter_viewzSchema.alter_view  s     D$''))r   c                     |st        d      t        | |      }|j                         st        | |      S |st        d      |S )NzTable name is invalidzTable already exists)r   r[   r*   r   )r   r   ru   r^   s       r   create_tablezSchema.create_table*  sJ    "#:;;dD!'')'d33"#9::r   F)r/   r0   r1   r2   r   r*   r   rS   rW   r_   rU   rd   rf   rk   ro   rn   rt   ry   r|   r~   __classcell__r;   s   @r   r6   r6   h   s[    1=&5&


FJE02*r   r6   c                   ^     e Zd ZdZ fdZd ZddZd Zd ZddZ	ddZ
d	 Zd
 Zd Z xZS )rL   zRepresents a collection of documents on a schema.

    Args:
        schema (mysqlx.Schema): The Schema object.
        name (str): The collection name.
    c                 .    t         t        |   ||       y r   )r9   rL   r   r   r   r   r;   s      r   r   zCollection.__init__<  s    j$(6r   c                     t         j                  | j                  j                         | j                        }| j
                  j                  |      dk(  S r=   )_COUNT_TABLES_QUERYr?   r   r'   r   r   r@   rA   s     r   r*   zCollection.exists_in_database?  sC     "(()>)>)@$**M22371<<r   c                     t        | |      S )zRetrieves documents from a collection.

        Args:
            condition (Optional[str]): The string with the filter expression of
                                       the documents to be retrieved.
        )r   r   	conditions     r   findzCollection.findH  s     T9--r   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)r   valuess     r   r   zCollection.addQ  s     &|D!%%v..r   c                 B    | j                  dj                  |            S )zRemoves document by ID.

        Args:
            id (str): The document ID.

        Returns:
            mysqlx.RemoveStatement: RemoveStatement object.
        z_id = '{0}')remover?   )r   ids     r   
remove_onezCollection.remove_one\  s     {{=//344r   c                 B    t        |       }|r|j                  |       |S )a'  Removes documents based on the ``condition``.

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

        Returns:
            mysqlx.RemoveStatement: RemoveStatement object.
        )r   where)r   r   rss      r   r   zCollection.removeg  s"     T"HHY	r   c                     t        | |      S )a)  Modifies documents based on the ``condition``.

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

        Returns:
            mysqlx.ModifyStatement: ModifyStatement object.
        )r   r   s     r   modifyzCollection.modifyv       tY//r   c                     t         j                  | j                  j                  | j                        }| j
                  j                  |      S )z}Counts the documents in the collection.

        Returns:
            int: The total of documents in the collection.
        _COUNT_QUERYr?   r   r   r   r   r@   rA   s     r   countzCollection.count  ;     !!$,,"3"3TZZ@22377r   c                     t        | ||      S )zCreates a collection index.

        Args:
            index_name (str): Index name.
            is_unique (bool): `True` if the index is unique.
        )r   )r   
index_name	is_uniques      r   create_indexzCollection.create_index  s     .dJ	JJr   c                     t        | |      S )z[Drops a collection index.

        Args:
            index_name (str): Index name.
        )r   )r   r   s     r   
drop_indexzCollection.drop_index  s     ,D*==r   r   )r/   r0   r1   r2   r   r*   r   r   r   r   r   r   r   r   r   r   s   @r   rL   rL   5  s;    7=.	/	5
08K>r   rL   c                   N     e Zd ZdZ fdZd Zd Zd Zd Zd
dZ	d Z
d	 Z xZS )r[   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        |   ||       y r   )r9   r[   r   r   s      r   r   zTable.__init__  s    eT#FD1r   c                     t         j                  | j                  j                  | j                        }| j
                  j                  |      dk(  S r=   )r   r?   r   r   r   r   r@   rA   s     r   r*   zTable.exists_in_database  s@     "(():):DJJG22371<<r   c                     t        | g| S )zCreates a new :class:`mysqlx.SelectStatement` object.

        Args:
            *fields: The fields to be retrieved.

        Returns:
            mysqlx.SelectStatement: SelectStatement object
        )r   r   fieldss     r   selectzTable.select       t-f--r   c                     t        | g| S )zCreates a new :class:`mysqlx.InsertStatement` object.

        Args:
            *fields: The fields to be inserted.

        Returns:
            mysqlx.InsertStatement: InsertStatement object
        )r	   r   s     r   insertzTable.insert  r   r   c                     t        |       S )zCreates a new :class:`mysqlx.UpdateStatement` object.

        Args:
            *fields: The fields to update.

        Returns:
            mysqlx.UpdateStatement: UpdateStatement object
        )r   r!   s    r   updatezTable.update  s     t$$r   c                     t        | |      S )a)  Creates a new :class:`mysqlx.DeleteStatement` object.

        Args:
            condition (Optional[str]): The string with the filter expression of
                                       the rows to be deleted.

        Returns:
            mysqlx.DeleteStatement: DeleteStatement object
        )r
   r   s     r   deletezTable.delete  r   r   c                     t         j                  | j                  j                  | j                        }| j
                  j                  |      S )ziCounts the rows in the table.

        Returns:
            int: The total of rows in the table.
        r   rA   s     r   r   zTable.count  r   r   c                     t         j                  | j                  j                         | 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'   r   r   r@   rA   s     r   rm   zTable.is_view  sC     !''(=(=(?L22371<<r   r   )r/   r0   r1   r2   r   r*   r   r   r   r   r   rm   r   r   s   @r   r[   r[     s0    2=	.	.	%
08=r   r[   c                   6     e Zd ZdZ fdZd ZddZd Z xZS )rb   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        |   ||       y r   )r9   rb   r   r   s      r   r   zView.__init__  s    dD"640r   c                     t         j                  | j                  j                  | j                        }| j
                  j                  |      dk(  S r=   )r   r?   r   r   r   r   r@   rA   s     r   r*   zView.exists_in_database   s@     !''(9(94::F22371<<r   c                     t        | |      S )zCreates a new :class:`mysqlx.CreateViewStatement` object.

        Args:
            replace (Optional[bool]): `True` to add replace.

        Returns:
            mysqlx.CreateViewStatement: CreateViewStatement object.
        )r   )r   rx   s     r   rw   zView.get_create_statement	  s     #411r   c                     t        |       S )zCreates a new :class:`mysqlx.AlterViewStatement` object.

        Returns:
            mysqlx.AlterViewStatement: AlterViewStatement object.
        )r   r!   s    r   r{   zView.get_alter_statement  s     "$''r   r   )	r/   r0   r1   r2   r   r*   rw   r{   r   r   s   @r   rb   rb     s    1=	2(r   rb   N)r2   errorsr   	statementr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r>   r   ri   rq   objectr   r6   rL   r[   rb   r4   r   r   <module>r      s   0 3 $B B B BJ K 7 16 4 7V 7tJ^ JZe> e>PS=N S=l'(5 '(r   