/
base_collection.py
463 lines (381 loc) · 16 KB
/
base_collection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# Copyright 2017 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for representing collections for the Google Cloud Firestore API."""
import random
from google.api_core import retry as retries # type: ignore
from google.cloud.firestore_v1 import _helpers
from google.cloud.firestore_v1.document import DocumentReference
from typing import (
Any,
AsyncGenerator,
Coroutine,
Generator,
AsyncIterator,
Iterator,
Iterable,
NoReturn,
Tuple,
Union,
)
# Types needed only for Type Hints
from google.cloud.firestore_v1.base_document import DocumentSnapshot
from google.cloud.firestore_v1.base_query import BaseQuery
from google.cloud.firestore_v1.transaction import Transaction
_AUTO_ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
class BaseCollectionReference(object):
"""A reference to a collection in a Firestore database.
The collection may already exist or this class can facilitate creation
of documents within the collection.
Args:
path (Tuple[str, ...]): The components in the collection path.
This is a series of strings representing each collection and
sub-collection ID, as well as the document IDs for any documents
that contain a sub-collection.
kwargs (dict): The keyword arguments for the constructor. The only
supported keyword is ``client`` and it must be a
:class:`~google.cloud.firestore_v1.client.Client` if provided. It
represents the client that created this collection reference.
Raises:
ValueError: if
* the ``path`` is empty
* there are an even number of elements
* a collection ID in ``path`` is not a string
* a document ID in ``path`` is not a string
TypeError: If a keyword other than ``client`` is used.
"""
def __init__(self, *path, **kwargs) -> None:
_helpers.verify_path(path, is_collection=True)
self._path = path
self._client = kwargs.pop("client", None)
if kwargs:
raise TypeError(
"Received unexpected arguments", kwargs, "Only `client` is supported"
)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._path == other._path and self._client == other._client
@property
def id(self):
"""The collection identifier.
Returns:
str: The last component of the path.
"""
return self._path[-1]
@property
def parent(self):
"""Document that owns the current collection.
Returns:
Optional[:class:`~google.cloud.firestore_v1.document.DocumentReference`]:
The parent document, if the current collection is not a
top-level collection.
"""
if len(self._path) == 1:
return None
else:
parent_path = self._path[:-1]
return self._client.document(*parent_path)
def _query(self) -> BaseQuery:
raise NotImplementedError
def document(self, document_id: str = None) -> DocumentReference:
"""Create a sub-document underneath the current collection.
Args:
document_id (Optional[str]): The document identifier
within the current collection. If not provided, will default
to a random 20 character string composed of digits,
uppercase and lowercase and letters.
Returns:
:class:`~google.cloud.firestore_v1.document.DocumentReference`:
The child document.
"""
if document_id is None:
document_id = _auto_id()
child_path = self._path + (document_id,)
return self._client.document(*child_path)
def _parent_info(self) -> Tuple[Any, str]:
"""Get fully-qualified parent path and prefix for this collection.
Returns:
Tuple[str, str]: Pair of
* the fully-qualified (with database and project) path to the
parent of this collection (will either be the database path
or a document path).
* the prefix to a document in this collection.
"""
parent_doc = self.parent
if parent_doc is None:
parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join(
(self._client._database_string, "documents")
)
else:
parent_path = parent_doc._document_path
expected_prefix = _helpers.DOCUMENT_PATH_DELIMITER.join((parent_path, self.id))
return parent_path, expected_prefix
def _prep_add(
self,
document_data: dict,
document_id: str = None,
retry: retries.Retry = None,
timeout: float = None,
) -> Tuple[DocumentReference, dict]:
"""Shared setup for async / sync :method:`add`"""
if document_id is None:
document_id = _auto_id()
document_ref = self.document(document_id)
kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
return document_ref, kwargs
def add(
self,
document_data: dict,
document_id: str = None,
retry: retries.Retry = None,
timeout: float = None,
) -> Union[Tuple[Any, Any], Coroutine[Any, Any, Tuple[Any, Any]]]:
raise NotImplementedError
def _prep_list_documents(
self, page_size: int = None, retry: retries.Retry = None, timeout: float = None,
) -> Tuple[dict, dict]:
"""Shared setup for async / sync :method:`list_documents`"""
parent, _ = self._parent_info()
request = {
"parent": parent,
"collection_id": self.id,
"page_size": page_size,
"show_missing": True,
}
kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
return request, kwargs
def list_documents(
self, page_size: int = None, retry: retries.Retry = None, timeout: float = None,
) -> Union[
Generator[DocumentReference, Any, Any], AsyncGenerator[DocumentReference, Any]
]:
raise NotImplementedError
def select(self, field_paths: Iterable[str]) -> BaseQuery:
"""Create a "select" query with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.select` for
more information on this method.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as a projection
of document fields in the query results.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A "projected" query.
"""
query = self._query()
return query.select(field_paths)
def where(self, field_path: str, op_string: str, value) -> BaseQuery:
"""Create a "where" query with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.where` for
more information on this method.
Args:
field_path (str): A field path (``.``-delimited list of
field names) for the field to filter on.
op_string (str): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``>=``
and ``>``.
value (Any): The value to compare the field against in the filter.
If ``value`` is :data:`None` or a NaN, then ``==`` is the only
allowed operation.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A filtered query.
"""
query = self._query()
return query.where(field_path, op_string, value)
def order_by(self, field_path: str, **kwargs) -> BaseQuery:
"""Create an "order by" query with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.order_by` for
more information on this method.
Args:
field_path (str): A field path (``.``-delimited list of
field names) on which to order the query results.
kwargs (Dict[str, Any]): The keyword arguments to pass along
to the query. The only supported keyword is ``direction``,
see :meth:`~google.cloud.firestore_v1.query.Query.order_by`
for more information.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
An "order by" query.
"""
query = self._query()
return query.order_by(field_path, **kwargs)
def limit(self, count: int) -> BaseQuery:
"""Create a limited query with this collection as parent.
.. note::
`limit` and `limit_to_last` are mutually exclusive.
Setting `limit` will drop previously set `limit_to_last`.
See
:meth:`~google.cloud.firestore_v1.query.Query.limit` for
more information on this method.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A limited query.
"""
query = self._query()
return query.limit(count)
def limit_to_last(self, count: int):
"""Create a limited to last query with this collection as parent.
.. note::
`limit` and `limit_to_last` are mutually exclusive.
Setting `limit_to_last` will drop previously set `limit`.
See
:meth:`~google.cloud.firestore_v1.query.Query.limit_to_last`
for more information on this method.
Args:
count (int): Maximum number of documents to return that
match the query.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A limited to last query.
"""
query = self._query()
return query.limit_to_last(count)
def offset(self, num_to_skip: int) -> BaseQuery:
"""Skip to an offset in a query with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.offset` for
more information on this method.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
An offset query.
"""
query = self._query()
return query.offset(num_to_skip)
def start_at(
self, document_fields: Union[DocumentSnapshot, dict, list, tuple]
) -> BaseQuery:
"""Start query at a cursor with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.start_at` for
more information on this method.
Args:
document_fields (Union[:class:`~google.cloud.firestore_v1.\
document.DocumentSnapshot`, dict, list, tuple]):
A document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor.
"""
query = self._query()
return query.start_at(document_fields)
def start_after(
self, document_fields: Union[DocumentSnapshot, dict, list, tuple]
) -> BaseQuery:
"""Start query after a cursor with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[:class:`~google.cloud.firestore_v1.\
document.DocumentSnapshot`, dict, list, tuple]):
A document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor.
"""
query = self._query()
return query.start_after(document_fields)
def end_before(
self, document_fields: Union[DocumentSnapshot, dict, list, tuple]
) -> BaseQuery:
"""End query before a cursor with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.end_before` for
more information on this method.
Args:
document_fields (Union[:class:`~google.cloud.firestore_v1.\
document.DocumentSnapshot`, dict, list, tuple]):
A document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor.
"""
query = self._query()
return query.end_before(document_fields)
def end_at(
self, document_fields: Union[DocumentSnapshot, dict, list, tuple]
) -> BaseQuery:
"""End query at a cursor with this collection as parent.
See
:meth:`~google.cloud.firestore_v1.query.Query.end_at` for
more information on this method.
Args:
document_fields (Union[:class:`~google.cloud.firestore_v1.\
document.DocumentSnapshot`, dict, list, tuple]):
A document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor.
"""
query = self._query()
return query.end_at(document_fields)
def _prep_get_or_stream(
self, retry: retries.Retry = None, timeout: float = None,
) -> Tuple[Any, dict]:
"""Shared setup for async / sync :meth:`get` / :meth:`stream`"""
query = self._query()
kwargs = _helpers.make_retry_timeout_kwargs(retry, timeout)
return query, kwargs
def get(
self,
transaction: Transaction = None,
retry: retries.Retry = None,
timeout: float = None,
) -> Union[
Generator[DocumentSnapshot, Any, Any], AsyncGenerator[DocumentSnapshot, Any]
]:
raise NotImplementedError
def stream(
self,
transaction: Transaction = None,
retry: retries.Retry = None,
timeout: float = None,
) -> Union[Iterator[DocumentSnapshot], AsyncIterator[DocumentSnapshot]]:
raise NotImplementedError
def on_snapshot(self, callback) -> NoReturn:
raise NotImplementedError
def _auto_id() -> str:
"""Generate a "random" automatically generated ID.
Returns:
str: A 20 character string composed of digits, uppercase and
lowercase and letters.
"""
return "".join(random.choice(_AUTO_ID_CHARS) for _ in range(20))
def _item_to_document_ref(collection_reference, item) -> DocumentReference:
"""Convert Document resource to document ref.
Args:
collection_reference (google.api_core.page_iterator.GRPCIterator):
iterator response
item (dict): document resource
"""
document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1]
return collection_reference.document(document_id)