
    Ѯh                    ,   U d Z ddlmZ ddlZddl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 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 ddl 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. ddl/m0Z0 erddl#m1Z1 de2d<   de2d<   dZ3dZ4dZ5dZ6dZ7dZ8e.jr                  jt                  jv                  Z<ejz                  j|                  e"j~                  ejz                  j                  e"j                  iZB G d deC      ZDdJdZEdKd ZFdLd!ZG	 	 	 	 dMd"ZH G d# d$      ZIdNd%ZJ	 	 dOd&ZKdPd'ZLdQd(ZM e$j                  d)      ZO	 dR	 	 	 dSd*ZPdJd+ZQdNd,ZR G d- d.eC      ZSdTd/ZTdTd0ZU G d1 d2eS      ZV	 	 dTd3ZW G d4 d5eS      ZXdTd6ZYdUd7ZZ G d8 d9e[      Z\dVdWd:Z]dXd;Z^ G d< d=eC      Z_ G d> d?e_      Z` G d@ dAe_      Za	 	 	 	 	 	 dYdBZb	 dZ	 	 	 d[dCZc	 	 	 	 	 	 d\dDZd	 	 	 	 	 	 d]dEZe	 	 	 	 d^dFZfddG	 	 	 d_dHZg	 	 	 	 d`dIZhy)az<Common helpers shared across Google Cloud Firestore modules.    )annotationsN)AnyDict	GeneratorIteratorListOptionalSequenceTupleUnioncastTYPE_CHECKING)gapic_v1)retry)DatetimeWithNanoseconds)_datetime_to_pb_timestamp)
struct_pb2)	Timestamp)
latlng_pb2)
exceptions)
transformstypes)	FieldPathparse_field_path)commondocumentwrite)DocumentTransform)Vector)DocumentSnapshotztransforms.Sentinel
_EmptyDictdict_GRPC_ERROR_MAPPINGz<A path element must be a string. Received {}, which is a {}./z<Transaction not in progress, cannot be used in API requests.z,Attempted read after write in a transaction.zReference value {!r} in unexpected format, expected to be of the form ``projects/{{project}}/databases/{{database}}/documents/{{document_path}}``.zLDocument {!r} does not correspond to the same database ({!r}) as the client.c                  ,    e Zd ZdZddZddZd Zd Zy)	GeoPointzSimple container for a geo point value.

    Args:
        latitude (float): Latitude of a point.
        longitude (float): Longitude of a point.
    c                     || _         || _        y Nlatitude	longitude)selfr*   r+   s      t/home/www/academy-backend.kofcorporation.com/venv/lib/python3.12/site-packages/google/cloud/firestore_v1/_helpers.py__init__zGeoPoint.__init__T   s     "    c                X    t        j                  | j                  | j                        S )zConvert the current object to protobuf.

        Returns:
            google.type.latlng_pb2.LatLng: The current point as a protobuf.
        r)   )r   LatLngr*   r+   r,   s    r-   to_protobufzGeoPoint.to_protobufX   s       $--4>>RRr/   c                    t        |t              st        S | j                  |j                  k(  xr | j                  |j                  k(  S )zCompare two geo points for equality.

        Returns:
            Union[bool, NotImplemented]: :data:`True` if the points compare
            equal, else :data:`False`. (Or :data:`NotImplemented` if
            ``other`` is not a geo point.)
        )
