
    h]i                     f   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mZmZ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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 Z/d Z0 G d de-      Z1 G d de-      Z2 G d de-      Z3 G d d e-      Z4y)!z<The bulk write operations interface.

.. versionadded:: 2.7
    N)islice)ObjectId)RawBSONDocument)SON)_validate_session_write_concern)validate_is_mappingvalidate_is_document_typevalidate_ok_for_replacevalidate_ok_for_update)_RETRYABLE_ERROR_CODES)validate_collation_or_none)BulkWriteErrorConfigurationErrorInvalidOperationOperationFailure)_INSERT_UPDATE_DELETE_do_batched_insert_randint_BulkWriteContext_EncryptedBulkWriteContext)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     O/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/bulk.py__init__z_Run.__init__B   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.indexJ   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.addR   s&     	n-	"r-   N)__name__
__module____qualname____doc__r,   r0   r5    r-   r+   r$   r$   ?   s    #	#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 |j                  d      }|r|d   j                  |       yy)z<Merge a write command result into the full bulk result.
    nr   	nInsertednRemovedupsertedr0   	nUpsertednMatched	nModifiedwriteErrorswriteConcernErrorwriteConcernErrorsN)getr&   r   r   r   lenr0   extendcopyr(   _UOPr2   )runfull_resultoffsetresultaffectedr?   
n_upserteddocwrite_errorsreplacementr/   wc_errors               r+   _merge_commandrU   ^   s    zz#q!H
{{gK H, 		J8+		::j)XJ @"yyW)>?G@
#**84$
2$
#:(=>#
#x/#K F;$77 ::m,L 	;C((*Kg,'C#&99S>K  #K&--k:	; zz-.H()00: r-   c                 N    | d   r| d   j                  d        t        |       )z:Raise a BulkWriteError from the full bulk api result.
    rC   c                     | d   S )Nr0   r:   )errors    r+   <lambda>z)_raise_bulk_write_error.<locals>.<lambda>   s
    eGn r-   )key)sortr   )rL   s    r+   _raise_bulk_write_errorr\      s2     =!M"'', 	( 	.

%%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;;-6# < % 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)z3Add an insert document to the list of ops.
        document_idN)r	   
isinstancer   r   r(   r2   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)zACreate 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(   r2   r   )	r*   selectorr    r   r   r   array_filtersr   cmds	            r+   
add_updatez_Bulk.add_update   s     	v&C?S&MU#h%79 :.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)	zACreate a replace document and add it to the list of ops.
        r   r   )r   Fr   NTr   r   )r
   r   r   rk   rm   r(   r2   r   )r*   r   rS   r   r   r   r   s          r+   add_replacez_Bulk.add_replace   s~     	 ,C?S+$6#h%79 :.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)z@Create a delete document and add it to the list of ops.
        r   limitNTr   r   F)	r   r   rk   rm   _DELETE_ALLrn   r(   r2   r   )r*   r   r   r   r   r   s         r+   
add_deletez_Bulk.add_delete   sx     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&   r5   )r*   rK   r/   r&   r4   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(   r5   )r*   
operationsr/   r&   r4   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                  |	|       |rjt        t        |j                     | j
                  j                  fd| j                   fg      }|j"                  s|j$                  |d<   | j&                  r|j                   dk\  rd	|d
<   | j)                  |||||
||j                  | j
                  j*                        }|j,                  t/        |j0                        k  rl|rF|r#| j2                  s|j5                          d	| _        |j7                  ||t8        j:                         |j=                  |||	       t?        |j0                  |j,                  d       }|jA                  ||	      \  }}|jC                  di       }|jC                  dd      tD        v r8tG        jH                  |      }tK        |||j,                  |       tM        |       tK        |||j,                  |       d| _'        d| _        | j                   rd|v rnB|xj,                  t/        |      z  c_        |j,                  t/        |j0                        k  rl| j                   r|d   ry t        |d       x| _
        }|riy 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bypassDocumentValidationrD   coder   FrC   )(max_wire_versionrk   r   rm   rl   rg   rv   namerw   _event_listenersrq   nextvalidate_sessionr   	_COMMANDSr&   rh   is_server_defaultr}   rj   r{   rc   r)   rG   r(   rp   _start_retryable_write	_apply_tor   PRIMARYsend_cluster_timer   executerF   r   rI   deepcopyrU   r\   ro   )r*   	generatorwrite_concernsession	sock_infoop_id	retryablerL   db_namerw   	listenersrK   r   bwcr(   rN   to_sendwcefulls                      r+   _execute_commandz_Bulk._execute_command  s   %%)""(KM M~~(DF F%%)d.E.E$HJ J //**//))00++	#ID 	""673	#++.0D0DE!4<<02 3C 22&3&<&<N#""y'A'AQ'F26./%%i	7T__::<C ..3sww</ !)E)E6687;4%%c9n6L6LM++C&ASWWcnnd;"%++c6": jj!4b97761%)??  ==5D"3cnnfE+D1sKH %/4,<<MV$;#g,.; ..3sww</B ||M :%))T%::Ds_ 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   rC   rE   r=   r@   rA   rB   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_bulk`  s!    !!='9e;(r-   NrC   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_commandP  s    
 "$	
 
	( 	(
 ))00  ) 	<Q&&!!>1d<	< }%5I)J#K0	< 	<s   BBc           
      4   t        d| j                  j                  fd| j                  fg      }dt	        | j                        i}||d<   | j
                  r|j                  dk\  rd|d<   | j                  j                  }t        |j                  ||||j                  j                  dt        | j                  j                        }t        | j                  j                  |j                  d||| j                   | j                  j                  |       y)	z.Execute insert, returning no results.
        r   rh   wr   r   Tr   N)r   rg   r   rh   intrj   r   rv   r   rw   r   r   rc   r   	full_namer(   )	r*   r   rK   r   acknowledgedcommandconcerndbr   s	            r+   execute_insert_no_resultsz_Bulk.execute_insert_no_resultsn  s     $//"6"67!4<<02 3DLL)*")9#=#=#B26G./__%%GGWi		0J0J'4??88: 	OO%%swwlGdoo;;S	Br-   c           
      @   | j                   j                  j                  }| j                   j                  j                  }|j                  }t               }| j                  st        |      | _        | j                  }|rt        t        |j                     | j                   j                  fddddifg      }| j                  |||||d|j                  | j                   j                        }	|j                  t        |j                        k  rtt!        |j                  |j                  d      }
