
    hh                     j   d Z ddlZddlmZ ddlmZ ddl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mZ dd
lmZmZmZmZ ddlmZmZ ddlmZmZmZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& dZ'dZ(dZ)dZ*dZ+dZ,dZ- G d de.      Z/d Z0d Z1 G d de.      Z2 G d de.      Z3 G d de.      Z4 G d d e.      Z5y)!z<The bulk write operations interface.

.. versionadded:: 2.7
    N)islice)ObjectId)RawBSONDocument)SON)_validate_session_write_concern)validate_collation_or_none)validate_is_document_typevalidate_is_mappingvalidate_ok_for_replacevalidate_ok_for_update)BulkWriteErrorConfigurationErrorInvalidOperationOperationFailure)_RETRYABLE_ERROR_CODES_get_wce_doc)_DELETE_INSERT_UPDATE_BulkWriteContext_do_batched_insert_EncryptedBulkWriteContext_randint)ReadPreference)WriteConcern         @   )insertupdatedeleteopc                   "    e Zd ZdZd Zd Zd Zy)_Runz'Represents a batch of write operations.c                 <    || _         g | _        g | _        d| _        y)zInitialize a new Run object.r   N)op_type	index_mapops
idx_offset)selfr'   s     J/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/pymongo/bulk.py__init__z_Run.__init__H   s        c                      | j                   |   S )zGet the original index of an operation in this run.

        :Parameters:
          - `idx`: The Run index that maps to the original index.
        )r(   )r+   idxs     r,   indexz
_Run.indexO   s     ~~c""r.   c                 p    | j                   j                  |       | j                  j                  |       y)zAdd an operation to this Run instance.

        :Parameters:
          - `original_index`: The original index of this operation
            within a larger bulk operation.
          - `operation`: The operation document.
        N)r(   appendr)   )r+   original_index	operations      r,   addz_Run.addW   s&     	n-	"r.   N)__name__
__module____qualname____doc__r-   r1   r6    r.   r,   r%   r%   E   s    1#	#r.   r%   c                    |j                  dd      }| j                  t        k(  r|dxx   |z  cc<   n| j                  t        k(  r|dxx   |z  cc<   n| j                  t        k(  r|j                  d      }|r^t        |      }|D ]  }| j                  |d   |z         |d<    |d   j                  |       |dxx   |z  cc<   |dxx   ||z
  z  cc<   n|dxx   |z  cc<   |d	xx   |d	   z  cc<   |j                  d
      }|r]|D ]X  }|j                         }	|d   |z   }
| j                  |
      |	d<   | j                  |
   |	t        <   |d
   j                  |	       Z t        |      }|r|d   j                  |       yy)z7Merge a write command result into the full bulk result.nr   	nInsertednRemovedupsertedr1   	nUpsertednMatched	nModifiedwriteErrorswriteConcernErrorsN)getr'   r   r   r   lenr1   extendcopyr)   _UOPr3   r   )runfull_resultoffsetresultaffectedr@   
n_upserteddocwrite_errorsreplacementr0   wces               r,   _merge_commandrU   c   s   zz#q!H
{{gK H, 		J8+		::j)XJ @"yyW)>?G@
#**84$
2$
#x*'<<#
#x/#K F;$77 ::m,L 	;C((*Kg,'C#&99S>K  #K&--k:	; v
C
()005 r.   c                 N    | d   r| d   j                  d        t        |       )z5Raise a BulkWriteError from the full bulk api result.rD   c                     | d   S )Nr1   r;   )errors    r,   <lambda>z)_raise_bulk_write_error.<locals>.<lambda>   s
    %. r.   )key)sortr   )rL   s    r,   _raise_bulk_write_errorr\      s,    =!M"'',H'I

%%r.   c                       e Zd ZdZd Zed        Zd Z	 	 	 	 	 ddZddZ	ddZ
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zy)_Bulkz'The private guts of the bulk write API.c                 
   |j                  |j                  j                  dt                    | _        || _        g | _        d| _        || _        d| _	        d| _
        d| _        d| _        d| _        d| _        d| _        y)zInitialize a _Bulk instance.replace)unicode_decode_error_handlerdocument_class)codec_optionsFTN)with_optionsrc   _replacedict
collectionorderedr)   executedbypass_doc_valuses_collationuses_array_filters	uses_hintis_retryableretryingstarted_retryable_writecurrent_runr+   rg   rh   bypass_document_validations       r,   r-   z_Bulk.__init__   s    $11$22;;-6t <  2 

 8#"' ',$r.   c                     | j                   j                  j                  j                  }|r|j                  st
        S t        S N)rg   databaseclient