isinstancer&   NotImplementedr*   r+   r,   others     r-   __eq__zGeoPoint.__eq__`   s9     %*!!}}.T4>>U__3TTr/   c                F    | j                  |      }|t        u rt        S | S )zCompare two geo points for inequality.

        Returns:
            Union[bool, NotImplemented]: :data:`False` if the points compare
            equal, else :data:`True`. (Or :data:`NotImplemented` if
            ``other`` is not a geo point.)
        )r9   r6   )r,   r8   equality_vals      r-   __ne__zGeoPoint.__ne__m   s)     {{5)>)!!###r/   NreturnNone)r>   zlatlng_pb2.LatLng)__name__
__module____qualname____doc__r.   r3   r9   r<    r/   r-   r&   r&   L   s    #SU$r/   r&   c                   t        |       }|dk(  rt        d      |r|dz  dk(  rt        d      |dz  dk(  rt        d      | D ]<  }t        |t              rt        j                  |t        |            }t        |       y)aR  Verifies that a ``path`` has the correct form.

    Checks that all of the elements in ``path`` are strings.

    Args:
        path (Tuple[str, ...]): The components in a collection or
            document path.
        is_collection (bool): Indicates if the ``path`` represents
            a document or a collection.

    Raises:
        ValueError: if

            * the ``path`` is empty
            * ``is_collection=True`` and there are an even number of elements
            * ``is_collection=False`` and there are an odd number of elements
            * an element is not a string
    r   z+Document or collection path cannot be empty   z5A collection must have an odd number of path elements   z4A document must have an even number of path elementsN)len
ValueErrorr5   strBAD_PATH_TEMPLATEformattype)pathis_collectionnum_elementselementmsgs        r-   verify_pathrS   |   s    & t9LqFGG!q TUU !q STT "'3'#**7DMBCS/!"r/   c                    | $t        j                  t        j                        S t	        | t
              rt        j                  |       S t	        | t              rt        j                  |       S t	        | t              rt        j                  |       S t	        | t              r$t        j                  | j                               S t	        | t        j                        rt        j                  t        |             S t	        | t              rt        j                  |       S t	        | t              rt        j                  |       S t        | d	d      }|t        j                  |
      S t	        | t              r$t        j                  | j!                               S t	        | t"        t$        t&        t(        f      r>t%        d | D              }t        j*                  |      }t        j                  |      S t	        | t,              rt/        | j1                               S t	        | t2              r7t5        |       }t        j6                  |      }t        j                  |      S t9        d| dt;        |             )a  Converts a native Python value into a Firestore protobuf ``Value``.

    Args:
        value (Union[NoneType, bool, int, float, datetime.datetime,             str, bytes, dict, ~google.cloud.Firestore.GeoPoint,             ~google.cloud.firestore_v1.vector.Vector]): A native
            Python value to convert to a protobuf field.

    Returns:
        ~google.cloud.firestore_v1.types.Value: A
        value encoded as a Firestore protobuf.

    Raises:
        TypeError: If the ``value`` is not one of the accepted types.
    N)
null_value)boolean_value)integer_value)double_value)timestamp_value)string_value)bytes_value_document_path)reference_value)geo_point_valuec              3  2   K   | ]  }t        |        y wr(   )encode_value).0rQ   s     r-   	<genexpr>zencode_value.<locals>.<genexpr>   s     FW<0Fs   values)array_value)fields)	map_valuez#Cannot convert to a Firestore ValuezInvalid type)r   Valuer   
NULL_VALUEr5   boolintfloatr   timestamp_pbdatetimer   rJ   bytesgetattrr&   r3   listtupleset	frozenset
ArrayValuer   r`   to_map_valuer"   encode_dictMapValue	TypeErrorrM   )valuedocument_path
value_listvalue_pb
value_dicts        r-   r`   r`      s     }~~)>)>?? %~~E22%~~E22%~~511%01~~e.@.@.BCC%**+~~.G.NOO%~~511%~~%00 E#3T:M ~~m<<%"~~e.?.?.ABB%$sI67FFF
&&j9~~(33% E..011% '
$$J7~~11
-und5k r/   c                h    | j                         D ci c]  \  }}|t        |       c}}S c c}}w )a*  Encode a dictionary into protobuf ``Value``-s.

    Args:
        values_dict (dict): The dictionary to encode as protobuf fields.

    Returns:
        Dict[str, ~google.cloud.firestore_v1.types.Value]: A
        dictionary of string keys and ``Value`` protobufs as dictionary
        values.
    )itemsr`   )values_dictkeyrz   s      r-   rw   rw      s0     8C7H7H7JKeCe$$KKKs   .c                    ddl m} | j                  sy  || j                  j                  t        | j                        | j                  | j                        S )Nr   )Document)namerf   create_timeupdate_time)	google.cloud.firestore_v1.typesr   exists	referencer\   rw   _datar   r   )snapshotr   s     r-   document_snapshot_to_protobufr      sK     9??..8>>*((((	 r/   c                  <    e Zd ZdZddZedd       Zedd       Zy)DocumentReferenceValuea  DocumentReference path container with accessors for each relevant chunk.

    Usage:
        doc_ref_val = DocumentReferenceValue(
            'projects/my-proj/databases/(default)/documents/my-col/my-doc',
        )
        assert doc_ref_val.project_name == 'my-proj'
        assert doc_ref_val.collection_name == 'my-col'
        assert doc_ref_val.document_id == 'my-doc'
        assert doc_ref_val.database_name == '(default)'

    Raises:
        ValueError: If the supplied value cannot satisfy a complete path.
    c                   || _         |j                  t              }t        |      dk  r t        j                  |      }t        |      |d   | _        |d   | _        |d   | _	        dj                  |dd        | _        y )N   rG         r$      )_reference_valuesplitDOCUMENT_PATH_DELIMITERrH   BAD_REFERENCE_ERRORrL   rI   project_namecollection_namedatabase_namejoindocument_id)r,   r]   partsrR   s       r-   r.   zDocumentReferenceValue.__init__  s}     /  %%&=>u:>%,,_=CS/!!!H$Qx"1X88E!"I.r/   c                P    dj                  | j                  | j                  g      S )zSComputed property for a DocumentReference's collection_name and
        document Idr$   )r   r   r   r2   s    r-   full_keyzDocumentReferenceValue.full_key"  s$     xx--t/?/?@AAr/   c           	         | j                   xs@ dj                  d| j                  d| j                  d| j                  | j
                  g      S )Nr$   projects	databases	documents)r   r   r   r   r   r   r2   s    r-   	full_pathz DocumentReferenceValue.full_path(  sR    $$ 

!!""$$  
)
 
	
r/   N)r]   rJ   r>   rJ   )r@   rA   rB   rC   r.   propertyr   r   rD   r/   r-   r   r     s6    / B B
 
 
r/   r   c                    ddl m} t        |       }|j                  |j                        }|j
                  | k7  r+t        j                  | |j                        }t        |      |S )a  Convert a reference value string to a document.

    Args:
        reference_value (str): A document reference value.
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            A client that has a document factory.

    Returns:
        :class:`~google.cloud.firestore_v1.document.DocumentReference`:
            The document corresponding to ``reference_value``.

    Raises:
        ValueError: If the ``reference_value`` is not of the expected
            format: ``projects/{project}/databases/{database}/documents/...``.
        ValueError: If the ``reference_value`` does not come from the same
            project / database combination as the ``client``.
    r   )BaseDocumentReference)
'google.cloud.firestore_v1.base_documentr   r   r   r   r\   WRONG_APP_REFERENCErL   _database_stringrI   )r]   clientr   doc_ref_valuer   rR   s         r-   reference_value_to_documentr   7  s[    $ N*?;M&,oom6L6L&MH/1!((&:Q:QRoOr/   c                   t        | d|       }|j                  d      }|dk(  ry|dk(  r|j                  S |dk(  r|j                  S |dk(  r|j                  S |dk(  rt        j                  |j                        S |d	k(  r|j                  S |d
k(  r|j                  S |dk(  rt        |j                  |      S |dk(  r4t        |j                  j                  |j                  j                        S |dk(  r.|j                   j"                  D cg c]  }t%        ||       c}S |dk(  r t'        |j(                  j*                  |      S t-        d|      c c}w )a  Converts a Firestore protobuf ``Value`` to a native Python value.

    Args:
        value (google.cloud.firestore_v1.types.Value): A
            Firestore protobuf to be decoded / parsed / converted.
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            A client that has a document factory.

    Returns:
        Union[NoneType, bool, int, float, datetime.datetime,             str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
        Python value converted from the ``value``.

    Raises:
        NotImplementedError: If the ``value_type`` is ``reference_value``.
        ValueError: If the ``value_type`` is unknown.
    _pb
value_typerU   NrV   rW   rX   rY   rZ   r[   r]   r^   re   rg   zUnknown ``value_type``)rp   
WhichOneofrV   rW   rX   r   from_timestamp_pbrY   rZ   r[   r   r]   r&   r^   r*   r+   re   rd   decode_valuedecode_dictrg   rf   rI   )rz   r   r}   r   rQ   s        r-   r   r   U  sk   , ueU+H$$\2J\!		&%%%		&%%%	~	%$$$	(	(&889Q9QRR	~	%$$$	}	$###	(	(*8+C+CVLL	(	($$--x/G/G/Q/Q
 	
 
}	$9A9M9M9T9T
.5L&)
 	
 
{	"8--44f==1:>>
s   Ec           	         t        | d|       }|j                         D ci c]  \  }}|t        ||       }}}|j                  dd      dk(  r%t	        t
        t           |d         }t        |      S |S c c}}w )a   Converts a protobuf map of Firestore ``Value``-s.

    Args:
        value_fields (google.protobuf.pyext._message.MessageMapContainer): A
            protobuf map of Firestore ``Value``-s.
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            A client that has a document factory.

    Returns:
        Dict[str, Union[NoneType, bool, int, float, datetime.datetime,             str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
        of native Python values converted from the ``value_fields``.
    r   __type__N
__vector__rz   )rp   r   r   getr   r
   rl   r   )value_fieldsr   value_fields_pbr   rz   resrd   s          r-   r   r     s|     lE<@O>M>S>S>U
V
U3UF++
VC
V
wwz4 L0 huos7|4f~J Ws   A7c                    | j                   j                  t        d      \  }}||k7  rt        d| j                   d|      |S )a  Parse a document ID from a document protobuf.

    Args:
        document_pb (google.cloud.firestore_v1.            document.Document): A protobuf for a document that
            was created in a ``CreateDocument`` RPC.
        expected_prefix (str): The expected collection prefix for the
            fully-qualified document name.

    Returns:
        str: The document ID from the protobuf.

    Raises:
        ValueError: If the name does not begin with the prefix.
    rG   zUnexpected document namezExpected to begin with)r   rsplitr   rI   )document_pbexpected_prefixprefixr   s       r-   
get_doc_idr     sQ      &**112I1MFK &$	
 	
 r/   zMarker for an empty dict valuec              #  N  K   | s|t         f yt        | j                               D ]x  \  }}|rt        j                  |      }nt        |      }t        |j
                  |j
                  z    }t        |t              rt        ||      D ]  \  }}||f  s||f z yw)z7Do depth-first walk of tree, yielding field_path, valueN)	r!   sortedr   r   from_stringr   r5   r"   extract_fields)	document_dataprefix_pathexpand_dotsr   rz   sub_key
field_paths_paths_values	            r-   r   r     s      :%% !4!4!67 	(JC#//4#C."[%6%6%FHJ%&'5eZ'H *OFG '/)* !%''	(s   B#B%c                    | }|j                   dd D ]  }|j                  |i       } |t        u ri }|||j                   d   <   y)z,Set a value into a document for a field_pathN)r   
setdefaultr!   )r   r   rz   currentrQ   s        r-   set_field_valuer     sW    G##CR( 2$$Wb12
$)GJR !r/   c                    |j                   st        d      | }|j                   d d D ]  }||   }	 ||j                   d      S )Nz
Empty pathr   )r   rI   )r   r   r   rQ   s       r-   get_field_valuer     sW    &&G##CR( #'"#:##B'((r/   c                  z    e Zd ZdZddZ	 	 	 	 ddZed        Zed        Z	 d	 ddZ		 d	 ddZ
	 	 dd	Zddd
Zy)DocumentExtractora  Break document data up into actual data and transforms.

    Handle special values such as ``DELETE_FIELD``, ``SERVER_TIMESTAMP``.

    Args:
        document_data (dict):
            Property names and values to use for sending a change to
            a document.
    c                @   || _         g | _        g | _        g | _        i | _        i | _        i | _        i | _        i | _        i | _	        d| _
        t               }| j                  |      }|D ]  \  }}||k(  r|t        u rd| _
        |t        j                  u r| j                  j!                  |       J|t        j"                  u r| j                  j!                  |       xt%        |t        j&                        r|j(                  | j                  |<   t%        |t        j*                        r|j(                  | j
                  |<   t%        |t        j,                        r|j.                  | j                  |<   t%        |t        j0                        r|j.                  | j                  |<   Jt%        |t        j2                        r|j.                  | j                  |<   | j                  j!                  |       t5        | j                  ||        y )NFT)r   field_pathsdeleted_fieldsserver_timestampsarray_removesarray_unions
incrementsminimumsmaximums
set_fieldsempty_documentr   _get_document_iteratorr!   r   DELETE_FIELDappendSERVER_TIMESTAMPr5   ArrayRemoverd   
ArrayUnion	Incrementrz   MaximumMinimumr   )r,   r   r   iteratorr   rz   s         r-   r.   zDocumentExtractor.__init__  s   * !# "#k..{;!) 	DJ[(Uj-@&*#*111##**:6*555&&--j9E:#9#9:16"":.E:#8#8905!!*-E:#7#78.3kk
+E:#5#56,1KKj)E:#5#56,1KKj)   ''
3UC7	Dr/   c                .    t        | j                  |      S r(   r   r   r,   r   s     r-   r   z(DocumentExtractor._get_document_iterator'  s     d00+>>r/   c                    t        | j                  xsD | j                  xs6 | j                  xs( | j                  xs | j
                  xs | j                        S r(   )rj   r   r   r   r   r   r   r2   s    r-   has_transformsz DocumentExtractor.has_transforms,  s^    "" !!    }}	
 }}
 	
r/   c                   t        | j                  t        | j                        z   t        | j                        z   t        | j
                        z   t        | j                        z   t        | j                        z         S r(   )r   r   rq   r   r   r   r   r   r2   s    r-   transform_pathsz!DocumentExtractor.transform_paths7  sw    ""4%%&'4$$%& 4??#$ 4==!	"
 4==!"
 	
r/   c                     y r(   rD   )r,   allow_empty_masks     r-   _get_update_maskz"DocumentExtractor._get_update_maskB  s     r/   Nc                    |t        j                  |      }nd }t        j                  t	        j
                  |t        | j                              | j                  |      |      }|S )Nr   )r   rf   )updateupdate_maskcurrent_document)	r   Preconditionr   Writer   r   rw   r   r   )r,   r{   r   r   r   	update_pbs         r-   get_update_pbzDocumentExtractor.get_update_pbG  sg     %22&A#KK$$";t+G --.>?-
	 r/   c                    d }| j                   D cg c]7  }|t        j                  j                  |j	                         t
              f9 c}| j                  j                         D cg c]<  \  }}|t        j                  j                  |j	                          ||            f> c}}z   | j                  j                         D cg c]<  \  }}|t        j                  j                  |j	                          ||            f> c}}z   | j                  j                         D cg c]?  \  }}|t        j                  j                  |j	                         t        |            fA c}}z   | j                  j                         D cg c]?  \  }}|t        j                  j                  |j	                         t        |            fA c}}z   | j                  j                         D cg c]?  \  }}|t        j                  j                  |j	                         t        |            fA c}}z   }t        |      D cg c]  \  }}|	 c}}S c c}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w )Nc                h    | D cg c]  }t        |       }}t        j                  |      S c c}w )Nrc   )r`   r   ru   )rd   rQ   r|   s      r-   make_array_valuezCDocumentExtractor.get_field_transform_pbs.<locals>.make_array_value\  s1    ?EFG,w/FJF&&j99 Gs   /)r   set_to_server_value)r   remove_all_from_array)r   append_missing_elements)r   	increment)r   maximum)r   minimum)r   r   r   FieldTransformto_api_reprREQUEST_TIME_ENUMr   r   r   r   r`   r   r   r   )r,   r{   r  rN   rd   rz   path_field_transforms	transforms           r-   get_field_transform_pbsz)DocumentExtractor.get_field_transform_pbsY  s   	: !22	  ++::#'#3#3#5,= ; 	$ %)$6$6$<$<$>	 !D& ++::#'#3#3#5.>v.F ; 	8 %)$5$5$;$;$=	 !D& ++::#'#3#3#50@0H ; 	)J $(??#8#8#:  D% ++::#'#3#3#5eAT ; =&\ $(==#6#6#8  D% ++::#'#3#3#5|E?R ; O/n $(==#6#6#8  D% ++::#'#3#3#5|E?R ; a8 	v 288M1NOodI	OOu			 Ps.   <I'-AI,AI23AI8AI>?AJJ
c                   | j                  |      }t        j                  t        j                  ||            }|C|j                  j
                  j                  t        j                  |      j                         |S )N)r   field_transforms)r  r   )	r  r   r   r   r   r   CopyFromr   r   )r,   r{   r   r  transform_pbs        r-   get_transform_pbz"DocumentExtractor.get_transform_pb  ss    77F{{--&9I

 --66##6266 r/   r=   r   r   r>   z%Generator[Tuple[Any, Any], Any, None]Fr>   z#Optional[types.common.DocumentMask])NFr>   ztypes.write.Write)r>   z2List[types.write.DocumentTransform.FieldTransform]r(   )r@   rA   rB   rC   r.   r   r   r   r   r   r   r  r  rD   r/   r-   r   r     s    +DZ?$?	.?
 
 
 
 
  %	, <A	$BP	;BPHr/   r   c                    t        |      }|j                  rt        d      |j                  | d      }|j                  r,|j                  |       }|j                  j                  |       |gS )ai  Make ``Write`` protobufs for ``create()`` methods.

    Args:
        document_path (str): A fully-qualified document path.
        document_data (dict): Property names and values to use for
            creating a document.

    Returns:
        List[google.cloud.firestore_v1.types.Write]: One or two
        ``Write`` protobuf instances for ``create()``.
    z.Cannot apply DELETE_FIELD in a create request.Fr   r   r   rI   r   r   r  update_transformsextend)r{   r   	extractor	create_pbfield_transform_pbss        r-   pbs_for_creater    so     "-0IIJJ''e'DI'??N##**+>?;r/   c                    t        |      }|j                  rt        d      |j                  |       }|j                  r,|j                  |       }|j                  j                  |       |gS )ad  Make ``Write`` protobufs for ``set()`` methods.

    Args:
        document_path (str): A fully-qualified document path.
        document_data (dict): Property names and values to use for
            replacing a document.

    Returns:
        List[google.cloud.firestore_v1.types.Write]: One
        or two ``Write`` protobuf instances for ``set()``.
    zdCannot apply DELETE_FIELD in a set request without specifying 'merge=True' or 'merge=[field_paths]'.r  )r{   r   r  set_pbr  s        r-   pbs_for_set_no_merger"    sr     "-0I@
 	

 $$]3F'??N  ''(;<8Or/   c                  Z     e Zd ZdZd	 fdZd	dZd
dZddZd	dZd	dZ		 d	 ddZ
 xZS )DocumentExtractorForMerge7Break document data up into actual data and transforms.c                V    t         t        |   |       g | _        g | _        g | _        y r(   )superr$  r.   
data_mergetransform_mergemerge)r,   r   	__class__s     r-   r.   z"DocumentExtractorForMerge.__init__  s)    '7F "%'
r/   c                    t        | j                  | j                  z         | _        | j                  | _        t        | j                  | j                  z         | _        y r(   )r   r   r   r(  r   r)  r*  r2   s    r-   _apply_merge_allz*DocumentExtractorForMerge._apply_merge_all  sH     !1!1D4G4G!GH#33DOOd.B.BBC
r/   c              #  j   K   |D ]*  }t        |t              r| t        t        |        , y wr(   )r5   r   r   )r,   r*  merge_fields      r-   _construct_merge_pathsz0DocumentExtractorForMerge._construct_merge_paths  s8       	@K+y1!!!1+!>??		@s   13c                   t        | j                  |            }t        t        |      dz
        D ];  }||   ||dz      }}|j	                  |      s"t        dj                  ||             |D ](  }|| j                  v r	 t        | j                  |       * |S # t        $ r t        dj                  |            w xY w)NrG   zMerge paths overlap: {}, {}zInvalid merge path: {})r   r0  rangerH   eq_or_parentrI   rL   r   r   r   KeyError)r,   r*  merge_pathsindexlhsrhs
merge_paths          r-   _normalize_merge_pathsz0DocumentExtractorForMerge._normalize_merge_paths  s    T88?@ 3{+a/0 	QE"5);uqy+AC$ !>!E!Ec3!OPP	Q
 & 	NJT000N 2 2J?		N   N !9!@!@!LMMNs   B$Cc                   | j                   rt        d      | j                  |      }| j                  d d = | j                  d d = || _        |D ]i  }|| j                  v r| j                  j                  |       | j                  D ]/  }|j                  |      s| j                  j                  |       1 k i }| j                  D ]%  }t        | j                  |      }t        |||       ' || _        | j                  D cg c]  }|| j
                  vr| }}|rt        dj                  |            t!        | j                  | j                  z         | _        t#               }| j
                  D ]=  }| j                  D 	cg c]  }	|j                  |	      r|	 }
}	|j%                  |
       ? | j&                  D cg c]	  }||v s| c}| _        | j(                  j+                         D ci c]  \  }}||v r|| c}}| _        | j,                  j+                         D ci c]  \  }}||v r|| c}}| _        y c c}w c c}	w c c}w c c}}w c c}}w )Nz1Cannot merge specific fields with empty document.z!Cannot delete unmerged fields: {})r   rI   r:  r(  r)  r*  r   r   r   r3  r   r   r   r   r   rL   r   rs   r   r   r   r   r   )r,   r*  r5  r9  r   merged_set_fieldsrz   unmerged_deleted_fieldsmerged_transform_pathstransform_pathtranform_merge_pathsrN   rd   s                r-   _apply_merge_pathsz,DocumentExtractorForMerge._apply_merge_paths  s   PQQ11%8OOA  # 
% 	7JT111$$++J7".. 7
**:6OO**:67		7 #%// 	BJ#D$6$6
CE-z5A	B , #11#
+ #
 #

 #3::;RS  !43F3F!FG "%** 	@J '+&:&:$"**>: $  $
 #))*>?	@ "33"
t?U7UD"
 !% 2 2 8 8 :
f-- &L
 !% 1 1 7 7 9
f-- &L
?#
$"


s$   I
I	II:I1I!c                P    |du r| j                          y | j                  |       y )NT)r-  rA  )r,   r*  s     r-   apply_mergez%DocumentExtractorForMerge.apply_mergeK  s#    D=!!###E*r/   c                    | j                   D cg c]   }|| j                  vr|j                         " }}t        j                  |      S c c}w N)r   )r*  r)  r
  r   DocumentMask)r,   r   r   
mask_pathss       r-   r   z*DocumentExtractorForMerge._get_update_maskQ  sT     #jj
!5!55 ""$

 
 ""z::
s   %Ar=   )r>   zGenerator[Any, Any, None])r>   rq   r  r  )r@   rA   rB   rC   r.   r-  r0  r:  rA  rC  r   __classcell__r+  s   @r-   r$  r$    s9    AD@(<
|+  %
;	,
;r/   r$  c                    t        |      }|j                  |       |j                  |       }|j                  r,|j	                  |       }|j
                  j                  |       |gS )a  Make ``Write`` protobufs for ``set()`` methods.

    Args:
        document_path (str): A fully-qualified document path.
        document_data (dict): Property names and values to use for
            replacing a document.
        merge (Optional[bool] or Optional[List<apispec>]):
            If True, merge all fields; else, merge only the named fields.

    Returns:
        List[google.cloud.firestore_v1.types.Write]: One
        or two ``Write`` protobuf instances for ``set()``.
    )r$  rC  r   r   r  r  r  )r{   r   r*  r  r!  r  s         r-   pbs_for_set_with_mergerK  ^  sb      *-8I% $$]3F  '??N  ''(;<8Or/   c                  >     e Zd ZdZd fdZ	 	 	 	 ddZdddZ xZS )	DocumentExtractorForUpdater%  c                   t         t        |   |       t        |D cg c]  }t	        j
                  |       c}      | _        t        | j                        }| j                  D ]6  }|j                         D ]!  }||v st        dj                  ||             8 | j                  D ]   }||vst        dj                  |             y c c}w )NzConflicting field path: {}, {}z"Cannot update with nest delete: {})r'  rM  r.   r   r   r   top_level_pathsrs   lineagerI   rL   r   )r,   r   r   topstop_level_pathancestorr   r+  s          r-   r.   z#DocumentExtractorForUpdate.__init__}  s    ($8G%3@ACY""3'A 
 4''("22 	N*224 t#$8??*H 	 -- 	J% 8??
K 	 Bs   Cc                2    t        | j                  |d      S )NT)r   r   r   s     r-   r   z1DocumentExtractorForUpdate._get_document_iterator  s     d00+4PPr/   c                    g }| j                   D ]0  }|| j                  vs|j                  |j                                2 t	        j
                  |      S rE  )rO  r   r   r
  r   rF  )r,   r   rG  r   s       r-   r   z+DocumentExtractorForUpdate._get_update_mask  sT    
.. 	<J!5!55!!*"8"8":;	< ""z::r/   r=   r  r  )r>   ztypes.common.DocumentMask)r@   rA   rB   rC   r.   r   r   rH  rI  s   @r-   rM  rM  z  s-    A*Q$Q	.Q
; ;r/   rM  c                   t        |      }|j                  rt        d      |t        d      }|j	                  |       }|j                  |       |j                  r,|j                  |       }|j                  j                  |       |gS )aC  Make ``Write`` protobufs for ``update()`` methods.

    Args:
        document_path (str): A fully-qualified document path.
        field_updates (dict): Field names or paths to update and values
            to update with.
        option (optional[:class:`~google.cloud.firestore_v1.client.WriteOption`]):
            A write option to make assertions / preconditions on the server
            state of the document before applying changes.

    Returns:
        List[google.cloud.firestore_v1.types.Write]: One
        or two ``Write`` protobuf instances for ``update()``.
    z%Cannot update with an empty document.Tr   )
rM  r   rI   ExistsOptionr   modify_writer   r  r  r  )r{   field_updatesoptionr  r   r  s         r-   pbs_for_updater[    s     +=9I@AA~T*''6I
	"'??N##**+>?;r/   c                X    t        j                  |       }||j                  |       |S )a  Make a ``Write`` protobuf for ``delete()`` methods.

    Args:
        document_path (str): A fully-qualified document path.
        option (optional[:class:`~google.cloud.firestore_v1.client.WriteOption`]):
            A write option to make assertions / preconditions on the server
            state of the document before applying changes.

    Returns:
        google.cloud.firestore_v1.types.Write: A
        ``Write`` protobuf instance for the ``delete()``.
    )delete)r   r   rX  )r{   rZ  write_pbs      r-   pb_for_deleter_    s+     {{-0HH%Or/   c                      e Zd ZdZy)ReadAfterWriteErrorzhRaised when a read is attempted after a write.

    Raised by "read" methods that use transactions.
    N)r@   rA   rB   rC   rD   r/   r-   ra  ra    s    r/   ra  c                    | y| j                   st        t              |r't        | j                        dkD  rt        t              | j                  S )a  Get the transaction ID from a ``Transaction`` object.

    Args:
        transaction (Optional[:class:`~google.cloud.firestore_v1.transaction.            Transaction`]):
            An existing transaction that this query will run in.
        read_operation (Optional[bool]): Indicates if the transaction ID
            will be used in a read operation. Defaults to :data:`True`.

    Returns:
        Optional[bytes]: The ID of the transaction, or :data:`None` if the
        ``transaction`` is :data:`None`.

    Raises:
        ValueError: If the ``transaction`` is not in progress (only if
            ``transaction`` is not :data:`None`).
        ReadAfterWriteError: If the ``transaction`` has writes stored on
            it and ``read_operation`` is :data:`True`.
    Nr   )in_progressrI   INACTIVE_TXNrH   
_write_pbsra  READ_AFTER_WRITE_ERRORid)transactionread_operations     r-   get_transaction_idrj    sL    ( &&\**c+"8"89A=%&<==~~r/   c                    d| fgS )zCreate RPC metadata containing a prefix.

    Args:
        prefix (str): appropriate resource path.

    Returns:
        List[Tuple[str, str]]: RPC metadata with supplied prefix
    zgoogle-cloud-resource-prefixrD   )r   kws     r-   metadata_with_prefixrm    s     ,V455r/   c                      e Zd ZdZdddZy)WriteOptionz7Option used to assert a condition on a write operation.Nc                    t         )a>  Modify a ``Write`` protobuf based on the state of this write option.

        This is a virtual method intended to be implemented by subclasses.

        Args:
            write (google.cloud.firestore_v1.types.Write): A
                ``Write`` protobuf instance to be modified with a precondition
                determined by the state of this option.
            no_create_msg (Optional[str]): A message to use to indicate that
                a create operation is not allowed.

        Raises:
            NotImplementedError: Always, this method is virtual.
        )NotImplementedError)r,   r   no_create_msgs      r-   rX  zWriteOption.modify_write	  s
     "!r/   r(   r=   )r@   rA   rB   rC   rX  rD   r/   r-   ro  ro    s
    A"r/   ro  c                  &    e Zd ZdZddZd ZddZy)LastUpdateOptiona*  Option used to assert a "last update" condition on a write operation.

    This will typically be created by
    :meth:`~google.cloud.firestore_v1.client.Client.write_option`.

    Args:
        last_update_time (google.protobuf.timestamp_pb2.Timestamp): A
            timestamp. When set, the target document must exist and have
            been last updated at that time. Protobuf ``update_time`` timestamps
            are typically returned from methods that perform write operations
            as part of a "write result" protobuf or directly.
    c                    || _         y r(   )_last_update_time)r,   last_update_times     r-   r.   zLastUpdateOption.__init__)  s
    !1r/   c                l    t        || j                        st        S | j                  |j                  k(  S r(   )r5   r+  r6   rv  r7   s     r-   r9   zLastUpdateOption.__eq__,  s-    %0!!%%)@)@@@r/   c                    t        j                  | j                        }|j                  j                  j                  |j                         y)ac  Modify a ``Write`` protobuf based on the state of this write option.

        The ``last_update_time`` is added to ``write_pb`` as an "update time"
        precondition. When set, the target document must exist and have been
        last updated at that time.

        Args:
            write_pb (google.cloud.firestore_v1.types.Write): A
                ``Write`` protobuf instance to be modified with a precondition
                determined by the state of this option.
            unused_kwargs (Dict[str, Any]): Keyword arguments accepted by
                other subclasses that are unused here.
        )r   N)r   r   rv  r   r   r  r,   r   unused_argsunused_kwargscurrent_docs        r-   rX  zLastUpdateOption.modify_write1  s6     ((T5K5KL		""++KOO<r/   Nr=   r@   rA   rB   rC   r.   r9   rX  rD   r/   r-   rt  rt    s    2A
=r/   rt  c                  &    e Zd ZdZddZd ZddZy)rW  a  Option used to assert existence on a write operation.

    This will typically be created by
    :meth:`~google.cloud.firestore_v1.client.Client.write_option`.

    Args:
        exists (bool): Indicates if the document being modified
            should already exist.
    c                    || _         y r(   )_exists)r,   r   s     r-   r.   zExistsOption.__init__N  s	    r/   c                l    t        || j                        st        S | j                  |j                  k(  S r(   )r5   r+  r6   r  r7   s     r-   r9   zExistsOption.__eq__Q  s)    %0!!||u}},,r/   c                    t        j                  | j                        }|j                  j                  j                  |j                         y)aB  Modify a ``Write`` protobuf based on the state of this write option.

        If:

        * ``exists=True``, adds a precondition that requires existence
        * ``exists=False``, adds a precondition that requires non-existence

        Args:
            write (google.cloud.firestore_v1.types.Write): A
                ``Write`` protobuf instance to be modified with a precondition
                determined by the state of this option.
            unused_kwargs (Dict[str, Any]): Keyword arguments accepted by
                other subclasses that are unused here.
        r   N)r   r   r  r   r   r  rz  s        r-   rX  zExistsOption.modify_writeV  s4     ((=		""++KOO<r/   Nr=   r~  rD   r/   r-   rW  rW  C  s    -
=r/   rW  c                Z    i }| t         j                  j                  ur| |d<   |||d<   |S )zCHelper fo API methods which take optional 'retry' / 'timeout' args.r   timeout)r   methodDEFAULT)r   r  kwargss      r-   make_retry_timeout_kwargsr  i  s9     FHOO+++w#yMr/   c                x    t        | xs. t        j                  t        j                  j
                              S )z7Returns the supplied datetime (or "now") as a Timestamp)tz)r   r   nowrn   timezoneutc)dts    r-   build_timestampr  x  s1     %
C%))X->->-B-BC r/   c                   t        | t              st        |       n| } t        |t              st        |      n|}| j                  | j                  dz  z   }|j                  |j                  dz  z   }||k(  ry||kD  rdS dS )Ng    eAr   rG   r   )r5   r   r  nanosseconds)ts1ts2	ts1_nanos	ts2_nanoss       r-   compare_timestampsr    sy     '1i&@/#
cC&0i&@/#
cC		CKK#--I		CKK#--III%1-2-r/   c                   ddl m}m} dgg dg ddgddgd}|d	   }d
}d
}t        |       D ]  }t	        |j                               }	t        |	      dk7  rt        d      |	d   }
|
|vrt        d|
 d|       	 |j                  t        j                  |            }||
dk(  sJ  |||
   d         }|}n|j                  |||
       ||
   } d|vrt        d      t        ||      }t        ||      }|j                  ||d       |S # t        $ r$}|j                  d   dk(  rt        d      |d
}~ww xY w)a  Inverse operation to a `FirestoreBundle` instance's `build()` method.

    Args:
        serialized (Union[str, bytes]): The result of `FirestoreBundle.build()`.
            Should be a list of dictionaries in string format.
        client (BaseClient): A connected Client instance.

    Returns:
        FirestoreBundle: A bundle equivalent to that which called `build()` and
            initially created the `serialized` value.

    Raises:
        ValueError: If any of the dictionaries in the list contain any more than
            one top-level key.
        ValueError: If any unexpected BundleElement types are encountered.
        ValueError: If the serialized bundle ends before expected.
    r   )BundleElementFirestoreBundlemetadata)
namedQuerydocumentMetadata__end__r   r  r  )__initial__r  r  r  r   r  NrG   z8Expected serialized BundleElement with one top-level keyz"Encountered BundleElement of type z. Expected one of z%'dict' object has no attribute 'find'z[Invalid serialization of datetimes. Cannot deserialize Bundles created from the NodeJS SDK.rg  )r   rM   z,Unexpected end to serialized FirestoreBundle)google.cloud.firestore_bundler  r  _parse_bundle_elements_datarq   keysrH   rI   	from_jsonjsondumpsAttributeErrorargs_add_bundle_elementr   )
serializedr   r  r  bundle_state_machineallowed_next_element_typesmetadata_bundle_elementbundledatar  r   bundle_elementes                r-   deserialize_bundler    s   * M #|AC'L'3 -A,O 8<(,F+J7 '? tyy{+t9>WXX7004SE :##=">@ 		*44TZZ5EFN >*$$$$T#Yt_5F&4# &&~f3&O &:#%>"O'?R 22GHH/6*F"=2IJ
   MC  	vvayCC N  G	s   =$D	E D;;E c              #    K   t        t        | t              r| n| j                  d            }d}	 t	        |d      }|yt        |      }|j                         r||z  }n{|dk(  rt        d      t        |      }d}t        |g      }d}||k  r%|j                  t	        |             |dz  }||k  r%t        j                  |j                  d             w)a
  Reads through a serialized FirestoreBundle and yields JSON chunks that
    were created via `BundleElement.to_json(bundle_element)`.

    Serialized FirestoreBundle instances are length-prefixed JSON objects, and
    so are of the form "123{...}57{...}"
    To correctly and safely read a bundle, we must first detect these length
    prefixes, read that many bytes of data, and attempt to JSON-parse that.

    Raises:
        ValueError: If a chunk of JSON ever starts without following a length
            prefix.
    zutf-8 NzExpected length prefixrG   )iterr5   ro   encodenextchr	isnumericrI   rk   	bytearrayr   r  loadsdecode)r  _serializedlength_prefixbyte_str_length_prefix_bytes_counters           r-   r  r    s      "& U3
9J9J79S"K M
";5<I>>T!M" !9:: /NMv&FH^+d;/0A ^+ **V]]7344+ s   B4C7'C)
query_namec             #     K   ddl m} | j                  j                         D ]+  }|r||j                  j
                  vr|j                   - y w)Nr   )_BundledDocument)$google.cloud.firestore_bundle.bundler  r   rd   r  queriesr   )r  r  r  bundled_docs       r-   _get_documents_from_bundler    sQ      F ''..0 #*K,@,@,H,HH"""#s   AAc               V    | j                   j                  |      }|r|j                  S y r(   )r   r   r   )r  r   r  s      r-   _get_document_from_bundler  (  s,    
 ""&&{3K###r/   r=   )r>   ztypes.document.Value)r>   r"   )r   z'DocumentSnapshot'r>   z4Optional['google.cloud.firestore_v1.types.Document'])r>   r   )r>   zZUnion[None, bool, int, float, list, datetime.datetime, str, bytes, dict, GeoPoint, Vector])r>   zUnion[dict, Vector]r   r  r  )r>   zList[types.write.Write]r  )T)r>   zUnion[bytes, None])r   rJ   r>   zList[Tuple[str, str]])r   z2retries.Retry | retries.AsyncRetry | object | Noner  zfloat | Noner>   r"   r(   )r  z;Optional[Union[DatetimeWithNanoseconds, datetime.datetime]]r>   r   )r  #Union[Timestamp, datetime.datetime]r  r  r>   rk   )r  Union[str, bytes]r   z-'google.cloud.firestore_v1.client.BaseClient'r>   z/'google.cloud.firestore_bundle.FirestoreBundle')r  r  r>   zGenerator[Dict, None, None])r  zOptional[str]r>   z)Generator['DocumentSnapshot', None, None])r   rJ   r>   zOptional['DocumentSnapshot'])irC   
__future__r   rn   r  typingr   r   r   r   r   r	   r
   r   r   r   r   grpcgoogle.api_corer   r   retries google.api_core.datetime_helpersr   google.cloud._helpersr   google.protobufr   google.protobuf.timestamp_pb2r   google.typer   googlegoogle.cloudr   google.cloud.firestore_v1r   r   $google.cloud.firestore_v1.field_pathr   r   r   r   r   r   %google.cloud.firestore_v1.types.writer    google.cloud.firestore_v1.vectorr   r    __annotations__rK   r   rd  rf  r   r   r	  ServerValueREQUEST_TIMEr  
StatusCodeALREADY_EXISTSConflict	NOT_FOUNDNotFoundr#   objectr&   rS   r`   rw   r   r   r   r   r   r   Sentinelr!   r   r   r   r   r  r"  r$  rK  rM  r[  r_  	Exceptionra  rj  rm  ro  rt  rW  r  r  r  r  r  r  r  rD   r/   r-   <module>r     s   C "       $ , D ; & 3 "  # 7 L C C C 3:   S  MG %  V  &44@@MM OO""J$7$7OOz22 -$v -$`""JAHL 9 1
 1
h<4?4?n48 !Z  !AB
 8=( )(*(,*)z zz4:x; 1 x;v8#;!2 #;LB() <	6"& "*%={ %=P#=; #=L=HT	  GKC
.	,
.	,
. 	
._!_9_ 5_D)5!)5 )5Z ,0	#(	#.	#	 	 "		r/   