o
    7cJ                     @   s>  d Z ddlZddl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 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 ddlmZmZ ddl 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Z0G dd de1Z2dd Z3dedefddZ4G dd de1Z5dS ) z<The bulk write operations interface.

.. versionadded:: 2.7
    N)islice)AnyNoReturn)ObjectId)RawBSONDocument)SON)_csotcommon)_validate_session_write_concern)validate_collation_or_none)validate_is_document_typevalidate_ok_for_replacevalidate_ok_for_update)BulkWriteErrorConfigurationErrorInvalidOperationOperationFailure)_RETRYABLE_ERROR_CODES_get_wce_doc)_DELETE_INSERT_UPDATE_BulkWriteContext_EncryptedBulkWriteContext_randint)ReadPreference)WriteConcern         @   )insertupdatedeletec                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_Runz'Represents a batch of write operations.c                 C   s   || _ g | _g | _d| _dS )zInitialize a new Run object.r   N)op_type	index_mapops
idx_offset)selfr%    r*   J/var/www/milkbook_backend/env/lib/python3.10/site-packages/pymongo/bulk.py__init__B   s   
z_Run.__init__c                 C   s
   | 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)   idxr*   r*   r+   indexI   s   
z
_Run.indexc                 C   s   | j | | j| dS )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	operationr*   r*   r+   addQ   s   z_Run.addN)__name__
__module____qualname____doc__r,   r.   r2   r*   r*   r*   r+   r$   ?   s
    r$   c                 C   sT  | dd}| jtkr|d  |7  < nZ| jtkr"|d  |7  < nL| jtkrn| d}|r\t|}|D ]}| |d | |d< q4|d | |d  |7  < |d  || 7  < n|d  |7  < |d	  |d	 7  < | d
}|r|D ]!}| }	|d | }
| |
|	d< | j	|
 |	d< |d
 
|	 qwt|}|r|d 
| dS dS )z7Merge a write command result into the full bulk result.nr   	nInsertednRemovedupsertedr.   	nUpsertednMatched	nModifiedwriteErrorsopwriteConcernErrorsN)getr%   r   r   r   lenr.   extendcopyr'   r/   r   )runfull_resultoffsetresultaffectedr:   
n_upserteddocwrite_errorsreplacementr-   wcer*   r*   r+   _merge_command]   s8   




rO   rF   returnc                 C   s$   | d r| d j dd d t| )z5Raise a BulkWriteError from the full bulk api result.r>   c                 S   s   | d S )Nr.   r*   )errorr*   r*   r+   <lambda>   s    z)_raise_bulk_write_error.<locals>.<lambda>)key)sortr   )rF   r*   r*   r+   _raise_bulk_write_error   s   rU   c                   @   s   e Zd ZdZd ddZedd Zdd Z							d!d
dZd"ddZ	d ddZ
dd Zdd Z	d#ddZdd Zdd Zdd Zdd Zdd ZdS )$_Bulkz'The private guts of the bulk write API.Nc                 C   s   |j |jjdtdd| _|| _| jdurtd| j || _|| _	g | _
d| _|| _d| _d| _d| _d| _d| _d| _d| _d| _d| _dS )zInitialize a _Bulk instance.replace)unicode_decode_error_handlerdocument_class)codec_optionsNletFT)with_optionsrZ   _replacedict
collectionr[   r	   r   commentorderedr'   executedbypass_doc_valuses_collationuses_array_filtersuses_hint_updateuses_hint_deleteis_retryableretryingstarted_retryable_writecurrent_runnext_run)r)   r_   ra   bypass_document_validationr`   r[   r*   r*   r+   r,      s,   

z_Bulk.__init__c                 C   s   | j jjj}|r|jstS tS N)r_   databaseclient
_encrypter_bypass_auto_encryptionr   r   )r)   	encrypterr*   r*   r+   bulk_ctx_class   s   
z_Bulk.bulk_ctx_classc                 C   s:   t d| t|tsd|v st |d< | jt|f dS )z*Add an insert document to the list of ops.document_idN)r   
isinstancer   r   r'   r/   r   )r)   ru   r*   r*   r+   
add_insert   s   

