
    [jP                       U d Z ddlmZ ddl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 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 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l0m1Z1 ddl2m3Z3 e	rddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z; dZ<de=d<   dZ>de=d<   dZ?de=d<   dZ@de=d<   dZAde=d<   dZBd e=d!<    G d" d#          ZCd2d,ZDd3d/ZE G d0 d1          ZFdS )4z<The bulk write operations interface.

.. versionadded:: 2.7
    )annotationsN)MutableMapping)islice)TYPE_CHECKINGAnyIteratorMappingNoReturnOptionalTypeUnion)ObjectId)RawBSONDocument)SON)_csotcommon)ClientSession_validate_session_write_concern)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)
Collection)
Connection)_DocumentOut_DocumentType	_Pipelineint_DELETE_ALL   _DELETE_ONE   
_BAD_VALUE   _UNKNOWN_ERROR@   _WRITE_CONCERN_ERROR)insertupdatedeleteztuple[str, str, str]	_COMMANDSc                  *    e Zd ZdZddZddZddZdS )_Runz'Represents a batch of write operations.op_typer+   returnNonec                >    || _         g | _        g | _        d| _        dS )zInitialize a new Run object.r   N)r;   	index_mapops
idx_offset)selfr;   s     P/var/www/app.qaans.com/backend/venv/lib/python3.11/site-packages/pymongo/bulk.py__init__z_Run.__init__R   s"    #$&      idxc                    | j         |         S )zGet the original index of an operation in this run.

        :Parameters:
          - `idx`: The Run index that maps to the original index.
        )r?   )rB   rF   s     rC   indexz
