o
    sDijA                     @  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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# 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GenericIteratorMappingNoReturnOptionalSequenceUnion)CodecOptions&_convert_raw_document_lists_to_streams)_csot)_CURSOR_CLOSED_ERRORS)ConnectionFailureInvalidOperationOperationFailure)_CursorAddress_GetMore_OpMsg_OpReply_RawBatchGetMore)PinnedResponse)_ConnectionManager)_Address_DocumentOut_DocumentType)ClientSession)
Collection)
ConnectionTc                   @  sP  e Zd ZdZeZ				dgdhddZdiddZdjddZdkddZ	e
dldd Zdmd#d$Z		%dndod.d/Ze
dkd0d1Ze
dpd2d3Ze
dqd4d5Ze
drd6d7Zdsd9d:Zdid;d<Zdid=d>Zdid?d@ZdidAdBZdtdEdFZdpdGdHZdudJdKZdvdMdNZdvdOdPZdwdSdTZdxdydXdYZdzdZd[Zd{d\d]Zd|dadbZ e!j"dxd}dedfZ#dS )~CommandCursorz)A cursor / iterator over command cursors.r   N
collectionCollection[_DocumentType]cursor_infoMapping[str, Any]addressOptional[_Address]
batch_sizeintmax_await_time_msOptional[int]sessionOptional[ClientSession]commentr   returnNonec                 C  s   d| _ || _|d | _t|d | _|d| _|| _|| _|| _	| jj
jjj| _|| _| jdur5d| j_| jdk| _|| _| jrE|   d|v rO|d | _n|j| _| | t|tsj|durltdt| dS dS )	zCreate a new command cursor.Nid
firstBatchpostBatchResumeTokenTr   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_attached_to_cursor_killed_comment_end_session_ns	full_namer(   
isinstancer)   	TypeErrortypeselfr"   r$   r&   r(   r*   r,   r.    rO   `/home/alumno/antzosa8961/venv/lib/python3.10/site-packages/pymongo/synchronous/command_cursor.py__init__;   s6   


zCommandCursor.__init__c                 C     |    d S N)_die_no_lockrN   rO   rO   rP   __del__e      zCommandCursor.__del__CommandCursor[_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      )rJ   r)   rK   rL   
ValueErrorr<   )rN   r(   rO   rO   rP   r(   h   s   
zCommandCursor.batch_sizeboolc                 C  s   t | jdkS )z^Returns `True` if the cursor has documents remaining from the
        previous batch.
        r   )lenr8   rU   rO   rO   rP   	_has_next   s   zCommandCursor._has_nextOptional[Mapping[str, Any]]c                 C     | j S )zlRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.
        )r:   rU   rO   rO   rP   _post_batch_resume_token   s   z&CommandCursor._post_batch_resume_tokenconnr    c                 C  sV   | j jj}|| jsd S | js)|  t|d}| jdkr$|	  d S || _d S d S )NFr   )
r6   r>   r?   _should_pin_cursorrC   r5   
pin_cursorr   r7   close)rN   rb   r?   conn_mgrrO   rO   rP   _maybe_pin_connection   s   



z#CommandCursor._maybe_pin_connectionFresponseUnion[_OpReply, _OpMsg]	cursor_idcodec_optionsCodecOptions[Mapping[str, Any]]user_fieldslegacy_responseSequence[_DocumentOut]c                 C  s   | ||||S rS   )unpack_response)rN   rh   rj   rk   rm   rn   rO   rO   rP   _unpack_response   s   zCommandCursor._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::

            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]   r8   rE   rU   rO   rO   rP   alive   s   zCommandCursor.alivec                 C  r`   )zReturns the id of the cursor.)r7   rU   rO   rO   rP   rj      s   zCommandCursor.cursor_idc                 C  r`   )zUThe (host, port) of the server used, or None.

        .. versionadded:: 3.0
        )r;   rU   rO   rO   rP   r&      s   zCommandCursor.addressc                 C  s   | j r
| j js
| j S dS )zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None.

        .. versionadded:: 3.6
        N)rC   	_implicitrU   rO   rO   rP   r,      s   zCommandCursor.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   )rE   r7   r;   r   rH   )rN   already_killedrj   r&   rO   rO   rP   _prepare_to_die   s   
zCommandCursor._prepare_to_diec                 C  L   |   \}}| jjj||| j| j | jr!| jjr!d| j_d| _d| _dS )z,Closes this cursor without acquiring a lock.FN)	rv   r6   r>   r?   _cleanup_cursor_no_lockr5   rC   rs   rD   rN   rj   r&   rO   rO   rP   rT      s   

zCommandCursor._die_no_lockc                 C  rw   )zCloses this cursor.FN)	rv   r6   r>   r?   _cleanup_cursor_lockr5   rC   rs   rD   ry   rO   rO   rP   	_die_lock   s   

zCommandCursor._die_lockc                 C  s2   | j r| j jrd| j _| j   d | _ d S d S d S NF)rC   rs   rD   _end_implicit_sessionrU   rO   rO   rP   rG      s
   

zCommandCursor._end_sessionc                 C  s   |    dS )z$Explicitly close / kill this cursor.N)r{   rU   rO   rO   rP   re      s   zCommandCursor.close	operationr   c              
   C  s,  | j jj}z|j|| j| jd}W n: ty2 } z|jtv r!d| _	|j
