Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/firestore_v1/async_collection.py: 51%

37 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-09 06:27 +0000

1# Copyright 2020 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. 

14 

15"""Classes for representing collections for the Google Cloud Firestore API.""" 

16 

17from google.api_core import gapic_v1 

18from google.api_core import retry as retries 

19 

20from google.cloud.firestore_v1.base_collection import ( 

21 BaseCollectionReference, 

22 _item_to_document_ref, 

23) 

24from google.cloud.firestore_v1 import async_query, async_document, async_aggregation 

25 

26from google.cloud.firestore_v1.document import DocumentReference 

27 

28from typing import AsyncIterator 

29from typing import Any, AsyncGenerator, Tuple 

30 

31# Types needed only for Type Hints 

32from google.cloud.firestore_v1.transaction import Transaction 

33 

34 

35class AsyncCollectionReference(BaseCollectionReference[async_query.AsyncQuery]): 

36 """A reference to a collection in a Firestore database. 

37 

38 The collection may already exist or this class can facilitate creation 

39 of documents within the collection. 

40 

41 Args: 

42 path (Tuple[str, ...]): The components in the collection path. 

43 This is a series of strings representing each collection and 

44 sub-collection ID, as well as the document IDs for any documents 

45 that contain a sub-collection. 

46 kwargs (dict): The keyword arguments for the constructor. The only 

47 supported keyword is ``client`` and it must be a 

48 :class:`~google.cloud.firestore_v1.client.Client` if provided. It 

49 represents the client that created this collection reference. 

50 

51 Raises: 

52 ValueError: if 

53 

54 * the ``path`` is empty 

55 * there are an even number of elements 

56 * a collection ID in ``path`` is not a string 

57 * a document ID in ``path`` is not a string 

58 TypeError: If a keyword other than ``client`` is used. 

59 """ 

60 

61 def __init__(self, *path, **kwargs) -> None: 

62 super(AsyncCollectionReference, self).__init__(*path, **kwargs) 

63 

64 def _query(self) -> async_query.AsyncQuery: 

65 """Query factory. 

66 

67 Returns: 

68 :class:`~google.cloud.firestore_v1.query.Query` 

69 """ 

70 return async_query.AsyncQuery(self) 

71 

72 def _aggregation_query(self) -> async_aggregation.AsyncAggregationQuery: 

73 """AsyncAggregationQuery factory. 

74 

75 Returns: 

76 :class:`~google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery 

77 """ 

78 return async_aggregation.AsyncAggregationQuery(self._query()) 

79 

80 async def _chunkify(self, chunk_size: int): 

81 async for page in self._query()._chunkify(chunk_size): 

82 yield page 

83 

84 async def add( 

85 self, 

86 document_data: dict, 

87 document_id: str = None, 

88 retry: retries.Retry = gapic_v1.method.DEFAULT, 

89 timeout: float = None, 

90 ) -> Tuple[Any, Any]: 

91 """Create a document in the Firestore database with the provided data. 

92 

93 Args: 

94 document_data (dict): Property names and values to use for 

95 creating the document. 

96 document_id (Optional[str]): The document identifier within the 

97 current collection. If not provided, an ID will be 

98 automatically assigned by the server (the assigned ID will be 

99 a random 20 character string composed of digits, 

100 uppercase and lowercase letters). 

101 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

102 should be retried. Defaults to a system-specified policy. 

103 timeout (float): The timeout for this request. Defaults to a 

104 system-specified value. 

105 

106 Returns: 

107 Tuple[:class:`google.protobuf.timestamp_pb2.Timestamp`, \ 

108 :class:`~google.cloud.firestore_v1.async_document.AsyncDocumentReference`]: 

109 Pair of 

110 

111 * The ``update_time`` when the document was created/overwritten. 

112 * A document reference for the created document. 

113 

114 Raises: 

115 :class:`google.cloud.exceptions.Conflict`: 

116 If ``document_id`` is provided and the document already exists. 

117 """ 

118 document_ref, kwargs = self._prep_add( 

119 document_data, 

120 document_id, 

121 retry, 

122 timeout, 

123 ) 

124 write_result = await document_ref.create(document_data, **kwargs) 

125 return write_result.update_time, document_ref 

126 

127 def document( 

128 self, document_id: str = None 

129 ) -> async_document.AsyncDocumentReference: 

