o
    hSB                     @  s$  d Z ddlm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 ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZm Z m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z' erzddl(m)Z) ddl*m+Z+ ddl,m-Z- dZ.G dd de	e' Z/G dd de/e' Z0dS )z4CommandCursor class to iterate over command results.    )annotations)deque)	TYPE_CHECKINGAnyAsyncIteratorGenericMappingNoReturnOptionalSequenceUnion)CodecOptions&_convert_raw_document_lists_to_streams)_csot)_ConnectionManager)_CURSOR_CLOSED_ERRORS)ConnectionFailureInvalidOperationOperationFailure)_CursorAddress_GetMore_OpMsg_OpReply_RawBatchGetMore)PinnedResponse)_Address_DocumentOut_DocumentType)AsyncClientSession)AsyncCollection)AsyncConnectionFc                   @  sR  e Zd ZdZeZ					dhdiddZdjddZdkddZdlddZ	e
dmd!d"Zdnd%d&Z		dodpd/d0Ze
dld1d2Ze
dqd3d4Ze
drd5d6Ze
dsd7d8Zdtd:d;Zdjd<d=Zdjd>d?Zdjd@dAZdjdBdCZdudFdGZdqdHdIZdvdKdLZdwdNdOZdwdPdQZdxdTdUZdydzdYdZZd{d[d\Zd|d]d^Zd}dbdcZ e!j"dyd~dfdgZ#dS )AsyncCommandCursorz7An asynchronous cursor / iterator over command cursors.r   NF
collectionAsyncCollection[_DocumentType]cursor_infoMapping[str, Any]addressOptional[_Address]
batch_sizeintmax_await_time_msOptional[int]sessionOptional[AsyncClientSession]explicit_sessionboolcommentr   returnNonec	           	      C  s   d| _ || _|d | _t|d | _|d| _|| _|| _|| _	| jj
jjj| _|| _|| _| jdk| _|| _| jr?|   d|v rI|d | _n|j| _| | t|tsd|durftdt| dS dS )zCreate a new command cursor.Nid
firstBatchpostBatchResumeTokenr   nsz2max_await_time_ms must be an integer or None, not )	_sock_mgr_collection_idr   _dataget_postbatchresumetoken_address_batch_size_max_await_time_msdatabaseclientoptionstimeout_timeout_session_explicit_session_killed_comment_end_session_nsZ	full_namer(   
isinstancer)   	TypeErrortype	selfr"   r$   r&   r(   r*   r,   r.   r0    rP   V/var/www/html/venv/lib/python3.10/site-packages/pymongo/asynchronous/command_cursor.py__init__;   s4   

zAsyncCommandCursor.__init__c                 C  s   |    d S N)_die_no_lockrO   rP   rP   rQ   __del__e   s   zAsyncCommandCursor.__del__!AsyncCommandCursor[_DocumentType]c                 C  sB   t |tstdt| |dk rtd|dkrdp|| _| S )a  Limits the number of documents returned in one batch. Each batch
        requires a round trip to the server. It can be adjusted to optimize
        performance and limit data transfer.

        .. note:: batch_size can not override MongoDB's internal limits on the
           amount of data it will return to the client in a single batch (i.e
           if you set batch size to 1,000,000,000, MongoDB will currently only
           return 4-16MB of results per batch).

        Raises :exc:`TypeError` if `batch_size` is not an integer.
        Raises :exc:`ValueError` if `batch_size` is less than ``0``.

        :param batch_size: The size of each batch of results requested.
        z#batch_size must be an integer, not r   zbatch_size must be >= 0      )rK   r)   rL   rM   
ValueErrorr>   )rO   r(   rP   rP   rQ   r(   h   s   
zAsyncCommandCursor.batch_sizec                 C  s   t | jdkS )z^Returns `True` if the cursor has documents remaining from the
        previous batch.
        r   )lenr:   rU   rP   rP   rQ   	_has_next   s   zAsyncCommandCursor._has_nextOptional[Mapping[str, Any]]c                 C     | j S )zlRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.
        )r<   rU   rP   rP   rQ   _post_batch_resume_token   s   z+AsyncCommandCursor._post_batch_resume_tokenconnr    c                   s^   | j jj}|| jsd S | js-|  t|d}| jdkr(|	 I d H  d S || _d S d S )NFr   )