z_Bulk.add_insertFc           	      C   s   t | td|fd|fd|fd|fg}t|}|dur#d| _||d< |dur.d| _||d< |dur9d| _||d	< |r>d
| _| jt	|f dS )z8Create an update document and add it to the list of ops.qumultiupsertNT	collationarrayFiltershintF)
r   r   r   rd   re   rf   rh   r'   r/   r   )	r)   selectorr"   r{   r|   r}   array_filtersr   cmdr*   r*   r+   
add_update   s    z_Bulk.add_updatec                 C   sl   t | td|fd|fdd|fg}t|}|dur!d| _||d< |dur,d| _||d< | jt|f dS )	z8Create a replace document and add it to the list of ops.ry   rz   )r{   Fr|   NTr}   r   )r   r   r   rd   rf   r'   r/   r   )r)   r   rM   r|   r}   r   r   r*   r*   r+   add_replace   s   z_Bulk.add_replacec                 C   sj   t d|fd|fg}t|}|durd| _||d< |dur$d| _||d< |tkr+d| _| jt|f dS )z7Create a delete document and add it to the list of ops.ry   limitNTr}   r   F)	r   r   rd   rg   _DELETE_ALLrh   r'   r/   r   )r)   r   r   r}   r   r   r*   r*   r+   
add_delete   s   z_Bulk.add_deletec                 c   s^    d}t | jD ]!\}\}}|du rt|}n|j|kr#|V  t|}||| q|V  dS )ziGenerate batches of operations, batched by type of
        operation, in the order **provided**.
        N)	enumerater'   r$   r%   r2   )r)   rE   r-   r%   r1   r*   r*   r+   gen_ordered   s   


z_Bulk.gen_orderedc                 c   sZ    t tt tt tg}t| jD ]\}\}}|| || q|D ]}|jr*|V  q"dS )zbGenerate batches of operations, batched by type of
        operation, in arbitrary order.
        N)r$   r   r   r   r   r'   r2   )r)   
operationsr-   r%   r1   rE   r*   r*   r+   gen_unordered   s   z_Bulk.gen_unorderedc	              
   C   sv  | j jj}	| j jj}
|
j}| jst|| _d | _| j}||
| d}|r9| j	s6t|d | _| jd u r6d}t
|j }| |	||||||j| j j}|jt|jk r$|rct|j|j dkrc|pb|}t|| j jfd| jfg}| jrx| j|d< t|| | jrd|d< | jd ur|jttfv r| j|d< |r|r| js|  d| _|||tj| ||||
 | | |!|
| t"|j|jd }|j#r|$|||
\}}|%di }|%d	d
t&v rt'(|}t)|||j| t*| t)|||j| d| _	d| _| jrd|v rnn|+|||
}| jt|7  _|jt|jk sS| jr/|d r/d S | j | _}|s&d S d S )NFTr   ra   r`   bypassDocumentValidationr[   writeConcernErrorcoder   r>   ),r_   ro   namerp   _event_listenersrk   nextrl   validate_sessionri   	_COMMANDSr%   rt   rZ   r(   rB   r'   r   ra   r`   r   apply_write_concernrc   r[   r   r   rj   _start_retryable_write	_apply_tor   PRIMARYsend_cluster_timeadd_server_apiapply_timeoutr   acknowledgedexecuterA   r   rD   deepcopyrO   rU   execute_unack)r)   	generatorwrite_concernsession	sock_infoop_id	retryablerF   final_write_concerndb_namerp   	listenersrE   last_runcmd_namebwcr   r'   rH   to_sendrN   fullr*   r*   r+   _execute_command
  s   









