
    nh@                    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	                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/synchronous/command_cursor.py__init__zCommandCursor.__init__;   s     #6@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CommandCursor.__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CommandCursor.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CommandCursor._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&CommandCursor._post_batch_resume_token   s    
 )))rM   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       rK   _maybe_pin_connectionz#CommandCursor._maybe_pin_connection   sn    !!**11((7~~OO)$6H xx1} !) rM   c                *    |j                  ||||      S rO   )unpack_response)rC   response	cursor_idcodec_optionsuser_fieldslegacy_responses         rK   _unpack_responsezCommandCursor._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::

            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CommandCursor.alive   s#     C

O9DLL(8::rM   c                    | j                   S )zReturns the id of the cursor.)r+   rQ   s    rK   rf   zCommandCursor.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CommandCursor.address   s     }}rM   c                4    | j                   r| j                  S y)zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None.

        .. versionadded:: 3.6
        N)r8   r7   rQ   s    rK   rH   zCommandCursor.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CommandCursor._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CommandCursor._die_no_lock   sg    !113	7!!((@@wt?U?U	
 %% DMrM   c                    | j                         \  }}| j                  j                  j                  j	                  ||| j
                  | j                  | j                         | j                  sd| _        d| _        y)zCloses this cursor.N)rs   r*   r2   r3   _cleanup_cursor_lockr)   r7   r8   rv   s      rK   	_die_lockzCommandCursor._die_lock   sk    !113	7!!((==NNMM""	
 %% DMrM   c                z    | j                   r/| j                  s"| j                   j                          d | _         y y y rO   )r7   r8   _end_implicit_sessionrQ   s    rK   r;   zCommandCursor._end_session   s/    ==!7!7MM//1 DM "8=rM   c                $    | j                          y)z$Explicitly close / kill this cursor.N)ry   rQ   s    rK   r_   zCommandCursor.close   s    rM   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_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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.
        .rT   F)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CommandCursor._refresh&  s     tzz?dlltzz?"88#xx~~c15FH((==dllKI##$$HH$$22MM$$--44++NNMM" NN4::rM   c                    | S rO    rQ   s    rK   __iter__zCommandCursor.__iter__H      rM   c                j    | j                   r"| j                  d      }||S | j                   r"t        )zAdvance the cursor.T)rm   	_try_nextStopIteration)rC   docs     rK   nextzCommandCursor.nextK  s4     jj..&C
 jj
 rM   c                "    | j                         S rO   )r   rQ   s    rK   __next__zCommandCursor.__next__U  s    yy{rM   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)rX   r,   r9   r   popleft)rC   get_more_alloweds     rK   r   zCommandCursor._try_nextX  s@    4::t||8HMMOtzz?::%%''rM   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)
rX   r,   r9   r   extendclearrangeminappendr   )rC   resulttotal_s       rK   _next_batchzCommandCursor._next_batcha  s    4::t||MMOtzz?}djj)

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

rM   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
        rT   z'to_list() length must be greater than 0r   )r?   r@   rV   rm   r   rX   )rC   lengthres	remainings       rK   to_listzCommandCursor.to_list  s      $&	fc"vzFGGjj##C3
 
	 !"SX-	>
 jj 
rM   r   NNFNrD   zCollection[_DocumentType]rE   zMapping[str, Any]rF   Optional[_Address]r>   r@   rG   Optional[int]rH   Optional[ClientSession]rI   rl   rJ   r   returnNone)r   r   )r>   r@   r   CommandCursor[_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Iterator[_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   3N +/+/!&(-( '( $	(
 ( )( )( ( ( 
(T.# * **& 48 %`)` !` 7	`
 1` ` 
 ` ; ;       "!
*&X D5$ [[ rM   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-   superrL   )
rC   rD   rE   rF   r>   rG   rH   rI   rJ   	__class__s
            rK   rL   zRawBatchCommandCursor.__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&RawBatchCommandCursor._unpack_response  s0      ,,YK,P 3<?CrM   c                    t        d      )Nz0Cannot call __getitem__ on RawBatchCommandCursor)r   )rC   indexs     rK   __getitem__z!RawBatchCommandCursor.__getitem__  s    QRRrM   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 +/+/!&
-
 '
 $	

 
 )
 )
 
 
 

H 48 %) ! $	
 1  
!SrM   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   rM   rK   <module>r      s    ; " 
 
 
 F  7 P P  , 9 A A@93mGM* m`2SM-8 2SrM   