_Run.indexY   s     ~c""rE   original_index	operationr   c                n    | 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@   )rB   rI   rJ   s      rC   addz_Run.adda   s4     	n---	"""""rE   N)r;   r+   r<   r=   )rF   r+   r<   r+   )rI   r+   rJ   r   r<   r=   )__name__
__module____qualname____doc__rD   rH   rM    rE   rC   r:   r:   O   sV        11! ! ! !# # # #	# 	# 	# 	# 	# 	#rE   r:   runfull_resultMutableMapping[str, Any]offsetresultMapping[str, Any]r<   r=   c                   |                     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|                     d          }|rtt          |          }|D ]#}|                     |d         |z             |d<   $|d                             |           |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<   |                     d
          }|rg|D ]d}|                                }	|d         |z   }
|                     |
          |	d<   | j	        |
         |	d<   |d
         
                    |	           et          |          }|r|d         
                    |           dS dS )z7Merge a write command result into the full bulk result.nr   	nInsertednRemovedupsertedrH   	nUpsertednMatched	nModifiedwriteErrorsopwriteConcernErrorsN)getr;   r   r   r    lenrH   extendcopyr@   rL   r   )rS   rT   rV   rW   affectedr]   
n_upserteddocwrite_errorsreplacementrF   wces               rC   _merge_commandrn   m   s)    zz#q!!H
{gK   H,    			J8+			::j)) 	0XJ @ @"yyW)>??G
#**8444$$$
2$$$
###x*'<<####
###x/###K   F;$77   ::m,,L ; 	; 	;C((**Kg,'C#&99S>>K  #K&--k::::
v

C
 6()00555556 6rE   r(   r
   c                j    | d         r| d                              d            t          |           )z5Raise a BulkWriteError from the full bulk api result.ra   c                    | d         S )NrH   rR   )errors    rC   <lambda>z)_raise_bulk_write_error.<locals>.<lambda>   s
    %. rE   )key)sortr   )rT   s    rC   _raise_bulk_write_errorru      s>    =! JM"'',H,H'III

%
%%rE   c                      e Zd ZdZ	 	 dAdBdZedCd            ZdDdZ	 	 	 	 	 dEdFd!Z	 	 	 dGdHd#Z		 	 dAdId&Z
dJd(ZdKd*Z	 dLdMd9ZdNd;ZdOd<ZdPd=ZdPd>ZdQd@ZdS )R_Bulkz'The private guts of the bulk write API.N
collectionCollection[_DocumentType]orderedboolbypass_document_validationcommentOptional[str]letOptional[Any]r<   r=   c                   |                     |j                            dt                              | _        || _        | j        t          j        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_optionsNr   FT)with_optionsr   _replacedictrx   r   r   r   r}   rz   r@   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)rB   rx   rz   r|   r}   r   s         rC   rD   z_Bulk.__init__   s     %11$2;;-6t <   2 
 

 8,UDH===&-8:8#"' % % ',$rE   Type[_BulkWriteContext]c                \    | j         j        j        j        }|r|j        st
          S t          S N)rx   databaseclient
_encrypter_bypass_auto_encryptionr"   r!   )rB   	encrypters     rC   bulk_ctx_classz_Bulk.bulk_ctx_class   s0    O,3>	 	%Y> 	%--$$rE   documentr(   c                    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.r   _idN)r   
isinstancer   r   r@   rL   r   )rB   r   s     rC   
add_insertz_Bulk.add_insert   sZ    !*h7778_55 	)(9J9J&jjHUO(+,,,,,rE   FselectorrX   r6   #Union[Mapping[str, Any], _Pipeline]multiupsert	collationOptional[Mapping[str, Any]]array_filters!Optional[list[Mapping[str, Any]]]hintUnion[str, SON[str, Any], None]c                   t          |           t          d|fd|fd|fd|fg          }|d| _        ||d<   |d| _        ||d<   |d| _        ||d	<   |rd
| _        | j                            t          |f           dS )z8Create an update document and add it to the list of ops.qur   r   NTr   arrayFiltersr   F)	r   r   r   r   r   r   r@   rL   r    )	rB   r   r6   r   r   r   r   r   cmds	            rC   
add_updatez_Bulk.add_update   s     	v&&&"8_sFmgu-=&?QR
 
  "&D(C$&*D#"/C$(D!CK 	& %D#'''''rE   rl   c                    t          |           t          d|fd|fdd|fg          }|d| _        ||d<   |d| _        ||d<   | j                            t          |f           dS )	z8Create a replace document and add it to the list of ops.r   r   )r   Fr   NTr   r   )r   r   r   r   r@   rL   r    )rB   r   rl   r   r   r   r   s          rC   add_replacez_Bulk.add_replace   s     	 ,,,C?S+$68H8U[J\]^^ "&D(C$(D!CK#'''''rE   limitr+   c                    t          d|fd|fg          }|d| _        ||d<   |d| _        ||d<   |t          k    rd| _        | j                            t          |f           dS )z7Create a delete document and add it to the list of ops.r   r   NTr   r   F)r   r   r   r,   r   r@   rL   r   )rB   r   r   r   r   r   s         rC   
add_deletez_Bulk.add_delete  s     C?We$4566 "&D(C$(D!CKK %D#'''''rE   Iterator[Optional[_Run]]c              #     K   d}t          | j                  D ]N\  }\  }}|t          |          }n|j        |k    r|V  t          |          }|                    ||           O|V  dS )ziGenerate batches of operations, batched by type of
        operation, in the order **provided**.
        N)	enumerater@   r:   r;   rM   )rB   rS   rF   r;   rJ   s        rC   gen_orderedz_Bulk.gen_ordered  s       )248)<)< 	$ 	$%C%'9{7mm''			7mmGGC####					rE   Iterator[_Run]c              #    K   t          t                    t          t                    t          t                    g}t	          | j                  D ]$\  }\  }}||                             ||           %|D ]}|j        r|V  dS )zbGenerate batches of operations, batched by type of
        operation, in arbitrary order.
        N)r:   r   r    r   r   r@   rM   )rB   
operationsrF   r;   rJ   rS   s         rC   gen_unorderedz_Bulk.gen_unordered&  s       7mmT']]DMMB
)248)<)< 	4 	4%C%'9w##C3333 	 	Cw 				 	rE   	generatorIterator[Any]write_concernr%   sessionOptional[ClientSession]connr'   op_id	retryablerT   rU   final_write_concernOptional[WriteConcern]c	           
        | j         j        j        }	| j         j        j        }
|
j        }| j        st          |          | _        d | _        | j        }|                    |
|           d}|r| j	        st          |d           | _        | j        d}t          |j                 }|                     |	||||||j        | j         j                  }|j        t          |j                  k     rY|r$t          |j                  |j        z
  dk    r|p|}t#          || j         j        fd| j        fg          }| j        r
| j        |d<   t)          j        ||           | j        rd|d<   | j        |j        t0          t2          fv r
| j        |d<   |rF|r"| j        s|                                 d| _        |                    ||t:          j        |           |                    |||
           |                     |           |!                    |
|           tE          |j        |j        d           }|j#        r|$                    |||
          \  }}|%                    di           }|%                    d	d
          tL          v r:tO          j(        |          }tS          |||j        |           tU          |           tS          |||j        |           d| _	        d| _        | j        rd|v rnSn|+                    |||
          }|xj        t          |          z  c_        |j        t          |j                  k     Y| j        r
|d         rd S | j        x| _        }|d S d S )NFTr-   rz   r}   bypassDocumentValidationr   writeConcernErrorcoder   ra   ),rx   r   namer   _event_listenersr   nextr   validate_sessionr   r8   r;   r   r   rA   re   r@   r   rz   r}   r   apply_write_concernr   r   r   r    r   _start_retryable_write	_apply_tor$   PRIMARYsend_cluster_timeadd_server_apiapply_timeoutr   acknowledgedexecuterd   r   rg   deepcopyrn   ru   execute_unack)rB   r   r   r   r   r   r   rT   r   db_namer   	listenersrS   last_runcmd_namebwcr   r@   rW   to_sendrm   fulls                         rC   _execute_commandz_Bulk._execute_command2  s    /*/)0+	 	!#ID DM 	fg... L	3= $ $Y 5 5=(#H -H%%-	 	C .3sw<<//  ISW!>1 D D$7$H=MHdo&:;i=VWXX< 2%)\C	N)#}===& ;6:C238'CKGW;M,M,M!%CJ T ! <)E <668887;4%%c9n6LdSSS&&sGV<<<##C(((""63///SWcnd;; !- B&)kk#sF&C&COFG !**%8"==Cwwvq))-CCC  $}[99&sD#.&III/555"3S^VLLL %*DM38D0| (?(?!//S&AAG#g,,.g .3sw<<//n | M : %)]2DsY  L	3 L	3 L	3 L	3 L	3rE   dict[str, Any]c           	          g g dddddg dt                      d fd} j        j        j        }|                     j        ||            d         sd         rt                     S )zExecute using write commands.r   ra   rc   r[   r^   r_   r`   r\   r]   r   r   r   r'   r   r{   r<   r=   c           	     >                         | ||           d S r   )r   )r   r   r   rT   r   r   rB   r   s      rC   retryable_bulkz-_Bulk.execute_command.<locals>.retryable_bulk  s<     !!    rE   )bulkra   rc   )r   r   r   r'   r   r{   r<   r=   )r#   rx   r   r   _retryable_writer   ru   )rB   r   r   r   r   r   rT   r   s   ```   @@rC   execute_commandz_Bulk.execute_command  s     "$	
 	
 

	 	 	 	 	 	 	 	 	 	 )0 1>7QUVVV}% 	15I)J 	1#K000rE   c           
        | j         j        j        }| j         j        j        }|j        }t                      }| j        st          |          | _        | j        }|rt          |j	                 }| 
                    |||||d|j	        | j         j                  }	|j        t          |j                  k     rt          || j         j        fddddifg          }
|                    |
           t#          |j        |j        d          }|	                    |
||          }|xj        t          |          z  c_        |j        t          |j                  k     t          |d          x| _        }|dS dS )zCExecute write commands with OP_MSG and w=0 writeConcern, unordered.N)rz   FwriteConcernwr   )rx   r   r   r   r   r#   r   r   r8   r;   r   r   rA   re   r@   r   r   r   r   )rB   r   r   r   r   r   r   rS   r   r   r   r@   r   s                rC   execute_op_msg_no_resultsz_Bulk.execute_op_msg_no_results  s   /*/)0+	

 	/#ID 	; -H%%-	 	C .3sw<<//!4?#78*'#q2  ##C(((SWcnd;;++Cf==#g,,. .3sw<<// &*)T%:%::Ds5  	; 	; 	; 	; 	;rE   c           
         g g dddddg d}t                      }t                      }	 |                     ||d||d||           dS # t          $ r Y dS w xY w)zAExecute write commands with OP_MSG and w=0 WriteConcern, ordered.r   r   NF)r%   r#   r   r   )rB   r   r   r   rT   initial_write_concernr   s          rC   execute_command_no_resultsz _Bulk.execute_command_no_results  s     "$	
 	
 !-

	!!%	 	 	 	 	   	 	 	DD	s   A 
AAc                   | j         rt          d          | j        rt          d          |o|j         }|r!| j        r|j        dk     rt          d          |r!| j        r|j        dk     rt          d          | j        rt          d          | j	        r| 
                    |||          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.r1   zPMust be connected to MongoDB 4.2+ to use hint on unacknowledged update commands.zGCannot set bypass_document_validation with unacknowledged write concern)r   r   r   r   r   max_wire_versionr   r   r   rz   r   r   )rB   r   r   r   unacks        rC   execute_no_resultsz_Bulk.execute_no_results  s     	\$%Z[[[" 	_$%]^^^@m&@"@ 	T* 	t/Dq/H/H$b    	T* 	t/Dq/H/H$b    	"Y   < 	S224MRRR--dI>>>rE   r   c                   | j         st          d          | j        rt          d          d| _        |p| j        j        }t          ||          }| j        r|                                 }n|                                 }| j        j	        j
        }|j        sH|                    |          5 }|                     |||           	 ddd           dS # 1 swxY w Y   dS |                     |||          S )zExecute operations.zNo operations to executez*Bulk operations can only be executed once.TN)r@   r   r   rx   r   r   rz   r   r   r   r   r   _conn_for_writesr   r   )rB   r   r   r   r   
connections         rC   r   z_Bulk.execute+  sK   x 	?"#=>>>= 	Q"#OPPP%F)F1'=II< 	-((**II**,,I)0) 	K((11 Z''
I}MMM                  ''	='JJJs   /CCC)NN)rx   ry   rz   r{   r|   r{   r}   r~   r   r   r<   r=   )r<   r   )r   r(   r<   r=   )FFNNN)r   rX   r6   r   r   r{   r   r{   r   r   r   r   r   r   r<   r=   )FNN)r   rX   rl   rX   r   r{   r   r   r   r   r<   r=   )
r   rX   r   r+   r   r   r   r   r<   r=   )r<   r   )r<   r   r   )r   r   r   r%   r   r   r   r'   r   r+   r   r{   rT   rU   r   r   r<   r=   )r   r   r   r%   r   r   r<   r   )r   r'   r   r   r<   r=   )r   r'   r   r   r   r%   r<   r=   )r   r%   r   r   r<   r   )rN   rO   rP   rQ   rD   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   rR   rE   rC   rw   rw      s       11 "&!    B % % % X%- - - - 15;?04( ( ( ( (B 1504( ( ( ( (. 2604( ( ( ( ((   
 
 
 
* 7;e3 e3 e3 e3 e3N& & & &P%; %; %; %;N" " " "H? ? ? ?>K K K K K KrE   rw   )
rS   r:   rT   rU   rV   r+   rW   rX   r<   r=   )rT   r(   r<   r
   )GrQ   
__future__r   rg   collections.abcr   	itertoolsr   typingr   r   r   r	   r
   r   r   r   bson.objectidr   bson.raw_bsonr   bson.sonr   pymongor   r   pymongo.client_sessionr   r   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%   pymongo.collectionr&   pymongo.poolr'   pymongo.typingsr(   r)   r*   r,   __annotations__r.   r0   r2   r4   r8   r:   rn   ru   rw   rR   rE   rC   <module>r     sk     # " " " " "  * * * * * *      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 # " " " " " ) ) ) ) ) )       ! ! ! ! ! ! ! ! Q Q Q Q Q Q Q Q         
            A @ @ @ @ @ @ @                4 3 3 3 3 3 . . . . . . G------''''''FFFFFFFFFF         
             "@	 @ @ @ @# # # # # # # #<)6 )6 )6 )6X& & & &`K `K `K `K `K `K `K `K `K `KrE   