Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/base_document.py: 39%
150 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 06:27 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 06:27 +0000
1# Copyright 2017 Google LLC All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Classes for representing documents for the Google Cloud Firestore API."""
17import copy
19from google.api_core import retry as retries
21from google.cloud.firestore_v1.types import Document
22from google.cloud.firestore_v1 import _helpers
23from google.cloud.firestore_v1 import field_path as field_path_module
24from google.cloud.firestore_v1.types import common
26# Types needed only for Type Hints
27from google.cloud.firestore_v1.types import firestore
28from google.cloud.firestore_v1.types import write
29from typing import Any, Dict, Iterable, NoReturn, Optional, Union, Tuple
32class BaseDocumentReference(object):
33 """A reference to a document in a Firestore database.
35 The document may already exist or can be created by this class.
37 Args:
38 path (Tuple[str, ...]): The components in the document path.
39 This is a series of strings representing each collection and
40 sub-collection ID, as well as the document IDs for any documents
41 that contain a sub-collection (as well as the base document).
42 kwargs (dict): The keyword arguments for the constructor. The only
43 supported keyword is ``client`` and it must be a
44 :class:`~google.cloud.firestore_v1.client.Client`. It represents
45 the client that created this document reference.
47 Raises:
48 ValueError: if
50 * the ``path`` is empty
51 * there are an even number of elements
52 * a collection ID in ``path`` is not a string
53 * a document ID in ``path`` is not a string
54 TypeError: If a keyword other than ``client`` is used.
55 """
57 _document_path_internal = None
59 def __init__(self, *path, **kwargs) -> None:
60 _helpers.verify_path(path, is_collection=False)
61 self._path = path
62 self._client = kwargs.pop("client", None)
63 if kwargs:
64 raise TypeError(
65 "Received unexpected arguments", kwargs, "Only `client` is supported"
66 )
68 def __copy__(self):
69 """Shallow copy the instance.
71 We leave the client "as-is" but tuple-unpack the path.
73 Returns:
74 .DocumentReference: A copy of the current document.
75 """
76 result = self.__class__(*self._path, client=self._client)
77 result._document_path_internal = self._document_path_internal
78 return result
80 def __deepcopy__(self, unused_memo):
81 """Deep copy the instance.
83 This isn't a true deep copy, wee leave the client "as-is" but
84 tuple-unpack the path.
86 Returns:
87 .DocumentReference: A copy of the current document.
88 """
89 return self.__copy__()
91 def __eq__(self, other):
92 """Equality check against another instance.
94 Args:
95 other (Any): A value to compare against.
97 Returns:
98 Union[bool, NotImplementedType]: Indicating if the values are
99 equal.
100 """
101 if isinstance(other, self.__class__):
102 return self._client == other._client and self._path == other._path
103 else:
104 return NotImplemented
106 def __hash__(self):
107 return hash(self._path) + hash(self._client)
109 def __ne__(self, other):
110 """Inequality check against another instance.
112 Args:
113 other (Any): A value to compare against.
115 Returns:
116 Union[bool, NotImplementedType]: Indicating if the values are
117 not equal.
118 """
119 if isinstance(other, self.__class__):
120 return self._client != other._client or self._path != other._path
121 else:
122 return NotImplemented
124 @property
125 def path(self):
126 """Database-relative for this document.
128 Returns:
129 str: The document's relative path.
130 """
131 return "/".join(self._path)
133 @property
134 def _document_path(self):
135 """Create and cache the full path for this document.
137 Of the form:
139 ``projects/{project_id}/databases/{database_id}/...
140 documents/{document_path}``
142 Returns:
143 str: The full document path.
145 Raises:
146 ValueError: If the current document reference has no ``client``.
147 """
148 if self._document_path_internal is None:
149 if self._client is None:
150 raise ValueError("A document reference requires a `client`.")
151 self._document_path_internal = _get_document_path(self._client, self._path)
153 return self._document_path_internal
155 @property
156 def id(self):
157 """The document identifier (within its collection).
159 Returns:
160 str: The last component of the path.
161 """
162 return self._path[-1]
164 @property
165 def parent(self):
166 """Collection that owns the current document.
168 Returns:
169 :class:`~google.cloud.firestore_v1.collection.CollectionReference`:
170 The parent collection.
171 """
172 parent_path = self._path[:-1]
173 return self._client.collection(*parent_path)
175 def collection(self, collection_id: str) -> Any:
176 """Create a sub-collection underneath the current document.
178 Args:
179 collection_id (str): The sub-collection identifier (sometimes
180 referred to as the "kind").
182 Returns:
183 :class:`~google.cloud.firestore_v1.collection.CollectionReference`:
184 The child collection.
185 """
186 child_path = self._path + (collection_id,)
187 return self._client.collection(*child_path)
189 def _prep_create(
190 self,
191 document_data: dict,
192 retry: retries.Retry = None,
193 timeout: float = None,
194 ) -> Tuple[Any, dict]:
195 batch = self._client.batch()
196 batch.create(self, document_data)
197 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
199 return batch, kwargs
201 def create(
202 self,
203 document_data: dict,
204 retry: retries.Retry = None,
205 timeout: float = None,
206 ) -> NoReturn:
207 raise NotImplementedError
209 def _prep_set(
210 self,
211 document_data: dict,
212 merge: bool = False,
213 retry: retries.Retry = None,
214 timeout: float = None,
215 ) -> Tuple[Any, dict]:
216 batch = self._client.batch()
217 batch.set(self, document_data, merge=merge)
218 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
220 return batch, kwargs
222 def set(
223 self,
224 document_data: dict,
225 merge: bool = False,
226 retry: retries.Retry = None,
227 timeout: float = None,
228 ) -> NoReturn:
229 raise NotImplementedError
231 def _prep_update(
232 self,
233 field_updates: dict,
234 option: _helpers.WriteOption = None,
235 retry: retries.Retry = None,
236 timeout: float = None,
237 ) -> Tuple[Any, dict]:
238 batch = self._client.batch()
239 batch.update(self, field_updates, option=option)
240 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
242 return batch, kwargs
244 def update(
245 self,
246 field_updates: dict,
247 option: _helpers.WriteOption = None,
248 retry: retries.Retry = None,
249 timeout: float = None,
250 ) -> NoReturn:
251 raise NotImplementedError
253 def _prep_delete(
254 self,
255 option: _helpers.WriteOption = None,
256 retry: retries.Retry = None,
257 timeout: float = None,
258 ) -> Tuple[dict, dict]:
259 """Shared setup for async/sync :meth:`delete`."""
260 write_pb = _helpers.pb_for_delete(self._document_path, option)
261 request = {
262 "database": self._client._database_string,
263 "writes": [write_pb],
264 "transaction": None,
265 }
266 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
268 return request, kwargs
270 def delete(
271 self,
272 option: _helpers.WriteOption = None,
273 retry: retries.Retry = None,
274 timeout: float = None,
275 ) -> NoReturn:
276 raise NotImplementedError
278 def _prep_batch_get(
279 self,
280 field_paths: Iterable[str] = None,
281 transaction=None,
282 retry: retries.Retry = None,
283 timeout: float = None,
284 ) -> Tuple[dict, dict]:
285 """Shared setup for async/sync :meth:`get`."""
286 if isinstance(field_paths, str):
287 raise ValueError("'field_paths' must be a sequence of paths, not a string.")
289 if field_paths is not None:
290 mask = common.DocumentMask(field_paths=sorted(field_paths))
291 else:
292 mask = None
294 request = {
295 "database": self._client._database_string,
296 "documents": [self._document_path],
297 "mask": mask,
298 "transaction": _helpers.get_transaction_id(transaction),
299 }
300 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
302 return request, kwargs
304 def get(
305 self,
306 field_paths: Iterable[str] = None,
307 transaction=None,
308 retry: retries.Retry = None,
309 timeout: float = None,
310 ) -> "DocumentSnapshot":
311 raise NotImplementedError
313 def _prep_collections(
314 self,
315 page_size: int = None,
316 retry: retries.Retry = None,
317 timeout: float = None,
318 ) -> Tuple[dict, dict]:
319 """Shared setup for async/sync :meth:`collections`."""
320 request = {"parent": self._document_path, "page_size": page_size}
321 kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
323 return request, kwargs
325 def collections(
326 self,
327 page_size: int = None,
328 retry: retries.Retry = None,
329 timeout: float = None,
330 ) -> None:
331 raise NotImplementedError
333 def on_snapshot(self, callback) -> None:
334 raise NotImplementedError
337class DocumentSnapshot(object):
338 """A snapshot of document data in a Firestore database.
340 This represents data retrieved at a specific time and may not contain
341 all fields stored for the document (i.e. a hand-picked selection of
342 fields may have been retrieved).
344 Instances of this class are not intended to be constructed by hand,
345 rather they'll be returned as responses to various methods, such as
346 :meth:`~google.cloud.DocumentReference.get`.
348 Args:
349 reference (:class:`~google.cloud.firestore_v1.document.DocumentReference`):
350 A document reference corresponding to the document that contains
351 the data in this snapshot.
352 data (Dict[str, Any]):
353 The data retrieved in the snapshot.
354 exists (bool):
355 Indicates if the document existed at the time the snapshot was
356 retrieved.
357 read_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
358 The time that this snapshot was read from the server.
359 create_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
360 The time that this document was created.
361 update_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
362 The time that this document was last updated.
363 """
365 def __init__(
366 self, reference, data, exists, read_time, create_time, update_time
367 ) -> None:
368 self._reference = reference
369 # We want immutable data, so callers can't modify this value
370 # out from under us.
371 self._data = copy.deepcopy(data)
372 self._exists = exists
373 self.read_time = read_time
374 self.create_time = create_time
375 self.update_time = update_time
377 def __eq__(self, other):
378 if not isinstance(other, self.__class__):
379 return NotImplemented
380 return self._reference == other._reference and self._data == other._data
382 def __hash__(self):
383 return hash(self._reference) + hash(self.update_time)
385 @property
386 def _client(self):
387 """The client that owns the document reference for this snapshot.
389 Returns:
390 :class:`~google.cloud.firestore_v1.client.Client`:
391 The client that owns this document.
392 """
393 return self._reference._client
395 @property
396 def exists(self):
397 """Existence flag.
399 Indicates if the document existed at the time this snapshot
400 was retrieved.
402 Returns:
403 bool: The existence flag.
404 """
405 return self._exists
407 @property
408 def id(self):
409 """The document identifier (within its collection).
411 Returns:
412 str: The last component of the path of the document.
413 """
414 return self._reference.id
416 @property
417 def reference(self):
418 """Document reference corresponding to document that owns this data.
420 Returns:
421 :class:`~google.cloud.firestore_v1.document.DocumentReference`:
422 A document reference corresponding to this document.
423 """
424 return self._reference
426 def get(self, field_path: str) -> Any:
427 """Get a value from the snapshot data.
429 If the data is nested, for example:
431 .. code-block:: python
433 >>> snapshot.to_dict()
434 {
435 'top1': {
436 'middle2': {
437 'bottom3': 20,
438 'bottom4': 22,
439 },
440 'middle5': True,
441 },
442 'top6': b'\x00\x01 foo',
443 }
445 a **field path** can be used to access the nested data. For
446 example:
448 .. code-block:: python
450 >>> snapshot.get('top1')
451 {
452 'middle2': {
453 'bottom3': 20,
454 'bottom4': 22,
455 },
456 'middle5': True,
457 }
458 >>> snapshot.get('top1.middle2')
459 {
460 'bottom3': 20,
461 'bottom4': 22,
462 }
463 >>> snapshot.get('top1.middle2.bottom3')
464 20
466 See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
467 more information on **field paths**.
469 A copy is returned since the data may contain mutable values,
470 but the data stored in the snapshot must remain immutable.
472 Args:
473 field_path (str): A field path (``.``-delimited list of
474 field names).
476 Returns:
477 Any or None:
478 (A copy of) the value stored for the ``field_path`` or
479 None if snapshot document does not exist.
481 Raises:
482 KeyError: If the ``field_path`` does not match nested data
483 in the snapshot.
484 """
485 if not self._exists:
486 return None
487 nested_data = field_path_module.get_nested_value(field_path, self._data)
488 return copy.deepcopy(nested_data)
490 def to_dict(self) -> Union[Dict[str, Any], None]:
491 """Retrieve the data contained in this snapshot.
493 A copy is returned since the data may contain mutable values,
494 but the data stored in the snapshot must remain immutable.
496 Returns:
497 Dict[str, Any] or None:
498 The data in the snapshot. Returns None if reference
499 does not exist.
500 """
501 if not self._exists:
502 return None
503 return copy.deepcopy(self._data)
505 def _to_protobuf(self) -> Optional[Document]:
506 return _helpers.document_snapshot_to_protobuf(self)
509def _get_document_path(client, path: Tuple[str]) -> str:
510 """Convert a path tuple into a full path string.
512 Of the form:
514 ``projects/{project_id}/databases/{database_id}/...
515 documents/{document_path}``
517 Args:
518 client (:class:`~google.cloud.firestore_v1.client.Client`):
519 The client that holds configuration details and a GAPIC client
520 object.
521 path (Tuple[str, ...]): The components in a document path.
523 Returns:
524 str: The fully-qualified document path.
525 """
526 parts = (client._database_string, "documents") + path
527 return _helpers.DOCUMENT_PATH_DELIMITER.join(parts)
530def _consume_single_get(response_iterator) -> firestore.BatchGetDocumentsResponse:
531 """Consume a gRPC stream that should contain a single response.
533 The stream will correspond to a ``BatchGetDocuments`` request made
534 for a single document.
536 Args:
537 response_iterator (~google.cloud.exceptions.GrpcRendezvous): A
538 streaming iterator returned from a ``BatchGetDocuments``
539 request.
541 Returns:
542 ~google.cloud.proto.firestore.v1.\
543 firestore.BatchGetDocumentsResponse: The single "get"
544 response in the batch.
546 Raises:
547 ValueError: If anything other than exactly one response is returned.
548 """
549 # Calling ``list()`` consumes the entire iterator.
550 all_responses = list(response_iterator)
551 if len(all_responses) != 1:
552 raise ValueError(
553 "Unexpected response from `BatchGetDocumentsResponse`",
554 all_responses,
555 "Expected only one result",
556 )
558 return all_responses[0]
561def _first_write_result(write_results: list) -> write.WriteResult:
562 """Get first write result from list.
564 For cases where ``len(write_results) > 1``, this assumes the writes
565 occurred at the same time (e.g. if an update and transform are sent
566 at the same time).
568 Args:
569 write_results (List[google.cloud.proto.firestore.v1.\
570 write.WriteResult, ...]: The write results from a
571 ``CommitResponse``.
573 Returns:
574 google.cloud.firestore_v1.types.WriteResult: The
575 lone write result from ``write_results``.
577 Raises:
578 ValueError: If there are zero write results. This is likely to
579 **never** occur, since the backend should be stable.
580 """
581 if not write_results:
582 raise ValueError("Expected at least one write result")
584 return write_results[0]