
    nhSB                    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 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- 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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                     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AsyncCommandCursorz7An asynchronous cursor / iterator over command cursors.Nc	                b   d| _         || _        |d   | _        t        |d         | _        |j                  d      | _        || _        || _        || _	        | j                  j                  j                  j                  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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_ns	full_name
batch_size
isinstanceint	TypeErrortype)	self
collectioncursor_infoaddressr>   max_await_time_mssessionexplicit_sessioncomments	            /var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/venv/lib/python3.12/site-packages/pymongo/asynchronous/command_cursor.py__init__zAsyncCommandCursor.__init__;   s     #;Et$;|45
BM//"C
"  %"3((1188@@HH!1xx1}<<;"4(DH!++DH
#+S16G6SDTJ[E\D]^  7T1    c                $    | j                          y N)_die_no_lockrC   s    rK   __del__zAsyncCommandCursor.__del__e   s    rM   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     rK   r>   zAsyncCommandCursor.batch_sizeh   sU     *c*A$zBRASTUU>677%?0q>JrM   c                2    t        | j                        dkD  S )z^Returns `True` if the cursor has documents remaining from the
        previous batch.
        r   )lenr,   rQ   s    rK   	_has_nextzAsyncCommandCursor._has_next   s     4::""rM   c                    | j                   S )zlRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.
        )r.   rQ   s    rK   _post_batch_resume_tokenz+AsyncCommandCursor._post_batch_resume_token   s    
 )))rM   c                8  K   | j                   j                  j                  }|j                  | j                        sy | j
                  sL|j                          t        |d      }| j                  dk(  r|j                          d {    y || _        y y 7 w)NFr   )
r*   r2   r3   _should_pin_cursorr7   r)   
pin_cursorr   r+   close)rC   connr3   conn_mgrs       rK   _maybe_pin_connectionz(AsyncCommandCursor._maybe_pin_connection   s}     !!**11((7~~OO)$6H xx1}nn&&&!)  's   BB	B
Bc                *    |j                  ||||      S rO   )unpack_response)rC   response	cursor_idcodec_optionsuser_fieldslegacy_responses         rK   _unpack_responsez#AsyncCommandCursor._unpack_response   s     ''	=+__rM   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::

            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.
        )boolrX   r,   r9   rQ   s    rK   alivezAsyncCommandCursor.alive   s#     C

O9DLL(8::rM   c                    | j                   S )zReturns the id of the cursor.)r+   rQ   s    rK   rf   zAsyncCommandCursor.cursor_id   s     xxrM   c                    | j                   S )zUThe (host, port) of the server used, or None.

        .. versionadded:: 3.0
        )r/   rQ   s    rK   rF   zAsyncCommandCursor.address   s     }}rM   c                4    | j                   r| j                  S y)zThe cursor's :class:`~pymongo.asynchronous.client_session.AsyncClientSession`, or None.

        .. versionadded:: 3.6
        N)r8   r7   rQ   s    rK   rH   zAsyncCommandCursor.session   s     !!== rM   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_killedrf   rF   s       rK   _prepare_to_diez"AsyncCommandCursor._prepare_to_die   sl    88NI==,,,$T]]DHH=G
 '!! IG'!!rM   c                    | j                         \  }}| j                  j                  j                  j	                  ||| j
                  | j                  | j                         | j                  sd| _        d| _        y)z,Closes this cursor without acquiring a lock.N)rs   r*   r2   r3   _cleanup_cursor_no_lockr)   r7   r8   rC   rf   rF   s      rK   rP   zAsyncCommandCursor._die_no_lock   sg    !113	7!!((@@wt?U?U	
 %% DMrM   c                  K   | j                         \  }}| j                  j                  j                  j	                  ||| j
                  | j                  | j                         d{    | j                  sd| _        d| _        y7 w)zCloses this cursor.N)rs   r*   r2   r3   _cleanup_cursor_lockr)   r7   r8   rv   s      rK   	_die_lockzAsyncCommandCursor._die_lock   s~     !113	7''..CCNNMM""
 	
 	
 %% DM	