_encrypter_bypass_auto_encryptionr   r   )r+   	encrypters     r,   bulk_ctx_classz_Bulk.bulk_ctx_class   s4    OO,,33>>	Y>>--$$r.   c                     t        d|       t        |t              sd|v st               |d<   | j                  j                  t        |f       y)z*Add an insert document to the list of ops.document_idN)r	   
isinstancer   r   r)   r3   r   r+   r}   s     r,   
add_insertz_Bulk.add_insert   s=    !*h78_5(9J&jHUO(+,r.   Nc                    t        |       t        d|fd|fd|fd|fg      }t        |      }|d| _        ||d<   |d| _        ||d<   |d| _        ||d	<   |rd
| _        | j                  j                  t        |f       y)z8Create an update document and add it to the list of ops.qumultiupsertNT	collationarrayFiltershintF)
r   r   r   rk   rl   rm   rn   r)   r3   r   )	r+   selectorr!   r   r   r   array_filtersr   cmds	            r,   
add_updatez_Bulk.add_update   s     	v&C?S&MGU3ChPVEWXY.y9	 "&D(C$&*D#"/C!DNCK %D#'r.   c                     t        |       t        d|fd|fdd|fg      }t        |      }|d| _        ||d<   |d| _        ||d<   | j
                  j                  t        |f       y)	z8Create a replace document and add it to the list of ops.r   r   )r   Fr   NTr   r   )r   r   r   rk   rm   r)   r3   r   )r+   r   rS   r   r   r   r   s          r,   add_replacez_Bulk.add_replace   sy    ,C?S+$68H8U[J\]^.y9	 "&D(C!DNCK#'r.   c                     t        d|fd|fg      }t        |      }|d| _        ||d<   |d| _        ||d<   |t        k(  rd| _        | j                  j                  t        |f       y)z7Create a delete document and add it to the list of ops.r   limitNTr   r   F)	r   r   rk   rm   _DELETE_ALLrn   r)   r3   r   )r+   r   r   r   r   r   s         r,   
add_deletez_Bulk.add_delete   sv    C?We$456.y9	 "&D(C!DNCKK %D#'r.   c              #      K   d}t        | j                        D ]F  \  }\  }}|t        |      }n|j                  |k7  r| t        |      }|j	                  ||       H | yw)ziGenerate batches of operations, batched by type of
        operation, in the order **provided**.
        N)	enumerater)   r%   r'   r6   )r+   rK   r0   r'   r5   s        r,   gen_orderedz_Bulk.gen_ordered   sl      )2488)< 	$%C%'9{7m'	7mGGC#	$ 	s   A&A(c              #      K   t        t              t        t              t        t              g}t	        | j
                        D ]  \  }\  }}||   j                  ||        |D ]  }|j
                  s|  yw)zbGenerate batches of operations, batched by type of
        operation, in arbitrary order.
        N)r%   r   r   r   r   r)   r6   )r+   
operationsr0   r'   r5   rK   s         r,   gen_unorderedz_Bulk.gen_unordered   st      7mT']DMB
)2488)< 	4%C%'9w##C3	4  	Cww		s   A3A=6A=c           
         |j                   dk  r.| j                  rt        d      | j                  rt        d      |j                   dk  r| j                  rt        d      | j
                  j                  j                  }| j
                  j                  j                  }	|	j                  }
| j                  st        |      | _
        | j                  }|j                  |	|       |rt        |j                     }| j                  |||||
||j                  | j
                  j                         }|j"                  t%        |j&                        k  rt)        || j
                  j                  fd| j*                  fg      }|j,                  s|j.                  |d<   | j0                  r|j                   dk\  rd	|d