|	j#                  |
|      }|xj                  t        |      z  c_        |j                  t        |j                        k  rtt        |d      x| _        }|ryy)zLExecute write commands with OP_MSG and w=0 writeConcern, unordered.
        )rh   Fr   r   r   N)rg   rv   r   rw   r   r   rq   r   r   r   r&   r{   rc   r)   rG   r(   r   execute_unack)r*   r   r   r   rw   r   r   rK   r   r   r(   r   s               r+   execute_op_msg_no_resultsz_Bulk.execute_op_msg_no_results  sN    //**//))00++	
#ID	#++.0D0DE)&a13 4C %%i	4T__::<C ..3sww</SWWcnnd;++C8#g,.	 ..3sww</
 &*)T%::Ds 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)zJExecute 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  sj     "$	
 %
	!!=$5%6   		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)z<Execute 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_ackr4   rQ   
check_keyss               r+   execute_no_resultsz_Bulk.execute_no_results  s8    $EG G""$HJ J>>$@B B 9#=#=#B" $C D D %%)||66y)LL11)YGG %s4<<'89
	? CIt,H=)=I;;')22!3y:[[G+%(WW @	'n%)
4S	?#=#=c#B).J%%cN%h/&%g.*7"'$(LL+/+>+> % 
@@" &)WW 3	Y%.s^)27);%;%2%*%)\\33; H $ <<  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"#=>>==" $< = =%F)F)F1'=I<<((*I**,I))00))**73 >y''	9=> > ''	='JJ> >s   C55C>)FFNNN)FNN)NN)r6   r7   r8   r9   r,   propertyr{   r   r   r   r   r   r   r   r   r   r   r   r   r   r:   r-   r+   r^   r^      sy     ( % %- @E<@(, 9>)-( ( 
G;R<B$;62DL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__      "$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  s1     	t%U4)-)9)9 	 	;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.update(  s1     	t%T$)-)9)9 	 	;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_one2  s.     	T*.*:*: 	  	<r-   N)	r6   r7   r8   r9   	__slots__r,   r   r    r   r:   r-   r+   r   r     s"     8I%
;;<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
)BulkWriteOperationz9An interface for adding update or remove operations.
    r   c                 .    || _         || _        || _        y ru   )_BulkWriteOperation__selector_BulkWriteOperation__bulk_BulkWriteOperation__collationr   s       r+   r,   zBulkWriteOperation.__init__B  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_oneG  s.     	te)-)9)9 	 	;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.updateP  s.     	td)-)9)9 	 	;r-   c                 h    | j                   j                  | j                  || j                         y)r   r   N)r   r   r   r   r   s     r+   r   zBulkWriteOperation.replace_oneY  s,     	*.*:*: 	  	<r-   c                 p    | j                   j                  | j                  t        | j                         y)zARemove a single document matching the selector criteria.
        r  N)r   r   r   _DELETE_ONEr   r*   s    r+   
remove_onezBulkWriteOperation.remove_oneb  ,     	t)-)9)9 	 	;r-   c                 p    | j                   j                  | j                  t        | j                         y)z=Remove all documents matching the selector criteria.
        r  N)r   r   r   r   r   r  s    r+   removezBulkWriteOperation.removeh  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.upsertn  s&     #4??DKK#'#3#35 	5r-   N)r6   r7   r8   r9   r   r,   r   r    r   r  r	  r   r:   r-   r+   r   r   <  s1     8I%
;;<;;	5r-   r   c                   6    e Zd ZdZdZ	 	 ddZd	dZd Zd	dZy)
BulkOperationBuilderzL**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    4 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   )	r6   r7   r8   r9   r   r,   r  r   r   r:   r-   r+   r  r  z  s+     I+/,1M8D*)	@r-   r  )5r9   rI   	itertoolsr   bson.objectidr   bson.raw_bsonr   bson.sonr   pymongo.client_sessionr   pymongo.commonr   r	   r
   r   pymongo.helpersr   pymongo.collationr   pymongo.errorsr   r   r   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4 4 3 8. .9 9 9
 4 .  
 *	 #6 #>%;P&AKF AKH&<& &<R;5 ;5|J@6 J@r-   