yixiaoshen commented on code in PR #22175:
URL: https://github.com/apache/beam/pull/22175#discussion_r916315190


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/QueryUtils.java:
##########
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.io.gcp.firestore;
+
+import com.google.firestore.v1.StructuredQuery;
+import com.google.firestore.v1.StructuredQuery.Direction;
+import com.google.firestore.v1.StructuredQuery.FieldFilter;
+import com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
+import com.google.firestore.v1.StructuredQuery.FieldReference;
+import com.google.firestore.v1.StructuredQuery.Filter;
+import com.google.firestore.v1.StructuredQuery.Order;
+import com.google.firestore.v1.StructuredQuery.UnaryFilter;
+import com.google.firestore.v1.Value;
+import com.google.firestore.v1.Value.ValueTypeCase;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Ascii;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/**
+ * Contains several internal utility functions for Firestore query handling, 
such as filling
+ * implicit ordering or escaping field references.
+ */
+class QueryUtils {
+
+  private static final ImmutableSet<Operator> INEQUALITY_FIELD_FILTER_OPS =
+      ImmutableSet.of(
+          FieldFilter.Operator.LESS_THAN,
+          FieldFilter.Operator.LESS_THAN_OR_EQUAL,
+          FieldFilter.Operator.GREATER_THAN,
+          FieldFilter.Operator.GREATER_THAN_OR_EQUAL,
+          FieldFilter.Operator.NOT_EQUAL,
+          FieldFilter.Operator.NOT_IN);
+  private static final ImmutableSet<UnaryFilter.Operator> 
INEQUALITY_UNARY_FILTER_OPS =
+      ImmutableSet.of(UnaryFilter.Operator.IS_NOT_NAN, 
UnaryFilter.Operator.IS_NOT_NULL);
+
+  static List<Order> getImplicitOrderBy(StructuredQuery query) {
+    List<String> expectedImplicitOrders = new ArrayList<>();
+    if (query.hasWhere()) {
+      fillInequalityFields(query.getWhere(), expectedImplicitOrders);
+    }
+    if (!expectedImplicitOrders.contains("__name__")) {
+      expectedImplicitOrders.add("__name__");
+    }
+    for (Order order : query.getOrderByList()) {
+      String orderField = order.getField().getFieldPath();
+      expectedImplicitOrders.remove(orderField);
+    }
+
+    List<Order> additionalOrders = new ArrayList<>();
+    if (!expectedImplicitOrders.isEmpty()) {
+      Direction lastDirection =
+          query.getOrderByCount() == 0
+              ? Direction.ASCENDING
+              : query.getOrderByList().get(query.getOrderByCount() - 
1).getDirection();
+
+      for (String field : expectedImplicitOrders) {
+        additionalOrders.add(
+            Order.newBuilder()
+                .setDirection(lastDirection)
+                
.setField(FieldReference.newBuilder().setFieldPath(field).build())
+                .build());
+      }
+    }
+
+    return additionalOrders;
+  }
+
+  private static void fillInequalityFields(Filter filter, List<String> result) 
{
+    switch (filter.getFilterTypeCase()) {
+      case FIELD_FILTER:
+        if 
(INEQUALITY_FIELD_FILTER_OPS.contains(filter.getFieldFilter().getOp())) {
+          String fieldPath = filter.getFieldFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      case COMPOSITE_FILTER:
+        filter.getCompositeFilter().getFiltersList().forEach(f -> 
fillInequalityFields(f, result));
+        break;
+      case UNARY_FILTER:
+        if 
(INEQUALITY_UNARY_FILTER_OPS.contains(filter.getUnaryFilter().getOp())) {
+          String fieldPath = filter.getUnaryFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  @Nullable
+  static Value lookupDocumentValue(List<String> segments, Map<String, Value> 
valueMap) {
+    String field = segments.remove(0);
+    Value value = valueMap.get(field);
+    if (segments.isEmpty()) {
+      return value;
+    }
+    // Field path traversal is not done, recurse into map values.
+    if (value == null || 
!value.getValueTypeCase().equals(ValueTypeCase.MAP_VALUE)) {
+      return null;
+    }
+    return lookupDocumentValue(segments, value.getMapValue().getFieldsMap());
+  }
+
+  private static final String UNQUOTED_NAME_REGEX_STRING = 
"([a-zA-Z_][a-zA-Z_0-9]*)";
+  private static final String QUOTED_NAME_REGEX_STRING = 
"(`(?:[^`\\\\]|(?:\\\\.))+`)";
+  // After each segment follows a dot and more characters, or the end of the 
string.
+  private static final Pattern FIELD_PATH_SEGMENT_REGEX =
+      Pattern.compile(
+          String.format("(?:%s|%s)(\\..+|$)", UNQUOTED_NAME_REGEX_STRING, 
QUOTED_NAME_REGEX_STRING),
+          Pattern.DOTALL);
+
+  static List<String> resolveOrderByFieldPath(String fieldPath) throws 
IllegalArgumentException {
+    if (fieldPath.isEmpty()) {
+      throw new IllegalArgumentException("Could not resolve empty field path");
+    }
+    List<String> segments = new ArrayList<>();
+    while (!fieldPath.isEmpty()) {
+      Matcher segmentMatcher = FIELD_PATH_SEGMENT_REGEX.matcher(fieldPath);
+      boolean foundMatch = segmentMatcher.lookingAt();
+      if (!foundMatch) {
+        throw new IllegalArgumentException("OrderBy field path was malformed");
+      }
+      String fieldName = segmentMatcher.group(1);
+      // Unquoted group is null, use quoted group.
+      if (fieldName == null) {
+        fieldName = segmentMatcher.group(2);
+        String escaped = escapeFieldName(fieldName.substring(1, 
fieldName.length() - 1));
+        segments.add(escaped);
+      } else {
+        segments.add(fieldName);
+      }
+      fieldPath = fieldPath.substring(fieldName.length());
+      if (fieldPath.startsWith(".")) {
+        fieldPath = fieldPath.substring(1);
+      }
+    }
+    return segments;
+  }
+
+  private static String escapeFieldName(String fieldName) throws 
IllegalArgumentException {
+    if (fieldName.isEmpty()) {

Review Comment:
   I feel this should ideally be added as some class in 
googleapis/java-firestore and imported by beam as a library, in that way we 
will have better control over this logic and less likely to have it diverge 
from our backend (not that this logic is changed that frequently though). I 
guess it's OK as a temporary quick fix.



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/QueryUtils.java:
##########
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.io.gcp.firestore;
+
+import com.google.firestore.v1.StructuredQuery;
+import com.google.firestore.v1.StructuredQuery.Direction;
+import com.google.firestore.v1.StructuredQuery.FieldFilter;
+import com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
+import com.google.firestore.v1.StructuredQuery.FieldReference;
+import com.google.firestore.v1.StructuredQuery.Filter;
+import com.google.firestore.v1.StructuredQuery.Order;
+import com.google.firestore.v1.StructuredQuery.UnaryFilter;
+import com.google.firestore.v1.Value;
+import com.google.firestore.v1.Value.ValueTypeCase;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Ascii;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/**
+ * Contains several internal utility functions for Firestore query handling, 
such as filling
+ * implicit ordering or escaping field references.
+ */
+class QueryUtils {
+
+  private static final ImmutableSet<Operator> INEQUALITY_FIELD_FILTER_OPS =
+      ImmutableSet.of(
+          FieldFilter.Operator.LESS_THAN,
+          FieldFilter.Operator.LESS_THAN_OR_EQUAL,
+          FieldFilter.Operator.GREATER_THAN,
+          FieldFilter.Operator.GREATER_THAN_OR_EQUAL,
+          FieldFilter.Operator.NOT_EQUAL,
+          FieldFilter.Operator.NOT_IN);
+  private static final ImmutableSet<UnaryFilter.Operator> 
INEQUALITY_UNARY_FILTER_OPS =
+      ImmutableSet.of(UnaryFilter.Operator.IS_NOT_NAN, 
UnaryFilter.Operator.IS_NOT_NULL);
+
+  static List<Order> getImplicitOrderBy(StructuredQuery query) {
+    List<String> expectedImplicitOrders = new ArrayList<>();
+    if (query.hasWhere()) {
+      fillInequalityFields(query.getWhere(), expectedImplicitOrders);
+    }
+    if (!expectedImplicitOrders.contains("__name__")) {
+      expectedImplicitOrders.add("__name__");
+    }
+    for (Order order : query.getOrderByList()) {
+      String orderField = order.getField().getFieldPath();
+      expectedImplicitOrders.remove(orderField);
+    }
+
+    List<Order> additionalOrders = new ArrayList<>();
+    if (!expectedImplicitOrders.isEmpty()) {
+      Direction lastDirection =
+          query.getOrderByCount() == 0
+              ? Direction.ASCENDING
+              : query.getOrderByList().get(query.getOrderByCount() - 
1).getDirection();
+
+      for (String field : expectedImplicitOrders) {
+        additionalOrders.add(
+            Order.newBuilder()
+                .setDirection(lastDirection)
+                
.setField(FieldReference.newBuilder().setFieldPath(field).build())
+                .build());
+      }
+    }
+
+    return additionalOrders;
+  }
+
+  private static void fillInequalityFields(Filter filter, List<String> result) 
{
+    switch (filter.getFilterTypeCase()) {
+      case FIELD_FILTER:
+        if 
(INEQUALITY_FIELD_FILTER_OPS.contains(filter.getFieldFilter().getOp())) {
+          String fieldPath = filter.getFieldFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      case COMPOSITE_FILTER:
+        filter.getCompositeFilter().getFiltersList().forEach(f -> 
fillInequalityFields(f, result));
+        break;
+      case UNARY_FILTER:
+        if 
(INEQUALITY_UNARY_FILTER_OPS.contains(filter.getUnaryFilter().getOp())) {
+          String fieldPath = filter.getUnaryFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  @Nullable
+  static Value lookupDocumentValue(List<String> segments, Map<String, Value> 
valueMap) {
+    String field = segments.remove(0);

Review Comment:
   nit: potential IndexOutOfBoundsException if the list is empty, given the 
method is not public the risk should be small. Maybe still worth adding an 
empty check before trying to remove from the list?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/QueryUtils.java:
##########
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.io.gcp.firestore;
+
+import com.google.firestore.v1.StructuredQuery;
+import com.google.firestore.v1.StructuredQuery.Direction;
+import com.google.firestore.v1.StructuredQuery.FieldFilter;
+import com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
+import com.google.firestore.v1.StructuredQuery.FieldReference;
+import com.google.firestore.v1.StructuredQuery.Filter;
+import com.google.firestore.v1.StructuredQuery.Order;
+import com.google.firestore.v1.StructuredQuery.UnaryFilter;
+import com.google.firestore.v1.Value;
+import com.google.firestore.v1.Value.ValueTypeCase;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Ascii;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/**
+ * Contains several internal utility functions for Firestore query handling, 
such as filling
+ * implicit ordering or escaping field references.
+ */
+class QueryUtils {
+
+  private static final ImmutableSet<Operator> INEQUALITY_FIELD_FILTER_OPS =
+      ImmutableSet.of(
+          FieldFilter.Operator.LESS_THAN,
+          FieldFilter.Operator.LESS_THAN_OR_EQUAL,
+          FieldFilter.Operator.GREATER_THAN,
+          FieldFilter.Operator.GREATER_THAN_OR_EQUAL,
+          FieldFilter.Operator.NOT_EQUAL,
+          FieldFilter.Operator.NOT_IN);
+  private static final ImmutableSet<UnaryFilter.Operator> 
INEQUALITY_UNARY_FILTER_OPS =
+      ImmutableSet.of(UnaryFilter.Operator.IS_NOT_NAN, 
UnaryFilter.Operator.IS_NOT_NULL);
+
+  static List<Order> getImplicitOrderBy(StructuredQuery query) {
+    List<String> expectedImplicitOrders = new ArrayList<>();
+    if (query.hasWhere()) {
+      fillInequalityFields(query.getWhere(), expectedImplicitOrders);
+    }
+    if (!expectedImplicitOrders.contains("__name__")) {
+      expectedImplicitOrders.add("__name__");
+    }
+    for (Order order : query.getOrderByList()) {
+      String orderField = order.getField().getFieldPath();
+      expectedImplicitOrders.remove(orderField);
+    }
+
+    List<Order> additionalOrders = new ArrayList<>();
+    if (!expectedImplicitOrders.isEmpty()) {
+      Direction lastDirection =
+          query.getOrderByCount() == 0
+              ? Direction.ASCENDING
+              : query.getOrderByList().get(query.getOrderByCount() - 
1).getDirection();
+
+      for (String field : expectedImplicitOrders) {
+        additionalOrders.add(
+            Order.newBuilder()
+                .setDirection(lastDirection)
+                
.setField(FieldReference.newBuilder().setFieldPath(field).build())
+                .build());
+      }
+    }
+
+    return additionalOrders;
+  }
+
+  private static void fillInequalityFields(Filter filter, List<String> result) 
{
+    switch (filter.getFilterTypeCase()) {
+      case FIELD_FILTER:
+        if 
(INEQUALITY_FIELD_FILTER_OPS.contains(filter.getFieldFilter().getOp())) {
+          String fieldPath = filter.getFieldFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      case COMPOSITE_FILTER:
+        filter.getCompositeFilter().getFiltersList().forEach(f -> 
fillInequalityFields(f, result));
+        break;
+      case UNARY_FILTER:
+        if 
(INEQUALITY_UNARY_FILTER_OPS.contains(filter.getUnaryFilter().getOp())) {
+          String fieldPath = filter.getUnaryFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  @Nullable
+  static Value lookupDocumentValue(List<String> segments, Map<String, Value> 
valueMap) {
+    String field = segments.remove(0);
+    Value value = valueMap.get(field);
+    if (segments.isEmpty()) {
+      return value;
+    }
+    // Field path traversal is not done, recurse into map values.
+    if (value == null || 
!value.getValueTypeCase().equals(ValueTypeCase.MAP_VALUE)) {
+      return null;
+    }
+    return lookupDocumentValue(segments, value.getMapValue().getFieldsMap());
+  }
+
+  private static final String UNQUOTED_NAME_REGEX_STRING = 
"([a-zA-Z_][a-zA-Z_0-9]*)";

Review Comment:
   nit: consider moving all constants to before all methods in the class



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/FirestoreV1ReadFn.java:
##########
@@ -109,44 +107,37 @@ protected ServerStreamingCallable<RunQueryRequest, 
RunQueryResponse> getCallable
     protected RunQueryRequest setStartFrom(
         RunQueryRequest element, RunQueryResponse runQueryResponse) {
       StructuredQuery query = element.getStructuredQuery();
-      StructuredQuery.Builder builder;
-      List<Order> orderByList = query.getOrderByList();
-      // if the orderByList is empty that means the default sort of "__name__ 
ASC" will be used
-      // Before we can set the cursor to the last document name read, we need 
to explicitly add
-      // the order of "__name__ ASC" because a cursor value must map to an 
order by
-      if (orderByList.isEmpty()) {
-        builder =
-            query
-                .toBuilder()
-                .addOrderBy(
-                    Order.newBuilder()
-                        
.setField(FieldReference.newBuilder().setFieldPath("__name__").build())
-                        .setDirection(Direction.ASCENDING)
-                        .build())
-                .setStartAt(
-                    Cursor.newBuilder()
-                        .setBefore(false)
-                        .addValues(
-                            Value.newBuilder()
-                                
.setReferenceValue(runQueryResponse.getDocument().getName())
-                                .build()));
-      } else {
-        Cursor.Builder cursor = Cursor.newBuilder().setBefore(false);
-        Map<String, Value> fieldsMap = 
runQueryResponse.getDocument().getFieldsMap();
-        for (Order order : orderByList) {
-          String fieldPath = order.getField().getFieldPath();
-          Value value = fieldsMap.get(fieldPath);
-          if (value != null) {
-            cursor.addValues(value);
-          } else if ("__name__".equals(fieldPath)) {
-            cursor.addValues(
-                Value.newBuilder()
-                    
.setReferenceValue(runQueryResponse.getDocument().getName())
-                    .build());
+      StructuredQuery.Builder builder = query.toBuilder();
+      builder.addAllOrderBy(QueryUtils.getImplicitOrderBy(query));
+      Cursor.Builder cursor = Cursor.newBuilder().setBefore(false);
+
+      Map<String, Value> valueMap = 
runQueryResponse.getDocument().getFieldsMap();
+      for (Order order : builder.getOrderByList()) {
+        List<String> segments;
+        try {
+          segments = 
QueryUtils.resolveOrderByFieldPath(order.getField().getFieldPath());
+        } catch (IllegalArgumentException e) {
+          // Rethrow as something specific to RunQuery
+          throw new IllegalArgumentException(
+              "Could not retry query due to malformed orderBy field", 
e.getCause());
+        }
+        // __name__ is a special field and doesn't exist in valueMap
+        if (segments.size() == 1 && "__name__".equals(segments.get(0))) {
+          cursor.addValues(
+              Value.newBuilder()
+                  .setReferenceValue(runQueryResponse.getDocument().getName())
+                  .build());
+        } else {
+          Value value;
+          value = QueryUtils.lookupDocumentValue(segments, valueMap);

Review Comment:
   nit: can we combine these two lines?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/QueryUtils.java:
##########
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.io.gcp.firestore;
+
+import com.google.firestore.v1.StructuredQuery;
+import com.google.firestore.v1.StructuredQuery.Direction;
+import com.google.firestore.v1.StructuredQuery.FieldFilter;
+import com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
+import com.google.firestore.v1.StructuredQuery.FieldReference;
+import com.google.firestore.v1.StructuredQuery.Filter;
+import com.google.firestore.v1.StructuredQuery.Order;
+import com.google.firestore.v1.StructuredQuery.UnaryFilter;
+import com.google.firestore.v1.Value;
+import com.google.firestore.v1.Value.ValueTypeCase;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Ascii;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/**
+ * Contains several internal utility functions for Firestore query handling, 
such as filling
+ * implicit ordering or escaping field references.
+ */
+class QueryUtils {
+
+  private static final ImmutableSet<Operator> INEQUALITY_FIELD_FILTER_OPS =
+      ImmutableSet.of(
+          FieldFilter.Operator.LESS_THAN,
+          FieldFilter.Operator.LESS_THAN_OR_EQUAL,
+          FieldFilter.Operator.GREATER_THAN,
+          FieldFilter.Operator.GREATER_THAN_OR_EQUAL,
+          FieldFilter.Operator.NOT_EQUAL,
+          FieldFilter.Operator.NOT_IN);
+  private static final ImmutableSet<UnaryFilter.Operator> 
INEQUALITY_UNARY_FILTER_OPS =
+      ImmutableSet.of(UnaryFilter.Operator.IS_NOT_NAN, 
UnaryFilter.Operator.IS_NOT_NULL);
+
+  static List<Order> getImplicitOrderBy(StructuredQuery query) {
+    List<String> expectedImplicitOrders = new ArrayList<>();
+    if (query.hasWhere()) {
+      fillInequalityFields(query.getWhere(), expectedImplicitOrders);
+    }
+    if (!expectedImplicitOrders.contains("__name__")) {
+      expectedImplicitOrders.add("__name__");
+    }
+    for (Order order : query.getOrderByList()) {
+      String orderField = order.getField().getFieldPath();
+      expectedImplicitOrders.remove(orderField);
+    }
+
+    List<Order> additionalOrders = new ArrayList<>();
+    if (!expectedImplicitOrders.isEmpty()) {
+      Direction lastDirection =
+          query.getOrderByCount() == 0
+              ? Direction.ASCENDING
+              : query.getOrderByList().get(query.getOrderByCount() - 
1).getDirection();
+
+      for (String field : expectedImplicitOrders) {
+        additionalOrders.add(
+            Order.newBuilder()
+                .setDirection(lastDirection)
+                
.setField(FieldReference.newBuilder().setFieldPath(field).build())
+                .build());
+      }
+    }
+
+    return additionalOrders;
+  }
+
+  private static void fillInequalityFields(Filter filter, List<String> result) 
{
+    switch (filter.getFilterTypeCase()) {
+      case FIELD_FILTER:
+        if 
(INEQUALITY_FIELD_FILTER_OPS.contains(filter.getFieldFilter().getOp())) {
+          String fieldPath = filter.getFieldFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      case COMPOSITE_FILTER:
+        filter.getCompositeFilter().getFiltersList().forEach(f -> 
fillInequalityFields(f, result));
+        break;
+      case UNARY_FILTER:
+        if 
(INEQUALITY_UNARY_FILTER_OPS.contains(filter.getUnaryFilter().getOp())) {
+          String fieldPath = filter.getUnaryFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  @Nullable
+  static Value lookupDocumentValue(List<String> segments, Map<String, Value> 
valueMap) {
+    String field = segments.remove(0);
+    Value value = valueMap.get(field);
+    if (segments.isEmpty()) {
+      return value;
+    }
+    // Field path traversal is not done, recurse into map values.
+    if (value == null || 
!value.getValueTypeCase().equals(ValueTypeCase.MAP_VALUE)) {
+      return null;
+    }
+    return lookupDocumentValue(segments, value.getMapValue().getFieldsMap());
+  }
+
+  private static final String UNQUOTED_NAME_REGEX_STRING = 
"([a-zA-Z_][a-zA-Z_0-9]*)";
+  private static final String QUOTED_NAME_REGEX_STRING = 
"(`(?:[^`\\\\]|(?:\\\\.))+`)";
+  // After each segment follows a dot and more characters, or the end of the 
string.
+  private static final Pattern FIELD_PATH_SEGMENT_REGEX =
+      Pattern.compile(
+          String.format("(?:%s|%s)(\\..+|$)", UNQUOTED_NAME_REGEX_STRING, 
QUOTED_NAME_REGEX_STRING),
+          Pattern.DOTALL);
+
+  static List<String> resolveOrderByFieldPath(String fieldPath) throws 
IllegalArgumentException {
+    if (fieldPath.isEmpty()) {
+      throw new IllegalArgumentException("Could not resolve empty field path");
+    }
+    List<String> segments = new ArrayList<>();
+    while (!fieldPath.isEmpty()) {
+      Matcher segmentMatcher = FIELD_PATH_SEGMENT_REGEX.matcher(fieldPath);
+      boolean foundMatch = segmentMatcher.lookingAt();
+      if (!foundMatch) {
+        throw new IllegalArgumentException("OrderBy field path was malformed");
+      }
+      String fieldName = segmentMatcher.group(1);
+      // Unquoted group is null, use quoted group.
+      if (fieldName == null) {
+        fieldName = segmentMatcher.group(2);
+        String escaped = escapeFieldName(fieldName.substring(1, 
fieldName.length() - 1));
+        segments.add(escaped);
+      } else {
+        segments.add(fieldName);
+      }
+      fieldPath = fieldPath.substring(fieldName.length());
+      if (fieldPath.startsWith(".")) {

Review Comment:
   this line looks a bit suspicious, when fieldPath is not empty here, when 
would it start with "." and when would it not start with "."?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/firestore/QueryUtils.java:
##########
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.io.gcp.firestore;
+
+import com.google.firestore.v1.StructuredQuery;
+import com.google.firestore.v1.StructuredQuery.Direction;
+import com.google.firestore.v1.StructuredQuery.FieldFilter;
+import com.google.firestore.v1.StructuredQuery.FieldFilter.Operator;
+import com.google.firestore.v1.StructuredQuery.FieldReference;
+import com.google.firestore.v1.StructuredQuery.Filter;
+import com.google.firestore.v1.StructuredQuery.Order;
+import com.google.firestore.v1.StructuredQuery.UnaryFilter;
+import com.google.firestore.v1.Value;
+import com.google.firestore.v1.Value.ValueTypeCase;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Ascii;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+/**
+ * Contains several internal utility functions for Firestore query handling, 
such as filling
+ * implicit ordering or escaping field references.
+ */
+class QueryUtils {
+
+  private static final ImmutableSet<Operator> INEQUALITY_FIELD_FILTER_OPS =
+      ImmutableSet.of(
+          FieldFilter.Operator.LESS_THAN,
+          FieldFilter.Operator.LESS_THAN_OR_EQUAL,
+          FieldFilter.Operator.GREATER_THAN,
+          FieldFilter.Operator.GREATER_THAN_OR_EQUAL,
+          FieldFilter.Operator.NOT_EQUAL,
+          FieldFilter.Operator.NOT_IN);
+  private static final ImmutableSet<UnaryFilter.Operator> 
INEQUALITY_UNARY_FILTER_OPS =
+      ImmutableSet.of(UnaryFilter.Operator.IS_NOT_NAN, 
UnaryFilter.Operator.IS_NOT_NULL);
+
+  static List<Order> getImplicitOrderBy(StructuredQuery query) {
+    List<String> expectedImplicitOrders = new ArrayList<>();
+    if (query.hasWhere()) {
+      fillInequalityFields(query.getWhere(), expectedImplicitOrders);
+    }
+    if (!expectedImplicitOrders.contains("__name__")) {
+      expectedImplicitOrders.add("__name__");
+    }
+    for (Order order : query.getOrderByList()) {
+      String orderField = order.getField().getFieldPath();
+      expectedImplicitOrders.remove(orderField);
+    }
+
+    List<Order> additionalOrders = new ArrayList<>();
+    if (!expectedImplicitOrders.isEmpty()) {
+      Direction lastDirection =
+          query.getOrderByCount() == 0
+              ? Direction.ASCENDING
+              : query.getOrderByList().get(query.getOrderByCount() - 
1).getDirection();
+
+      for (String field : expectedImplicitOrders) {
+        additionalOrders.add(
+            Order.newBuilder()
+                .setDirection(lastDirection)
+                
.setField(FieldReference.newBuilder().setFieldPath(field).build())
+                .build());
+      }
+    }
+
+    return additionalOrders;
+  }
+
+  private static void fillInequalityFields(Filter filter, List<String> result) 
{
+    switch (filter.getFilterTypeCase()) {
+      case FIELD_FILTER:
+        if 
(INEQUALITY_FIELD_FILTER_OPS.contains(filter.getFieldFilter().getOp())) {
+          String fieldPath = filter.getFieldFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      case COMPOSITE_FILTER:
+        filter.getCompositeFilter().getFiltersList().forEach(f -> 
fillInequalityFields(f, result));
+        break;
+      case UNARY_FILTER:
+        if 
(INEQUALITY_UNARY_FILTER_OPS.contains(filter.getUnaryFilter().getOp())) {
+          String fieldPath = filter.getUnaryFilter().getField().getFieldPath();
+          if (!result.contains(fieldPath)) {
+            result.add(fieldPath);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  @Nullable
+  static Value lookupDocumentValue(List<String> segments, Map<String, Value> 
valueMap) {
+    String field = segments.remove(0);
+    Value value = valueMap.get(field);
+    if (segments.isEmpty()) {
+      return value;
+    }
+    // Field path traversal is not done, recurse into map values.
+    if (value == null || 
!value.getValueTypeCase().equals(ValueTypeCase.MAP_VALUE)) {
+      return null;
+    }
+    return lookupDocumentValue(segments, value.getMapValue().getFieldsMap());
+  }
+
+  private static final String UNQUOTED_NAME_REGEX_STRING = 
"([a-zA-Z_][a-zA-Z_0-9]*)";
+  private static final String QUOTED_NAME_REGEX_STRING = 
"(`(?:[^`\\\\]|(?:\\\\.))+`)";
+  // After each segment follows a dot and more characters, or the end of the 
string.
+  private static final Pattern FIELD_PATH_SEGMENT_REGEX =
+      Pattern.compile(
+          String.format("(?:%s|%s)(\\..+|$)", UNQUOTED_NAME_REGEX_STRING, 
QUOTED_NAME_REGEX_STRING),
+          Pattern.DOTALL);
+
+  static List<String> resolveOrderByFieldPath(String fieldPath) throws 
IllegalArgumentException {

Review Comment:
   RuntimeExceptions do not need to be declared in the throws clause. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to