130 """Create a sub-document underneath the current collection. 

131 

132 Args: 

133 document_id (Optional[str]): The document identifier 

134 within the current collection. If not provided, will default 

135 to a random 20 character string composed of digits, 

136 uppercase and lowercase and letters. 

137 

138 Returns: 

139 :class:`~google.cloud.firestore_v1.document.async_document.AsyncDocumentReference`: 

140 The child document. 

141 """ 

142 return super(AsyncCollectionReference, self).document(document_id) 

143 

144 async def list_documents( 

145 self, 

146 page_size: int = None, 

147 retry: retries.Retry = gapic_v1.method.DEFAULT, 

148 timeout: float = None, 

149 ) -> AsyncGenerator[DocumentReference, None]: 

150 """List all subdocuments of the current collection. 

151 

152 Args: 

153 page_size (Optional[int]]): The maximum number of documents 

154 in each page of results from this request. Non-positive values 

155 are ignored. Defaults to a sensible value set by the API. 

156 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

157 should be retried. Defaults to a system-specified policy. 

158 timeout (float): The timeout for this request. Defaults to a 

159 system-specified value. 

160 

161 Returns: 

162 Sequence[:class:`~google.cloud.firestore_v1.collection.DocumentReference`]: 

163 iterator of subdocuments of the current collection. If the 

164 collection does not exist at the time of `snapshot`, the 

165 iterator will be empty 

166 """ 

167 request, kwargs = self._prep_list_documents(page_size, retry, timeout) 

168 

169 iterator = await self._client._firestore_api.list_documents( 

170 request=request, 

171 metadata=self._client._rpc_metadata, 

172 **kwargs, 

173 ) 

174 async for i in iterator: 

175 yield _item_to_document_ref(self, i) 

176 

177 async def get( 

178 self, 

179 transaction: Transaction = None, 

180 retry: retries.Retry = gapic_v1.method.DEFAULT, 

181 timeout: float = None, 

182 ) -> list: 

183 """Read the documents in this collection. 

184 

185 This sends a ``RunQuery`` RPC and returns a list of documents 

186 returned in the stream of ``RunQueryResponse`` messages. 

187 

188 Args: 

189 transaction 

190 (Optional[:class:`~google.cloud.firestore_v1.transaction.Transaction`]): 

191 An existing transaction that this query will run in. 

192 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

193 should be retried. Defaults to a system-specified policy. 

194 timeout (float): The timeout for this request. Defaults to a 

195 system-specified value. 

196 

197 If a ``transaction`` is used and it already has write operations 

198 added, this method cannot be used (i.e. read-after-write is not 

199 allowed). 

200 

201 Returns: 

202 list: The documents in this collection that match the query. 

203 """ 

204 query, kwargs = self._prep_get_or_stream(retry, timeout) 

205 

206 return await query.get(transaction=transaction, **kwargs) 

207 

208 async def stream( 

209 self, 

210 transaction: Transaction = None, 

211 retry: retries.Retry = gapic_v1.method.DEFAULT, 

212 timeout: float = None, 

213 ) -> AsyncIterator[async_document.DocumentSnapshot]: 

214 """Read the documents in this collection. 

215 

216 This sends a ``RunQuery`` RPC and then returns an iterator which 

217 consumes each document returned in the stream of ``RunQueryResponse`` 

218 messages. 

219 

220 .. note:: 

221 

222 The underlying stream of responses will time out after 

223 the ``max_rpc_timeout_millis`` value set in the GAPIC 

224 client configuration for the ``RunQuery`` API. Snapshots 

225 not consumed from the iterator before that point will be lost. 

226 

227 If a ``transaction`` is used and it already has write operations 

228 added, this method cannot be used (i.e. read-after-write is not 

229 allowed). 

230 

231 Args: 

232 transaction (Optional[:class:`~google.cloud.firestore_v1.transaction.\ 

233 Transaction`]): 

234 An existing transaction that the query will run in. 

235 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

236 should be retried. Defaults to a system-specified policy. 

237 timeout (float): The timeout for this request. Defaults to a 

238 system-specified value. 

239 

240 Yields: 

241 :class:`~google.cloud.firestore_v1.document.DocumentSnapshot`: 

242 The next document that fulfills the query. 

243 """ 

244 query, kwargs = self._prep_get_or_stream(retry, timeout) 

245 

246 async for d in query.stream(transaction=transaction, **kwargs): 

247 yield d # pytype: disable=name-error