r8   r@   rA   Z_should_pin_cursorrE   r7   Z
pin_cursorr   r9   close)rO   r`   rA   Zconn_mgrrP   rP   rQ   _maybe_pin_connection   s   



z(AsyncCommandCursor._maybe_pin_connectionresponseUnion[_OpReply, _OpMsg]	cursor_idcodec_optionsCodecOptions[Mapping[str, Any]]user_fieldslegacy_responseSequence[_DocumentOut]c                 C  s   | ||||S rS   )Zunpack_response)rO   rc   re   rf   rh   ri   rP   rP   rQ   _unpack_response   s   z#AsyncCommandCursor._unpack_responsec                 C  s   t t| jp	| j S )a  Does this cursor have the potential to return more data?

        Even if :attr:`alive` is ``True``, :meth:`next` can raise
        :exc:`StopIteration`. Best to use a for loop::

            async for doc in collection.aggregate(pipeline):
                print(doc)

        .. note:: :attr:`alive` can be True while iterating a cursor from
          a failed server. In this case :attr:`alive` will return False after
          :meth:`next` fails to retrieve the next batch of results from the
          server.
        )r/   r[   r:   rG   rU   rP   rP   rQ   alive   s   zAsyncCommandCursor.alivec                 C  r^   )zReturns the id of the cursor.)r9   rU   rP   rP   rQ   re      s   zAsyncCommandCursor.cursor_idc                 C  r^   )zUThe (host, port) of the server used, or None.

        .. versionadded:: 3.0
        )r=   rU   rP   rP   rQ   r&      s   zAsyncCommandCursor.addressc                 C  s   | j r| jS dS )zThe cursor's :class:`~pymongo.asynchronous.client_session.AsyncClientSession`, or None.

        .. versionadded:: 3.6
        N)rF   rE   rU   rP   rP   rQ   r,      s   zAsyncCommandCursor.session$tuple[int, Optional[_CursorAddress]]c                 C  sP   | j }d| _ | jr |s | j}| jd usJ t| j| j}||fS d}d }||fS )NTr   )rG   r9   r=   r   rJ   )rO   Zalready_killedre   r&   rP   rP   rQ   _prepare_to_die   s   
z"AsyncCommandCursor._prepare_to_diec                 C  s@   |   \}}| jjj||| j| j| j | jsd| _d| _dS )z,Closes this cursor without acquiring a lock.N)rn   r8   r@   rA   Z_cleanup_cursor_no_lockr7   rE   rF   rO   re   r&   rP   rP   rQ   rT      s   

zAsyncCommandCursor._die_no_lockc                   sH   |   \}}| jjj||| j| j| jI dH  | jsd| _d| _dS )zCloses this cursor.N)rn   r8   r@   rA   Z_cleanup_cursor_lockr7   rE   rF   ro   rP   rP   rQ   	_die_lock   s   


zAsyncCommandCursor._die_lockc                 C  s(   | j r| js| j   d | _ d S d S d S rS   )rE   rF   Z_end_implicit_sessionrU   rP   rP   rQ   rI      s   

zAsyncCommandCursor._end_sessionc                   s   |   I dH  dS )z$Explicitly close / kill this cursor.N)rp   rU   rP   rP   rQ   ra      s   zAsyncCommandCursor.close	operationr   c              
     sL  | j jj}z|j|| j| jdI dH }W nC ty9 } z|jtv r%d| _	|j
r-|    |  I dH   d}~w tyJ   d| _	|  I dH    tyX   |  I dH   w t|tri| jsit|j|j| _|jr|jd d }|d }|d| _|d | _n|j}t|jtsJ |jj| _| jdkr|  I dH  t|| _dS )	z/Send a getmore message and handle the response.)r&   NTr   cursorZ	nextBatchr5   r3   )r8   r@   rA   Z_run_operationrk   r=   r   coder   rG   rC   rT   ra   r   	ExceptionrK   r   r7   r   r`   Zmore_to_comeZfrom_commanddocsr;   r<   r9   datar   re   r   r:   )rO   rq   rA   rc   excrr   Z	documentsrP   rP   rQ   _send_message   sJ   





z AsyncCommandCursor._send_messagec                   s   t | js	| jrt | jS | jrC| jdd\}}| j| j}| 	| 
||| j| j| jj|| j| jjj| j| jd| jI dH  n|  I dH  t | jS )a  Refreshes the cursor with more data from the server.

        Returns the length of self._data after refresh. Will exit early if
        self._data is already non-empty. Raises OperationFailure when the
        cursor cannot be refreshed due to an error on the query.
        .rX   FN)r[   r:   rG   r9   rJ   splitr8   Z_read_preference_forr,   rx   _getmore_classr>   rf   rE   r@   rA   r?   r7   rH   rp   )rO   ZdbnameZcollnameZ	read_prefrP   rP   rQ   _refresh&  s0   

zAsyncCommandCursor._refreshAsyncIterator[_DocumentType]c                 C  s   | S rS   rP   rU   rP   rP   rQ   	__aiter__H  s   zAsyncCommandCursor.__aiter__r   c                   s.   | j r| dI dH }|dur|S | j st)zAdvance the cursor.TN)rl   	_try_nextStopAsyncIteration)rO   docrP   rP   rQ   nextK  s   zAsyncCommandCursor.nextc                   s   |   I d H S rS   )r   rU   rP   rP   rQ   	__anext__U  s   zAsyncCommandCursor.__anext__get_more_allowedOptional[_DocumentType]c                   s<   t | js| js|r|  I dH  t | jr| j S dS )z<Advance the cursor blocking for at most one getMore command.N)r[   r:   rG   r|   popleft)rO   r   rP   rP   rQ   r   X  s   

