Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import com.google.cloud.firestore.pipeline.stages.Distinct;
import com.google.cloud.firestore.pipeline.stages.FindNearest;
import com.google.cloud.firestore.pipeline.stages.FindNearestOptions;
import com.google.cloud.firestore.pipeline.stages.Insert;
import com.google.cloud.firestore.pipeline.stages.Limit;
import com.google.cloud.firestore.pipeline.stages.Offset;
import com.google.cloud.firestore.pipeline.stages.PipelineExecuteOptions;
Expand All @@ -63,6 +64,7 @@
import com.google.cloud.firestore.pipeline.stages.Unnest;
import com.google.cloud.firestore.pipeline.stages.UnnestOptions;
import com.google.cloud.firestore.pipeline.stages.Update;
import com.google.cloud.firestore.pipeline.stages.Upsert;
import com.google.cloud.firestore.pipeline.stages.Where;
import com.google.cloud.firestore.telemetry.MetricsUtil.MetricsContext;
import com.google.cloud.firestore.telemetry.TelemetryConstants;
Expand All @@ -76,6 +78,7 @@
import com.google.firestore.v1.ExecutePipelineRequest;
import com.google.firestore.v1.ExecutePipelineResponse;
import com.google.firestore.v1.StructuredPipeline;
import com.google.firestore.v1.TransactionOptions;
import com.google.firestore.v1.Value;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
Expand Down Expand Up @@ -1306,6 +1309,21 @@ public Pipeline update(Update update) {
return append(update);
}

@BetaApi
public Pipeline insert(Insert insert) {
return append(insert);
}

@BetaApi
public Pipeline upsert(Upsert upsert) {
return append(upsert);
}

@BetaApi
public Pipeline upsert(Selectable... transformedFields) {
return append(new Upsert(transformedFields));
}

/**
* Performs an insert operation using documents from previous stages. Adds a generic stage to the
* pipeline.
Expand Down Expand Up @@ -1526,6 +1544,12 @@ void executeInternal(

if (transactionId != null) {
request.setTransaction(transactionId);
} else if (options.isAtomic()) {
request.setNewTransaction(
TransactionOptions.newBuilder()
.setReadWrite(TransactionOptions.ReadWrite.getDefaultInstance())
.build());
request.setAutoCommitTransaction(true);
}

if (readTime != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2026 Google LLC
*
* 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.
*/

package com.google.cloud.firestore.pipeline.stages;

import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.cloud.firestore.PipelineUtils;
import com.google.cloud.firestore.pipeline.expressions.Expression;
import com.google.firestore.v1.Value;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;