<   |rG|r#| j2                  s|j5                          d	| _        |j7                  ||t8        j:                  |       |j=                  |||	       |j?                  |       tA        |j&                  |j"                  d       }|jC                  |||	      \  }}|jE                  di       }|jE                  dd      tF        v r8tI        jJ                  |      }tM        |||j"                  |       tO        |       tM        |||j"                  |       d| _(        d| _        | j*                  rd|v rnB|xj"                  t%        |      z  c_        |j"                  t%        |j&                        k  r| j*                  r|d   ry t        |d       x| _
        }|r~y y )N   z5Must be connected to MongoDB 3.4+ to use a collation.z.Must be connected to MongoDB 3.4+ to use hint.   z6Must be connected to MongoDB 3.6+ to use arrayFilters.rh   writeConcern   TbypassDocumentValidationwriteConcernErrorcoder   FrD   ))max_wire_versionrk   r   rm   rl   rg   rv   namerw   _event_listenersrq   nextvalidate_session	_COMMANDSr'   r{   rc   r*   rG   r)   r   rh   is_server_defaultr}   rj   rp   _start_retryable_write	_apply_tor   PRIMARYsend_cluster_timeadd_server_apir   executerF   r   rI   deepcopyrU   r\   ro   )r+   	generatorwrite_concernsession	sock_infoop_id	retryablerL   db_namerw   	listenersrK   cmd_namebwcr   r)   rN   to_sendrT   fulls                       r,   _execute_commandz_Bulk._execute_command
  s    %%)""()`aa~~()YZZ%%)d.E.E$%]^^//**//))00++	#ID 	""673 -H%%--	C ..3sww</Hdoo&:&:;i=VWX$66*7*@*@C'&&9+E+E+J6:C23 !)E)E6687;4%%c9n6L6LiX++C&A((-SWWcnnd;"%++c3"? jj!4b97761%)??  ==5D"3cnnfE+D1sKH %/4,<<MV$;#g,.G ..3sww</N ||M :%))T%::Dso r.   c           	      >    g g dddddg dt                fd} j                  j                  j                  }|j	                  |      5 }|j                   j                  ||        ddd       d   sd   rt               S # 1 sw Y    xY w)zExecute using write commands.r   rD   rE   r>   rA   rB   rC   r?   r@   c           	      4    j                  | ||       y ru   )r   )r   r   r   rL   r   r   r+   r   s      r,   retryable_bulkz-_Bulk.execute_command.<locals>.retryable_bulkh  s!    !!='9eYP[r.   NrD   rE   )r   rg   rv   rw   _tmp_session_retry_with_sessionrn   r\   )	r+   r   r   r   r   rw   srL   r   s	   ```    @@r,   execute_commandz_Bulk.execute_commandY  s     "$	
 
	 	
 ))00  ) 	SQ&&t'8'8.!TR	S }%5I)J#K0	S 	Ss   BBc                 4   | j                   j                  }dt        | j                        i}t	        d| j                   j
                  fd| j                  fd|fg      }| j                  r|j                  dk\  rd|d<   t        |j
                  d|||j                  j                  dt        | j                   j                  |		      }t        | j                   j                  |j                  d||| j                   | j                   j                  |       y)
z%Execute insert, returning no results.wr    rh   r   r   Tr   N)
cmd_legacy)rg   rv   intrh   r   r   rj   r   r   rw   r   r   rc   r   	full_namer)   )	r+   r   rK   r   acknowledgeddbconcernr   r   s	            r,   execute_insert_no_resultsz_Bulk.execute_insert_no_resultsu  s    __%%DLL)*,,-	4<</H>[bJcd
 9#=#=#B.2C*+GGII&&OO))

 	OO%%GGOO))		
r.   c           
      h   | j                   j                  j                  }| j                   j                  j                  }|j                  }t               }| j                  st        |      | _        | j                  }|r1t        |j                     }| j                  |||||d|j                  | j                   j                        }	|j                  t        |j                        k  rt        || j                   j                  fddddifg      }
|j!                  |
       t#        |j                  |j                  d      }|	j%                  |
||      }|xj                  t        |      z  c_        |j                  t        |j                        k  rt        |d      x| _        }|r0yy)zCExecute write commands with OP_MSG and w=0 writeConcern, unordered.N)rh   Fr   r   r   )rg   rv   r   rw   r   r   rq   r   r   r'   r{   rc   r*   rG   r)   r   r   r   execute_unack)r+   r   r   r   rw   r   r   rK   r   r   r   r)   r   s                r,   execute_op_msg_no_resultsz_Bulk.execute_op_msg_no_results  sh   //**//))00++	
#ID -H%%--	C ..3sww</!4??#7#78*'#q2 ((-SWWcnnd;++Cf=#g,. ..3sww</ &*)T%::Ds5 r.   c           	          g g dddddg d}t               }t               }	 | j                  ||d||d|       y# t        $ r Y yw xY w)zAExecute write commands with OP_MSG and w=0 WriteConcern, ordered.r   r   NF)r   r   r   r   )r+   r   r   rL   r   r   s         r,   execute_command_no_resultsz _Bulk.execute_command_no_results  si     "$	
 %
	!!=$	5%   		s   9 	AAc                 :   | j                   rt        d      | j                  rt        d      | j                  rt        d      | j                  r|j
                  dk\  rt        d      |j
                  dkD  r0| j                  r| j                  ||      S | j                  ||      S | j                  }t        t        | j                              }t               }t        |      }|r|}t        |d      }| j                  xr |du}	 |j                  t         k(  r| j#                  ||||       n|j                  t$        k(  rx|j&                  D ]h  }	|	d	   }
d
}|
r%t        t)        |
            j+                  d      rd}|j-                  ||	d   |