r)|    |    d}~w ty@   d| _	|     tyK   |    w t|tr\| js\t|j|j| _|jrv|jd d }|d }|d| _|d | _n|j}t|jtsJ |jj| _| jdkr|   t|| _dS )	z/Send a getmore message and handle the response.)r&   TNr   cursor	nextBatchr3   r1   )r6   r>   r?   _run_operationrq   r;   r   coder   rE   rA   rT   re   r   	ExceptionrJ   r   r5   r   rb   more_to_comefrom_commanddocsr9   r:   r7   datar   rj   r   r8   )rN   r~   r?   rh   excr   	documentsrO   rO   rP   _send_message   sH   






zCommandCursor._send_messagec                 C  s   t | js| jrt | jS | jr?| jdd\}}| j| j}| 	| 
||| j| j| jj|| j| jjj| j| jd| j n|   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.
        .rY   F)r]   r8   rE   r7   rH   splitr6   _read_preference_forr,   r   _getmore_classr<   rk   rC   r>   r?   r=   r5   rF   r{   )rN   dbnamecollname	read_prefrO   rO   rP   _refresh(  s.   

zCommandCursor._refreshIterator[_DocumentType]c                 C     | S rS   rO   rU   rO   rO   rP   __iter__J     zCommandCursor.__iter__r   c                 C  s&   | j r| d}|dur|S | j st)zAdvance the cursor.TN)rr   	_try_nextStopIteration)rN   docrO   rO   rP   nextM  s   
zCommandCursor.nextc                 C  s   |   S rS   )r   rU   rO   rO   rP   __next__W     zCommandCursor.__next__get_more_allowedOptional[_DocumentType]c                 C  s4   t | js| js|r|   t | jr| j S dS )z<Advance the cursor blocking for at most one getMore command.N)r]   r8   rE   r   popleft)rN   r   rO   rO   rP   r   Z  s
   

zCommandCursor._try_nextresultlisttotalc                 C  sv   t | js| js|   t | jr9|du r"|| j | j  dS ttt | j|D ]
}|| j	  q,dS dS )z4Get all or some available documents from the cursor.NTF)
r]   r8   rE   r   extendclearrangeminappendr   )rN   r   r   _rO   rO   rP   _next_batchc  s   

zCommandCursor._next_batchc                 C  s   | j dd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   )r   rU   rO   rO   rP   try_nextr  s   zCommandCursor.try_nextc                 C  r   rS   rO   rU   rO   rO   rP   	__enter__  r   zCommandCursor.__enter__exc_typeexc_valexc_tbc                 C  rR   rS   )re   )rN   r   r   r   rO   rO   rP   __exit__  rW   zCommandCursor.__exit__lengthlist[_DocumentType]c                 C  sf   g }|}t |tr|dk rtd| jr1| ||s	 |S |dur.|t| }|dkr.	 |S | js|S )ak  Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``.

        To use::

          >>> cursor.to_list()

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

          >>> cursor.to_list(n)

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

        .. versionadded:: 4.9
        rY   z'to_list() length must be greater than 0Nr   )rJ   r)   r[   rr   r   r]   )rN   r   res	remainingrO   rO   rP   to_list  s   zCommandCursor.to_listr   NNNr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r   r/   r0   )r/   r0   )r(   r)   r/   rX   )r/   r\   )r/   r_   )rb   r    r/   r0   r|   )rh   ri   rj   r+   rk   rl   rm   r_   rn   r\   r/   ro   )r/   r)   )r/   r'   )r/   r-   )r/   rt   )r~   r   r/   r0   )r/   r   )r/   r   )r   r\   r/   r   rS   )r   r   r   r+   r/   r\   )r/   r   )r/   rX   )r   r   r   r   r   r   r/   r0   )r   r+   r/   r   )$__name__
__module____qualname____doc__r   r   rQ   rV   r(   r^   propertyra   rg   rq   rr   rj   r&   r,   rv   rT   r{   rG   re   r   r   r   r   r   r   r   r   r   r   r   applyr   rO   rO   rO   rP   r!   6   sT    
*




	





,
"



	


r!   c                      sF   e Zd ZeZ				d&d' fddZ		d(d)d d!Zd*d$d%Z  ZS )+RawBatchCommandCursorr   Nr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r   r/   r0   c              	     s*   | drJ t ||||||| dS )aL  Create a new cursor / iterator over raw batches of BSON data.

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

        .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
        r2   N)r9   superrQ   rM   	__class__rO   rP   rQ     s   zRawBatchCommandCursor.__init__Frh   ri   rj   rk   CodecOptions[dict[str, Any]]rm   r_   rn   r\   list[Mapping[str, Any]]c                 C  s"   |j ||d}|st|d  |S )N)rm   r   )raw_responser   )rN   rh   rj   rk   rm   rn   r   rO   rO   rP   rq     s   z&RawBatchCommandCursor._unpack_responseindexr	   c                 C  s   t d)Nz0Cannot call __getitem__ on RawBatchCommandCursor)r   )rN   r   rO   rO   rP   __getitem__  r   z!RawBatchCommandCursor.__getitem__r   r   r|   )rh   ri   rj   r+   rk   r   rm   r_   rn   r\   r/   r   )r   r)   r/   r	   )	r   r   r   r   r   rQ   rq   r   __classcell__rO   rO   r   rP   r     s    "r   N)1r   
__future__r   collectionsr   typingr   r   r   r   r   r	   r
   r   r   bsonr   r   pymongor   pymongo.cursor_sharedr   pymongo.errorsr   r   r   pymongo.messager   r   r   r   r   pymongo.responser   pymongo.synchronous.cursorr   pymongo.typingsr   r   r   "pymongo.synchronous.client_sessionr   pymongo.synchronous.collectionr   pymongo.synchronous.poolr    _IS_SYNCr!   r   rO   rO   rO   rP   <module>   s*   ,  t