|
| 1 | +# Copyright 2025 Google LLC |
| 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 | +from __future__ import annotations |
| 16 | +from typing import Iterable, Sequence, TYPE_CHECKING |
| 17 | +from google.cloud.firestore_v1 import _pipeline_stages as stages |
| 18 | +from google.cloud.firestore_v1.types.pipeline import ( |
| 19 | + StructuredPipeline as StructuredPipeline_pb, |
| 20 | +) |
| 21 | +from google.cloud.firestore_v1.types.firestore import ExecutePipelineRequest |
| 22 | +from google.cloud.firestore_v1.pipeline_result import PipelineResult |
| 23 | +from google.cloud.firestore_v1.pipeline_expressions import Expr |
| 24 | +from google.cloud.firestore_v1 import _helpers |
| 25 | + |
| 26 | +if TYPE_CHECKING: # pragma: NO COVER |
| 27 | + from google.cloud.firestore_v1.client import Client |
| 28 | + from google.cloud.firestore_v1.async_client import AsyncClient |
| 29 | + from google.cloud.firestore_v1.types.firestore import ExecutePipelineResponse |
| 30 | + from google.cloud.firestore_v1.transaction import BaseTransaction |
| 31 | + |
| 32 | + |
| 33 | +class _BasePipeline: |
| 34 | + """ |
| 35 | + Base class for building Firestore data transformation and query pipelines. |
| 36 | +
|
| 37 | + This class is not intended to be instantiated directly. |
| 38 | + Use `client.collection.("...").pipeline()` to create pipeline instances. |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, client: Client | AsyncClient): |
| 42 | + """ |
| 43 | + Initializes a new pipeline. |
| 44 | +
|
| 45 | + Pipelines should not be instantiated directly. Instead, |
| 46 | + call client.pipeline() to create an instance |
| 47 | +
|
| 48 | + Args: |
| 49 | + client: The client associated with the pipeline |
| 50 | + """ |
| 51 | + self._client = client |
| 52 | + self.stages: Sequence[stages.Stage] = tuple() |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def _create_with_stages( |
| 56 | + cls, client: Client | AsyncClient, *stages |
| 57 | + ) -> _BasePipeline: |
| 58 | + """ |
| 59 | + Initializes a new pipeline with the given stages. |
| 60 | +
|
| 61 | + Pipeline classes should not be instantiated directly. |
| 62 | +
|
| 63 | + Args: |
| 64 | + client: The client associated with the pipeline |
| 65 | + *stages: Initial stages for the pipeline. |
| 66 | + """ |
| 67 | + new_instance = cls(client) |
| 68 | + new_instance.stages = tuple(stages) |
| 69 | + return new_instance |
| 70 | + |
| 71 | + def __repr__(self): |
| 72 | + cls_str = type(self).__name__ |
| 73 | + if not self.stages: |
| 74 | + return f"{cls_str}()" |
| 75 | + elif len(self.stages) == 1: |
| 76 | + return f"{cls_str}({self.stages[0]!r})" |
| 77 | + else: |
| 78 | + stages_str = ",\n ".join([repr(s) for s in self.stages]) |
| 79 | + return f"{cls_str}(\n {stages_str}\n)" |
| 80 | + |
| 81 | + def _to_pb(self) -> StructuredPipeline_pb: |
| 82 | + return StructuredPipeline_pb( |
| 83 | + pipeline={"stages": [s._to_pb() for s in self.stages]} |
| 84 | + ) |
| 85 | + |
| 86 | + def _append(self, new_stage): |
| 87 | + """ |
| 88 | + Create a new Pipeline object with a new stage appended |
| 89 | + """ |
| 90 | + return self.__class__._create_with_stages(self._client, *self.stages, new_stage) |
| 91 | + |
| 92 | + def _prep_execute_request( |
| 93 | + self, transaction: BaseTransaction | None |
| 94 | + ) -> ExecutePipelineRequest: |
| 95 | + """ |
| 96 | + shared logic for creating an ExecutePipelineRequest |
| 97 | + """ |
| 98 | + database_name = ( |
| 99 | + f"projects/{self._client.project}/databases/{self._client._database}" |
| 100 | + ) |
| 101 | + transaction_id = ( |
| 102 | + _helpers.get_transaction_id(transaction) |
| 103 | + if transaction is not None |
| 104 | + else None |
| 105 | + ) |
| 106 | + request = ExecutePipelineRequest( |
| 107 | + database=database_name, |
| 108 | + transaction=transaction_id, |
| 109 | + structured_pipeline=self._to_pb(), |
| 110 | + ) |
| 111 | + return request |
| 112 | + |
| 113 | + def _execute_response_helper( |
| 114 | + self, response: ExecutePipelineResponse |
| 115 | + ) -> Iterable[PipelineResult]: |
| 116 | + """ |
| 117 | + shared logic for unpacking an ExecutePipelineReponse into PipelineResults |
| 118 | + """ |
| 119 | + for doc in response.results: |
| 120 | + ref = self._client.document(doc.name) if doc.name else None |
| 121 | + yield PipelineResult( |
| 122 | + self._client, |
| 123 | + doc.fields, |
| 124 | + ref, |
| 125 | + response._pb.execution_time, |
| 126 | + doc._pb.create_time if doc.create_time else None, |
| 127 | + doc._pb.update_time if doc.update_time else None, |
| 128 | + ) |
| 129 | + |
| 130 | + def generic_stage(self, name: str, *params: Expr) -> "_BasePipeline": |
| 131 | + """ |
| 132 | + Adds a generic, named stage to the pipeline with specified parameters. |
| 133 | +
|
| 134 | + This method provides a flexible way to extend the pipeline's functionality |
| 135 | + by adding custom stages. Each generic stage is defined by a unique `name` |
| 136 | + and a set of `params` that control its behavior. |
| 137 | +
|
| 138 | + Example: |
| 139 | + >>> # Assume we don't have a built-in "where" stage |
| 140 | + >>> pipeline = client.pipeline().collection("books") |
| 141 | + >>> pipeline = pipeline.generic_stage("where", [Field.of("published").lt(900)]) |
| 142 | + >>> pipeline = pipeline.select("title", "author") |
| 143 | +
|
| 144 | + Args: |
| 145 | + name: The name of the generic stage. |
| 146 | + *params: A sequence of `Expr` objects representing the parameters for the stage. |
| 147 | +
|
| 148 | + Returns: |
| 149 | + A new Pipeline object with this stage appended to the stage list |
| 150 | + """ |
| 151 | + return self._append(stages.GenericStage(name, *params)) |
0 commit comments