|	d   ||	d   ||| j                  | j                  
       j n8|j&                  D ])  }	|j/                  ||	d   |	d    ||| j                         + |ryy# t        $ r | j                  rY yY w xY w)z3Execute all operations, returning no results (w=0).z3Collation is unsupported for unacknowledged writes.z6arrayFilters is unsupported for unacknowledged writes.z.hint is unsupported for unacknowledged writes.r   zGCannot set bypass_document_validation with unacknowledged write concernr   )r   Nr   T$Fr   r   r   )r   r   rh   rj   r   )rk   r   rl   rm   rj   r   r   rh   r   r   rg   r   r   r   r   r'   r   r   r   r)   iter
startswith_update_delete)r+   r   r   collr   r   next_runrK   	needs_ackr5   rQ   
check_keyss               r,   execute_no_resultsz_Bulk.execute_no_results  s   $%Z[[""$%]^^>>$%UVV9#=#=#B"\ 
 %%)||66y)LL11)YGG %s4<<'89
	? CIt,H=)=I!;;')229c5)T[[G+%(WW 	'n%)
4S	?#=#=c#B).J%%cN%h/&%g.*7"'$(LL+/+>+> % $ &)WW 	%%cN )' 22)! LL; L $ <<  s   C+H   HHc                    | j                   st        d      | j                  rt        d      d| _        |xs | j                  j                  }t        ||      }| j                  r| j                         }n| j                         }| j                  j                  j                  }|j                  s-|j                  |      5 }| j                  ||       ddd       y| j                  |||      S # 1 sw Y   yxY w)zExecute operations.zNo operations to executez*Bulk operations can only be executed once.TN)r)   r   ri   rg   r   r   rh   r   r   rv   rw   r   _socket_for_writesr   r   )r+   r   r   r   rw   r   s         r,   r   z_Bulk.execute  s    xx"#=>>=="#RSS%F)F)F1'=I<<((*I**,I))00))**73 >y''	9=> > ''	='JJ> >s   C55C>)FFNNN)FNN)NN)r7   r8   r9   r:   r-   propertyr{   r   r   r   r   r   r   r   r   r   r   r   r   r   r;   r.   r,   r^   r^      sw    1 ( % %- (8((
M;^8
@%;N0CJKr.   r^   c                   ,    e Zd ZdZdZd Zd Zd Zd Zy)BulkUpsertOperationz*An interface for adding upsert operations.
__selector__bulk__collationc                 .    || _         || _        || _        y ru   )_BulkUpsertOperation__selector_BulkUpsertOperation__bulk_BulkUpsertOperation__collationr+   r   bulkr   s       r,   r-   zBulkUpsertOperation.__init__5      "$r.   c                 l    | j                   j                  | j                  |dd| j                         y)zUpdate one document matching the selector.

        :Parameters:
          - `update` (dict): the update operations to apply
        FTr   r   r   Nr   r   r   r   r+   r!   s     r,   
update_onezBulkUpsertOperation.update_one:  s0     	OOV5IYIY 	 	
r.   c                 l    | j                   j                  | j                  |dd| j                         y)zUpdate all documents matching the selector.

        :Parameters:
          - `update` (dict): the update operations to apply
        Tr   Nr   r   s     r,   r!   zBulkUpsertOperation.updateD  s0     	OOV4HXHX 	 	
r.   c                 j    | j                   j                  | j                  |d| j                         y)Replace one entire document matching the selector criteria.

        :Parameters:
          - `replacement` (dict): the replacement document
        T)r   r   N)r   r   r   r   r+   rS   s     r,   replace_onezBulkUpsertOperation.replace_oneN  s.     	OO[AQAQ 	  	
r.   N)	r7   r8   r9   r:   	__slots__r-   r   r!   r   r;   r.   r,   r   r   0  s    47I%



