
    ]*ijA                    4   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rddl(m)Z) ddl*m+Z+ ddl,m-Z- dZ. G d dee'         Z/ G d de/e'         Z0y)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                     e Zd ZdZeZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd dZd!dZd"dZ	e
d#d       Zd$dZ	 	 d%	 	 	 	 	 	 	 	 	 	 	 d&d	Ze
d"d
       Ze
d'd       Ze
d(d       Ze
d)d       Zd*dZd dZd dZd dZd dZd+dZd'dZd,dZd-dZd-dZd.dZd/d0dZd1dZd2dZd3dZ e!jD                  d/d4d       Z#y)5CommandCursorz)A cursor / iterator over command cursors.Nc                   d| _         || _        |d   | _        t        |d         | _        |j                  d      | _        || _        || _        || _	        | j                  j                  j                  j                  j                  | _        || _        | j                  d| j                  _        | j                  dk(  | _        || _        | j"                  r| j'                          d|v r|d   | _        n|j*                  | _        | j-                  |       t/        |t0              s|t3        dt5        |             yy)	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_name
batch_size
isinstanceint	TypeErrortype)self
collectioncursor_infoaddressr>   max_await_time_mssessioncomments           \/home/alumno/antonio/venv/lib/python3.12/site-packages/pymongo/synchronous/command_cursor.py__init__zCommandCursor.__init__;   s.    #6@t$;|45
BM//"C
"  %"3((1188@@HH==$04DMM-xx1}<<;"4(DH!++DH
#+S16G6SDTJ[E\D]^  7T1    c                $    | j                          y N)_die_no_lockrC   s    rJ   __del__zCommandCursor.__del__e   s    rL   c                    t        |t              st        dt        |             |dk  rt	        d      |dk(  xr dxs || _        | 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      )r?   r@   rA   rB   
ValueErrorr0   )rC   r>   s     rJ   r>   zCommandCursor.batch_sizeh   sU     *c*A$zBRASTUU>677%?0q>JrL   c                2    t        | j                        dkD  S )z^Returns `True` if the cursor has documents remaining from the
        previous batch.
        r   )lenr,   rP   s    rJ   	_has_nextzCommandCursor._has_next   s     4::""rL   c                    | j                   S )zlRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.
        )r.   rP   s    rJ   _post_batch_resume_tokenz&CommandCursor._post_batch_resume_token   s    
 )))rL   c                   | j                   j                  j                  }|j                  | j                        sy | j
                  sD|j                          t        |d      }| j                  dk(  r|j                          y || _        y y )NFr   )
r*   r2   r3   _should_pin_cursorr7   r)   
pin_cursorr   r+   close)rC   connr3   conn_mgrs       rJ   _maybe_pin_connectionz#CommandCursor._maybe_pin_connection   sn    !!**11((7~~OO)$6H xx1} !) rL   c                *    |j                  ||||      S rN   )unpack_response)rC   response	cursor_idcodec_optionsuser_fieldslegacy_responses         rJ   _unpack_responsezCommandCursor._unpack_response   s     ''	=+__rL   c                \    t        t        | j                        xs | 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.
        )boolrW   r,   r9   rP   s    rJ   alivezCommandCursor.alive   s#     C

