
    h*                     x    d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
mZmZmZ  G d de      Z G d d	e      Zy
)z4CommandCursor class to iterate over command results.    )deque)integer_types)ConnectionFailureInvalidOperationNotMasterErrorOperationFailure)_CursorAddress_GetMore_RawBatchGetMorec                       e Zd ZdZeZ	 	 	 ddZd ZddZd Z	d Z
d Zd	 Zed
        Zd Z	 ddZd Zed        Zed        Zed        Zed        Zd Zd ZeZd Zd Zd Zy)CommandCursorz)A cursor / iterator over command cursors.Nc	                    || _         |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)	zSCreate a new command cursor.

        The parameter 'retrieved' is unused.
        id
firstBatchpostBatchResumeTokenr   TnsNz,max_await_time_ms must be an integer or None)_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__end_session_CommandCursor__ns	full_name
batch_size
isinstancer   	TypeError)	self
collectioncursor_infoaddress	retrievedr!   max_await_time_mssessionexplicit_sessions	            Y/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/command_cursor.py__init__zCommandCursor.__init__!   s     '%	K56&1oo6L&M# &#4  "2a==t$;#D)DI",,DI
#,m<%1JKK 2 =    c                 X    | j                   r| j                  s| j                          y y y N)r   r   _CommandCursor__dier$   s    r,   __del__zCommandCursor.__del__@   s    99T]]JJL +9r.   c                    | j                   }d| _         | j                  r|st        | j                  | j                  j
                        }|rG| j                  j                  j                  j                  | j                  || j                         n:| j                  j                  j                  j                  | j                  |       | j                  |       y)zCloses this cursor.
        T)r*   N)r   r   r	   r   r   r    databaseclient_close_cursor_nowr   _close_cursorr   )r$   synchronousalready_killedr'   s       r,   __diezCommandCursor.__dieD   s     99^$ 1 1 ; ;=G!!**11CCIIw D @ !!**11??IIw(;'r.   c                 ~    | j                   r1| j                  s$| j                   j                  |       d | _         y y y )N)lock)r   r   _end_session)r$   r9   s     r,   __end_sessionzCommandCursor.__end_sessionU   s4    >>$"9"9NN''['9!DN #:>r.   c                 &    | j                  d       y)z-Explicitly close / kill this cursor.
        TN)r1   r2   s    r,   closezCommandCursor.closeZ   s     	

4r.   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``.

        :Parameters:
          - `batch_size`: The size of each batch of results requested.
        zbatch_size must be an integerr   zbatch_size must be >= 0      )r"   r   r#   
ValueErrorr   )r$   r!   s     r,   r!   zCommandCursor.batch_size_   sH      *m4;<<>677&!O1?Zr.   c                 2    t        | j                        dkD  S )zUReturns `True` if the cursor has documents remaining from the
        previous batch.r   )lenr   r2   s    r,   	_has_nextzCommandCursor._has_nextw   s     4;;!##r.   c                     | j                   S )zcRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.)r   r2   s    r,   _post_batch_resume_tokenz&CommandCursor._post_batch_resume_token|   s     ***r.   c                 X     fd} j                   j                  j                  }	 |j                  | j                   j
                        }|j                  }|j                  }|j                  }|r.|d   d   }|d   }	|j                  d       _        |d    _        n|}	|j"                   _         j                   dk(  r |        t%        |	       _        y# t        $ r	  |         t        $ r	  |         t        $ r	  |         t        $ r  j                           w xY w)	z8Send a getmore message and handle the response.
        c                  6    d _          j                  d       y )NT)r   r   r2   s   r,   killz*CommandCursor.__send_message.<locals>.kill   s     DMt$r.   )r'   r   cursor	nextBatchr   r   N)r   r5   r6   _run_operation_with_response_unpack_responser   r   r   r   	Exceptionr1   from_commanddatadocsr   r   r   	cursor_idr   r   )
