def build_document_snapshot(
    *,
    collection_name: str = "col",
    document_id: str = "doc",
    client: typing.Optional[BaseClient] = None,
    data: typing.Optional[typing.Dict] = None,
    exists: bool = True,
    create_time: typing.Optional[Timestamp] = None,
    read_time: typing.Optional[Timestamp] = None,
    update_time: typing.Optional[Timestamp] = None,
) -> DocumentSnapshot:
    return DocumentSnapshot(
        DocumentReference(collection_name, document_id, client=client),
        data or {"hello", "world"},
        exists=exists,
        read_time=read_time or build_timestamp(),
        create_time=create_time or build_timestamp(),
        update_time=update_time or build_timestamp(),
    )
Beispiel #2
0
    def build(self) -> str:
        """Iterates over the bundle's stored documents and queries and produces
        a single length-prefixed json string suitable for long-term storage.

        Example:

            from google.cloud import firestore

            db = firestore.Client()
            collection_ref = db.collection(u'users')

            bundle = firestore.FirestoreBundle('my bundle')
            bundle.add_named_query('app-users', collection_ref._query())

            serialized_bundle: str = bundle.build()

            # Now upload `serialized_bundle` to Google Cloud Storage, store it
            # in Memorystore, or any other storage solution.

        Returns:
            str: The length-prefixed string representation of this bundle'
                contents.
        """
        buffer: str = ""

        named_query: NamedQuery
        for named_query in self.named_queries.values():
            buffer += self._compile_bundle_element(
                BundleElement(named_query=named_query)
            )

        bundled_document: "_BundledDocument"  # type: ignore
        document_count: int = 0
        for bundled_document in self.documents.values():
            buffer += self._compile_bundle_element(
                BundleElement(document_metadata=bundled_document.metadata)
            )
            document_count += 1
            buffer += self._compile_bundle_element(
                BundleElement(document=bundled_document.snapshot._to_protobuf()._pb,)
            )

        metadata: BundleElement = BundleElement(
            metadata=self._deserialized_metadata
            or BundleMetadata(
                id=self.name,
                create_time=_helpers.build_timestamp(),
                version=FirestoreBundle.BUNDLE_SCHEMA_VERSION,
                total_documents=document_count,
                total_bytes=len(buffer.encode("utf-8")),
            )
        )
        return f"{self._compile_bundle_element(metadata)}{buffer}"
Beispiel #3
0
 def _build_named_query(
     self, name: str, snapshot: BaseQuery, read_time: datetime.datetime,
 ) -> NamedQuery:
     return NamedQuery(
         name=name,
         bundled_query=BundledQuery(
             parent=name,
             structured_query=snapshot._to_protobuf()._pb,
             limit_type=limit_type_of_query(snapshot),
         ),
         read_time=_helpers.build_timestamp(read_time),
     )
 def _send(self, batch: BulkWriteBatch) -> BatchWriteResponse:
     """Generate a fake `BatchWriteResponse` for the supplied batch instead
     of actually submitting it to the server.
     """
     return BatchWriteResponse(
         write_results=[
             WriteResult(update_time=build_timestamp())
             if index not in self._fail_indices
             else WriteResult()
             for index, el in enumerate(batch._document_references.values())
         ],
         status=[
             status_pb2.Status(code=0 if index not in self._fail_indices else 1)
             for index, el in enumerate(batch._document_references.values())
         ],
     )