O9DLL(8::rL   c                    | j                   S )zReturns the id of the cursor.)r+   rP   s    rJ   re   zCommandCursor.cursor_id   s     xxrL   c                    | j                   S )zUThe (host, port) of the server used, or None.

        .. versionadded:: 3.0
        )r/   rP   s    rJ   rF   zCommandCursor.address   s     }}rL   c                `    | j                   r"| j                   j                  s| j                   S y)zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None.

        .. versionadded:: 3.6
        N)r7   	_implicitrP   s    rJ   rH   zCommandCursor.session   s$     ==!8!8== rL   c                    | j                   }d| _         | j                  r@|s>| j                  }| j                  J t        | j                  | j                        }||fS d}d }||fS )NTr   )r9   r+   r/   r   r<   )rC   already_killedre   rF   s       rJ   _prepare_to_diezCommandCursor._prepare_to_die   sl    88NI==,,,$T]]DHH=G
 '!! IG'!!rL   c                8   | j                         \  }}| j                  j                  j                  j	                  ||| j
                  | j                         | j                  r.| j                  j                  rd| j                  _        d| _        d| _        y)z,Closes this cursor without acquiring a lock.FN)	rs   r*   r2   r3   _cleanup_cursor_no_lockr)   r7   rp   r8   rC   re   rF   s      rJ   rO   zCommandCursor._die_no_lock   su    !113	7!!((@@w	
 ==T]]4405DMM- DMrL   c                8   | j                         \  }}| j                  j                  j                  j	                  ||| j
                  | j                         | j                  r.| j                  j                  rd| j                  _        d| _        d| _        y)zCloses this cursor.FN)	rs   r*   r2   r3   _cleanup_cursor_lockr)   r7   rp   r8   rv   s      rJ   	_die_lockzCommandCursor._die_lock   sx    !113	7!!((==NNMM		
 ==T]]4405DMM- DMrL   c                    | j                   rJ| j                   j                  r3d| j                   _        | j                   j                          d | _         y y y NF)r7   rp   r8   _end_implicit_sessionrP   s    rJ   r;   zCommandCursor._end_session   s?    ==T]]4405DMM-MM//1 DM 5=rL   c                $    | j                          y)z$Explicitly close / kill this cursor.N)ry   rP   s    rJ   r^   zCommandCursor.close   s    rL   c                   | j                   j                  j                  }	 |j                  || j                  | j
                        }t        |t               r1| j"                  s%t%        |j&                  |j(                        | _        |j*                  r8|j,                  d   d   }|d   }|j/                  d      | _        |d   | _        nC|j,                  }t        |j4                  t6              sJ |j4                  j8                  | _        | j2                  dk(  r| j                          t;        |      | _        y# t        $ rL}|j                  t        v rd| _	        |j                  r| j                           | j                           d}~wt        $ r d| _	        | j                           t        $ r | j                           w xY w)	z/Send a getmore message and handle the response.)rF   TNr   cursor	nextBatchr'   r%   )r*   r2   r3   _run_operationri   r/   r   coder   r9   r5   rO   r^   r   	Exceptionr?   r   r)   r   r_   more_to_comefrom_commanddocsr-   r.   r+   datar   re   r   r,   )rC   	operationr3   rd   excr   	documentss          rJ   _send_messagezCommandCursor._send_message   s|   !!**11	,,400$-- - H. h/>>!3HMM8CXCX!Y  ]]1%h/F{+I)/4J)KD&d|DH IhmmX666}}..DH88q=JJL9%
G   		xx00#{{!!#  

  	DLJJL 	JJL	s   (E 	GAF>Gc                   t        | j                        s| j                  rt        | j                        S | j                  r| j                  j                  dd      \  }}| j                  j                  | j                        }| j                  | j                  ||| j                  | j                  | j                  j                  || j                  | j                  j                  j                  | j                   | j"                  d| j$                               n| j'                          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.
        .rS   F)rW   r,   r9   r+   r<   splitr*   _read_preference_forrH   r   _getmore_classr0   rf   r7   r2   r3   r1   r)   r:   ry   )rC   dbnamecollname	read_prefs       rJ   _refreshzCommandCursor._refresh(  s     tzz?dlltzz?"88#xx~~c15FH((==dllKI##$$HH$$22MM$$--44++NNMM" NN4::rL   c                    | S rN    rP   s    rJ   __iter__zCommandCursor.__iter__J      rL   c                j    | j                   r"| j                  d      }||S | j                   r"t        )zAdvance the cursor.T)rl   	_try_nextStopIteration)rC   docs     rJ   nextzCommandCursor.nextM  s4     jj..&C
 jj
 rL   c                "    | j                         S rN   )r   rP   s    rJ   __next__zCommandCursor.__next__W  s    yy{rL   c                    t        | j                        s| j                  s|r| j                          t        | j                        r| j                  j	                         S y)z<Advance the cursor blocking for at most one getMore command.N)rW   r,   r9   r   popleft)rC   get_more_alloweds     rJ   r   zCommandCursor._try_nextZ  s@    4::t||8HMMOtzz?::%%''rL   c                   t        | j                        s| j                  s| j                          t        | j                        r|6|j	                  | j                         | j                  j                          yt        t        t        | j                        |            D ]+  }|j                  | j                  j                                - yy)z4Get all or some available documents from the cursor.TF)
rW   r,   r9   r   extendclearrangeminappendr   )rC   resulttotal_s       rJ   _next_batchzCommandCursor._next_batchc  s    4::t||MMOtzz?}djj)

  "  s3tzz?E:; 8AMM$**"4"4"678rL   c                &    | j                  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   rP   s    rJ   try_nextzCommandCursor.try_nextr  s      ~~t~44rL   c                    | S rN   r   rP   s    rJ   	__enter__zCommandCursor.__enter__  r   rL   c                $    | j                          y rN   )r^   )rC   exc_typeexc_valexc_tbs       rJ   __exit__zCommandCursor.__exit__  s    

rL   c                    g }|}t        |t              r|dk  rt        d      | j                  r:| j	                  ||      s	 |S ||t        |      z
  }|dk(  r	 |S | j                  r:|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
        rS   z'to_list() length must be greater than 0r   )r?   r@   rU   rl   r   rW   )rC   lengthres	remainings       rJ   to_listzCommandCursor.to_list  s      $&	fc"vzFGGjj##C3
 
	 !"SX-	>
 jj 
rL   r   NNNrD   zCollection[_DocumentType]rE   zMapping[str, Any]rF   Optional[_Address]r>   r@   rG   Optional[int]rH   Optional[ClientSession]rI   r   returnNone)r   r   )r>   r@   r   CommandCursor[_DocumentType])r   rk   )r   Optional[Mapping[str, Any]])r_   r!   r   r   r{   )rd   Union[_OpReply, _OpMsg]re   r   rf   zCodecOptions[Mapping[str, Any]]rg   r   rh   rk   r   zSequence[_DocumentOut])r   r@   )r   r   )r   r   )r   z$tuple[int, Optional[_CursorAddress]])r   r   r   r   )r   zIterator[_DocumentType])r   r   )r   rk   r   Optional[_DocumentType]rN   )r   listr   r   r   rk   )r   r   )r   r   )r   r   r   r   r   r   r   r   )r   r   r   zlist[_DocumentType])$__name__
__module____qualname____doc__r   r   rK   rQ   r>   rX   propertyrZ   ra   ri   rl   re   rF   rH   rs   rO   ry   r;   r^   r   r   r   r   r   r   r   r   r   r   r   applyr   r   rL   rJ   r#   r#   6   s   3N +/+/(-( '( $	(
 ( )( )( ( 
(T.# * **& 48 %`)` !` 7	`
 1` ` 
 ` ; ;       "	!*&X D5$ [[ rL   r#   c                  x     e Zd ZeZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )	RawBatchCommandCursorc           	     V    |j                  d      rJ t        | 	  |||||||       y)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>`_.
        r&   N)r-   superrK   )	rC   rD   rE   rF   r>   rG   rH   rI   	__class__s	           rJ   rK   zRawBatchCommandCursor.__init__  s9    $ ??<000	
rL   c                L    |j                  ||      }|st        |d          |S )N)rg   r   )raw_responser   )rC   rd   re   rf   rg   rh   r   s          rJ   ri   z&RawBatchCommandCursor._unpack_response  s0      ,,YK,P 3<?CrL   c                    t        d      )Nz0Cannot call __getitem__ on RawBatchCommandCursor)r   )rC   indexs     rJ   __getitem__z!RawBatchCommandCursor.__getitem__  s    QRRrL   r   r   r{   )rd   r   re   r   rf   zCodecOptions[dict[str, Any]]rg   r   rh   rk   r   zlist[Mapping[str, Any]])r   r@   r   r
   )	r   r   r   r   r   rK   ri   r   __classcell__)r   s   @rJ   r   r     s    %N +/+/
-
 '
 $	

 
 )
 )
 
 

D 48 %) ! 4	
 1  
!SrL   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   r   rL   rJ   <module>r      s    ; " 
 
 
 F  7 P P  , 9 A A@93oGM* od0SM-8 0SrL   