@InternalApi
public final class Insert extends Stage {

@Nullable private final String collectionPath;
@Nullable private final Expression documentIdExpr;

private Insert(
@Nullable String collectionPath,
@Nullable Expression documentIdExpr,
InternalOptions options) {
super("insert", buildOptions(collectionPath, documentIdExpr, options));
this.collectionPath = collectionPath;
this.documentIdExpr = documentIdExpr;
}

@BetaApi
public Insert() {
this(null, null, InternalOptions.EMPTY);
}

@BetaApi
public Insert withCollection(String collectionPath) {
return new Insert(collectionPath, this.documentIdExpr, this.options);
}

@BetaApi
public Insert withDocumentId(Expression documentIdExpr) {
return new Insert(this.collectionPath, documentIdExpr, this.options);
}

private static InternalOptions buildOptions(
@Nullable String collectionPath,
@Nullable Expression documentIdExpr,
InternalOptions baseOptions) {
Map<String, Value> optsMap = new HashMap<>(baseOptions.options);
if (collectionPath != null) {
String path = collectionPath.startsWith("/") ? collectionPath : "/" + collectionPath;
optsMap.put("collection", Value.newBuilder().setReferenceValue(path).build());
}
if (documentIdExpr != null) {
optsMap.put("document_id", PipelineUtils.encodeValue(documentIdExpr));
}
return new InternalOptions(optsMap);
}

@Override
Iterable<Value> toStageArgs() {
return new ArrayList<>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,13 @@ public PipelineExecuteOptions withExplainOptions(ExplainOptions options) {
public PipelineExecuteOptions withIndexMode(String indexMode) {
return with("index_mode", indexMode);
}

public PipelineExecuteOptions withAtomic(boolean atomic) {
return with("atomic", atomic);
}

boolean isAtomic() {
return options.options.containsKey("atomic")
&& options.options.get("atomic").getBooleanValue();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Copyright 2026 Google LLC
*
* 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.
*/

package com.google.cloud.firestore.pipeline.stages;

import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.cloud.firestore.PipelineUtils;
import com.google.cloud.firestore.pipeline.expressions.Expression;
import com.google.cloud.firestore.pipeline.expressions.Selectable;
import com.google.firestore.v1.Value;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

@InternalApi
public final class Upsert extends Stage {

@Nullable private final Selectable[] transformedFields;
@Nullable private final String collectionPath;
@Nullable private final Expression documentIdExpr;

private Upsert(
@Nullable Selectable[] transformedFields,
@Nullable String collectionPath,
@Nullable Expression documentIdExpr,
InternalOptions options) {
super("upsert", buildOptions(collectionPath, documentIdExpr, options));
this.transformedFields = transformedFields;
this.collectionPath = collectionPath;
this.documentIdExpr = documentIdExpr;
}

@BetaApi
public Upsert() {
this(null, null, null, InternalOptions.EMPTY);
}

@BetaApi
public Upsert(Selectable... transformedFields) {
this(transformedFields, null, null, InternalOptions.EMPTY);
}

@BetaApi
public Upsert withCollection(String collectionPath) {
return new Upsert(this.transformedFields, collectionPath, this.documentIdExpr, this.options);
}

@BetaApi
public Upsert withDocumentId(Expression documentIdExpr) {
return new Upsert(this.transformedFields, this.collectionPath, documentIdExpr, this.options);
}

private static InternalOptions buildOptions(
@Nullable String collectionPath,
@Nullable Expression documentIdExpr,
InternalOptions baseOptions) {
Map<String, Value> optsMap = new HashMap<>(baseOptions.options);
if (collectionPath != null) {
String path = collectionPath.startsWith("/") ? collectionPath : "/" + collectionPath;
optsMap.put("collection", Value.newBuilder().setReferenceValue(path).build());
}
if (documentIdExpr != null) {
optsMap.put("document_id", PipelineUtils.encodeValue(documentIdExpr));
}
return new InternalOptions(optsMap);
}

@Override
Iterable<Value> toStageArgs() {
List<Value> args = new ArrayList<>();
if (transformedFields != null && transformedFields.length > 0) {
Map<String, Expression> map = PipelineUtils.selectablesToMap(transformedFields);
Map<String, Value> encodedMap = new HashMap<>();
for (Map.Entry<String, Expression> entry : map.entrySet()) {
encodedMap.put(entry.getKey(), PipelineUtils.encodeValue(entry.getValue()));
}
args.add(PipelineUtils.encodeValue(encodedMap));
}
return args;
}
Comment on lines +84 to +96

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The manual loop to encode each entry of the map is redundant. PipelineUtils.encodeValue recursively encodes map values, so we can pass the Map<String, Expression> directly to PipelineUtils.encodeValue to simplify the implementation.

  @Override
  Iterable<Value> toStageArgs() {
    List<Value> args = new ArrayList<>();
    if (transformedFields != null && transformedFields.length > 0) {
      Map<String, Expression> map = PipelineUtils.selectablesToMap(transformedFields);
      args.add(PipelineUtils.encodeValue(map));
    }
    return args;
  }

}
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,75 @@ public void testSearchStageProtoEncoding() {
Value addFields = optionsMap.get("add_fields");
assertThat(addFields.getMapValue().getFieldsMap().get("bar").getBooleanValue()).isTrue();
}

@Test
public void testInsertStageProtoEncoding() {
FirestoreOptions options =
FirestoreOptions.newBuilder()
.setProjectId("new-project")
.setDatabaseId("(default)")
.build();
Firestore firestore = options.getService();

java.util.Map<String, Object> data = new java.util.HashMap<>();
data.put("title", "Test Book");

Pipeline pipeline =
firestore
.pipeline()
.literals(data)
.insert(
new com.google.cloud.firestore.pipeline.stages.Insert()
.withCollection("books")
.withDocumentId(constant("book1")));

com.google.firestore.v1.Pipeline protoPipeline = pipeline.toProto();
assertThat(protoPipeline.getStagesCount()).isEqualTo(2);

Stage insertStage = protoPipeline.getStages(1);
assertThat(insertStage.getName()).isEqualTo("insert");
assertThat(insertStage.getArgsCount()).isEqualTo(0);

java.util.Map<String, Value> optionsMap = insertStage.getOptionsMap();
assertThat(optionsMap.get("collection").getReferenceValue()).isEqualTo("/books");
assertThat(optionsMap.get("document_id").getStringValue()).isEqualTo("book1");
}

@Test
public void testUpsertStageProtoEncoding() {
FirestoreOptions options =
FirestoreOptions.newBuilder()
.setProjectId("new-project")
.setDatabaseId("(default)")
.build();
Firestore firestore = options.getService();

java.util.Map<String, Object> data = new java.util.HashMap<>();
data.put("title", "Upsert Book");
data.put("count", 1);

Pipeline pipeline =
firestore
.pipeline()
.literals(data)
.upsert(
new com.google.cloud.firestore.pipeline.stages.Upsert(
com.google.cloud.firestore.pipeline.expressions.Expression.add(
field("count"), constant(1))
.as("count"))
.withCollection("books")
.withDocumentId(constant("book1")));

com.google.firestore.v1.Pipeline protoPipeline = pipeline.toProto();
assertThat(protoPipeline.getStagesCount()).isEqualTo(2);

Stage upsertStage = protoPipeline.getStages(1);
assertThat(upsertStage.getName()).isEqualTo("upsert");
assertThat(upsertStage.getArgsCount()).isEqualTo(1);
assertThat(upsertStage.getArgs(0).getMapValue().getFieldsMap()).containsKey("count");

java.util.Map<String, Value> optionsMap = upsertStage.getOptionsMap();
assertThat(optionsMap.get("collection").getReferenceValue()).isEqualTo("/books");
assertThat(optionsMap.get("document_id").getStringValue()).isEqualTo("book1");
}
}
Loading
Loading