zAsyncCommandCursor._try_nextresultlisttotalc                   s~   t | js| js|  I dH  t | jr=|du r&|| j | j  dS ttt | j|D ]
}|| j	  q0dS dS )z4Get all or some available documents from the cursor.NTF)
r[   r:   rG   r|   extendclearrangeminappendr   )rO   r   r   _rP   rP   rQ   _next_batcha  s   

zAsyncCommandCursor._next_batchc                   s   | j ddI dH S )ar  Advance the cursor without blocking indefinitely.

        This method returns the next document without waiting
        indefinitely for data.

        If no document is cached locally then this method runs a single
        getMore command. If the getMore yields any documents, the next
        document is returned, otherwise, if the getMore returns no documents
        (because there is no additional data) then ``None`` is returned.

        :return: The next document or ``None`` when no document is available
          after running a single getMore or when the cursor is closed.

        .. versionadded:: 4.5
        T)r   N)r   rU   rP   rP   rQ   try_nextp  s   zAsyncCommandCursor.try_nextc                   s   | S rS   rP   rU   rP   rP   rQ   
__aenter__  s   zAsyncCommandCursor.__aenter__exc_typeexc_valexc_tbc                   s   |   I d H  d S rS   )ra   )rO   r   r   r   rP   rP   rQ   	__aexit__  s   zAsyncCommandCursor.__aexit__lengthlist[_DocumentType]c                   sn   g }|}t |tr|dk rtd| jr5| ||I dH s!	 |S |dur2|t| }|dkr2	 |S | js|S )a}  Converts the contents of this cursor to a list more efficiently than ``[doc async for doc in cursor]``.

        To use::

          >>> await cursor.to_list()

        Or, so read at most n items from the cursor::

          >>> await cursor.to_list(n)

        If the cursor is empty or has no more results, an empty list will be returned.

        .. versionadded:: 4.9
        rX   z'to_list() length must be greater than 0Nr   )rK   r)   rZ   rl   r   r[   )rO   r   res	remainingrP   rP   rQ   to_list  s    zAsyncCommandCursor.to_listr   NNFNr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r   r1   r2   )r1   r2   )r(   r)   r1   rW   )r1   r/   )r1   r]   )r`   r    r1   r2   NF)rc   rd   re   r+   rf   rg   rh   r]   ri   r/   r1   rj   )r1   r)   )r1   r'   )r1   r-   )r1   rm   )rq   r   r1   r2   )r1   r}   )r1   r   )r   r/   r1   r   rS   )r   r   r   r+   r1   r/   )r1   r   )r1   rW   )r   r   r   r   r   r   r1   r2   )r   r+   r1   r   )$__name__
__module____qualname____doc__r   r{   rR   rV   r(   r\   propertyr_   rb   rk   rl   re   r&   r,   rn   rT   rp   rI   ra   rx   r|   r~   r   r   r   r   r   r   r   r   applyr   rP   rP   rP   rQ   r!   6   sV    
*




	






,
"



	


r!   c                      sH   e Zd ZeZ					d'd( fddZ		d)d*d!d"Zd+d%d&Z  ZS ),AsyncRawBatchCommandCursorr   NFr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r   r1   r2   c	           	   
     s,   | drJ t |||||||| dS )a^  Create a new cursor / iterator over raw batches of BSON data.

        Should not be called directly by application developers -
        see :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate_raw_batches`
        instead.

        .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
        r4   N)r;   superrR   rN   	__class__rP   rQ   rR     s   z#AsyncRawBatchCommandCursor.__init__rc   rd   re   rf   r   rh   r]   ri   list[Mapping[str, Any]]c                 C  s"   |j ||d}|st|d  |S )N)rh   r   )raw_responser   )rO   rc   re   rf   rh   ri   r   rP   rP   rQ   rk     s   z+AsyncRawBatchCommandCursor._unpack_responseindexr	   c                 C  s   t d)Nz5Cannot call __getitem__ on AsyncRawBatchCommandCursor)r   )rO   r   rP   rP   rQ   __getitem__  s   z&AsyncRawBatchCommandCursor.__getitem__r   r   r   )rc   rd   re   r+   rf   r   rh   r]   ri   r/   r1   r   )r   r)   r1   r	   )	r   r   r   r   r{   rR   rk   r   __classcell__rP   rP   r   rQ   r     s    $r   N)1r   
__future__r   collectionsr   typingr   r   r   r   r   r	   r
   r   r   Zbsonr   r   Zpymongor   Zpymongo.asynchronous.cursorr   Zpymongo.cursor_sharedr   Zpymongo.errorsr   r   r   Zpymongo.messager   r   r   r   r   Zpymongo.responser   Zpymongo.typingsr   r   r   Z#pymongo.asynchronous.client_sessionr   Zpymongo.asynchronous.collectionr   Zpymongo.asynchronous.poolr    Z_IS_SYNCr!   r   rP   rP   rP   rQ   <module>   s*   ,  r