o
    NDi%                     @   s   d dl mZ d dlmZmZ d dlmZ d dlmZ d dl	Z	d dl
mZmZ d dlZeeZeddd	gZd
ddefddZG dd deZG dd deZG dd deZdd ZdS )    )
namedtuple)heappushheappop)cycle)	ConditionN)	ResultSetEXEC_PROFILE_DEFAULTExecutionResultsuccessresult_or_excd   TFc                 C   s@   |dkrt d|sg S |rt| ||nt| ||}|||S )a?  
    Executes a sequence of (statement, parameters) tuples concurrently.  Each
    ``parameters`` item must be a sequence or :const:`None`.

    The `concurrency` parameter controls how many statements will be executed
    concurrently.  When :attr:`.Cluster.protocol_version` is set to 1 or 2,
    it is recommended that this be kept below 100 times the number of
    core connections per host times the number of connected hosts (see
    :meth:`.Cluster.set_core_connections_per_host`).  If that amount is exceeded,
    the event loop thread may attempt to block on new connection creation,
    substantially impacting throughput.  If :attr:`~.Cluster.protocol_version`
    is 3 or higher, you can safely experiment with higher levels of concurrency.

    If `raise_on_first_error` is left as :const:`True`, execution will stop
    after the first failed statement and the corresponding exception will be
    raised.

    `results_generator` controls how the results are returned.

    * If :const:`False`, the results are returned only after all requests have completed.
    * If :const:`True`, a generator expression is returned. Using a generator results in a constrained
      memory footprint when the results set will be large -- results are yielded
      as they return instead of materializing the entire list at once. The trade for lower memory
      footprint is marginal CPU overhead (more thread coordination and sorting out-of-order results
      on-the-fly).

    `execution_profile` argument is the execution profile to use for this
    request, it is passed directly to :meth:`Session.execute_async`.

    A sequence of ``ExecutionResult(success, result_or_exc)`` namedtuples is returned
    in the same order that the statements were passed in.  If ``success`` is :const:`False`,
    there was an error executing the statement, and ``result_or_exc`` will be
    an :class:`Exception`.  If ``success`` is :const:`True`, ``result_or_exc``
    will be the query result.

    Example usage::

        select_statement = session.prepare("SELECT * FROM users WHERE id=?")

        statements_and_params = []
        for user_id in user_ids:
            params = (user_id, )
            statements_and_params.append((select_statement, params))

        results = execute_concurrent(
            session, statements_and_params, raise_on_first_error=False)

        for (success, result) in results:
            if not success:
                handle_error(result)  # result will be an Exception
            else:
                process_user(result[0])  # result will be a list of rows

    Note: in the case that `generators` are used, it is important to ensure the consumers do not
    block or attempt further synchronous requests, because no further IO will be processed until
    the consumer returns. This may also produce a deadlock in the IO event thread.
    r   z"concurrency must be greater than 0)
ValueErrorConcurrentExecutorGenResultsConcurrentExecutorListResultsexecute)sessionstatements_and_parametersconcurrencyraise_on_first_errorresults_generatorexecution_profileexecutor r   M/var/www/Datamplify/venv/lib/python3.10/site-packages/cassandra/concurrent.pyexecute_concurrent   s   :
r   c                   @   s@   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S )_ConcurrentExecutorr   c                 C   sD   || _ tt|| _|| _t | _d| _g | _d| _	d| _
d| _d S )NFr   )r   	enumerateiter_enum_statements_execution_profiler   
_condition
_fail_fast_results_queue_current_exec_count_exec_depth)selfr   statements_and_paramsr   r   r   r   __init__g   s   
z_ConcurrentExecutor.__init__c                 C   sz   || _ g | _d| _d| _| j" t|D ]}|  s nqW d    |  S W d    |  S 1 s4w   Y  |  S )Nr   )r!   r"   r#   r$   r    range_execute_next_results)r&   r   	fail_fastnr   r   r   r   r   s"   

