o
    NDi7                     @   s<  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mZ d dlmZ d dlmZ eeZeZdadae Zi ZeeZd&ddZG d	d
 d
eZG dd deZ			d'ddZ dd Z!dd Z"d(ddZ#dd Z$dd Z%			d)ddZ&ddedfddZ'd(ddZ(d(d d!Z)d(d"d#Z*d$d% Z+dS )*    )defaultdictN)Cluster_ConfigMode_NOT_SETNoHostAvailableUserTypeDoesNotExistConsistencyLevel)SimpleStatementdict_factory)CQLEngineException)BaseCQLStatementc                 C   s.   |pd}|rd ||| } | S d || } | S )z9Format log message to add keyspace and connection contextDEFAULT_CONNECTIONz$[Connection: {0}, Keyspace: {1}] {2}z[Connection: {0}] {1})format)msg
connectionkeyspaceconnection_info r   W/var/www/Datamplify/venv/lib/python3.10/site-packages/cassandra/cqlengine/connection.pyformat_log_context+   s   r   c                   @   s   e Zd ZdS )UndefinedKeyspaceExceptionN)__name__
__module____qualname__r   r   r   r   r   6   s    r   c                   @   sf   e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZ		dddZedd Zdd	 Zd
d Zdd ZdS )
ConnectionzCQLEngine ConnectionNFc                 C   s:   || _ || _|| _|| _|| _|r|ni | _t | _d S N)	hostsnameconsistencylazy_connectretry_connectcluster_options	threadingRLocklazy_connect_lock)selfr   r   r   r   r    r!   r   r   r   __init__I   s   zConnection.__init__c                 C   s*   | ||j d}|j||_|_|  |S )N)r   r   )r   clustersessionsetup_session)clsr   r(   instancer   r   r   from_sessionS   s   zConnection.from_sessionc              	   C   s   d| j v s
d| j v rtd| jrdS d| j v r,| jr"td| j tdi | j | _nt| jfi | j | _z| j | _	t
td| jd W n tya   | jr`ttd	| jd d
| _ w ttv rvtt | krvtt jatt j	a	|   dS )zSetup the connectionusernamepasswordzNUsername & Password are now handled by using the native driver's auth_providerNcloudz6Ignoring hosts %s because a cloud config was provided.z6connection initialized with internally created sessionr   z6connect failed, setting up for re-attempt on first useTr   )r!   r   r   r   logwarningr   r'   connectr(   debugr   r   r   r    r   _connectionsr)   r%   r   r   r   setupZ   s,   


zConnection.setupc                 C   st   | j jtjkrt| j jj_| jd ur| j| j jj_	nt| j
_| jd ur(| j| j
_| j
j}|j|jt< t| j
j  d S r   )r'   _config_moder   PROFILESr
   profile_managerdefaultrow_factoryr   consistency_levelr(   default_consistency_levelencodercql_encode_tuplemappingtuple_register_known_types)r%   encr   r   r   r)   z   s   


zConnection.setup_sessionc                 C   sn   | j sd S | j% | j r%ttd| jd d| _ |   W d    d S W d    d S 1 s0w   Y  d S )NzLazy connect enabledr0   F)r   r$   r1   r4   r   r   r7   r6   r   r   r   handle_lazy_connect   s   
"zConnection.handle_lazy_connect)NFFN)r   r   r   __doc__r   r   r   r    r   r$   r!   r'   r(   r&   classmethodr,   r7   r)   rE   r   r   r   r   r   :   s&    


 r   Fc           
      C   s   | t v rtd|  |dur2|dup#|dup#|dup#|dup#|du}|r*tdtj| |d}	nt| |||||d}	|	  |	t | < |rJt|  |	S )a  
    Add a connection to the connection registry. ``hosts`` and ``session`` are
    mutually exclusive, and ``consistency``, ``lazy_connect``,
    ``retry_connect``, and ``cluster_options`` only work with ``hosts``. Using
    ``hosts`` will create a new :class:`cassandra.cluster.Cluster` and
    :class:`cassandra.cluster.Session`.

    :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`).
    :param int consistency: The default :class:`~.ConsistencyLevel` for the
        registered connection's new session. Default is the same as
        :attr:`.Session.default_consistency_level`. For use with ``hosts`` only;
        will fail when used with ``session``.
    :param bool lazy_connect: True if should not connect until first use. For
        use with ``hosts`` only; will fail when used with ``session``.
    :param bool retry_connect: True if we should retry to connect even if there
        was a connection failure initially. For use with ``hosts`` only; will
        fail when used with ``session``.
    :param dict cluster_options: A dict of options to be used as keyword
        arguments to :class:`cassandra.cluster.Cluster`. For use with ``hosts``
        only; will fail when used with ``session``.
    :param bool default: If True, set the new connection as the cqlengine
        default
    :param Session session: A :class:`cassandra.cluster.Session` to be used in
        the created connection.
    z4Registering connection '{0}' when it already exists.NFzMSession configuration arguments and 'session' argument are mutually exclusive)r(   )r   r   r   r    r!   )	r5   r1   r2   r   r   r   r,   r7   set_default_connection)
