U
    d+                     @  s  U d Z ddlmZ ddlZddl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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mZmZmZmZm Z m!Z!m"Z"m#Z# dd	l$m%Z% erdd
l&m'Z' ddl(m)Z) ddl*m+Z+ e,ddgZ-de.d< e,ddddddge-B Z/de.d< e/e,dddddgB Z0de.d< dZ1de.d < d!d"d#d$d%Z2dVd&d'd(d)d*d+Z3d!d,d-d.d/Z4dWd1d2d3d4d5d6d7d8Z5d9d:d;d<d=Z6d>d:d?d@dAZ7dBdCdDdEdFZ8dBd5dDdGdHZ9dId"dBdJdKdLZ:d5dMdNdOZ;edPe
dQe	f dRZ<dPdPdSdTdUZ=dS )XzCBits and pieces used by the driver that don't really fit elsewhere.    )annotationsN)abc)TYPE_CHECKINGAnyCallable	ContainerIterableListMappingNoReturnOptionalSequenceTupleTypeVarUnioncast)SON)	ASCENDING)	CursorNotFoundDuplicateKeyErrorExecutionTimeoutNotPrimaryErrorOperationFailureWriteConcernError
WriteErrorWTimeoutError_wtimeout_error)HelloCompat)_Hint)
_IndexList)_DocumentOutiP-  [   	frozenset_SHUTDOWN_CODESiJ'  i{'  i{4  iR-  i|4     _NOT_PRIMARY_CODES      Y   i)#  i  _RETRYABLE_ERROR_CODESi  int_REAUTHENTICATION_REQUIRED_CODEr   str)keysreturnc                 C  s   d dd | D S )z9Generate an index name from the set of fields it is over._c                 S  s   g | ]}d j | qS )z{}_{})format).0item r3   3/tmp/pip-unpacked-wheel-oblwsawz/pymongo/helpers.py
<listcomp>b   s     z#_gen_index_name.<locals>.<listcomp>)join)r-   r3   r3   r4   _gen_index_name`   s    r7   r   zOptional[Union[int, str]]z8Sequence[Tuple[str, Union[int, str, Mapping[str, Any]]]])key_or_list	directionr.   c                 C  s   |dk	r$t | tstd| |fgS t | tr8| tfgS t | tjrLt| S t | ttfsbtdg }| D ] }t |tr|tf}|| qj|S dS )zHelper to generate a list of (key, direction) pairs.

    Takes such a list, or a single key, or a single key and direction.
    Nz!Expected a string and a directionzEif no direction is specified, key_or_list must be an instance of list)	
isinstancer,   	TypeErrorr   r   	ItemsViewlisttupleappend)r8   r9   valuesr2   r3   r3   r4   _index_liste   s     




rA   zSON[str, Any])
index_listr.   c                 C  s   t | tjr"tdt|   nt | ttfs@tdt|  t| sPt	dt
 }| D ]R}t |trp|tf}|\}}t |tstdt |tttjfstd|||< qZ|S )zbHelper to generate an index specifying document.

    Takes a list of (key, direction) pairs.
    zhpassing a dict to sort/create_index/hint is not allowed - use a list of tuples instead. did you mean %r?z0must use a list of (key, direction) pairs, not: z&key_or_list must not be the empty listz6first item in each key pair must be an instance of strz[second item in each key pair must be 1, -1, '2d', or another valid MongoDB index specifier.)r:   r   r
   r;   r=   itemsr>   reprlen
ValueErrorr   r,   r   r*   )rB   indexr2   keyvaluer3   r3   r4   _index_document   s.    



rJ   Fr    zOptional[int]z$Optional[Container[Union[int, str]]]boolNone)responsemax_wire_versionallowable_errorsparse_write_concern_errorr.   c           
      C  sr  d| kr"t | d| d| ||rZd| krZ| d }| d}|rR|d|i t| | d rfdS | }d| kr| d  D ] }|dr~|ds~|} qq~|d }|d}	|r|	dk	r|	|krdS n||krdS |	dk	r|	tkrt|| n tj|ks