r.   r   c                   >    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	 Zy
)BulkWriteOperationz4An interface for adding update or remove operations.r   c                 .    || _         || _        || _        y ru   )_BulkWriteOperation__selector_BulkWriteOperation__bulk_BulkWriteOperation__collationr   s       r,   r-   zBulkWriteOperation.__init__^  r   r.   c                 j    | j                   j                  | j                  |d| j                         y)zUpdate one document matching the selector criteria.

        :Parameters:
          - `update` (dict): the update operations to apply
        Fr   r   Nr   r   r   r   r   s     r,   r   zBulkWriteOperation.update_onec  s)     	tetO_O_`r.   c                 j    | j                   j                  | j                  |d| j                         y)zUpdate all documents matching the selector criteria.

        :Parameters:
          - `update` (dict): the update operations to apply
        Tr   Nr  r   s     r,   r!   zBulkWriteOperation.updatek  s)     	tddN^N^_r.   c                 h    | j                   j                  | j                  || j                         y)r   r   N)r   r   r   r   r   s     r,   r   zBulkWriteOperation.replace_ones  s'     	HXHXYr.   c                 p    | j                   j                  | j                  t        | j                         y)z8Remove a single document matching the selector criteria.r  N)r   r   r   _DELETE_ONEr   r+   s    r,   
remove_onezBulkWriteOperation.remove_one{  %    ttGWGWXr.   c                 p    | j                   j                  | j                  t        | j                         y)z4Remove all documents matching the selector criteria.r  N)r   r   r   r   r   r  s    r,   removezBulkWriteOperation.remove  r	  r.   c                 X    t        | j                  | j                  | j                        S )zSpecify that all chained update operations should be
        upserts.

        :Returns:
          - A :class:`BulkUpsertOperation` instance, used to add
            update operations to this bulk operation.
        )r   r   r   r   r  s    r,   r   zBulkWriteOperation.upsert  s!     #4??DKKAQAQRRr.   N)r7   r8   r9   r:   r   r-   r   r!   r   r  r  r   r;   r.   r,   r   r   Y  s3    >7I%
a`ZYYSr.   r   c                   2    e Zd ZdZdZddZd	dZd Zd	dZy)
BulkOperationBuilderzG**DEPRECATED**: An interface for executing a batch of write operations.r   c                 (    t        |||      | _        y)a(  **DEPRECATED**: Initialize a new BulkOperationBuilder instance.

        :Parameters:
          - `collection`: A :class:`~pymongo.collection.Collection` instance.
          - `ordered` (optional): If ``True`` all operations will be executed
            serially, in the order provided, and the entire execution will
            abort on the first error. If ``False`` operations will be executed
            in arbitrary order (possibly in parallel on the server), reporting
            any errors that occurred after attempting all operations. Defaults
            to ``True``.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.

        .. note:: `bypass_document_validation` requires server version
          **>= 3.2**

        .. versionchanged:: 3.5
           Deprecated. Use :meth:`~pymongo.collection.Collection.bulk_write`
           instead.

        .. versionchanged:: 3.2
          Added bypass_document_validation support
        N)r^   _BulkOperationBuilder__bulkrr   s       r,   r-   zBulkOperationBuilder.__init__  s    2 J1KLr.   Nc                 H    t        d|       t        || j                  |      S )a;  Specify selection criteria for bulk operations.

        :Parameters:
          - `selector` (dict): the selection criteria for update
            and remove operations.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only
            supported on MongoDB 3.4 and above.

        :Returns:
          - A :class:`BulkWriteOperation` instance, used to add
            update and remove operations to this bulk operation.

        .. versionchanged:: 3.4
           Added the `collation` option.

        r   )r
   r   r  )r+   r   r   s      r,   findzBulkOperationBuilder.find  s!    $ 	J1!(DKKCCr.   c                 :    | j                   j                  |       y)zInsert a single document.

        :Parameters:
          - `document` (dict): the document to insert

        .. seealso:: :ref:`writes-and-ids`
        N)r  r   r   s     r,   r    zBulkOperationBuilder.insert  s     	x(r.   c                 V    |t        di |}| j                  j                  |d      S )zExecute all provided operations.

        :Parameters:
          - write_concern (optional): the write concern for this bulk
            execution.
        N)r   r;   )r   r  r   )r+   r   s     r,   r   zBulkOperationBuilder.execute  s1     $(9=9M{{""=$"??r.   )TFru   )	r7   r8   r9   r:   r   r-   r  r    r   r;   r.   r,   r  r    s!    QIM6D*)	@r.   r  )6r:   rI   	itertoolsr   bson.objectidr   bson.raw_bsonr   bson.sonr   pymongo.client_sessionr   pymongo.collationr   pymongo.commonr	   r
   r   r   pymongo.errorsr   r   r   r   pymongo.helpersr   r   pymongo.messager   r   r   r   r   r   r   pymongo.read_preferencesr   pymongo.write_concernr   r   r  
_BAD_VALUE_UNKNOWN_ERROR_WRITE_CONCERN_ERRORr   rJ   objectr%   rU   r\   r^   r   r   r  r;   r.   r,   <module>r%     s      " )  B 8   A   4 . 
 *	 #6 #<$6N&\KF \K~&
& &
R2S 2SjH@6 H@r.   