
    df 8                       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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rddl%m&Z& ddl'm(Z( ddl)m*Z*  G d dee$         Z+ G d de+ee$         Z,y)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)_CURSOR_CLOSED_ERRORS_ConnectionManager)ConnectionFailureInvalidOperationOperationFailure)_CursorAddress_GetMore_OpMsg_OpReply_RawBatchGetMore)PinnedResponse)_Address_DocumentOut_DocumentType)ClientSession)
Collection)
Connectionc                  F   e Zd ZdZeZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZdddZddZ	ddZ
ddZdd	Zed d
       Zd!dZd"dZ	 	 d#	 	 	 	 	 	 	 	 	 	 	 d$dZ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eZd*dZd+dZd,dZd-dZy).CommandCursorz)A cursor / iterator over command cursors.Nc	                   d| _         || _        |d   | _        t        |d         | _        |j                  d      | _        || _        || _        || _	        || _
        || _        | j                  dk(  | _        || _        | j                  r| j                  d       d|v r|d   | _        n|j                   | _        | j#                  |       t%        |t&              s|t)        d      yy)	zCreate a new command cursor.Nid
firstBatchpostBatchResumeTokenr   Tnsz,max_await_time_ms must be an integer or None)_CommandCursor__sock_mgr_CommandCursor__collection_CommandCursor__idr   _CommandCursor__dataget$_CommandCursor__postbatchresumetoken_CommandCursor__address_CommandCursor__batch_size!_CommandCursor__max_await_time_ms_CommandCursor__session _CommandCursor__explicit_session_CommandCursor__killed_CommandCursor__comment_CommandCursor__end_session_CommandCursor__ns	full_name
batch_size
isinstanceint	TypeError)	self
collectioncursor_infoaddressr8   max_await_time_mssessionexplicit_sessioncomments	            O/home/api-vastappli/venv/lib/python3.12/site-packages/pymongo/command_cursor.py__init__zCommandCursor.__init__1   s      $7A%	K56CN??"D
# !&#4  "2		Q ==t$;#D)DI",,DI
#+S16G6SJKK 7T1    c                $    | j                          y N_CommandCursor__dier<   s    rD   __del__zCommandCursor.__del__X       

rF   c                   | j                   }d| _         | j                  r=|s;| j                  }| j                  J t        | j                  | j                        }nd}d}| j
                  j                  j                  j                  |||| j                  | j                  | j                         | j                  sd| _
        d| _	        y)zCloses this cursor.TNr   )r3   r*   r.   r   r6   r)   databaseclient_cleanup_cursorr(   r1   r2   )r<   synchronousalready_killed	cursor_idr?   s        rD   __diezCommandCursor.__die[   s    99^		I>>--$T^^TYY?G IG""))99OONN##	
 &&!DNrF   c                ~    | j                   r1| j                  s$| j                   j                  |       d | _         y y y )N)lock)r1   r2   _end_session)r<   rR   s     rD   __end_sessionzCommandCursor.__end_sessions   s4    >>$"9"9NN''['9!DN #:>rF   c                &    | j                  d       y)z$Explicitly close / kill this cursor.TNrI   rK   s    rD   closezCommandCursor.closex   s    

4rF   c                    t        |t              st        d      |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 integerr   zbatch_size must be >= 0      )r9   r:   r;   
ValueErrorr/   )r<   r8   s     rD   r8   zCommandCursor.batch_size|   sH     *c*;<<>677&!O1?ZrF   c                2    t        | j                        dkD  S )z^Returns `True` if the cursor has documents remaining from the
        previous batch.
        r   )lenr+   rK   s    rD   	_has_nextzCommandCursor._has_next   s     4;;!##rF   c                    | j                   S )zlRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.
        )r-   rK   s    rD   _post_batch_resume_tokenz&CommandCursor._post_batch_resume_token   s    
 ***rF   c                   | j                   j                  j                  }|j                  | j                        sy | j
                  sD|j                          t        |d      }| j                  dk(  r|j                          y || _        y y )NFr   )