d	|krt|| |	d
kr.t	||	| |n2|	dkrHt
||	| |n|	dkr`t||	| |t ||	| |dS )z+Check the response to a command for errors.okz$errcodewriteConcernErrorerrorLabelsNrawerrmsgznode is recovering)*  i*  i&1  2   +   )r   getupdate_raise_write_concern_errorr@   r%   r   r   ZLEGACY_ERRORr   r   r   )
rM   rN   rO   rP   _errorZ_labelsdetailsZshardrV   rR   r3   r3   r4   _check_command_response   sR    





r_   z	List[Any]r   )write_errorsr.   c                 C  sD   | d }| ddkr(t| dd|t| d| d|d S )NrR   rW   rV   )rZ   r   r   )r`   errorr3   r3   r4   _raise_last_write_error   s    rc   r   )rb   r.   c                 C  s<   t | r t| d| d| t| d| d| d S )NrV   rR   )r   r   rZ   r   )rb   r3   r3   r4   r\      s    r\   zMapping[str, Any]zOptional[Mapping[str, Any]])resultr.   c                 C  s(   |  d}|r$|  d}|r$||d< |S )z%Return the writeConcernError or None.rS   rT   )rZ   )rd   wceZerror_labelsr3   r3   r4   _get_wce_doc   s    

rf   c                 C  s.   |  d}|rt| t| }|r*t| dS )z?Backward compatibility helper for write command error handling.ZwriteErrorsN)rZ   rc   rf   r\   )rd   r`   re   r3   r3   r4   _check_write_command_response   s    
rg   z'Union[Mapping[str, Any], Iterable[str]])fieldsoption_namer.   c                 C  s`   t | tjr| S t | tjtjfrNtdd | D sBt| dt| dS t| ddS )zTakes a sequence of field names and returns a matching dictionary.

    ["a", "b"] becomes {"a": 1, "b": 1}

    and

    ["a.b.c", "d", "a.c"] becomes {"a.b.c": 1, "d": 1, "a.c": 1}
    c                 s  s   | ]}t |tV  qd S )N)r:   r,   )r1   fieldr3   r3   r4   	<genexpr>  s     z'_fields_list_to_dict.<locals>.<genexpr>z5 must be a list of key names, each an instance of str   z' must be a mapping or list of key namesN)	r:   r   r
   r   Setallr;   dictfromkeys)rh   ri   r3   r3   r4   _fields_list_to_dict
  s    rq   )r.   c                  C  sV   t jrRt  } z>z$t| d | d | d dt j W n tk
rH   Y nX W 5 ~ X dS )z1Print exceptions raised by subscribers to stderr.r   rl      N)sysstderrexc_info	tracebackprint_exceptionOSError)Zeinfor3   r3   r4   _handle_exception   s    $
ry   F.)bound)funcr.   c                   s    dddd fdd}t t|S )Nr   )argskwargsr.   c               
     s   | dd}ddlm} ddlm} z | |W S  tk
r } zp|rH |jtkrd }| D ]*}t||rp|} qt||rZ|j	} qqZ|r|j
dd n  | | W Y S  W 5 d }~X Y nX d S )N	no_reauthFr   )_BulkWriteContext)
ConnectionT)Zreauthenticate)popZpymongo.messager   Zpymongo.poolr   r   rR   r+   r:   connZauthenticate)r}   r~   r   r   r   excr   argr|   r3   r4   inner5  s,    


z_handle_reauth.<locals>.inner)r   rz   )r|   r   r3   r   r4   _handle_reauth4  s    r   )N)NF)>__doc__
__future__r   rs   rv   collectionsr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   Zbson.sonr   Zpymongor   Zpymongo.errorsr   r   r   r   r   r   r   r   r   Zpymongo.hellor   Zpymongo.cursorr   Zpymongo.operationsr   Zpymongo.typingsr    r"   r#   __annotations__r%   r)   r+   r7   rA   rJ   r_   rc   r\   rf   rg   rq   ry   rz   r   r3   r3   r3   r4   <module>   sl   @,


 #  C	