z_ConcurrentExecutor.executec                 C   sJ   zt | j\}\}}|  jd7  _| ||| W dS  ty$   Y d S w )N   T)nextr   r$   _executeStopIteration)r&   idx	statementparamsr   r   r   r*   }   s   z!_ConcurrentExecutor._execute_nextc              
   C   s   |  j d7  _ z| jj||d | jd}||f}|j| j|| j|d W n* tyM } z| j | jk r9| 	||d n
| j
| j	||d W Y d }~nd }~ww |  j d8  _ d S )Nr.   )timeoutr   )callbackcallback_argserrbackerrback_argsF)r%   r   execute_asyncr   add_callbacks_on_success	_on_error	Exceptionmax_error_recursion_put_resultsubmit)r&   r2   r3   r4   futureargsexcr   r   r   r0      s   
z_ConcurrentExecutor._executec                 C   s    |   | t|||d d S )NT)clear_callbacksr@   r   r&   resultrB   r2   r   r   r   r<      s   z_ConcurrentExecutor._on_successc                 C   s   |  ||d d S )NF)r@   rF   r   r   r   r=      s   z_ConcurrentExecutor._on_errorN)
__name__
__module____qualname__r?   r(   r   r*   r0   r<   r=   r   r   r   r   r   c   s    
r   c                   @   s   e Zd Zdd Zdd ZdS )r   c                 C   sT   | j  t| j|t||f |   | j   W d    d S 1 s#w   Y  d S N)r    r   r"   r	   r*   notifyr&   rG   r2   r
   r   r   r   r@      s
   "z(ConcurrentExecutorGenResults._put_resultc              	   c   s&   | j  | j| jk r| jr| jd d | jkr*| j   | jr| jd d | jks| jrs| jd d | jkrst| j\}}z| j   | jrO|d sO|d |V  W | j   n| j   w |  jd7  _| jrs| jd d | jks7| j| jk sW d    d S W d    d S 1 sw   Y  d S )Nr   r.   )	r    r#   r$   r"   waitr   releaser!   acquire)r&   _resr   r   r   r+      s(   

"z%ConcurrentExecutorGenResults._resultsN)rH   rI   rJ   r@   r+   r   r   r   r   r      s    r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )r   Nc                    s   d | _ tt| ||S rK   )
_exceptionsuperr   r   )r&   r   r,   	__class__r   r   r      s   z%ConcurrentExecutorListResults.executec                 C   s   | j |t||f | jH |  jd7  _|s'| jr'| js!|| _| j  n|  s>| j| j	krN| j  W d    d S W d    d S W d    d S W d    d S 1 sYw   Y  d S )Nr.   )
r"   appendr	   r    r#   r!   rS   rL   r*   r$   rM   r   r   r   r@      s    
"z)ConcurrentExecutorListResults._put_resultc                 C   s   | j " | j| jk r| j   | jr| jr| j| j| jk s
W d    n1 s(w   Y  | jr6| jr6| jdd t| jD S )Nc                 S   s   g | ]}|d  qS )r.   r   ).0rr   r   r   
<listcomp>   s    z:ConcurrentExecutorListResults._results.<locals>.<listcomp>)r    r#   r$   rN   rS   r!   sortedr"   )r&   r   r   r   r+      s   
z&ConcurrentExecutorListResults._results)rH   rI   rJ   rS   r   r@   r+   __classcell__r   r   rU   r   r      s
    r   c                 O   s$   t | tt|f|g|R i |S )a  
    Like :meth:`~cassandra.concurrent.execute_concurrent()`, but takes a single
    statement and a sequence of parameters.  Each item in ``parameters``
    should be a sequence or :const:`None`.

    Example usage::

        statement = session.prepare("INSERT INTO mytable (a, b) VALUES (1, ?)")
        parameters = [(x,) for x in range(1000)]
        execute_concurrent_with_args(session, statement, parameters, concurrency=50)
    )r   zipr   )r   r3   
parametersrC   kwargsr   r   r   execute_concurrent_with_args   s   $r`   )collectionsr   heapqr   r   	itertoolsr   	threadingr   syscassandra.clusterr   r   logging	getLoggerrH   logr	   r   objectr   r   r   r`   r   r   r   r   <module>   s   
E>