s   A(B*B
+ Bc                z    | j                   r/| j                  s"| j                   j                          d | _         y y y rO   )r7   r8   _end_implicit_sessionrQ   s    rK   r;   zAsyncCommandCursor._end_session   s/    ==!7!7MM//1 DM "8=rM   c                @   K   | j                          d{    y7 w)z$Explicitly close / kill this cursor.N)ry   rQ   s    rK   r_   zAsyncCommandCursor.close   s     nn   c                  K   | j                   j                  j                  }	 |j                  || j                  | j
                         d{   }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                          d{    t;        |      | _        y7 # t        $ rU}|j                  t        v rd| _	        |j                  r| j                           | j                          d{  7    d}~wt        $ r" d| _	        | j                          d{  7    t        $ r | j                          d{  7    w xY w7 ĭw)	z/Send a getmore message and handle the response.)rF   NTr   cursor	nextBatchr'   r%   )r*   r2   r3   _run_operationrj   r/   r   coder   r9   r5   rP   r_   r   	Exceptionr?   r   r)   r   r`   more_to_comefrom_commanddocsr-   r.   r+   datar   rf   r   r,   )rC   	operationr3   re   excr   	documentss          rK   _send_messagez AsyncCommandCursor._send_message   s    !!**11	#22400$-- 3  H. h/>>!3HMM8CXCX!Y  ]]1%h/F{+I)/4J)KD&d|DH IhmmX666}}..DH88q=**,9%
M   		xx00#{{!!#  jjl""  	DL**, 	**,	$ sl   !H+E EE C*H>H?HE 	H  A	F0)F,*F00&H G!H 8G;9H  Hc                  K   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$                               d{    n| j'                          d{    t        | j                        S 7 27 w)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.
        .rT   FN)rX   r,   r9   r+   r<   splitr*   _read_preference_forrH   r   _getmore_classr0   rg   r7   r2   r3   r1   r)   r:   ry   )rC   dbnamecollname	read_prefs       rK   _refreshzAsyncCommandCursor._refresh&  s     tzz?dlltzz?"88#xx~~c15FH((==dllKI$$##$$HH$$22MM$$--44++NNMM  " .."""4::'" #s$   D#E%E&E>E?EEc                    | S rO    rQ   s    rK   	__aiter__zAsyncCommandCursor.__aiter__H  s    rM   c                   K   | j                   r*| j                  d       d{   }||S | j                   r*t        7 w)zAdvance the cursor.TN)rm   	_try_nextStopAsyncIteration)rC   docs     rK   nextzAsyncCommandCursor.nextK  s@      jjt,,C
 jj
 ! 	 -s   !A?AAc                >   K   | j                          d {   S 7 wrO   )r   rQ   s    rK   	__anext__zAsyncCommandCursor.__anext__U  s     YY[   s   c                   K   t        | j                        s&| j                  s|r| j                          d{    t        | j                        r| j                  j	                         S y7 4w)z<Advance the cursor blocking for at most one getMore command.N)rX   r,   r9   r   popleft)rC   get_more_alloweds     rK   r   zAsyncCommandCursor._try_nextX  sO     4::t||8H--/!!tzz?::%%''	 "s   7A0A.5A0c                  K   t        | j                        s$| j                  s| j                          d{    t        | j                        r|6|j	                  | j                         | j                  j                          yt        t        t        | j                        |            D ]+  }|j                  | j                  j                                - yy7 w)z4Get all or some available documents from the cursor.NTF)
rX   r,   r9   r   extendclearrangeminappendr   )rC   resulttotal_s       rK   _next_batchzAsyncCommandCursor._next_batcha  s     4::t||--/!!tzz?}djj)

  "  s3tzz?E:; 8AMM$**"4"4"678 "s   5C#C!B*C#c                B   K   | j                  d       d{   S 7 w)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   rQ   s    rK   try_nextzAsyncCommandCursor.try_nextp  s       ^^T^::::s   c                   K   | S wrO   r   rQ   s    rK   
__aenter__zAsyncCommandCursor.__aenter__  s     s   c                @   K   | j                          d {    y 7 wrO   )r_   )rC   exc_typeexc_valexc_tbs       rK   	__aexit__zAsyncCommandCursor.__aexit__  s     jjlr}   c                   K   g }|}t        |t              r|dk  rt        d      | j                  rB| j	                  ||       d{   s	 |S ||t        |      z
  }|dk(  r	 |S | j                  rB|S 7 .w)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
        rT   z'to_list() length must be greater than 0Nr   )r?   r@   rV   rm   r   rX   )rC   lengthres	remainings       rK   to_listzAsyncCommandCursor.to_list  s       $&	fc"vzFGGjj))#y999
 
	 !"SX-	>
 jj 
 :s   AA9A7	+A95A9r   NNFNrD   zAsyncCollection[_DocumentType]rE   zMapping[str, Any]rF   Optional[_Address]r>   r@   rG   Optional[int]rH   Optional[AsyncClientSession]rI   rl   rJ   r   returnNone)r   r   )r>   r@   r   !AsyncCommandCursor[_DocumentType])r   rl   )r   Optional[Mapping[str, Any]])r`   r!   r   r   NF)re   Union[_OpReply, _OpMsg]rf   r   rg   zCodecOptions[Mapping[str, Any]]rh   r   ri   rl   r   zSequence[_DocumentOut])r   r@   )r   r   )r   r   )r   z$tuple[int, Optional[_CursorAddress]])r   r   r   r   )r   zAsyncIterator[_DocumentType])r   r   )r   rl   r   Optional[_DocumentType]rO   )r   listr   r   r   rl   )r   r   )r   r   )r   r   r   r   r   r   r   r   )r   r   r   zlist[_DocumentType])$__name__
__module____qualname____doc__r   r   rL   rR   r>   rY   propertyr[   rb   rj   rm   rf   rF   rH   rs   rP   ry   r;   r_   r   r   r   r   r   r   r   r   r   r   r   applyr   r   rM   rK   r#   r#   6   s   AN +/04!&(2( '( $	(
 ( )( .( ( ( 
(T.# * **& 48 %`)` !` 7	`
 1` ` 
 ` ; ;       "!
*&X D!!;$ [[ rM   r#   c                  ~     e Zd ZeZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )	AsyncRawBatchCommandCursorc	           
     X    |j                  d      rJ t        	| 	  ||||||||       y)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>`_.
        r&   N)r-   superrL   )
rC   rD   rE   rF   r>   rG   rH   rI   rJ   	__class__s
            rK   rL   z#AsyncRawBatchCommandCursor.__init__  s<    & ??<000		
rM   c                L    |j                  ||      }|st        |d          |S )N)rh   r   )raw_responser   )rC   re   rf   rg   rh   ri   r   s          rK   rj   z+AsyncRawBatchCommandCursor._unpack_response  s0      ,,YK,P 3<?CrM   c                    t        d      )Nz5Cannot call __getitem__ on AsyncRawBatchCommandCursor)r   )rC   indexs     rK   __getitem__z&AsyncRawBatchCommandCursor.__getitem__  s    VWWrM   r   r   r   )re   r   rf   r   rg   r   rh   r   ri   rl   r   zlist[Mapping[str, Any]])r   r@   r   r
   )	r   r   r   r   r   rL   rj   r   __classcell__)r   s   @rK   r   r     s    %N +/04!&
2
 '
 $	

 
 )
 .
 
 
 

H 48 %) ! $	
 1  
!XrM   r   N)1r   
__future__r   collectionsr   typingr   r   r   r   r	   r
   r   r   r   bsonr   r   pymongor   pymongo.asynchronous.cursorr   pymongo.cursor_sharedr   pymongo.errorsr   r   r   pymongo.messager   r   r   r   r   pymongo.responser   pymongo.typingsr   r   r   #pymongo.asynchronous.client_sessionr   pymongo.asynchronous.collectionr    pymongo.asynchronous.poolr!   _IS_SYNCr#   r   r   rM   rK   <module>r      s    ; " 
 
 
 F  : 7 P P  , A AF?9m/ m`2X!3M!B 2XrM   