7z_Bulk._execute_commandc              	      s   g g dddddg d t   fdd}jjj}||}|j|| W d   n1 s6w   Y   d sC d rGt   S )zExecute using write commands.r   r>   r@   r8   r;   r<   r=   r9   r:   c              	      s    | ||  d S rn   )r   )r   r   r   rF   r   r   r)   r   r*   r+   retryable_bulk  s   z-_Bulk.execute_command.<locals>.retryable_bulkNr>   r@   )r   r_   ro   rp   _tmp_session_retry_with_sessionrh   rU   )r)   r   r   r   r   rp   sr*   r   r+   execute_commandq  s$   

z_Bulk.execute_commandc              
   C   s   | j jj}| j jj}|j}t }| jst|| _| j}|ryt|j	 }| 
|||||d|j	| j j}	|jt|jk rmt|| j jfddddifg}
||
 t|j|jd}|	|
||}| jt|7  _|jt|jk s9t|d | _}|sdS dS )zCExecute write commands with OP_MSG and w=0 writeConcern, unordered.N)ra   FwriteConcernwr   )r_   ro   r   rp   r   r   rk   r   r   r%   rt   rZ   r(   rB   r'   r   r   r   r   )r)   r   r   r   rp   r   r   rE   r   r   r   r'   r   r*   r*   r+   execute_op_msg_no_results  sB   






z_Bulk.execute_op_msg_no_resultsc              
   C   sV   g g dddddg d}t  }t }z| ||d||d|| W dS  ty*   Y dS w )zAExecute write commands with OP_MSG and w=0 WriteConcern, ordered.r   r   NF)r   r   r   r   )r)   r   r   r   rF   initial_write_concernr   r*   r*   r+   execute_command_no_results  s2   

z _Bulk.execute_command_no_resultsc                 C   s   | j rtd| jrtd|o|j }|r"| jr"|jdk r"td|r0| jr0|jdk r0td| jr7td| j	rA| 
|||S | ||S )z3Execute all operations, returning no results (w=0).z3Collation is unsupported for unacknowledged writes.z6arrayFilters is unsupported for unacknowledged writes.	   zPMust be connected to MongoDB 4.4+ to use hint on unacknowledged delete commands.r   zPMust be connected to MongoDB 4.2+ to use hint on unacknowledged update commands.zGCannot set bypass_document_validation with unacknowledged write concern)rd   r   re   r   rg   max_wire_versionrf   rc   r   ra   r   r   )r)   r   r   r   unackr*   r*   r+   execute_no_results  s(   z_Bulk.execute_no_resultsc                 C   s   | j std| jrtdd| _|p| jj}t||}| jr$|  }n|  }| jj	j
}|jsO||}| ||| W d   dS 1 sHw   Y  dS | |||S )zExecute operations.zNo operations to executez*Bulk operations can only be executed once.TN)r'   r   rb   r_   r   r
   ra   r   r   ro   rp   r   _socket_for_writesr   r   )r)   r   r   r   rp   r   r*   r*   r+   r     s    


"z_Bulk.execute)NN)FFNNN)FNNrn   )r3   r4   r5   r6   r,   propertyrt   rx   r   r   r   r   r   r   r   r   r   r   r   r*   r*   r*   r+   rV      s.    





g'rV   )6r6   rD   	itertoolsr   typingr   r   bson.objectidr   bson.raw_bsonr   bson.sonr   pymongor   r	   pymongo.client_sessionr
   pymongo.collationr   pymongo.commonr   r   r   pymongo.errorsr   r   r   r   pymongo.helpersr   r   pymongo.messager   r   r   r   r   r   pymongo.read_preferencesr   pymongo.write_concernr   r   _DELETE_ONE
_BAD_VALUE_UNKNOWN_ERROR_WRITE_CONCERN_ERRORr   objectr$   rO   rU   rV   r*   r*   r*   r+   <module>   s4    '