r   r   r   r   r    r!   r;   r(   invalid_config_argsconnr   r   r   register_connection   s6   rK   c                 C   sd   | t vrd S tt v rt |  t t krt t= d ad at |  }|jr%|j  t | = td|  d S )Nz4Connection '{0}' has been removed from the registry.)r5   r   r'   r(   shutdownr1   r4   r   r   rJ   r   r   r   unregister_connection   s   
rN   c                 C   sJ   | t vrtd| td|  t |  t t< t |  jat |  jad S )NzConnection '{0}' doesn't exist.z)Connection '{0}' has been set as default.)r5   r   r   r1   r4   r   r'   r(   )r   r   r   r   rH      s   
rH   c                 C   s2   | st } | tvrtd| t|  }|  |S )Nz4Connection name '{0}' doesn't exist in the registry.)r   r5   r   r   rE   rM   r   r   r   get_connection   s   rO   c                  C   s@   zt  } | jrtd W n   Y tdddd td dS )zp
    Configures the default connection to localhost, using the driver defaults
    (except for row_factory)
    zIconfiguring new default connection for cqlengine when one was already setr;   NT)r   r;   zBcqlengine connection initialized with default session to localhost)rO   r(   r1   r2   rK   r4   )rJ   r   r   r   r;      s   
r;   c                 C   s   zt  }W n ty   td| dd t  }Y n	w |jr!td t| jjj	j
tu o3| jjtjtjfv | j
tu oA| jjtjtjfv gsHtd| |_| j|_|jjr^ddlm} |jj|_|  td|  d	S )
z
    Configures the default connection with a preexisting :class:`cassandra.cluster.Session`

    Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``.
    This may be relaxed in the future
    r;   T)r(   r;   zFconfiguring new default session for cqlengine when one was already setz8Failed to initialize: row_factory must be 'dict_factory'r   modelsz0cqlengine default connection initialized with %sN)rO   r   rK   r(   r1   r2   anyr'   r:   r;   r<   r
   r8   r   r9   UNCOMMITTEDLEGACYr   cassandra.cqlenginerQ   DEFAULT_KEYSPACEr)   r4   )srJ   rQ   r   r   r   set_session  s(   


"
rX   c              	   K   s,   ddl m} ||_td| ||||dd dS )a~  
    Setup a the driver connection used by the mapper

    :param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`)
    :param str default_keyspace: The default keyspace to use
    :param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level`
    :param bool lazy_connect: True if should not connect until first use
    :param bool retry_connect: True if we should retry to connect even if there was a connection failure initially
    :param kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster`
    r   rP   r;   T)r   r   r   r    r!   r;   N)rU   rQ   rV   rK   )r   default_keyspacer   r   r    kwargsrQ   r   r   r   r7   7  s
   

r7   c                 C   s   t |}|jstdt| trnt| tr%|  }tt| || jd} nt| tr0t| |d} t	
td| j||d |jj| ||d}|S )Nz<It is required to setup() cqlengine before executing queries)r=   
fetch_size)r=   zQuery: {}, Params: {}r0   )timeout)rO   r(   r   
isinstancer	   r   get_contextstrr[   r1   r4   r   r   query_stringexecute)queryparamsr=   r\   r   rJ   resultr   r   r   ra   P  s   


ra   c                 C   s   t | }|jS r   )rO   r(   r   rJ   r   r   r   get_sessione  s   rf   c                 C   s    t | }|jstdt |jS )NzO%s.cluster is not configured. Call one of the setup or default functions first.)rO   r'   r   r   re   r   r   r   get_clusterj  s   rg   c                 C   sb   |t |  |< zt|}W n ty   d }Y nw |r/z
|| || W d S  ty.   Y d S w d S r   )udt_by_keyspacerg   r   register_user_typer   )r   	type_nameklassr   r'   r   r   r   register_udtq  s   rl   c              
   C   s^   ddl m} t D ]"\}}| D ]\}}z| |p|j|| W q ty+   Y qw q
d S )Nr   rP   )rU   rQ   rh   itemsri   rV   r   )r'   rQ   ks_namename_type_maprj   rk   r   r   r   rC     s   rC   )NN)NNFFNFNr   )NFF),collectionsr   loggingr"   cassandra.clusterr   r   r   r   r   r   cassandra.queryr	   r
   rU   r   cassandra.cqlengine.statementsr   	getLoggerr   r1   NOT_SETr'   r(   objectr   r5   dictrh   r   r   r   rK   rN   rH   rO   r;   rX   r7   ra   rf   rg   rl   rC   r   r   r   r   <module>   sF    

]
;
*