r)   rO   rP   _should_pin_cursorr1   r(   
pin_cursorr   r*   r[   )r<   connrP   conn_mgrs       rD   _maybe_pin_connectionz#CommandCursor._maybe_pin_connection   sn    ""++22((8OO)$6H yyA~ "* rF   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        $ rM}|j                  t        v rd| _	        |j                  r| j                  d        | j                           d}~wt        $ r d| _	        | j                           t        $ r | j                           w xY w)
z/Send a getmore message and handle the response.)r?   TFNr   cursor	nextBatchr&   r$   )r)   rO   rP   _run_operation_unpack_responser.   r   coder   r3   timeoutrJ   r[   r   	Exceptionr9   r   r(   r   rh   more_to_comefrom_commanddocsr,   r-   r*   datar   rT   r   r+   )r<   	operationrP   responseexcrl   	documentss          rD   __send_messagezCommandCursor.__send_message   sy   ""++22	,,400$.. - H. h/??"4X]]HDYDY"Z  ]]1%h/F{+I*0**5K*LD'tDI IhmmX66 //DI99>JJLI&G   		xx00 ${{

5!  

  	 DMJJL 	JJL	s   (E 	GAF>Gc                *    |j                  ||||      S rH   )unpack_response)r<   rx   rT   codec_optionsuser_fieldslegacy_responses         rD   ro   zCommandCursor._unpack_response   s     ''	=+__rF   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'                  d       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.
        .r]   FT)ra   r+   r3   r*   r6   splitr)   _read_preference_forrA   _CommandCursor__send_message_getmore_classr/   r~   r1   rO   rP   r0   r(   r4   rJ   )r<   dbnamecollname	read_prefs       rD   _refreshzCommandCursor._refresh   s     t{{t}}t{{##99#yysA6FH))>>t||LI##%%II%%33NN%%..55,,OONN" JJt4;;rF   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.
        )boolra   r+   r3   rK   s    rD   alivezCommandCursor.alive  s$     C$;T]]):<<rF   c                    | j                   S )zReturns the id of the cursor.)r*   rK   s    rD   rT   zCommandCursor.cursor_id  s     yyrF   c                    | j                   S )zUThe (host, port) of the server used, or None.

        .. versionadded:: 3.0
        )r.   rK   s    rD   r?   zCommandCursor.address  s     ~~rF   c                4    | j                   r| j                  S y)zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None.

        .. versionadded:: 3.6
        N)r2   r1   rK   s    rD   rA   zCommandCursor.session$  s     "">>!rF   c                    | S rH    rK   s    rD   __iter__zCommandCursor.__iter__.      rF   c                j    | j                   r"| j                  d      }||S | j                   r"t        )zAdvance the cursor.T)r   	_try_nextStopIteration)r<   docs     rD   nextzCommandCursor.next1  s4     jj..&C
 jj
 rF   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)ra   r+   r3   r   popleft)r<   get_more_alloweds     rD   r   zCommandCursor._try_next=  sB    4;;:JMMOt{{;;&&((rF   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   rK   s    rD   try_nextzCommandCursor.try_nextF  s      ~~t~44rF   c                    | S rH   r   rK   s    rD   	__enter__zCommandCursor.__enter__X  r   rF   c                $    | j                          y rH   )r[   )r<   exc_typeexc_valexc_tbs       rD   __exit__zCommandCursor.__exit__[  rM   rF   r   NNFNr=   zCollection[_DocumentType]r>   zMapping[str, Any]r?   Optional[_Address]r8   r:   r@   Optional[int]rA   Optional[ClientSession]rB   r   rC   r   returnNone)r   r   )F)rR   r   r   r   )r8   r:   r   CommandCursor[_DocumentType])r   r   )r   Optional[Mapping[str, Any]])rh   r    r   r   )rw   r   r   r   NF)rx   Union[_OpReply, _OpMsg]rT   r   r~   zCodecOptions[Mapping[str, Any]]r   r   r   r   r   zSequence[_DocumentOut])r   r:   )r   r   )r   r   )r   zIterator[_DocumentType])r   r   )r   r   r   Optional[_DocumentType])r   r   )r   r   )r   r   r   r   r   r   r   r   )__name__
__module____qualname____doc__r   r   rE   rL   rJ   r5   r[   r8   rb   propertyrd   rj   r   ro   r   r   rT   r?   rA   r   r   __next__r   r   r   r   r   rF   rD   r"   r"   ,   s   3N +/+/!&%L-%L '%L $	%L
 %L )%L )%L %L %L 
%LN0"
.$ + ++*'b 48 %`)` !` 7	`
 1` ` 
 `  D = =        H5$rF   r"   c                  ~     e Zd ZeZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )	RawBatchCommandCursorc	           
     X    |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,   superrE   )
r<   r=   r>   r?   r8   r@   rA   rB   rC   	__class__s
            rD   rE   zRawBatchCommandCursor.__init__b  s9    & ??<00		
rF   c                L    |j                  ||      }|st        |d          |S )N)r   r   )raw_responser   )r<   rx   rT   r~   r   r   r   s          rD   ro   z&RawBatchCommandCursor._unpack_response  s0      ,,YK,P 3<?CrF   c                    t        d      )Nz)Cannot call __getitem__ on RawBatchCursor)r   )r<   indexs     rD   __getitem__z!RawBatchCommandCursor.__getitem__  s    JKKrF   r   r   r   )rx   r   rT   r   r~   r   r   r   r   r   r   zlist[Mapping[str, Any]])r   r:   r   r
   )	r   r   r   r   r   rE   ro   r   __classcell__)r   s   @rD   r   r   _  s    %N +/+/!&
-
 '
 $	

 
 )
 )
 
 
 

H 48 %) ! $	
 1  
!LrF   r   N)-r   
__future__r   collectionsr   typingr   r   r   r   r	   r
   r   r   r   bsonr   r   pymongo.cursorr   r   pymongo.errorsr   r   r   pymongo.messager   r   r   r   r   pymongo.responser   pymongo.typingsr   r   r   pymongo.client_sessionr   pymongo.collectionr   pymongo.poolr    r"   r   r   rF   rD   <module>r      sr    ; " 
 
 
 F D P P X X + A A4-'pGM* pf	2LM7=+A 2LrF   