
    h.                         d Z ddlmZ ddlmZ ddl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 ddlmZ  G d	 d
e      Z G d de      Zy)z4CommandCursor class to iterate over command results.    )deque)&_convert_raw_document_lists_to_streams)integer_types)_CURSOR_CLOSED_ERRORS_SocketManager)ConnectionFailureInvalidOperationOperationFailure)_CursorAddress_GetMore_RawBatchGetMore)PinnedResponsec                       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 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| _         || _        |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.
        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__end_session_CommandCursor__ns	full_name
batch_size
isinstancer   	TypeError)	self
collectioncursor_infoaddress	retrievedr%   max_await_time_mssessionexplicit_sessions	            T/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/pymongo/command_cursor.py__init__zCommandCursor.__init__    s     &%	K56&1oo6L&M# &#4  "2		Q==t$;#D)DI",,DI
#+];@Q@]JKK A^;    c                 $    | j                          y N_CommandCursor__dier(   s    r0   __del__zCommandCursor.__del__G       

r2   c                    | j                   }d| _         | j                  r/|s-| j                  }t        | j                  | j                        }nd}d}| j
                  j                  j                  j                  |||| j                  | j                  | j                         | j                  sd| _
        d| _	        y)zCloses this cursor.Tr   N)r!   r   r   r   r#   r   databaseclient_cleanup_cursorr   r   r    )r(   synchronousalready_killed	cursor_idr+   s        r0   __diezCommandCursor.__dieJ   s    99^		I$T^^TYY?G IG""))99OONN##	
 &&!DNr2   c                 ~    | j                   r1| j                  s$| j                   j                  |       d | _         y y y )N)lock)r   r    _end_session)r(   r>   s     r0   __end_sessionzCommandCursor.__end_sessiona   s4    >>$"9"9NN''['9!DN #:>r2   c                 &    | j                  d       y)z$Explicitly close / kill this cursor.TNr5   r7   s    r0   closezCommandCursor.closef   s    

4r2   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     r0   r%   zCommandCursor.batch_sizej   sH      *m4;<<>677&!O1?Zr2   c                 2    t        | j                        dkD  S )zUReturns `True` if the cursor has documents remaining from the
        previous batch.r   )lenr   r7   s    r0   	_has_nextzCommandCursor._has_next   s     4;;!##r2   c                     | j                   S )zcRetrieve the postBatchResumeToken from the response to a
        changeStream aggregate or getMore.)r   r7   s    r0   _post_batch_resume_tokenz&CommandCursor._post_batch_resume_token   s     ***r2   c                    | j                   j                  j                  }|j                  | j                        sy | j
                  sD|j                          t        |d      }| j                  dk(  r|j                          y || _        y y )NFr   )
r   r;   r<   _should_pin_cursorr   r   
pin_cursorr   r   rG   )r(   	sock_infor<   sock_mgrs       r0   _maybe_pin_connectionz#CommandCursor._maybe_pin_connection   sp    ""++22((8  "%i7H yyA~ "* r2   c                 4   | j                   j                  j                  }	 |j                  || j                  | j
                        }t        |t              r1| j                  s%t!        |j"                  |j$                        | _        |j&                  r8|j(                  d   d   }|d   }|j+                  d      | _        |d   | _        n'|j(                  }|j0                  j2                  | _        | j.                  dk(  r| j                          t5        |      | _        y# t        $ r/}|j                  t        v r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+   TNr   cursor	nextBatchr   r   )r   r;   r<   _run_operation_unpack_responser   r
   coder   r!   rG   r   	Exceptionr&   r   r   r   socket_infomore_to_comefrom_commanddocsr   r   r   datar@   r   r   )r(   	operationr<   responseexcrX   	documentss          r0   __send_messagezCommandCursor.__send_message   sO   ""++22	,,400$.. - H( h/??"01E1ExG\G\"]  ]]1%h/F{+I*0**5K*LD'tDI I //DI99>JJLI&?   	xx00 $JJL  	 DMJJL 	JJL	s   (D& &	F/*E>Fc                 *    |j                  ||||      S r4   )unpack_response)r(   rd   r@   codec_optionsuser_fieldslegacy_responses         r0   r[   zCommandCursor._unpack_response   s     ''	=+__r2   c                 x   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             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.
        .rI   FT)rM   r   r!   r   r#   splitr   _read_preference_forr.   _CommandCursor__send_message_getmore_classr   rj   r   r;   r<   r   r   r6   )r(   dbnamecollname	read_prefs       r0   _refreshzCommandCursor._refresh   s     t{{t}}t{{##99#yysA6FH))>>t||LI##%%II%%33NN%%..55,,OO  JJt4;;r2   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.
        )boolrM   r   r!   r7   s    r0   alivezCommandCursor.alive   s$     C$;T]]):<<r2   c                     | j                   S )zReturns the id of the cursor.)r   r7   s    r0   r@   zCommandCursor.cursor_id   s     yyr2   c                     | j                   S )zUThe (host, port) of the server used, or None.

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

        .. versionadded:: 3.6
        N)r    r   r7   s    r0   r.   zCommandCursor.session  s     "">>! #r2   c                     | S r4    r7   s    r0   __iter__zCommandCursor.__iter__      r2   c                 j    | j                   r"| j                  d      }||S | j                   r"t        )zAdvance the cursor.T)ry   	_try_nextStopIteration)r(   docs     r0   nextzCommandCursor.next  s4     jj..&C
 jj
 r2   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)rM   r   r!   rv   r   r;   _fix_outgoingpopleft)r(   get_more_allowedcolls      r0   r   zCommandCursor._try_next  s^    4;;:JMMOt{{$$D==..t{{/B/B/DdKKr2   c                     | S r4   r~   r7   s    r0   	__enter__zCommandCursor.__enter__)  r   r2   c                 $    | j                          y r4   )rG   )r(   exc_typeexc_valexc_tbs       r0   __exit__zCommandCursor.__exit__,  r9   r2   r   r   NNF)FNF)__name__
__module____qualname____doc__r   rr   r1   r8   r6   r"   rG   r%   rN   propertyrP   rV   rq   r[   rv   ry   r@   r+   r.   r   r   __next__r   r   r   r~   r2   r0   r   r      s    3N %LN."
0$
 + +
+&'R UZ`
 B = =      " " Hr2   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)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   superr   r1   )
r(   r)   r*   r+   r,   r%   r-   r.   r/   	__class__s
            r0   r1   zRawBatchCommandCursor.__init__3  s?    & ??<000#T3		
r2   c                 L    |j                  ||      }|st        |d          |S )N)rk   r   )raw_responser   )r(   rd   r@   rj   rk   rl   r   s          r0   r[   z&RawBatchCommandCursor._unpack_responseR  s0      ,,YK,P 3<?Cr2   c                     t        d      )Nz)Cannot call __getitem__ on RawBatchCursor)r	   )r(   indexs     r0   __getitem__z!RawBatchCommandCursor.__getitem__\  s    JKKr2   r   r   )	r   r   r   r   rr   r1   r[   r   __classcell__)r   s   @r0   r   r   0  s1    %N 
@ UZLr2   r   N)r   collectionsr   bsonr   bson.py3compatr   pymongo.cursorr   r   pymongo.errorsr   r	   r
   pymongo.messager   r   r   pymongo.responser   objectr   r   r~   r2   r0   <module>r      sB    ;  7 ( @ P P F F +RF Rj-LM -Lr2   