r$   	operationrM   r6   responserS   replyrU   rN   	documentss
   `         r,   __send_messagezCommandCursor.__send_message   s"   	% ""++22	::400$.. ; JH,  ,,}}!WX&F{+I*0**5K*LD'tDIIDI99>FI&G   	F 	 F  	
 F 	JJL	s   (C AD)c                 *    |j                  ||||      S r0   )unpack_responser$   rX   rV   codec_optionsuser_fieldslegacy_responses         r,   rQ   zCommandCursor._unpack_response   s    ''	=+(79 	9r.   c                 p   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                   d
             nd| _        | 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.
        .rC   FT)rG   r   r   r   r   splitr   _read_preference_forr*   _CommandCursor__send_message_getmore_classr   r_   r   r5   r6   r   r   )r$   dbnamecollname	read_prefs       r,   _refreshzCommandCursor._refresh   s     t{{t}}t{{##99#yysA6FH))>>t||LI##F$,$($5$5$(II$($5$5$C$C$-$(NN$($5$5$>$>$E$E$($<$<$)	+
, !DMt$4;;r.   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.
        )boolrG   r   r   r2   s    r,   alivezCommandCursor.alive   s$     C$;T]]):<<r.   c                     | j                   S )zReturns the id of the cursor.)r   r2   s    r,   rV   zCommandCursor.cursor_id   s     yyr.   c                     | j                   S )zUThe (host, port) of the server used, or None.

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

        .. versionadded:: 3.6
        N)r   r   r2   s    r,   r*   zCommandCursor.session   s     "">>! #r.   c                     | S r0    r2   s    r,   __iter__zCommandCursor.__iter__       r.   c                 j    | j                   r"| j                  d      }||S | j                   r"t        )zAdvance the cursor.T)rn   	_try_nextStopIteration)r$   docs     r,   nextzCommandCursor.next   s4     jj..&C
 jj
 r.   c                    t        | j                        s| j                  s|r| j                          t        | j                        r@| j                  }|j
                  j                  | j                  j                         |      S y)z<Advance the cursor blocking for at most one getMore command.N)rG   r   r   rk   r   r5   _fix_outgoingpopleft)r$   get_more_allowedcolls      r,   rw   zCommandCursor._try_next  s^    4;;:JMMOt{{$$D==..t{{/B/B/DdKKr.   c                     | S r0   rs   r2   s    r,   	__enter__zCommandCursor.__enter__  ru   r.   c                 $    | j                          y r0   )rA   )r$   exc_typeexc_valexc_tbs       r,   __exit__zCommandCursor.__exit__  s    

r.   r   r   NNF)FNF)__name__
__module____qualname____doc__r
   rg   r-   r3   r1   r   rA   r!   rH   propertyrJ   rf   rQ   rk   rn   rV   r'   r*   rt   rz   __next__rw   r   r   rs   r.   r,   r   r      s    3NCD?C"'L>(""

0$
 + +
.'b <A9
 < = =      " " Hr.   r   c                   :     e Zd ZeZ	 	 	 d fd	Z	 ddZd Z xZS )RawBatchCommandCursorc	           
      `    |j                  d      rJ t        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.collection.Collection.aggregate_raw_batches`
        instead.

        .. mongodoc:: cursors
        r   N)r   superr   r-   )
r$   r%   r&   r'   r(   r!   r)   r*   r+   	__class__s
            r,   r-   zRawBatchCommandCursor.__init__  s:     ??<000#T3Wiw(8	:r.   c                 $    |j                  |      S r0   )raw_responser^   s         r,   rQ   z&RawBatchCommandCursor._unpack_response/  s    $$Y//r.   c                     t        d      )Nz)Cannot call __getitem__ on RawBatchCursor)r   )r$   indexs     r,   __getitem__z!RawBatchCommandCursor.__getitem__3  s    JKKr.   r   r   )	r   r   r   r   rg   r-   rQ   r   __classcell__)r   s   @r,   r   r     s'    %NCD?C"':" <A0Lr.   r   N)r   collectionsr   bson.py3compatr   pymongo.errorsr   r   r   r   pymongo.messager	   r
   r   objectr   r   rs   r.   r,   <module>r      sA    ;  (. ./ /
|F |~LM Lr.   