diff --git a/firebase-firestore/CHANGELOG.md b/firebase-firestore/CHANGELOG.md index 66fce5b35ce..d2f756372e9 100644 --- a/firebase-firestore/CHANGELOG.md +++ b/firebase-firestore/CHANGELOG.md @@ -1,5 +1,5 @@ # Unreleased - +* [feature] Pipelines # 25.1.2 * [fixed] Fixed a server and sdk mismatch in unicode string sorting. [#6615](//github.com/firebase/firebase-android-sdk/pull/6615) diff --git a/firebase-firestore/api.txt b/firebase-firestore/api.txt index e3a55cf729c..cb86b4b0932 100644 --- a/firebase-firestore/api.txt +++ b/firebase-firestore/api.txt @@ -72,7 +72,7 @@ package com.google.firebase.firestore { @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) public @interface DocumentId { } - public class DocumentReference { + public final class DocumentReference { method public com.google.firebase.firestore.ListenerRegistration addSnapshotListener(android.app.Activity, com.google.firebase.firestore.EventListener); method public com.google.firebase.firestore.ListenerRegistration addSnapshotListener(android.app.Activity, com.google.firebase.firestore.MetadataChanges, com.google.firebase.firestore.EventListener); method public com.google.firebase.firestore.ListenerRegistration addSnapshotListener(com.google.firebase.firestore.EventListener); @@ -85,6 +85,7 @@ package com.google.firebase.firestore { method public com.google.android.gms.tasks.Task get(); method public com.google.android.gms.tasks.Task get(com.google.firebase.firestore.Source); method public com.google.firebase.firestore.FirebaseFirestore getFirestore(); + method @RestrictTo(androidx.annotation.RestrictTo.Scope.LIBRARY) public String getFullPath(); method public String getId(); method public com.google.firebase.firestore.CollectionReference getParent(); method public String getPath(); @@ -143,6 +144,7 @@ package com.google.firebase.firestore { public final class FieldPath { method public static com.google.firebase.firestore.FieldPath documentId(); + method @RestrictTo(androidx.annotation.RestrictTo.Scope.LIBRARY) public static com.google.firebase.firestore.FieldPath fromDotSeparatedPath(String); method public static com.google.firebase.firestore.FieldPath of(java.lang.String!...!); } @@ -204,6 +206,7 @@ package com.google.firebase.firestore { method public com.google.firebase.firestore.LoadBundleTask loadBundle(byte[]); method public com.google.firebase.firestore.LoadBundleTask loadBundle(java.io.InputStream); method public com.google.firebase.firestore.LoadBundleTask loadBundle(java.nio.ByteBuffer); + method public com.google.firebase.firestore.PipelineSource pipeline(); method public com.google.android.gms.tasks.Task runBatch(com.google.firebase.firestore.WriteBatch.Function); method public com.google.android.gms.tasks.Task runTransaction(com.google.firebase.firestore.Transaction.Function); method public com.google.android.gms.tasks.Task runTransaction(com.google.firebase.firestore.TransactionOptions, com.google.firebase.firestore.Transaction.Function); @@ -416,6 +419,72 @@ package com.google.firebase.firestore { method public com.google.firebase.firestore.PersistentCacheSettings.Builder setSizeBytes(long); } + public final class Pipeline { + method public com.google.firebase.firestore.Pipeline addFields(com.google.firebase.firestore.pipeline.Selectable field, com.google.firebase.firestore.pipeline.Selectable... additionalFields); + method public com.google.firebase.firestore.Pipeline addStage(com.google.firebase.firestore.pipeline.Stage stage); + method public com.google.firebase.firestore.Pipeline aggregate(com.google.firebase.firestore.pipeline.AggregateStage aggregateStage); + method public com.google.firebase.firestore.Pipeline aggregate(com.google.firebase.firestore.pipeline.AggregateWithAlias accumulator, com.google.firebase.firestore.pipeline.AggregateWithAlias... additionalAccumulators); + method public com.google.firebase.firestore.Pipeline distinct(com.google.firebase.firestore.pipeline.Selectable group, java.lang.Object... additionalGroups); + method public com.google.firebase.firestore.Pipeline distinct(String groupField, java.lang.Object... additionalGroups); + method public com.google.android.gms.tasks.Task execute(); + method public com.google.android.gms.tasks.Task execute(com.google.firebase.firestore.pipeline.PipelineOptions options); + method public com.google.firebase.firestore.Pipeline findNearest(com.google.firebase.firestore.pipeline.Field vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.Pipeline findNearest(com.google.firebase.firestore.pipeline.Field vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.Pipeline findNearest(com.google.firebase.firestore.pipeline.FindNearestStage stage); + method public com.google.firebase.firestore.Pipeline findNearest(String vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.Pipeline findNearest(String vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.Pipeline limit(int limit); + method public com.google.firebase.firestore.Pipeline offset(int offset); + method public com.google.firebase.firestore.Pipeline removeFields(com.google.firebase.firestore.pipeline.Field field, com.google.firebase.firestore.pipeline.Field... additionalFields); + method public com.google.firebase.firestore.Pipeline removeFields(String field, java.lang.String... additionalFields); + method public com.google.firebase.firestore.Pipeline replace(com.google.firebase.firestore.pipeline.Expr mapValue); + method public com.google.firebase.firestore.Pipeline replace(String field); + method public com.google.firebase.firestore.Pipeline sample(com.google.firebase.firestore.pipeline.SampleStage sample); + method public com.google.firebase.firestore.Pipeline sample(int documents); + method public com.google.firebase.firestore.Pipeline select(com.google.firebase.firestore.pipeline.Selectable selection, java.lang.Object... additionalSelections); + method public com.google.firebase.firestore.Pipeline select(String fieldName, java.lang.Object... additionalSelections); + method public com.google.firebase.firestore.Pipeline sort(com.google.firebase.firestore.pipeline.Ordering order, com.google.firebase.firestore.pipeline.Ordering... additionalOrders); + method public com.google.firebase.firestore.Pipeline union(com.google.firebase.firestore.Pipeline other); + method public com.google.firebase.firestore.Pipeline unnest(com.google.firebase.firestore.pipeline.Selectable arrayWithAlias); + method public com.google.firebase.firestore.Pipeline unnest(com.google.firebase.firestore.pipeline.UnnestStage unnestStage); + method public com.google.firebase.firestore.Pipeline unnest(String arrayField, String alias); + method public com.google.firebase.firestore.Pipeline where(com.google.firebase.firestore.pipeline.BooleanExpr condition); + } + + public final class PipelineResult { + method public Object? get(com.google.firebase.firestore.FieldPath fieldPath); + method public Object? get(String field); + method public com.google.firebase.Timestamp? getCreateTime(); + method public java.util.Map getData(); + method public String? getId(); + method public com.google.firebase.firestore.DocumentReference? getRef(); + method public com.google.firebase.Timestamp? getUpdateTime(); + property public final com.google.firebase.Timestamp? createTime; + property public final com.google.firebase.firestore.DocumentReference? ref; + property public final com.google.firebase.Timestamp? updateTime; + } + + public final class PipelineSnapshot implements java.lang.Iterable kotlin.jvm.internal.markers.KMappedMarker { + method public com.google.firebase.Timestamp getExecutionTime(); + method public java.util.List getResults(); + method public java.util.Iterator iterator(); + property public final com.google.firebase.Timestamp executionTime; + property public final java.util.List results; + } + + public final class PipelineSource { + method public com.google.firebase.firestore.Pipeline collection(com.google.firebase.firestore.CollectionReference ref); + method public com.google.firebase.firestore.Pipeline collection(com.google.firebase.firestore.pipeline.CollectionSource stage); + method public com.google.firebase.firestore.Pipeline collection(String path); + method public com.google.firebase.firestore.Pipeline collectionGroup(String collectionId); + method public com.google.firebase.firestore.Pipeline convertFrom(com.google.firebase.firestore.AggregateQuery aggregateQuery); + method public com.google.firebase.firestore.Pipeline convertFrom(com.google.firebase.firestore.Query query); + method public com.google.firebase.firestore.Pipeline database(); + method public com.google.firebase.firestore.Pipeline documents(com.google.firebase.firestore.DocumentReference... documents); + method public com.google.firebase.firestore.Pipeline documents(java.lang.String... documents); + method public com.google.firebase.firestore.Pipeline pipeline(com.google.firebase.firestore.pipeline.CollectionGroupSource stage); + } + @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.FIELD}) public @interface PropertyName { method public abstract String value(); } @@ -606,3 +675,954 @@ package com.google.firebase.firestore.ktx { } +package com.google.firebase.firestore.pipeline { + + public abstract class AbstractOptions> { + method public final T with(String key, boolean value); + method public final T with(String key, com.google.firebase.firestore.pipeline.Field value); + method public final T with(String key, com.google.firebase.firestore.pipeline.GenericOptions value); + method protected final T with(String key, com.google.firebase.firestore.pipeline.InternalOptions value); + method public final T with(String key, double value); + method protected final T with(String key, error.NonExistentClass value); + method public final T with(String key, String value); + method public final T with(String key, long value); + } + + public final class AggregateFunction { + method public com.google.firebase.firestore.pipeline.AggregateWithAlias alias(String alias); + method public static com.google.firebase.firestore.pipeline.AggregateFunction avg(com.google.firebase.firestore.pipeline.Expr expression); + method public static com.google.firebase.firestore.pipeline.AggregateFunction avg(String fieldName); + method public static com.google.firebase.firestore.pipeline.AggregateFunction count(com.google.firebase.firestore.pipeline.Expr expression); + method public static com.google.firebase.firestore.pipeline.AggregateFunction count(String fieldName); + method public static com.google.firebase.firestore.pipeline.AggregateFunction countAll(); + method public static com.google.firebase.firestore.pipeline.AggregateFunction countIf(com.google.firebase.firestore.pipeline.BooleanExpr condition); + method public static com.google.firebase.firestore.pipeline.AggregateFunction generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + method public static com.google.firebase.firestore.pipeline.AggregateFunction maximum(com.google.firebase.firestore.pipeline.Expr expression); + method public static com.google.firebase.firestore.pipeline.AggregateFunction maximum(String fieldName); + method public static com.google.firebase.firestore.pipeline.AggregateFunction minimum(com.google.firebase.firestore.pipeline.Expr expression); + method public static com.google.firebase.firestore.pipeline.AggregateFunction minimum(String fieldName); + method public static com.google.firebase.firestore.pipeline.AggregateFunction sum(com.google.firebase.firestore.pipeline.Expr expression); + method public static com.google.firebase.firestore.pipeline.AggregateFunction sum(String fieldName); + field public static final com.google.firebase.firestore.pipeline.AggregateFunction.Companion Companion; + } + + public static final class AggregateFunction.Companion { + method public com.google.firebase.firestore.pipeline.AggregateFunction avg(com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.AggregateFunction avg(String fieldName); + method public com.google.firebase.firestore.pipeline.AggregateFunction count(com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.AggregateFunction count(String fieldName); + method public com.google.firebase.firestore.pipeline.AggregateFunction countAll(); + method public com.google.firebase.firestore.pipeline.AggregateFunction countIf(com.google.firebase.firestore.pipeline.BooleanExpr condition); + method public com.google.firebase.firestore.pipeline.AggregateFunction generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + method public com.google.firebase.firestore.pipeline.AggregateFunction maximum(com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.AggregateFunction maximum(String fieldName); + method public com.google.firebase.firestore.pipeline.AggregateFunction minimum(com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.AggregateFunction minimum(String fieldName); + method public com.google.firebase.firestore.pipeline.AggregateFunction sum(com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.AggregateFunction sum(String fieldName); + } + + public final class AggregateStage extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.AggregateStage withAccumulators(com.google.firebase.firestore.pipeline.AggregateWithAlias accumulator, com.google.firebase.firestore.pipeline.AggregateWithAlias... additionalAccumulators); + method public com.google.firebase.firestore.pipeline.AggregateStage withGroups(com.google.firebase.firestore.pipeline.Selectable group, java.lang.Object... additionalGroups); + method public com.google.firebase.firestore.pipeline.AggregateStage withGroups(String groupField, java.lang.Object... additionalGroups); + field public static final com.google.firebase.firestore.pipeline.AggregateStage.Companion Companion; + } + + public static final class AggregateStage.Companion { + method public com.google.firebase.firestore.pipeline.AggregateStage withAccumulators(com.google.firebase.firestore.pipeline.AggregateWithAlias accumulator, com.google.firebase.firestore.pipeline.AggregateWithAlias... additionalAccumulators); + } + + public final class AggregateWithAlias { + } + + public abstract class BaseStage> { + method protected final String getName(); + method public final T with(String key, boolean value); + method public final T with(String key, com.google.firebase.firestore.pipeline.Field value); + method public final T with(String key, double value); + method protected final T with(String key, error.NonExistentClass value); + method public final T with(String key, String value); + method public final T with(String key, long value); + property protected final String name; + } + + public class BooleanExpr extends com.google.firebase.firestore.pipeline.FunctionExpr { + method public final com.google.firebase.firestore.pipeline.Expr cond(com.google.firebase.firestore.pipeline.Expr thenExpr, com.google.firebase.firestore.pipeline.Expr elseExpr); + method public final com.google.firebase.firestore.pipeline.Expr cond(Object thenValue, Object elseValue); + method public final com.google.firebase.firestore.pipeline.AggregateFunction countIf(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + method public final com.google.firebase.firestore.pipeline.BooleanExpr not(); + field public static final com.google.firebase.firestore.pipeline.BooleanExpr.Companion Companion; + } + + public static final class BooleanExpr.Companion { + method public com.google.firebase.firestore.pipeline.BooleanExpr generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + } + + public final class CollectionGroupSource extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.CollectionGroupSource of(String collectionId); + method public error.NonExistentClass withForceIndex(String value); + field public static final com.google.firebase.firestore.pipeline.CollectionGroupSource.Companion Companion; + } + + public static final class CollectionGroupSource.Companion { + method public com.google.firebase.firestore.pipeline.CollectionGroupSource of(String collectionId); + } + + public final class CollectionSource extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.CollectionSource of(com.google.firebase.firestore.CollectionReference ref); + method public static com.google.firebase.firestore.pipeline.CollectionSource of(String path); + method public error.NonExistentClass withForceIndex(String value); + field public static final com.google.firebase.firestore.pipeline.CollectionSource.Companion Companion; + } + + public static final class CollectionSource.Companion { + method public com.google.firebase.firestore.pipeline.CollectionSource of(com.google.firebase.firestore.CollectionReference ref); + method public com.google.firebase.firestore.pipeline.CollectionSource of(String path); + } + + public final class ExplainOptions extends com.google.firebase.firestore.pipeline.AbstractOptions { + method public error.NonExistentClass withIndexRecommendation(boolean value); + method public error.NonExistentClass withMode(com.google.firebase.firestore.pipeline.ExplainOptions.ExplainMode value); + method public error.NonExistentClass withOutputFormat(com.google.firebase.firestore.pipeline.ExplainOptions.OutputFormat value); + method public error.NonExistentClass withProfiles(com.google.firebase.firestore.pipeline.ExplainOptions.Profiles value); + method public error.NonExistentClass withRedact(boolean value); + method public error.NonExistentClass withVerbosity(com.google.firebase.firestore.pipeline.ExplainOptions.Verbosity value); + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions DEFAULT; + } + + public static final class ExplainOptions.Companion { + } + + public static final class ExplainOptions.ExplainMode { + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.ExplainMode ANALYZE; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.ExplainMode.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.ExplainMode EXECUTE; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.ExplainMode EXPLAIN; + } + + public static final class ExplainOptions.ExplainMode.Companion { + } + + public static final class ExplainOptions.OutputFormat { + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.OutputFormat.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.OutputFormat JSON; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.OutputFormat STRUCT; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.OutputFormat TEXT; + } + + public static final class ExplainOptions.OutputFormat.Companion { + } + + public static final class ExplainOptions.Profiles { + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Profiles BYTES_THROUGHPUT; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Profiles.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Profiles LATENCY; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Profiles RECORDS_COUNT; + } + + public static final class ExplainOptions.Profiles.Companion { + } + + public static final class ExplainOptions.Verbosity { + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Verbosity.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Verbosity EXECUTION_TREE; + field public static final com.google.firebase.firestore.pipeline.ExplainOptions.Verbosity SUMMARY_ONLY; + } + + public static final class ExplainOptions.Verbosity.Companion { + } + + public abstract class Expr { + method public final com.google.firebase.firestore.pipeline.Expr add(com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr add(com.google.firebase.firestore.pipeline.Expr first, com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr add(com.google.firebase.firestore.pipeline.Expr first, Number second); + method public final com.google.firebase.firestore.pipeline.Expr add(Number second); + method public static final com.google.firebase.firestore.pipeline.Expr add(String numericFieldName, com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr add(String numericFieldName, Number second); + method public com.google.firebase.firestore.pipeline.ExprWithAlias alias(String alias); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr and(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + method public static final com.google.firebase.firestore.pipeline.Expr arrayConcat(com.google.firebase.firestore.pipeline.Expr firstArray, com.google.firebase.firestore.pipeline.Expr secondArray, java.lang.Object... otherArrays); + method public static final com.google.firebase.firestore.pipeline.Expr arrayConcat(com.google.firebase.firestore.pipeline.Expr firstArray, Object secondArray, java.lang.Object... otherArrays); + method public final com.google.firebase.firestore.pipeline.Expr arrayConcat(com.google.firebase.firestore.pipeline.Expr secondArray, java.lang.Object... otherArrays); + method public final com.google.firebase.firestore.pipeline.Expr arrayConcat(Object secondArray, java.lang.Object... otherArrays); + method public static final com.google.firebase.firestore.pipeline.Expr arrayConcat(String firstArrayField, com.google.firebase.firestore.pipeline.Expr secondArray, java.lang.Object... otherArrays); + method public static final com.google.firebase.firestore.pipeline.Expr arrayConcat(String firstArrayField, Object secondArray, java.lang.Object... otherArrays); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(com.google.firebase.firestore.pipeline.Expr element); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr element); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(com.google.firebase.firestore.pipeline.Expr array, Object element); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(Object element); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr element); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(String arrayFieldName, Object element); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(com.google.firebase.firestore.pipeline.Expr array, java.util.List values); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(String arrayFieldName, java.util.List values); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(java.util.List values); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(com.google.firebase.firestore.pipeline.Expr array, java.util.List values); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(String arrayFieldName, java.util.List values); + method public final com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(java.util.List values); + method public final com.google.firebase.firestore.pipeline.Expr arrayLength(); + method public static final com.google.firebase.firestore.pipeline.Expr arrayLength(com.google.firebase.firestore.pipeline.Expr array); + method public static final com.google.firebase.firestore.pipeline.Expr arrayLength(String arrayFieldName); + method public final com.google.firebase.firestore.pipeline.Expr arrayOffset(com.google.firebase.firestore.pipeline.Expr offset); + method public static final com.google.firebase.firestore.pipeline.Expr arrayOffset(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr offset); + method public static final com.google.firebase.firestore.pipeline.Expr arrayOffset(com.google.firebase.firestore.pipeline.Expr array, int offset); + method public final com.google.firebase.firestore.pipeline.Expr arrayOffset(int offset); + method public static final com.google.firebase.firestore.pipeline.Expr arrayOffset(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr offset); + method public static final com.google.firebase.firestore.pipeline.Expr arrayOffset(String arrayFieldName, int offset); + method public final com.google.firebase.firestore.pipeline.Expr arrayReverse(); + method public static final com.google.firebase.firestore.pipeline.Expr arrayReverse(com.google.firebase.firestore.pipeline.Expr array); + method public static final com.google.firebase.firestore.pipeline.Expr arrayReverse(String arrayFieldName); + method public final com.google.firebase.firestore.pipeline.Ordering ascending(); + method public final com.google.firebase.firestore.pipeline.AggregateFunction avg(); + method public final com.google.firebase.firestore.pipeline.Expr bitAnd(byte[] bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr bitAnd(com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitAnd(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitAnd(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitAnd(String bitsFieldName, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitAnd(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr bitLeftShift(com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitLeftShift(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitLeftShift(com.google.firebase.firestore.pipeline.Expr bits, int number); + method public final com.google.firebase.firestore.pipeline.Expr bitLeftShift(int number); + method public static final com.google.firebase.firestore.pipeline.Expr bitLeftShift(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitLeftShift(String bitsFieldName, int number); + method public final com.google.firebase.firestore.pipeline.Expr bitNot(); + method public static final com.google.firebase.firestore.pipeline.Expr bitNot(com.google.firebase.firestore.pipeline.Expr bits); + method public static final com.google.firebase.firestore.pipeline.Expr bitNot(String bitsFieldName); + method public final com.google.firebase.firestore.pipeline.Expr bitOr(byte[] bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr bitOr(com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitOr(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitOr(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitOr(String bitsFieldName, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitOr(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr bitRightShift(com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitRightShift(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitRightShift(com.google.firebase.firestore.pipeline.Expr bits, int number); + method public final com.google.firebase.firestore.pipeline.Expr bitRightShift(int number); + method public static final com.google.firebase.firestore.pipeline.Expr bitRightShift(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public static final com.google.firebase.firestore.pipeline.Expr bitRightShift(String bitsFieldName, int number); + method public final com.google.firebase.firestore.pipeline.Expr bitXor(byte[] bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr bitXor(com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitXor(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitXor(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitXor(String bitsFieldName, byte[] bitsOther); + method public static final com.google.firebase.firestore.pipeline.Expr bitXor(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public final com.google.firebase.firestore.pipeline.Expr byteLength(); + method public static final com.google.firebase.firestore.pipeline.Expr byteLength(com.google.firebase.firestore.pipeline.Expr value); + method public static final com.google.firebase.firestore.pipeline.Expr byteLength(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr ceil(); + method public static final com.google.firebase.firestore.pipeline.Expr ceil(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public static final com.google.firebase.firestore.pipeline.Expr ceil(String numericField); + method public final com.google.firebase.firestore.pipeline.Expr charLength(); + method public static final com.google.firebase.firestore.pipeline.Expr charLength(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr charLength(String fieldName); + method public static final com.google.firebase.firestore.pipeline.Expr cond(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.Expr thenExpr, com.google.firebase.firestore.pipeline.Expr elseExpr); + method public static final com.google.firebase.firestore.pipeline.Expr cond(com.google.firebase.firestore.pipeline.BooleanExpr condition, Object thenValue, Object elseValue); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr constant(boolean value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(byte[] value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.Blob value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.DocumentReference ref); + method public static final com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.GeoPoint value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.VectorValue value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.Timestamp value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(Number value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(String value); + method public static final com.google.firebase.firestore.pipeline.Expr constant(java.util.Date value); + method public final com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public final com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.VectorValue vector); + method public final com.google.firebase.firestore.pipeline.Expr cosineDistance(double[] vector); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public static final com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, double[] vector); + method public final com.google.firebase.firestore.pipeline.AggregateFunction count(); + method public final com.google.firebase.firestore.pipeline.Ordering descending(); + method public final com.google.firebase.firestore.pipeline.Expr divide(com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr divide(com.google.firebase.firestore.pipeline.Expr dividend, com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr divide(com.google.firebase.firestore.pipeline.Expr dividend, Number divisor); + method public final com.google.firebase.firestore.pipeline.Expr divide(Number divisor); + method public static final com.google.firebase.firestore.pipeline.Expr divide(String dividendFieldName, com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr divide(String dividendFieldName, Number divisor); + method public final com.google.firebase.firestore.pipeline.Expr documentId(); + method public static final com.google.firebase.firestore.pipeline.Expr documentId(com.google.firebase.firestore.DocumentReference docRef); + method public static final com.google.firebase.firestore.pipeline.Expr documentId(com.google.firebase.firestore.pipeline.Expr documentPath); + method public static final com.google.firebase.firestore.pipeline.Expr documentId(String documentPath); + method public final com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public final com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.VectorValue vector); + method public final com.google.firebase.firestore.pipeline.Expr dotProduct(double[] vector); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public static final com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, double[] vector); + method public final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(com.google.firebase.firestore.pipeline.Expr suffix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, com.google.firebase.firestore.pipeline.Expr suffix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, String suffix); + method public final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(String suffix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(String fieldName, com.google.firebase.firestore.pipeline.Expr suffix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr endsWith(String fieldName, String suffix); + method public final com.google.firebase.firestore.pipeline.BooleanExpr eq(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eq(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eq(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr eq(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eq(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eq(String fieldName, Object value); + method public final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(com.google.firebase.firestore.pipeline.Expr expression, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(com.google.firebase.firestore.pipeline.Expr expression, java.util.List values); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(String fieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(String fieldName, java.util.List values); + method public final com.google.firebase.firestore.pipeline.BooleanExpr eqAny(java.util.List values); + method public final com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public final com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.VectorValue vector); + method public final com.google.firebase.firestore.pipeline.Expr euclideanDistance(double[] vector); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public static final com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, double[] vector); + method public final com.google.firebase.firestore.pipeline.BooleanExpr exists(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr exists(com.google.firebase.firestore.pipeline.Expr value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr exists(String fieldName); + method public static final com.google.firebase.firestore.pipeline.Field field(com.google.firebase.firestore.FieldPath fieldPath); + method public static final com.google.firebase.firestore.pipeline.Field field(String name); + method public final com.google.firebase.firestore.pipeline.Expr floor(); + method public static final com.google.firebase.firestore.pipeline.Expr floor(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public static final com.google.firebase.firestore.pipeline.Expr floor(String numericField); + method public static final com.google.firebase.firestore.pipeline.Expr generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + method public final com.google.firebase.firestore.pipeline.BooleanExpr gt(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gt(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gt(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr gt(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gt(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gt(String fieldName, Object value); + method public final com.google.firebase.firestore.pipeline.BooleanExpr gte(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gte(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gte(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr gte(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gte(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr gte(String fieldName, Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr ifError(com.google.firebase.firestore.pipeline.BooleanExpr tryExpr, com.google.firebase.firestore.pipeline.BooleanExpr catchExpr); + method public final com.google.firebase.firestore.pipeline.Expr ifError(com.google.firebase.firestore.pipeline.Expr catchExpr); + method public static final com.google.firebase.firestore.pipeline.Expr ifError(com.google.firebase.firestore.pipeline.Expr tryExpr, com.google.firebase.firestore.pipeline.Expr catchExpr); + method public static final com.google.firebase.firestore.pipeline.Expr ifError(com.google.firebase.firestore.pipeline.Expr tryExpr, Object catchValue); + method public final com.google.firebase.firestore.pipeline.Expr ifError(Object catchValue); + method public final com.google.firebase.firestore.pipeline.BooleanExpr isAbsent(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isAbsent(com.google.firebase.firestore.pipeline.Expr value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isAbsent(String fieldName); + method public final com.google.firebase.firestore.pipeline.BooleanExpr isNan(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNan(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNan(String fieldName); + method public final com.google.firebase.firestore.pipeline.BooleanExpr isNotNan(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNotNan(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNotNan(String fieldName); + method public final com.google.firebase.firestore.pipeline.BooleanExpr isNotNull(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNotNull(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNotNull(String fieldName); + method public final com.google.firebase.firestore.pipeline.BooleanExpr isNull(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNull(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr isNull(String fieldName); + method public final com.google.firebase.firestore.pipeline.BooleanExpr like(com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr like(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr like(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public final com.google.firebase.firestore.pipeline.BooleanExpr like(String pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr like(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr like(String fieldName, String pattern); + method public static final com.google.firebase.firestore.pipeline.Expr logicalMaximum(com.google.firebase.firestore.pipeline.Expr expr, java.lang.Object... others); + method public final com.google.firebase.firestore.pipeline.Expr logicalMaximum(com.google.firebase.firestore.pipeline.Expr... others); + method public final com.google.firebase.firestore.pipeline.Expr logicalMaximum(java.lang.Object... others); + method public static final com.google.firebase.firestore.pipeline.Expr logicalMaximum(String fieldName, java.lang.Object... others); + method public static final com.google.firebase.firestore.pipeline.Expr logicalMinimum(com.google.firebase.firestore.pipeline.Expr expr, java.lang.Object... others); + method public final com.google.firebase.firestore.pipeline.Expr logicalMinimum(com.google.firebase.firestore.pipeline.Expr... others); + method public final com.google.firebase.firestore.pipeline.Expr logicalMinimum(java.lang.Object... others); + method public static final com.google.firebase.firestore.pipeline.Expr logicalMinimum(String fieldName, java.lang.Object... others); + method public final com.google.firebase.firestore.pipeline.BooleanExpr lt(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lt(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lt(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr lt(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lt(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lt(String fieldName, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr lte(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lte(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lte(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr lte(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lte(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr lte(String fieldName, Object value); + method public static final com.google.firebase.firestore.pipeline.Expr map(java.util.Map elements); + method public static final com.google.firebase.firestore.pipeline.Expr mapGet(com.google.firebase.firestore.pipeline.Expr mapExpression, String key); + method public final com.google.firebase.firestore.pipeline.Expr mapGet(String key); + method public static final com.google.firebase.firestore.pipeline.Expr mapGet(String fieldName, String key); + method public static final com.google.firebase.firestore.pipeline.Expr mapMerge(com.google.firebase.firestore.pipeline.Expr firstMap, com.google.firebase.firestore.pipeline.Expr secondMap, com.google.firebase.firestore.pipeline.Expr... otherMaps); + method public final com.google.firebase.firestore.pipeline.Expr mapMerge(com.google.firebase.firestore.pipeline.Expr mapExpr, com.google.firebase.firestore.pipeline.Expr... otherMaps); + method public static final com.google.firebase.firestore.pipeline.Expr mapMerge(String firstMapFieldName, com.google.firebase.firestore.pipeline.Expr secondMap, com.google.firebase.firestore.pipeline.Expr... otherMaps); + method public final com.google.firebase.firestore.pipeline.Expr mapRemove(com.google.firebase.firestore.pipeline.Expr key); + method public static final com.google.firebase.firestore.pipeline.Expr mapRemove(com.google.firebase.firestore.pipeline.Expr mapExpr, com.google.firebase.firestore.pipeline.Expr key); + method public static final com.google.firebase.firestore.pipeline.Expr mapRemove(com.google.firebase.firestore.pipeline.Expr mapExpr, String key); + method public final com.google.firebase.firestore.pipeline.Expr mapRemove(String key); + method public static final com.google.firebase.firestore.pipeline.Expr mapRemove(String mapField, com.google.firebase.firestore.pipeline.Expr key); + method public static final com.google.firebase.firestore.pipeline.Expr mapRemove(String mapField, String key); + method public final com.google.firebase.firestore.pipeline.AggregateFunction maximum(); + method public final com.google.firebase.firestore.pipeline.AggregateFunction minimum(); + method public final com.google.firebase.firestore.pipeline.Expr mod(com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr mod(com.google.firebase.firestore.pipeline.Expr dividend, com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr mod(com.google.firebase.firestore.pipeline.Expr dividend, Number divisor); + method public final com.google.firebase.firestore.pipeline.Expr mod(Number divisor); + method public static final com.google.firebase.firestore.pipeline.Expr mod(String dividendFieldName, com.google.firebase.firestore.pipeline.Expr divisor); + method public static final com.google.firebase.firestore.pipeline.Expr mod(String dividendFieldName, Number divisor); + method public final com.google.firebase.firestore.pipeline.Expr multiply(com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr multiply(com.google.firebase.firestore.pipeline.Expr first, com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr multiply(com.google.firebase.firestore.pipeline.Expr first, Number second); + method public final com.google.firebase.firestore.pipeline.Expr multiply(Number second); + method public static final com.google.firebase.firestore.pipeline.Expr multiply(String numericFieldName, com.google.firebase.firestore.pipeline.Expr second); + method public static final com.google.firebase.firestore.pipeline.Expr multiply(String numericFieldName, Number second); + method public final com.google.firebase.firestore.pipeline.BooleanExpr neq(com.google.firebase.firestore.pipeline.Expr other); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr neq(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr neq(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public final com.google.firebase.firestore.pipeline.BooleanExpr neq(Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr neq(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr neq(String fieldName, Object value); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr not(com.google.firebase.firestore.pipeline.BooleanExpr condition); + method public final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(com.google.firebase.firestore.pipeline.Expr expression, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(com.google.firebase.firestore.pipeline.Expr expression, java.util.List values); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(String fieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(String fieldName, java.util.List values); + method public final com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(java.util.List values); + method public static final com.google.firebase.firestore.pipeline.Expr nullValue(); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr or(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + method public final com.google.firebase.firestore.pipeline.Expr pow(com.google.firebase.firestore.pipeline.Expr exponent); + method public static final com.google.firebase.firestore.pipeline.Expr pow(com.google.firebase.firestore.pipeline.Expr numericExpr, com.google.firebase.firestore.pipeline.Expr exponent); + method public static final com.google.firebase.firestore.pipeline.Expr pow(com.google.firebase.firestore.pipeline.Expr numericExpr, Number exponent); + method public final com.google.firebase.firestore.pipeline.Expr pow(Number exponent); + method public static final com.google.firebase.firestore.pipeline.Expr pow(String numericField, com.google.firebase.firestore.pipeline.Expr exponent); + method public static final com.google.firebase.firestore.pipeline.Expr pow(String numericField, Number exponent); + method public static final com.google.firebase.firestore.pipeline.Expr rand(); + method public final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(String pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexContains(String fieldName, String pattern); + method public final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(String pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(String fieldName, String pattern); + method public final com.google.firebase.firestore.pipeline.Expr replaceAll(com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceAll(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceAll(com.google.firebase.firestore.pipeline.Expr stringExpression, String find, String replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceAll(String fieldName, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public final com.google.firebase.firestore.pipeline.Expr replaceAll(String find, String replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceAll(String fieldName, String find, String replace); + method public final com.google.firebase.firestore.pipeline.Expr replaceFirst(com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceFirst(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceFirst(com.google.firebase.firestore.pipeline.Expr stringExpression, String find, String replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceFirst(String fieldName, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public final com.google.firebase.firestore.pipeline.Expr replaceFirst(String find, String replace); + method public static final com.google.firebase.firestore.pipeline.Expr replaceFirst(String fieldName, String find, String replace); + method public final com.google.firebase.firestore.pipeline.Expr reverse(); + method public static final com.google.firebase.firestore.pipeline.Expr reverse(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public static final com.google.firebase.firestore.pipeline.Expr reverse(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr round(); + method public static final com.google.firebase.firestore.pipeline.Expr round(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public static final com.google.firebase.firestore.pipeline.Expr round(String numericField); + method public final com.google.firebase.firestore.pipeline.Expr roundToPrecision(com.google.firebase.firestore.pipeline.Expr decimalPlace); + method public static final com.google.firebase.firestore.pipeline.Expr roundToPrecision(com.google.firebase.firestore.pipeline.Expr numericExpr, com.google.firebase.firestore.pipeline.Expr decimalPlace); + method public static final com.google.firebase.firestore.pipeline.Expr roundToPrecision(com.google.firebase.firestore.pipeline.Expr numericExpr, int decimalPlace); + method public final com.google.firebase.firestore.pipeline.Expr roundToPrecision(int decimalPlace); + method public static final com.google.firebase.firestore.pipeline.Expr roundToPrecision(String numericField, com.google.firebase.firestore.pipeline.Expr decimalPlace); + method public static final com.google.firebase.firestore.pipeline.Expr roundToPrecision(String numericField, int decimalPlace); + method public final com.google.firebase.firestore.pipeline.Expr sqrt(); + method public static final com.google.firebase.firestore.pipeline.Expr sqrt(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public static final com.google.firebase.firestore.pipeline.Expr sqrt(String numericField); + method public final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(com.google.firebase.firestore.pipeline.Expr prefix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, com.google.firebase.firestore.pipeline.Expr prefix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, String prefix); + method public final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(String prefix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(String fieldName, com.google.firebase.firestore.pipeline.Expr prefix); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr startsWith(String fieldName, String prefix); + method public static final com.google.firebase.firestore.pipeline.Expr strConcat(com.google.firebase.firestore.pipeline.Expr firstString, com.google.firebase.firestore.pipeline.Expr... otherStrings); + method public static final com.google.firebase.firestore.pipeline.Expr strConcat(com.google.firebase.firestore.pipeline.Expr firstString, java.lang.Object... otherStrings); + method public final com.google.firebase.firestore.pipeline.Expr strConcat(com.google.firebase.firestore.pipeline.Expr... stringExpressions); + method public final com.google.firebase.firestore.pipeline.Expr strConcat(java.lang.Object... strings); + method public static final com.google.firebase.firestore.pipeline.Expr strConcat(String fieldName, com.google.firebase.firestore.pipeline.Expr... otherStrings); + method public static final com.google.firebase.firestore.pipeline.Expr strConcat(String fieldName, java.lang.Object... otherStrings); + method public final com.google.firebase.firestore.pipeline.Expr strConcat(java.lang.String... strings); + method public final com.google.firebase.firestore.pipeline.BooleanExpr strContains(com.google.firebase.firestore.pipeline.Expr substring); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr strContains(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr substring); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr strContains(com.google.firebase.firestore.pipeline.Expr stringExpression, String substring); + method public final com.google.firebase.firestore.pipeline.BooleanExpr strContains(String substring); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr strContains(String fieldName, com.google.firebase.firestore.pipeline.Expr substring); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr strContains(String fieldName, String substring); + method public final com.google.firebase.firestore.pipeline.Expr subtract(com.google.firebase.firestore.pipeline.Expr subtrahend); + method public static final com.google.firebase.firestore.pipeline.Expr subtract(com.google.firebase.firestore.pipeline.Expr minuend, com.google.firebase.firestore.pipeline.Expr subtrahend); + method public static final com.google.firebase.firestore.pipeline.Expr subtract(com.google.firebase.firestore.pipeline.Expr minuend, Number subtrahend); + method public final com.google.firebase.firestore.pipeline.Expr subtract(Number subtrahend); + method public static final com.google.firebase.firestore.pipeline.Expr subtract(String numericFieldName, com.google.firebase.firestore.pipeline.Expr subtrahend); + method public static final com.google.firebase.firestore.pipeline.Expr subtract(String numericFieldName, Number subtrahend); + method public final com.google.firebase.firestore.pipeline.AggregateFunction sum(); + method public final com.google.firebase.firestore.pipeline.Expr timestampAdd(com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampAdd(com.google.firebase.firestore.pipeline.Expr timestamp, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampAdd(com.google.firebase.firestore.pipeline.Expr timestamp, String unit, double amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampAdd(String fieldName, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public final com.google.firebase.firestore.pipeline.Expr timestampAdd(String unit, double amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampAdd(String fieldName, String unit, double amount); + method public final com.google.firebase.firestore.pipeline.Expr timestampSub(com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampSub(com.google.firebase.firestore.pipeline.Expr timestamp, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampSub(com.google.firebase.firestore.pipeline.Expr timestamp, String unit, double amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampSub(String fieldName, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public final com.google.firebase.firestore.pipeline.Expr timestampSub(String unit, double amount); + method public static final com.google.firebase.firestore.pipeline.Expr timestampSub(String fieldName, String unit, double amount); + method public final com.google.firebase.firestore.pipeline.Expr timestampToUnixMicros(); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixMicros(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixMicros(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr timestampToUnixMillis(); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixMillis(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixMillis(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr timestampToUnixSeconds(); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixSeconds(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr timestampToUnixSeconds(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr toLower(); + method public static final com.google.firebase.firestore.pipeline.Expr toLower(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public static final com.google.firebase.firestore.pipeline.Expr toLower(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr toUpper(); + method public static final com.google.firebase.firestore.pipeline.Expr toUpper(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public static final com.google.firebase.firestore.pipeline.Expr toUpper(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr trim(); + method public static final com.google.firebase.firestore.pipeline.Expr trim(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public static final com.google.firebase.firestore.pipeline.Expr trim(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr unixMicrosToTimestamp(); + method public static final com.google.firebase.firestore.pipeline.Expr unixMicrosToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr unixMicrosToTimestamp(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr unixMillisToTimestamp(); + method public static final com.google.firebase.firestore.pipeline.Expr unixMillisToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr unixMillisToTimestamp(String fieldName); + method public final com.google.firebase.firestore.pipeline.Expr unixSecondsToTimestamp(); + method public static final com.google.firebase.firestore.pipeline.Expr unixSecondsToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public static final com.google.firebase.firestore.pipeline.Expr unixSecondsToTimestamp(String fieldName); + method public static final com.google.firebase.firestore.pipeline.Expr vector(com.google.firebase.firestore.VectorValue vector); + method public static final com.google.firebase.firestore.pipeline.Expr vector(double[] vector); + method public final com.google.firebase.firestore.pipeline.Expr vectorLength(); + method public static final com.google.firebase.firestore.pipeline.Expr vectorLength(com.google.firebase.firestore.pipeline.Expr vectorExpression); + method public static final com.google.firebase.firestore.pipeline.Expr vectorLength(String fieldName); + method public static final com.google.firebase.firestore.pipeline.BooleanExpr xor(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + field public static final com.google.firebase.firestore.pipeline.Expr.Companion Companion; + } + + public static final class Expr.Companion { + method public com.google.firebase.firestore.pipeline.Expr add(com.google.firebase.firestore.pipeline.Expr first, com.google.firebase.firestore.pipeline.Expr second); + method public com.google.firebase.firestore.pipeline.Expr add(com.google.firebase.firestore.pipeline.Expr first, Number second); + method public com.google.firebase.firestore.pipeline.Expr add(String numericFieldName, com.google.firebase.firestore.pipeline.Expr second); + method public com.google.firebase.firestore.pipeline.Expr add(String numericFieldName, Number second); + method public com.google.firebase.firestore.pipeline.BooleanExpr and(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + method public com.google.firebase.firestore.pipeline.Expr arrayConcat(com.google.firebase.firestore.pipeline.Expr firstArray, com.google.firebase.firestore.pipeline.Expr secondArray, java.lang.Object... otherArrays); + method public com.google.firebase.firestore.pipeline.Expr arrayConcat(com.google.firebase.firestore.pipeline.Expr firstArray, Object secondArray, java.lang.Object... otherArrays); + method public com.google.firebase.firestore.pipeline.Expr arrayConcat(String firstArrayField, com.google.firebase.firestore.pipeline.Expr secondArray, java.lang.Object... otherArrays); + method public com.google.firebase.firestore.pipeline.Expr arrayConcat(String firstArrayField, Object secondArray, java.lang.Object... otherArrays); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr element); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(com.google.firebase.firestore.pipeline.Expr array, Object element); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr element); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContains(String arrayFieldName, Object element); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(com.google.firebase.firestore.pipeline.Expr array, java.util.List values); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAll(String arrayFieldName, java.util.List values); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(com.google.firebase.firestore.pipeline.Expr array, java.util.List values); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr arrayContainsAny(String arrayFieldName, java.util.List values); + method public com.google.firebase.firestore.pipeline.Expr arrayLength(com.google.firebase.firestore.pipeline.Expr array); + method public com.google.firebase.firestore.pipeline.Expr arrayLength(String arrayFieldName); + method public com.google.firebase.firestore.pipeline.Expr arrayOffset(com.google.firebase.firestore.pipeline.Expr array, com.google.firebase.firestore.pipeline.Expr offset); + method public com.google.firebase.firestore.pipeline.Expr arrayOffset(com.google.firebase.firestore.pipeline.Expr array, int offset); + method public com.google.firebase.firestore.pipeline.Expr arrayOffset(String arrayFieldName, com.google.firebase.firestore.pipeline.Expr offset); + method public com.google.firebase.firestore.pipeline.Expr arrayOffset(String arrayFieldName, int offset); + method public com.google.firebase.firestore.pipeline.Expr arrayReverse(com.google.firebase.firestore.pipeline.Expr array); + method public com.google.firebase.firestore.pipeline.Expr arrayReverse(String arrayFieldName); + method public com.google.firebase.firestore.pipeline.Expr bitAnd(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitAnd(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitAnd(String bitsFieldName, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitAnd(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitLeftShift(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public com.google.firebase.firestore.pipeline.Expr bitLeftShift(com.google.firebase.firestore.pipeline.Expr bits, int number); + method public com.google.firebase.firestore.pipeline.Expr bitLeftShift(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public com.google.firebase.firestore.pipeline.Expr bitLeftShift(String bitsFieldName, int number); + method public com.google.firebase.firestore.pipeline.Expr bitNot(com.google.firebase.firestore.pipeline.Expr bits); + method public com.google.firebase.firestore.pipeline.Expr bitNot(String bitsFieldName); + method public com.google.firebase.firestore.pipeline.Expr bitOr(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitOr(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitOr(String bitsFieldName, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitOr(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitRightShift(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public com.google.firebase.firestore.pipeline.Expr bitRightShift(com.google.firebase.firestore.pipeline.Expr bits, int number); + method public com.google.firebase.firestore.pipeline.Expr bitRightShift(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr numberExpr); + method public com.google.firebase.firestore.pipeline.Expr bitRightShift(String bitsFieldName, int number); + method public com.google.firebase.firestore.pipeline.Expr bitXor(com.google.firebase.firestore.pipeline.Expr bits, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitXor(com.google.firebase.firestore.pipeline.Expr bits, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitXor(String bitsFieldName, byte[] bitsOther); + method public com.google.firebase.firestore.pipeline.Expr bitXor(String bitsFieldName, com.google.firebase.firestore.pipeline.Expr bitsOther); + method public com.google.firebase.firestore.pipeline.Expr byteLength(com.google.firebase.firestore.pipeline.Expr value); + method public com.google.firebase.firestore.pipeline.Expr byteLength(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr ceil(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public com.google.firebase.firestore.pipeline.Expr ceil(String numericField); + method public com.google.firebase.firestore.pipeline.Expr charLength(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr charLength(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr cond(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.Expr thenExpr, com.google.firebase.firestore.pipeline.Expr elseExpr); + method public com.google.firebase.firestore.pipeline.Expr cond(com.google.firebase.firestore.pipeline.BooleanExpr condition, Object thenValue, Object elseValue); + method public com.google.firebase.firestore.pipeline.BooleanExpr constant(boolean value); + method public com.google.firebase.firestore.pipeline.Expr constant(byte[] value); + method public com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.Blob value); + method public com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.DocumentReference ref); + method public com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.GeoPoint value); + method public com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.firestore.VectorValue value); + method public com.google.firebase.firestore.pipeline.Expr constant(com.google.firebase.Timestamp value); + method public com.google.firebase.firestore.pipeline.Expr constant(Number value); + method public com.google.firebase.firestore.pipeline.Expr constant(String value); + method public com.google.firebase.firestore.pipeline.Expr constant(java.util.Date value); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public com.google.firebase.firestore.pipeline.Expr cosineDistance(String vectorFieldName, double[] vector); + method public com.google.firebase.firestore.pipeline.Expr divide(com.google.firebase.firestore.pipeline.Expr dividend, com.google.firebase.firestore.pipeline.Expr divisor); + method public com.google.firebase.firestore.pipeline.Expr divide(com.google.firebase.firestore.pipeline.Expr dividend, Number divisor); + method public com.google.firebase.firestore.pipeline.Expr divide(String dividendFieldName, com.google.firebase.firestore.pipeline.Expr divisor); + method public com.google.firebase.firestore.pipeline.Expr divide(String dividendFieldName, Number divisor); + method public com.google.firebase.firestore.pipeline.Expr documentId(com.google.firebase.firestore.DocumentReference docRef); + method public com.google.firebase.firestore.pipeline.Expr documentId(com.google.firebase.firestore.pipeline.Expr documentPath); + method public com.google.firebase.firestore.pipeline.Expr documentId(String documentPath); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public com.google.firebase.firestore.pipeline.Expr dotProduct(String vectorFieldName, double[] vector); + method public com.google.firebase.firestore.pipeline.BooleanExpr endsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, com.google.firebase.firestore.pipeline.Expr suffix); + method public com.google.firebase.firestore.pipeline.BooleanExpr endsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, String suffix); + method public com.google.firebase.firestore.pipeline.BooleanExpr endsWith(String fieldName, com.google.firebase.firestore.pipeline.Expr suffix); + method public com.google.firebase.firestore.pipeline.BooleanExpr endsWith(String fieldName, String suffix); + method public com.google.firebase.firestore.pipeline.BooleanExpr eq(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr eq(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr eq(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr eq(String fieldName, Object value); + method public com.google.firebase.firestore.pipeline.BooleanExpr eqAny(com.google.firebase.firestore.pipeline.Expr expression, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr eqAny(com.google.firebase.firestore.pipeline.Expr expression, java.util.List values); + method public com.google.firebase.firestore.pipeline.BooleanExpr eqAny(String fieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr eqAny(String fieldName, java.util.List values); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.pipeline.Expr vector2); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, com.google.firebase.firestore.VectorValue vector2); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(com.google.firebase.firestore.pipeline.Expr vector1, double[] vector2); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, com.google.firebase.firestore.pipeline.Expr vector); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, com.google.firebase.firestore.VectorValue vector); + method public com.google.firebase.firestore.pipeline.Expr euclideanDistance(String vectorFieldName, double[] vector); + method public com.google.firebase.firestore.pipeline.BooleanExpr exists(com.google.firebase.firestore.pipeline.Expr value); + method public com.google.firebase.firestore.pipeline.BooleanExpr exists(String fieldName); + method public com.google.firebase.firestore.pipeline.Field field(com.google.firebase.firestore.FieldPath fieldPath); + method public com.google.firebase.firestore.pipeline.Field field(String name); + method public com.google.firebase.firestore.pipeline.Expr floor(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public com.google.firebase.firestore.pipeline.Expr floor(String numericField); + method public com.google.firebase.firestore.pipeline.Expr generic(String name, com.google.firebase.firestore.pipeline.Expr... expr); + method public com.google.firebase.firestore.pipeline.BooleanExpr gt(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr gt(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr gt(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr gt(String fieldName, Object value); + method public com.google.firebase.firestore.pipeline.BooleanExpr gte(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr gte(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr gte(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr gte(String fieldName, Object value); + method public com.google.firebase.firestore.pipeline.BooleanExpr ifError(com.google.firebase.firestore.pipeline.BooleanExpr tryExpr, com.google.firebase.firestore.pipeline.BooleanExpr catchExpr); + method public com.google.firebase.firestore.pipeline.Expr ifError(com.google.firebase.firestore.pipeline.Expr tryExpr, com.google.firebase.firestore.pipeline.Expr catchExpr); + method public com.google.firebase.firestore.pipeline.Expr ifError(com.google.firebase.firestore.pipeline.Expr tryExpr, Object catchValue); + method public com.google.firebase.firestore.pipeline.BooleanExpr isAbsent(com.google.firebase.firestore.pipeline.Expr value); + method public com.google.firebase.firestore.pipeline.BooleanExpr isAbsent(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNan(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNan(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNotNan(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNotNan(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNotNull(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNotNull(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNull(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.BooleanExpr isNull(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr like(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr like(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr like(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr like(String fieldName, String pattern); + method public com.google.firebase.firestore.pipeline.Expr logicalMaximum(com.google.firebase.firestore.pipeline.Expr expr, java.lang.Object... others); + method public com.google.firebase.firestore.pipeline.Expr logicalMaximum(String fieldName, java.lang.Object... others); + method public com.google.firebase.firestore.pipeline.Expr logicalMinimum(com.google.firebase.firestore.pipeline.Expr expr, java.lang.Object... others); + method public com.google.firebase.firestore.pipeline.Expr logicalMinimum(String fieldName, java.lang.Object... others); + method public com.google.firebase.firestore.pipeline.BooleanExpr lt(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr lt(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr lt(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr lt(String fieldName, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr lte(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr lte(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr lte(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr lte(String fieldName, Object value); + method public com.google.firebase.firestore.pipeline.Expr map(java.util.Map elements); + method public com.google.firebase.firestore.pipeline.Expr mapGet(com.google.firebase.firestore.pipeline.Expr mapExpression, String key); + method public com.google.firebase.firestore.pipeline.Expr mapGet(String fieldName, String key); + method public com.google.firebase.firestore.pipeline.Expr mapMerge(com.google.firebase.firestore.pipeline.Expr firstMap, com.google.firebase.firestore.pipeline.Expr secondMap, com.google.firebase.firestore.pipeline.Expr... otherMaps); + method public com.google.firebase.firestore.pipeline.Expr mapMerge(String firstMapFieldName, com.google.firebase.firestore.pipeline.Expr secondMap, com.google.firebase.firestore.pipeline.Expr... otherMaps); + method public com.google.firebase.firestore.pipeline.Expr mapRemove(com.google.firebase.firestore.pipeline.Expr mapExpr, com.google.firebase.firestore.pipeline.Expr key); + method public com.google.firebase.firestore.pipeline.Expr mapRemove(com.google.firebase.firestore.pipeline.Expr mapExpr, String key); + method public com.google.firebase.firestore.pipeline.Expr mapRemove(String mapField, com.google.firebase.firestore.pipeline.Expr key); + method public com.google.firebase.firestore.pipeline.Expr mapRemove(String mapField, String key); + method public com.google.firebase.firestore.pipeline.Expr mod(com.google.firebase.firestore.pipeline.Expr dividend, com.google.firebase.firestore.pipeline.Expr divisor); + method public com.google.firebase.firestore.pipeline.Expr mod(com.google.firebase.firestore.pipeline.Expr dividend, Number divisor); + method public com.google.firebase.firestore.pipeline.Expr mod(String dividendFieldName, com.google.firebase.firestore.pipeline.Expr divisor); + method public com.google.firebase.firestore.pipeline.Expr mod(String dividendFieldName, Number divisor); + method public com.google.firebase.firestore.pipeline.Expr multiply(com.google.firebase.firestore.pipeline.Expr first, com.google.firebase.firestore.pipeline.Expr second); + method public com.google.firebase.firestore.pipeline.Expr multiply(com.google.firebase.firestore.pipeline.Expr first, Number second); + method public com.google.firebase.firestore.pipeline.Expr multiply(String numericFieldName, com.google.firebase.firestore.pipeline.Expr second); + method public com.google.firebase.firestore.pipeline.Expr multiply(String numericFieldName, Number second); + method public com.google.firebase.firestore.pipeline.BooleanExpr neq(com.google.firebase.firestore.pipeline.Expr left, com.google.firebase.firestore.pipeline.Expr right); + method public com.google.firebase.firestore.pipeline.BooleanExpr neq(com.google.firebase.firestore.pipeline.Expr left, Object right); + method public com.google.firebase.firestore.pipeline.BooleanExpr neq(String fieldName, com.google.firebase.firestore.pipeline.Expr expression); + method public com.google.firebase.firestore.pipeline.BooleanExpr neq(String fieldName, Object value); + method public com.google.firebase.firestore.pipeline.BooleanExpr not(com.google.firebase.firestore.pipeline.BooleanExpr condition); + method public com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(com.google.firebase.firestore.pipeline.Expr expression, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(com.google.firebase.firestore.pipeline.Expr expression, java.util.List values); + method public com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(String fieldName, com.google.firebase.firestore.pipeline.Expr arrayExpression); + method public com.google.firebase.firestore.pipeline.BooleanExpr notEqAny(String fieldName, java.util.List values); + method public com.google.firebase.firestore.pipeline.Expr nullValue(); + method public com.google.firebase.firestore.pipeline.BooleanExpr or(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + method public com.google.firebase.firestore.pipeline.Expr pow(com.google.firebase.firestore.pipeline.Expr numericExpr, com.google.firebase.firestore.pipeline.Expr exponent); + method public com.google.firebase.firestore.pipeline.Expr pow(com.google.firebase.firestore.pipeline.Expr numericExpr, Number exponent); + method public com.google.firebase.firestore.pipeline.Expr pow(String numericField, com.google.firebase.firestore.pipeline.Expr exponent); + method public com.google.firebase.firestore.pipeline.Expr pow(String numericField, Number exponent); + method public com.google.firebase.firestore.pipeline.Expr rand(); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexContains(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexContains(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexContains(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexContains(String fieldName, String pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(com.google.firebase.firestore.pipeline.Expr stringExpression, String pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(String fieldName, com.google.firebase.firestore.pipeline.Expr pattern); + method public com.google.firebase.firestore.pipeline.BooleanExpr regexMatch(String fieldName, String pattern); + method public com.google.firebase.firestore.pipeline.Expr replaceAll(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public com.google.firebase.firestore.pipeline.Expr replaceAll(com.google.firebase.firestore.pipeline.Expr stringExpression, String find, String replace); + method public com.google.firebase.firestore.pipeline.Expr replaceAll(String fieldName, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public com.google.firebase.firestore.pipeline.Expr replaceAll(String fieldName, String find, String replace); + method public com.google.firebase.firestore.pipeline.Expr replaceFirst(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public com.google.firebase.firestore.pipeline.Expr replaceFirst(com.google.firebase.firestore.pipeline.Expr stringExpression, String find, String replace); + method public com.google.firebase.firestore.pipeline.Expr replaceFirst(String fieldName, com.google.firebase.firestore.pipeline.Expr find, com.google.firebase.firestore.pipeline.Expr replace); + method public com.google.firebase.firestore.pipeline.Expr replaceFirst(String fieldName, String find, String replace); + method public com.google.firebase.firestore.pipeline.Expr reverse(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public com.google.firebase.firestore.pipeline.Expr reverse(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr round(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public com.google.firebase.firestore.pipeline.Expr round(String numericField); + method public com.google.firebase.firestore.pipeline.Expr roundToPrecision(com.google.firebase.firestore.pipeline.Expr numericExpr, com.google.firebase.firestore.pipeline.Expr decimalPlace); + method public com.google.firebase.firestore.pipeline.Expr roundToPrecision(com.google.firebase.firestore.pipeline.Expr numericExpr, int decimalPlace); + method public com.google.firebase.firestore.pipeline.Expr roundToPrecision(String numericField, com.google.firebase.firestore.pipeline.Expr decimalPlace); + method public com.google.firebase.firestore.pipeline.Expr roundToPrecision(String numericField, int decimalPlace); + method public com.google.firebase.firestore.pipeline.Expr sqrt(com.google.firebase.firestore.pipeline.Expr numericExpr); + method public com.google.firebase.firestore.pipeline.Expr sqrt(String numericField); + method public com.google.firebase.firestore.pipeline.BooleanExpr startsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, com.google.firebase.firestore.pipeline.Expr prefix); + method public com.google.firebase.firestore.pipeline.BooleanExpr startsWith(com.google.firebase.firestore.pipeline.Expr stringExpr, String prefix); + method public com.google.firebase.firestore.pipeline.BooleanExpr startsWith(String fieldName, com.google.firebase.firestore.pipeline.Expr prefix); + method public com.google.firebase.firestore.pipeline.BooleanExpr startsWith(String fieldName, String prefix); + method public com.google.firebase.firestore.pipeline.Expr strConcat(com.google.firebase.firestore.pipeline.Expr firstString, com.google.firebase.firestore.pipeline.Expr... otherStrings); + method public com.google.firebase.firestore.pipeline.Expr strConcat(com.google.firebase.firestore.pipeline.Expr firstString, java.lang.Object... otherStrings); + method public com.google.firebase.firestore.pipeline.Expr strConcat(String fieldName, com.google.firebase.firestore.pipeline.Expr... otherStrings); + method public com.google.firebase.firestore.pipeline.Expr strConcat(String fieldName, java.lang.Object... otherStrings); + method public com.google.firebase.firestore.pipeline.BooleanExpr strContains(com.google.firebase.firestore.pipeline.Expr stringExpression, com.google.firebase.firestore.pipeline.Expr substring); + method public com.google.firebase.firestore.pipeline.BooleanExpr strContains(com.google.firebase.firestore.pipeline.Expr stringExpression, String substring); + method public com.google.firebase.firestore.pipeline.BooleanExpr strContains(String fieldName, com.google.firebase.firestore.pipeline.Expr substring); + method public com.google.firebase.firestore.pipeline.BooleanExpr strContains(String fieldName, String substring); + method public com.google.firebase.firestore.pipeline.Expr subtract(com.google.firebase.firestore.pipeline.Expr minuend, com.google.firebase.firestore.pipeline.Expr subtrahend); + method public com.google.firebase.firestore.pipeline.Expr subtract(com.google.firebase.firestore.pipeline.Expr minuend, Number subtrahend); + method public com.google.firebase.firestore.pipeline.Expr subtract(String numericFieldName, com.google.firebase.firestore.pipeline.Expr subtrahend); + method public com.google.firebase.firestore.pipeline.Expr subtract(String numericFieldName, Number subtrahend); + method public com.google.firebase.firestore.pipeline.Expr timestampAdd(com.google.firebase.firestore.pipeline.Expr timestamp, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public com.google.firebase.firestore.pipeline.Expr timestampAdd(com.google.firebase.firestore.pipeline.Expr timestamp, String unit, double amount); + method public com.google.firebase.firestore.pipeline.Expr timestampAdd(String fieldName, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public com.google.firebase.firestore.pipeline.Expr timestampAdd(String fieldName, String unit, double amount); + method public com.google.firebase.firestore.pipeline.Expr timestampSub(com.google.firebase.firestore.pipeline.Expr timestamp, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public com.google.firebase.firestore.pipeline.Expr timestampSub(com.google.firebase.firestore.pipeline.Expr timestamp, String unit, double amount); + method public com.google.firebase.firestore.pipeline.Expr timestampSub(String fieldName, com.google.firebase.firestore.pipeline.Expr unit, com.google.firebase.firestore.pipeline.Expr amount); + method public com.google.firebase.firestore.pipeline.Expr timestampSub(String fieldName, String unit, double amount); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixMicros(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixMicros(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixMillis(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixMillis(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixSeconds(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr timestampToUnixSeconds(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr toLower(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public com.google.firebase.firestore.pipeline.Expr toLower(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr toUpper(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public com.google.firebase.firestore.pipeline.Expr toUpper(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr trim(com.google.firebase.firestore.pipeline.Expr stringExpression); + method public com.google.firebase.firestore.pipeline.Expr trim(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr unixMicrosToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr unixMicrosToTimestamp(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr unixMillisToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr unixMillisToTimestamp(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr unixSecondsToTimestamp(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Expr unixSecondsToTimestamp(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr vector(com.google.firebase.firestore.VectorValue vector); + method public com.google.firebase.firestore.pipeline.Expr vector(double[] vector); + method public com.google.firebase.firestore.pipeline.Expr vectorLength(com.google.firebase.firestore.pipeline.Expr vectorExpression); + method public com.google.firebase.firestore.pipeline.Expr vectorLength(String fieldName); + method public com.google.firebase.firestore.pipeline.BooleanExpr xor(com.google.firebase.firestore.pipeline.BooleanExpr condition, com.google.firebase.firestore.pipeline.BooleanExpr... conditions); + } + + public final class ExprWithAlias extends com.google.firebase.firestore.pipeline.Selectable { + } + + public final class Field extends com.google.firebase.firestore.pipeline.Selectable { + field public static final com.google.firebase.firestore.pipeline.Field.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.Field DOCUMENT_ID; + } + + public static final class Field.Companion { + } + + public final class FindNearestStage extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.FindNearestStage of(com.google.firebase.firestore.pipeline.Field vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public static com.google.firebase.firestore.pipeline.FindNearestStage of(com.google.firebase.firestore.pipeline.Field vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public static com.google.firebase.firestore.pipeline.FindNearestStage of(String vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public static com.google.firebase.firestore.pipeline.FindNearestStage of(String vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.pipeline.FindNearestStage withDistanceField(com.google.firebase.firestore.pipeline.Field distanceField); + method public com.google.firebase.firestore.pipeline.FindNearestStage withDistanceField(String distanceField); + method public com.google.firebase.firestore.pipeline.FindNearestStage withLimit(long limit); + field public static final com.google.firebase.firestore.pipeline.FindNearestStage.Companion Companion; + } + + public static final class FindNearestStage.Companion { + method public com.google.firebase.firestore.pipeline.FindNearestStage of(com.google.firebase.firestore.pipeline.Field vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.pipeline.FindNearestStage of(com.google.firebase.firestore.pipeline.Field vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.pipeline.FindNearestStage of(String vectorField, com.google.firebase.firestore.VectorValue vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + method public com.google.firebase.firestore.pipeline.FindNearestStage of(String vectorField, double[] vectorValue, com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure distanceMeasure); + } + + public static final class FindNearestStage.DistanceMeasure { + field public static final error.NonExistentClass COSINE; + field public static final com.google.firebase.firestore.pipeline.FindNearestStage.DistanceMeasure.Companion Companion; + field public static final error.NonExistentClass DOT_PRODUCT; + field public static final error.NonExistentClass EUCLIDEAN; + } + + public static final class FindNearestStage.DistanceMeasure.Companion { + } + + public class FunctionExpr extends com.google.firebase.firestore.pipeline.Expr { + } + + public final class GenericOptions extends com.google.firebase.firestore.pipeline.AbstractOptions { + field public static final com.google.firebase.firestore.pipeline.GenericOptions.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.GenericOptions DEFAULT; + } + + public static final class GenericOptions.Companion { + } + + public final class InternalOptions { + field public static final com.google.firebase.firestore.pipeline.InternalOptions.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.InternalOptions EMPTY; + } + + public static final class InternalOptions.Companion { + method public com.google.firebase.firestore.pipeline.InternalOptions of(String key, error.NonExistentClass value); + } + + public final class Ordering { + method public static com.google.firebase.firestore.pipeline.Ordering ascending(com.google.firebase.firestore.pipeline.Expr expr); + method public static com.google.firebase.firestore.pipeline.Ordering ascending(String fieldName); + method public static com.google.firebase.firestore.pipeline.Ordering descending(com.google.firebase.firestore.pipeline.Expr expr); + method public static com.google.firebase.firestore.pipeline.Ordering descending(String fieldName); + method public com.google.firebase.firestore.pipeline.Expr getExpr(); + method public com.google.firebase.firestore.pipeline.Ordering reverse(); + property public final com.google.firebase.firestore.pipeline.Expr expr; + field public static final com.google.firebase.firestore.pipeline.Ordering.Companion Companion; + } + + public static final class Ordering.Companion { + method public com.google.firebase.firestore.pipeline.Ordering ascending(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Ordering ascending(String fieldName); + method public com.google.firebase.firestore.pipeline.Ordering descending(com.google.firebase.firestore.pipeline.Expr expr); + method public com.google.firebase.firestore.pipeline.Ordering descending(String fieldName); + } + + public final class PipelineOptions extends com.google.firebase.firestore.pipeline.AbstractOptions { + method public com.google.firebase.firestore.pipeline.PipelineOptions withExplainOptions(com.google.firebase.firestore.pipeline.ExplainOptions options); + method public com.google.firebase.firestore.pipeline.PipelineOptions withIndexMode(com.google.firebase.firestore.pipeline.PipelineOptions.IndexMode indexMode); + field public static final com.google.firebase.firestore.pipeline.PipelineOptions.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.PipelineOptions DEFAULT; + } + + public static final class PipelineOptions.Companion { + } + + public static final class PipelineOptions.IndexMode { + field public static final com.google.firebase.firestore.pipeline.PipelineOptions.IndexMode.Companion Companion; + field public static final com.google.firebase.firestore.pipeline.PipelineOptions.IndexMode RECOMMENDED; + } + + public static final class PipelineOptions.IndexMode.Companion { + } + + public final class SampleStage extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.SampleStage withDocLimit(int documents); + method public static com.google.firebase.firestore.pipeline.SampleStage withPercentage(double percentage); + field public static final com.google.firebase.firestore.pipeline.SampleStage.Companion Companion; + } + + public static final class SampleStage.Companion { + method public com.google.firebase.firestore.pipeline.SampleStage withDocLimit(int documents); + method public com.google.firebase.firestore.pipeline.SampleStage withPercentage(double percentage); + } + + public static final class SampleStage.Mode { + field public static final com.google.firebase.firestore.pipeline.SampleStage.Mode.Companion Companion; + } + + public static final class SampleStage.Mode.Companion { + method public error.NonExistentClass getDOCUMENTS(); + method public error.NonExistentClass getPERCENT(); + property public final error.NonExistentClass DOCUMENTS; + property public final error.NonExistentClass PERCENT; + } + + public abstract class Selectable extends com.google.firebase.firestore.pipeline.Expr { + ctor public Selectable(); + } + + public final class Stage extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.Stage ofName(String name); + method public com.google.firebase.firestore.pipeline.Stage withArguments(java.lang.Object... arguments); + field public static final com.google.firebase.firestore.pipeline.Stage.Companion Companion; + } + + public static final class Stage.Companion { + method public com.google.firebase.firestore.pipeline.Stage ofName(String name); + } + + public final class UnnestStage extends com.google.firebase.firestore.pipeline.BaseStage { + method public static com.google.firebase.firestore.pipeline.UnnestStage withField(com.google.firebase.firestore.pipeline.Selectable arrayWithAlias); + method public static com.google.firebase.firestore.pipeline.UnnestStage withField(String arrayField, String alias); + method public com.google.firebase.firestore.pipeline.UnnestStage withIndexField(String indexField); + field public static final com.google.firebase.firestore.pipeline.UnnestStage.Companion Companion; + } + + public static final class UnnestStage.Companion { + method public com.google.firebase.firestore.pipeline.UnnestStage withField(com.google.firebase.firestore.pipeline.Selectable arrayWithAlias); + method public com.google.firebase.firestore.pipeline.UnnestStage withField(String arrayField, String alias); + } + +} + diff --git a/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/PipelineTest.java b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/PipelineTest.java new file mode 100644 index 00000000000..5c9e26f5acb --- /dev/null +++ b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/PipelineTest.java @@ -0,0 +1,901 @@ +// Copyright 2025 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.firebase.firestore; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.firebase.firestore.pipeline.Expr.add; +import static com.google.firebase.firestore.pipeline.Expr.and; +import static com.google.firebase.firestore.pipeline.Expr.arrayContains; +import static com.google.firebase.firestore.pipeline.Expr.arrayContainsAny; +import static com.google.firebase.firestore.pipeline.Expr.cosineDistance; +import static com.google.firebase.firestore.pipeline.Expr.endsWith; +import static com.google.firebase.firestore.pipeline.Expr.eq; +import static com.google.firebase.firestore.pipeline.Expr.euclideanDistance; +import static com.google.firebase.firestore.pipeline.Expr.field; +import static com.google.firebase.firestore.pipeline.Expr.gt; +import static com.google.firebase.firestore.pipeline.Expr.logicalMaximum; +import static com.google.firebase.firestore.pipeline.Expr.lt; +import static com.google.firebase.firestore.pipeline.Expr.lte; +import static com.google.firebase.firestore.pipeline.Expr.mapGet; +import static com.google.firebase.firestore.pipeline.Expr.neq; +import static com.google.firebase.firestore.pipeline.Expr.not; +import static com.google.firebase.firestore.pipeline.Expr.or; +import static com.google.firebase.firestore.pipeline.Expr.startsWith; +import static com.google.firebase.firestore.pipeline.Expr.strConcat; +import static com.google.firebase.firestore.pipeline.Expr.subtract; +import static com.google.firebase.firestore.pipeline.Expr.vector; +import static com.google.firebase.firestore.pipeline.Ordering.ascending; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.waitFor; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.google.android.gms.tasks.Task; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.truth.Correspondence; +import com.google.firebase.firestore.pipeline.AggregateFunction; +import com.google.firebase.firestore.pipeline.AggregateStage; +import com.google.firebase.firestore.pipeline.Expr; +import com.google.firebase.firestore.pipeline.Stage; +import com.google.firebase.firestore.testutil.IntegrationTestUtil; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class PipelineTest { + + private static final Correspondence> DATA_CORRESPONDENCE = + Correspondence.from( + (result, expected) -> { + assertThat(result.getData()) + .comparingValuesUsing( + Correspondence.from( + (x, y) -> { + if (x instanceof Long && y instanceof Integer) { + return (long) x == (long) (int) y; + } + if (x instanceof Double && y instanceof Integer) { + return (double) x == (double) (int) y; + } + return Objects.equals(x, y); + }, + "MapValueCompare")) + .containsExactlyEntriesIn(expected); + return true; + }, + "GetData"); + + private static final Correspondence ID_CORRESPONDENCE = + Correspondence.transforming(x -> x.getRef().getId(), "GetRefId"); + + private CollectionReference randomCol; + private FirebaseFirestore firestore; + + @After + public void tearDown() { + IntegrationTestUtil.tearDown(); + } + + private final Map> bookDocs = + mapOfEntries( + entry( + "book1", + mapOfEntries( + entry("title", "The Hitchhiker's Guide to the Galaxy"), + entry("author", "Douglas Adams"), + entry("genre", "Science Fiction"), + entry("published", 1979), + entry("rating", 4.2), + entry("tags", ImmutableList.of("comedy", "space", "adventure")), + entry("awards", ImmutableMap.of("hugo", true, "nebula", false)), + entry( + "nestedField", + ImmutableMap.of("level.1", ImmutableMap.of("level.2", true))))), + entry( + "book2", + mapOfEntries( + entry("title", "Pride and Prejudice"), + entry("author", "Jane Austen"), + entry("genre", "Romance"), + entry("published", 1813), + entry("rating", 4.5), + entry("tags", ImmutableList.of("classic", "social commentary", "love")), + entry("awards", ImmutableMap.of("none", true)))), + entry( + "book3", + mapOfEntries( + entry("title", "One Hundred Years of Solitude"), + entry("author", "Gabriel García Márquez"), + entry("genre", "Magical Realism"), + entry("published", 1967), + entry("rating", 4.3), + entry("tags", ImmutableList.of("family", "history", "fantasy")), + entry("awards", ImmutableMap.of("nobel", true, "nebula", false)))), + entry( + "book4", + mapOfEntries( + entry("title", "The Lord of the Rings"), + entry("author", "J.R.R. Tolkien"), + entry("genre", "Fantasy"), + entry("published", 1954), + entry("rating", 4.7), + entry("tags", ImmutableList.of("adventure", "magic", "epic")), + entry("awards", ImmutableMap.of("hugo", false, "nebula", false)))), + entry( + "book5", + mapOfEntries( + entry("title", "The Handmaid's Tale"), + entry("author", "Margaret Atwood"), + entry("genre", "Dystopian"), + entry("published", 1985), + entry("rating", 4.1), + entry("tags", ImmutableList.of("feminism", "totalitarianism", "resistance")), + entry( + "awards", ImmutableMap.of("arthur c. clarke", true, "booker prize", false)))), + entry( + "book6", + mapOfEntries( + entry("title", "Crime and Punishment"), + entry("author", "Fyodor Dostoevsky"), + entry("genre", "Psychological Thriller"), + entry("published", 1866), + entry("rating", 4.3), + entry("tags", ImmutableList.of("philosophy", "crime", "redemption")), + entry("awards", ImmutableMap.of("none", true)))), + entry( + "book7", + mapOfEntries( + entry("title", "To Kill a Mockingbird"), + entry("author", "Harper Lee"), + entry("genre", "Southern Gothic"), + entry("published", 1960), + entry("rating", 4.2), + entry("tags", ImmutableList.of("racism", "injustice", "coming-of-age")), + entry("awards", ImmutableMap.of("pulitzer", true)))), + entry( + "book8", + mapOfEntries( + entry("title", "1984"), + entry("author", "George Orwell"), + entry("genre", "Dystopian"), + entry("published", 1949), + entry("rating", 4.2), + entry("tags", ImmutableList.of("surveillance", "totalitarianism", "propaganda")), + entry("awards", ImmutableMap.of("prometheus", true)))), + entry( + "book9", + mapOfEntries( + entry("title", "The Great Gatsby"), + entry("author", "F. Scott Fitzgerald"), + entry("genre", "Modernist"), + entry("published", 1925), + entry("rating", 4.0), + entry("tags", ImmutableList.of("wealth", "american dream", "love")), + entry("awards", ImmutableMap.of("none", true)))), + entry( + "book10", + mapOfEntries( + entry("title", "Dune"), + entry("author", "Frank Herbert"), + entry("genre", "Science Fiction"), + entry("published", 1965), + entry("rating", 4.6), + entry("tags", ImmutableList.of("politics", "desert", "ecology")), + entry("awards", ImmutableMap.of("hugo", true, "nebula", true))))); + + @Before + public void setup() { + randomCol = IntegrationTestUtil.testCollectionWithDocs(bookDocs); + firestore = randomCol.firestore; + } + + @Test + public void emptyResults() { + Task execute = + firestore.pipeline().collection(randomCol.getPath()).limit(0).execute(); + assertThat(waitFor(execute).getResults()).isEmpty(); + } + + @Test + public void fullResults() { + Task execute = firestore.pipeline().collection(randomCol.getPath()).execute(); + assertThat(waitFor(execute).getResults()).hasSize(10); + } + + @Test + public void aggregateResultsCountAll() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .aggregate(AggregateFunction.countAll().alias("count")) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("count", 10)); + } + + @Test + @Ignore("Not supported yet") + public void aggregateResultsMany() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("genre", "Science Fiction")) + .aggregate( + AggregateFunction.countAll().alias("count"), + AggregateFunction.avg("rating").alias("avgRating"), + field("rating").maximum().alias("maxRating")) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries(entry("count", 10), entry("avgRating", 4.4), entry("maxRating", 4.6))); + } + + @Test + public void groupAndAccumulateResults() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(lt(field("published"), 1984)) + .aggregate( + AggregateStage.withAccumulators(AggregateFunction.avg("rating").alias("avgRating")) + .withGroups("genre")) + .where(gt("avgRating", 4.3)) + .sort(field("avgRating").descending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries(entry("avgRating", 4.7), entry("genre", "Fantasy")), + mapOfEntries(entry("avgRating", 4.5), entry("genre", "Romance")), + mapOfEntries(entry("avgRating", 4.4), entry("genre", "Science Fiction"))); + } + + @Test + public void groupAndAccumulateResultsGeneric() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .addStage(Stage.ofName("where").withArguments(lt(field("published"), 1984))) + .addStage( + Stage.ofName("aggregate") + .withArguments( + ImmutableMap.of("avgRating", AggregateFunction.avg("rating")), + ImmutableMap.of("genre", field("genre")))) + .addStage(Stage.ofName("where").withArguments(gt("avgRating", 4.3))) + .addStage( + Stage.ofName("sort").withArguments(field("avgRating").descending())) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries(entry("avgRating", 4.7), entry("genre", "Fantasy")), + mapOfEntries(entry("avgRating", 4.5), entry("genre", "Romance")), + mapOfEntries(entry("avgRating", 4.4), entry("genre", "Science Fiction"))); + } + + @Test + @Ignore("Not supported yet") + public void minAndMaxAccumulations() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .aggregate( + AggregateFunction.countAll().alias("count"), + field("rating").maximum().alias("maxRating"), + field("published").minimum().alias("minPublished")) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries(entry("count", 10), entry("maxRating", 4.7), entry("minPublished", 1813))); + } + + @Test + public void canSelectFields() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select("title", "author") + .sort(field("author").ascending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries( + entry("title", "The Hitchhiker's Guide to the Galaxy"), + entry("author", "Douglas Adams")), + mapOfEntries( + entry("title", "The Great Gatsby"), entry("author", "F. Scott Fitzgerald")), + mapOfEntries(entry("title", "Dune"), entry("author", "Frank Herbert")), + mapOfEntries( + entry("title", "Crime and Punishment"), entry("author", "Fyodor Dostoevsky")), + mapOfEntries( + entry("title", "One Hundred Years of Solitude"), + entry("author", "Gabriel García Márquez")), + mapOfEntries(entry("title", "1984"), entry("author", "George Orwell")), + mapOfEntries(entry("title", "To Kill a Mockingbird"), entry("author", "Harper Lee")), + mapOfEntries( + entry("title", "The Lord of the Rings"), entry("author", "J.R.R. Tolkien")), + mapOfEntries(entry("title", "Pride and Prejudice"), entry("author", "Jane Austen")), + mapOfEntries(entry("title", "The Handmaid's Tale"), entry("author", "Margaret Atwood"))) + .inOrder(); + } + + @Test + public void whereWithAnd() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(and(gt("rating", 4.5), eq("genre", "Science Fiction"))) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(ID_CORRESPONDENCE) + .containsExactly("book10"); + } + + @Test + public void whereWithOr() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(or(eq("genre", "Romance"), eq("genre", "Dystopian"))) + .select("title") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "Pride and Prejudice"), + ImmutableMap.of("title", "The Handmaid's Tale"), + ImmutableMap.of("title", "1984")); + } + + @Test + public void offsetAndLimits() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .sort(ascending("author")) + .offset(5) + .limit(3) + .select("title", "author") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries(entry("title", "1984"), entry("author", "George Orwell")), + mapOfEntries(entry("title", "To Kill a Mockingbird"), entry("author", "Harper Lee")), + mapOfEntries( + entry("title", "The Lord of the Rings"), entry("author", "J.R.R. Tolkien"))); + } + + @Test + public void arrayContainsWorks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(arrayContains("tags", "comedy")) + .select("title") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy")); + } + + @Test + public void arrayContainsAnyWorks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(arrayContainsAny("tags", ImmutableList.of("comedy", "classic"))) + .select("title") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy"), + ImmutableMap.of("title", "Pride and Prejudice")); + } + + @Test + public void arrayContainsAllWorks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(field("tags").arrayContainsAll(ImmutableList.of("adventure", "magic"))) + .select("title") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("title", "The Lord of the Rings")); + } + + @Test + public void arrayLengthWorks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("tags").arrayLength().alias("tagsCount")) + .where(eq("tagsCount", 3)) + .execute(); + assertThat(waitFor(execute).getResults()).hasSize(10); + } + + @Test + @Ignore("Not supported yet") + public void arrayConcatWorks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("title", "The Hitchhiker's Guide to the Galaxy")) + .select( + field("tags") + .arrayConcat(ImmutableList.of("newTag1", "newTag2")) + .alias("modifiedTags")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of( + "modifiedTags", + ImmutableList.of("comedy", "space", "adventure", "newTag1", "newTag2"))); + } + + @Test + public void testStrConcat() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("author").strConcat(" - ", field("title")).alias("bookInfo")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("bookInfo", "Douglas Adams - The Hitchhiker's Guide to the Galaxy")); + } + + @Test + public void testStartsWith() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(startsWith("title", "The")) + .select("title") + .sort(field("title").ascending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "The Great Gatsby"), + ImmutableMap.of("title", "The Handmaid's Tale"), + ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy"), + ImmutableMap.of("title", "The Lord of the Rings")); + } + + @Test + public void testEndsWith() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(endsWith("title", "y")) + .select("title") + .sort(field("title").descending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy"), + ImmutableMap.of("title", "The Great Gatsby")); + } + + @Test + public void testLength() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("title").charLength().alias("titleLength"), field("title")) + .where(gt("titleLength", 20)) + .sort(field("title").ascending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("titleLength", 29, "title", "One Hundred Years of Solitude"), + ImmutableMap.of("titleLength", 36, "title", "The Hitchhiker's Guide to the Galaxy"), + ImmutableMap.of("titleLength", 21, "title", "The Lord of the Rings"), + ImmutableMap.of("titleLength", 21, "title", "To Kill a Mockingbird")); + } + + @Test + @Ignore("Not supported yet") + public void testToLowercase() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("title").toLower().alias("lowercaseTitle")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("lowercaseTitle", "the hitchhiker's guide to the galaxy")); + } + + @Test + @Ignore("Not supported yet") + public void testToUppercase() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("author").toLower().alias("uppercaseAuthor")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("uppercaseAuthor", "DOUGLAS ADAMS")); + } + + @Test + @Ignore("Not supported yet") + public void testTrim() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .addFields(strConcat(" ", field("title"), " ").alias("spacedTitle")) + .select(field("spacedTitle").trim().alias("trimmedTitle")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of( + "spacedTitle", + " The Hitchhiker's Guide to the Galaxy ", + "trimmedTitle", + "The Hitchhiker's Guide to the Galaxy")); + } + + @Test + public void testLike() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(Expr.like("title", "%Guide%")) + .select("title") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy")); + } + + @Test + public void testRegexContains() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(Expr.regexContains("title", "(?i)(the|of)")) + .execute(); + assertThat(waitFor(execute).getResults()).hasSize(5); + } + + @Test + public void testRegexMatches() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(Expr.regexContains("title", ".*(?i)(the|of).*")) + .execute(); + assertThat(waitFor(execute).getResults()).hasSize(5); + } + + @Test + public void testArithmeticOperations() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select( + add(field("rating"), 1).alias("ratingPlusOne"), + subtract(field("published"), 1900).alias("yearsSince1900"), + field("rating").multiply(10).alias("ratingTimesTen"), + field("rating").divide(2).alias("ratingDividedByTwo")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries( + entry("ratingPlusOne", 5.2), + entry("yearsSince1900", 79), + entry("ratingTimesTen", 42), + entry("ratingDividedByTwo", 2.1))); + } + + @Test + public void testComparisonOperators() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where( + and(gt("rating", 4.2), lte(field("rating"), 4.5), neq("genre", "Science Function"))) + .select("rating", "title") + .sort(field("title").ascending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("rating", 4.3, "title", "Crime and Punishment"), + ImmutableMap.of("rating", 4.3, "title", "One Hundred Years of Solitude"), + ImmutableMap.of("rating", 4.5, "title", "Pride and Prejudice")); + } + + @Test + public void testLogicalOperators() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where( + or( + and(gt("rating", 4.5), eq("genre", "Science Fiction")), + lt(field("published"), 1900))) + .select("title") + .sort(field("title").ascending()) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "Crime and Punishment"), + ImmutableMap.of("title", "Dune"), + ImmutableMap.of("title", "Pride and Prejudice")); + } + + @Test + public void testChecks() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(not(field("rating").isNan())) + .select( + field("rating").isNull().alias("ratingIsNull"), + field("rating").eq(Expr.nullValue()).alias("ratingEqNull"), + not(field("rating").isNan()).alias("ratingIsNotNan")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries( + entry("ratingIsNull", false), + entry("ratingEqNull", null), + entry("ratingIsNotNan", true))); + } + + @Test + @Ignore("Not supported yet") + public void testLogicalMax() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(field("author").eq("Douglas Adams")) + .select( + field("rating").logicalMaximum(4.5).alias("max_rating"), + logicalMaximum(field("published"), 1900).alias("max_published")) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("max_rating", 4.5, "max_published", 1979)); + } + + @Test + @Ignore("Not supported yet") + public void testLogicalMin() { + Task execute = + firestore.pipeline().collection(randomCol).sort(field("rating").ascending()).execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly(ImmutableMap.of("min_rating", 4.2, "min_published", 1900)); + } + + @Test + public void testMapGet() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select(field("awards").mapGet("hugo").alias("hugoAward"), field("title")) + .where(eq("hugoAward", true)) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("hugoAward", true, "title", "The Hitchhiker's Guide to the Galaxy"), + ImmutableMap.of("hugoAward", true, "title", "Dune")); + } + + @Test + public void testDistanceFunctions() { + double[] sourceVector = {0.1, 0.1}; + double[] targetVector = {0.5, 0.8}; + Task execute = + firestore + .pipeline() + .collection(randomCol) + .select( + cosineDistance(vector(sourceVector), targetVector).alias("cosineDistance"), + Expr.dotProduct(vector(sourceVector), targetVector).alias("dotProductDistance"), + euclideanDistance(vector(sourceVector), targetVector).alias("euclideanDistance")) + .limit(1) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of( + "cosineDistance", 0.02560880430538015, + "dotProductDistance", 0.13, + "euclideanDistance", 0.806225774829855)); + } + + @Test + public void testNestedFields() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("awards.hugo", true)) + .select("title", "awards.hugo") + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + ImmutableMap.of("title", "The Hitchhiker's Guide to the Galaxy", "awards.hugo", true), + ImmutableMap.of("title", "Dune", "awards.hugo", true)); + } + + @Test + public void testMapGetWithFieldNameIncludingNotation() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("awards.hugo", true)) + .select( + "title", + field("nestedField.level.1"), + mapGet("nestedField", "level.1").mapGet("level.2").alias("nested")) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(DATA_CORRESPONDENCE) + .containsExactly( + mapOfEntries( + entry("title", "The Hitchhiker's Guide to the Galaxy"), + entry("nestedField.level.`1`", null), + entry("nested", true)), + mapOfEntries( + entry("title", "Dune"), + entry("nestedField.level.`1`", null), + entry("nested", null))); + } + + @Test + public void testListEquals() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("tags", ImmutableList.of("philosophy", "crime", "redemption"))) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(ID_CORRESPONDENCE) + .containsExactly("book6"); + } + + @Test + public void testMapEquals() { + Task execute = + firestore + .pipeline() + .collection(randomCol) + .where(eq("awards", ImmutableMap.of("nobel", true, "nebula", false))) + .execute(); + assertThat(waitFor(execute).getResults()) + .comparingElementsUsing(ID_CORRESPONDENCE) + .containsExactly("book3"); + } + + static Map.Entry entry(String key, T value) { + return new Map.Entry() { + private String k = key; + private T v = value; + + @Override + public String getKey() { + return k; + } + + @Override + public T getValue() { + return v; + } + + @Override + public T setValue(T value) { + T old = v; + v = value; + return old; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Map.Entry)) { + return false; + } + + Map.Entry that = (Map.Entry) o; + return com.google.common.base.Objects.equal(k, that.getKey()) + && com.google.common.base.Objects.equal(v, that.getValue()); + } + + @Override + public int hashCode() { + return com.google.common.base.Objects.hashCode(k, v); + } + }; + } + + @SafeVarargs + static Map mapOfEntries(Map.Entry... entries) { + Map res = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + res.put(entry.getKey(), entry.getValue()); + } + return Collections.unmodifiableMap(res); + } +} diff --git a/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/QueryToPipelineTest.java b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/QueryToPipelineTest.java new file mode 100644 index 00000000000..942d6291668 --- /dev/null +++ b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/QueryToPipelineTest.java @@ -0,0 +1,952 @@ +// Copyright 2018 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.firebase.firestore; + +import static com.google.common.io.Files.map; +import static com.google.firebase.firestore.Filter.and; +import static com.google.firebase.firestore.Filter.arrayContains; +import static com.google.firebase.firestore.Filter.arrayContainsAny; +import static com.google.firebase.firestore.Filter.equalTo; +import static com.google.firebase.firestore.Filter.inArray; +import static com.google.firebase.firestore.Filter.or; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.checkQueryAndPipelineResultsMatch; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.nullList; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.pipelineSnapshotToIds; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.pipelineSnapshotToValues; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.testCollection; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.testCollectionWithDocs; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.testFirestore; +import static com.google.firebase.firestore.testutil.IntegrationTestUtil.waitFor; +import static com.google.firebase.firestore.testutil.TestUtil.expectError; +import static com.google.firebase.firestore.testutil.TestUtil.map; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.google.android.gms.tasks.Task; +import com.google.common.collect.Lists; +import com.google.firebase.firestore.Query.Direction; +import com.google.firebase.firestore.testutil.IntegrationTestUtil; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class QueryToPipelineTest { + + @After + public void tearDown() { + IntegrationTestUtil.tearDown(); + } + + @Test + public void testLimitQueries() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("k", "a"), + "b", map("k", "b"), + "c", map("k", "c"))); + + Query query = collection.limit(2); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot set = waitFor(db.pipeline().convertFrom(query).execute()); + List> data = pipelineSnapshotToValues(set); + assertEquals(asList(map("k", "a"), map("k", "b")), data); + } + + @Test + public void testLimitQueriesUsingDescendingSortOrder() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("k", "a", "sort", 0), + "b", map("k", "b", "sort", 1), + "c", map("k", "c", "sort", 1), + "d", map("k", "d", "sort", 2))); + + Query query = collection.limit(2).orderBy("sort", Direction.DESCENDING); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot set = waitFor(db.pipeline().convertFrom(query).execute()); + + List> data = pipelineSnapshotToValues(set); + assertEquals(asList(map("k", "d", "sort", 2L), map("k", "c", "sort", 1L)), data); + } + + @Test + public void testLimitToLastMustAlsoHaveExplicitOrderBy() { + CollectionReference collection = testCollectionWithDocs(map()); + FirebaseFirestore db = collection.firestore; + + Query query = collection.limitToLast(2); + expectError( + () -> waitFor(db.pipeline().convertFrom(query).execute()), + "limitToLast() queries require specifying at least one orderBy() clause"); + } + + @Test + public void testLimitToLastQueriesWithCursors() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("k", "a", "sort", 0), + "b", map("k", "b", "sort", 1), + "c", map("k", "c", "sort", 1), + "d", map("k", "d", "sort", 2))); + + Query query = collection.limitToLast(3).orderBy("sort").endBefore(2); + FirebaseFirestore db = collection.firestore; + + PipelineSnapshot set = waitFor(db.pipeline().convertFrom(query).execute()); + List> data = pipelineSnapshotToValues(set); + assertEquals( + asList(map("k", "a", "sort", 0L), map("k", "b", "sort", 1L), map("k", "c", "sort", 1L)), + data); + + query = collection.limitToLast(3).orderBy("sort").endAt(1); + set = waitFor(db.pipeline().convertFrom(query).execute()); + data = pipelineSnapshotToValues(set); + assertEquals( + asList(map("k", "a", "sort", 0L), map("k", "b", "sort", 1L), map("k", "c", "sort", 1L)), + data); + + query = collection.limitToLast(3).orderBy("sort").startAt(2); + set = waitFor(db.pipeline().convertFrom(query).execute()); + data = pipelineSnapshotToValues(set); + assertEquals(asList(map("k", "d", "sort", 2L)), data); + + query = collection.limitToLast(3).orderBy("sort").startAfter(0); + set = waitFor(db.pipeline().convertFrom(query).execute()); + data = pipelineSnapshotToValues(set); + assertEquals( + asList(map("k", "b", "sort", 1L), map("k", "c", "sort", 1L), map("k", "d", "sort", 2L)), + data); + + query = collection.limitToLast(3).orderBy("sort").startAfter(-1); + set = waitFor(db.pipeline().convertFrom(query).execute()); + data = pipelineSnapshotToValues(set); + assertEquals( + asList(map("k", "b", "sort", 1L), map("k", "c", "sort", 1L), map("k", "d", "sort", 2L)), + data); + } + + @Test + public void testKeyOrderIsDescendingForDescendingInequality() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("foo", 42), + "b", map("foo", 42.0), + "c", map("foo", 42), + "d", map("foo", 21), + "e", map("foo", 21.0), + "f", map("foo", 66), + "g", map("foo", 66.0))); + + Query query = collection.whereGreaterThan("foo", 21.0).orderBy("foo", Direction.DESCENDING); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot result = waitFor(db.pipeline().convertFrom(query).execute()); + assertEquals(asList("g", "f", "c", "b", "a"), pipelineSnapshotToIds(result)); + } + + @Test + public void testUnaryFilterQueries() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("null", null, "nan", Double.NaN), + "b", map("null", null, "nan", 0), + "c", map("null", false, "nan", Double.NaN))); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot results = + waitFor( + db.pipeline() + .convertFrom(collection.whereEqualTo("null", null).whereEqualTo("nan", Double.NaN)) + .execute()); + assertEquals(1, results.getResults().size()); + PipelineResult result = results.getResults().get(0); + // Can't use assertEquals() since NaN != NaN. + assertEquals(null, result.get("null")); + assertTrue(((Double) result.get("nan")).isNaN()); + } + + @Test + public void testFilterOnInfinity() { + CollectionReference collection = + testCollectionWithDocs( + map( + "a", map("inf", Double.POSITIVE_INFINITY), + "b", map("inf", Double.NEGATIVE_INFINITY))); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot results = + waitFor( + db.pipeline() + .convertFrom(collection.whereEqualTo("inf", Double.POSITIVE_INFINITY)) + .execute()); + assertEquals(1, results.getResults().size()); + assertEquals(asList(map("inf", Double.POSITIVE_INFINITY)), pipelineSnapshotToValues(results)); + } + + @Test + public void testCanExplicitlySortByDocumentId() { + Map> testDocs = + map( + "a", map("key", "a"), + "b", map("key", "b"), + "c", map("key", "c")); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + // Ideally this would be descending to validate it's different than + // the default, but that requires an extra index + PipelineSnapshot docs = + waitFor(db.pipeline().convertFrom(collection.orderBy(FieldPath.documentId())).execute()); + assertEquals( + asList(testDocs.get("a"), testDocs.get("b"), testDocs.get("c")), + pipelineSnapshotToValues(docs)); + } + + @Test + public void testCanQueryByDocumentId() { + Map> testDocs = + map( + "aa", map("key", "aa"), + "ab", map("key", "ab"), + "ba", map("key", "ba"), + "bb", map("key", "bb")); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot docs = + waitFor( + db.pipeline() + .convertFrom(collection.whereEqualTo(FieldPath.documentId(), "ab")) + .execute()); + assertEquals(singletonList(testDocs.get("ab")), pipelineSnapshotToValues(docs)); + + docs = + waitFor( + db.pipeline() + .convertFrom( + collection + .whereGreaterThan(FieldPath.documentId(), "aa") + .whereLessThanOrEqualTo(FieldPath.documentId(), "ba")) + .execute()); + assertEquals(asList(testDocs.get("ab"), testDocs.get("ba")), pipelineSnapshotToValues(docs)); + } + + @Test + public void testCanQueryByDocumentIdUsingRefs() { + Map> testDocs = + map( + "aa", map("key", "aa"), + "ab", map("key", "ab"), + "ba", map("key", "ba"), + "bb", map("key", "bb")); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot docs = + waitFor( + db.pipeline() + .convertFrom( + collection.whereEqualTo(FieldPath.documentId(), collection.document("ab"))) + .execute()); + assertEquals(singletonList(testDocs.get("ab")), pipelineSnapshotToValues(docs)); + + docs = + waitFor( + db.pipeline() + .convertFrom( + collection + .whereGreaterThan(FieldPath.documentId(), collection.document("aa")) + .whereLessThanOrEqualTo(FieldPath.documentId(), collection.document("ba"))) + .execute()); + assertEquals(asList(testDocs.get("ab"), testDocs.get("ba")), pipelineSnapshotToValues(docs)); + } + + @Test + public void testCanQueryWithAndWithoutDocumentKey() { + CollectionReference collection = testCollection(); + FirebaseFirestore db = collection.firestore; + collection.add(map()); + Task query1 = + db.pipeline() + .convertFrom(collection.orderBy(FieldPath.documentId(), Direction.ASCENDING)) + .execute(); + Task query2 = db.pipeline().convertFrom(collection).execute(); + + waitFor(query1); + waitFor(query2); + + assertEquals( + pipelineSnapshotToValues(query1.getResult()), pipelineSnapshotToValues(query2.getResult())); + } + + @Test + public void testQueriesCanUseNotEqualFilters() { + // These documents are ordered by value in "zip" since the notEquals filter is an inequality, + // which results in documents being sorted by value. + Map docA = map("zip", Double.NaN); + Map docB = map("zip", 91102L); + Map docC = map("zip", 98101L); + Map docD = map("zip", "98101"); + Map docE = map("zip", asList(98101L)); + Map docF = map("zip", asList(98101L, 98102L)); + Map docG = map("zip", asList("98101", map("zip", 98101L))); + Map docH = map("zip", map("code", 500L)); + Map docI = map("code", 500L); + Map docJ = map("zip", null); + + Map> allDocs = + map( + "a", docA, "b", docB, "c", docC, "d", docD, "e", docE, "f", docF, "g", docG, "h", docH, + "i", docI, "j", docJ); + CollectionReference collection = testCollectionWithDocs(allDocs); + FirebaseFirestore db = collection.firestore; + + // Search for zips not matching 98101. + Map> expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("c"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + + PipelineSnapshot snapshot = + waitFor(db.pipeline().convertFrom(collection.whereNotEqualTo("zip", 98101L)).execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With objects. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("h"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereNotEqualTo("zip", map("code", 500))) + .execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With Null. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor(db.pipeline().convertFrom(collection.whereNotEqualTo("zip", null)).execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With NaN. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("a"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor(db.pipeline().convertFrom(collection.whereNotEqualTo("zip", Double.NaN)).execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + } + + @Test + public void testQueriesCanUseNotEqualFiltersWithDocIds() { + Map docA = map("key", "aa"); + Map docB = map("key", "ab"); + Map docC = map("key", "ba"); + Map docD = map("key", "bb"); + Map> testDocs = + map( + "aa", docA, + "ab", docB, + "ba", docC, + "bb", docD); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot docs = + waitFor( + db.pipeline() + .convertFrom(collection.whereNotEqualTo(FieldPath.documentId(), "aa")) + .execute()); + assertEquals(asList(docB, docC, docD), pipelineSnapshotToValues(docs)); + } + + @Test + public void testQueriesCanUseArrayContainsFilters() { + Map docA = map("array", asList(42L)); + Map docB = map("array", asList("a", 42L, "c")); + Map docC = map("array", asList(41.999, "42", map("a", asList(42)))); + Map docD = map("array", asList(42L), "array2", asList("bingo")); + Map docE = map("array", nullList()); + Map docF = map("array", asList(Double.NaN)); + CollectionReference collection = + testCollectionWithDocs( + map("a", docA, "b", docB, "c", docC, "d", docD, "e", docE, "f", docF)); + FirebaseFirestore db = collection.firestore; + + // Search for "array" to contain 42 + PipelineSnapshot snapshot = + waitFor(db.pipeline().convertFrom(collection.whereArrayContains("array", 42L)).execute()); + assertEquals(asList(docA, docB, docD), pipelineSnapshotToValues(snapshot)); + + // Note: whereArrayContains() requires a non-null value parameter, so no null test is needed. + // With NaN. + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereArrayContains("array", Double.NaN)) + .execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + } + + @Test + public void testQueriesCanUseInFilters() { + Map docA = map("zip", 98101L); + Map docB = map("zip", 91102L); + Map docC = map("zip", 98103L); + Map docD = map("zip", asList(98101L)); + Map docE = map("zip", asList("98101", map("zip", 98101L))); + Map docF = map("zip", map("code", 500L)); + Map docG = map("zip", asList(98101L, 98102L)); + Map docH = map("zip", null); + Map docI = map("zip", Double.NaN); + + CollectionReference collection = + testCollectionWithDocs( + map( + "a", docA, "b", docB, "c", docC, "d", docD, "e", docE, "f", docF, "g", docG, "h", + docH, "i", docI)); + FirebaseFirestore db = collection.firestore; + + // Search for zips matching 98101, 98103, or [98101, 98102]. + PipelineSnapshot snapshot = + waitFor( + db.pipeline() + .convertFrom( + collection.whereIn("zip", asList(98101L, 98103L, asList(98101L, 98102L)))) + .execute()); + assertEquals(asList(docA, docC, docG), pipelineSnapshotToValues(snapshot)); + + // With objects. + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereIn("zip", asList(map("code", 500L)))) + .execute()); + assertEquals(asList(docF), pipelineSnapshotToValues(snapshot)); + + // With null. + snapshot = waitFor(db.pipeline().convertFrom(collection.whereIn("zip", nullList())).execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + + // With null and a value. + List inputList = nullList(); + inputList.add(98101L); + snapshot = waitFor(db.pipeline().convertFrom(collection.whereIn("zip", inputList)).execute()); + assertEquals(asList(docA), pipelineSnapshotToValues(snapshot)); + + // With NaN. + snapshot = + waitFor(db.pipeline().convertFrom(collection.whereIn("zip", asList(Double.NaN))).execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + + // With NaN and a value. + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereIn("zip", asList(Double.NaN, 98101L))) + .execute()); + assertEquals(asList(docA), pipelineSnapshotToValues(snapshot)); + } + + @Test + public void testQueriesCanUseInFiltersWithDocIds() { + Map docA = map("key", "aa"); + Map docB = map("key", "ab"); + Map docC = map("key", "ba"); + Map docD = map("key", "bb"); + Map> testDocs = + map( + "aa", docA, + "ab", docB, + "ba", docC, + "bb", docD); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot docs = + waitFor( + db.pipeline() + .convertFrom(collection.whereIn(FieldPath.documentId(), asList("aa", "ab"))) + .execute()); + assertEquals(asList(docA, docB), pipelineSnapshotToValues(docs)); + } + + @Test + public void testQueriesCanUseNotInFilters() { + // These documents are ordered by value in "zip" since the notEquals filter is an inequality, + // which results in documents being sorted by value. + Map docA = map("zip", Double.NaN); + Map docB = map("zip", 91102L); + Map docC = map("zip", 98101L); + Map docD = map("zip", 98103L); + Map docE = map("zip", asList(98101L)); + Map docF = map("zip", asList(98101L, 98102L)); + Map docG = map("zip", asList("98101", map("zip", 98101L))); + Map docH = map("zip", map("code", 500L)); + Map docI = map("code", 500L); + Map docJ = map("zip", null); + + Map> allDocs = + map( + "a", docA, "b", docB, "c", docC, "d", docD, "e", docE, "f", docF, "g", docG, "h", docH, + "i", docI, "j", docJ); + CollectionReference collection = testCollectionWithDocs(allDocs); + FirebaseFirestore db = collection.firestore; + + // Search for zips not matching 98101, 98103, or [98101, 98102]. + Map> expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("c"); + expectedDocsMap.remove("d"); + expectedDocsMap.remove("f"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + + PipelineSnapshot snapshot = + waitFor( + db.pipeline() + .convertFrom( + collection.whereNotIn("zip", asList(98101L, 98103L, asList(98101L, 98102L)))) + .execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With objects. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("h"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereNotIn("zip", asList(map("code", 500L)))) + .execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With Null. + snapshot = + waitFor(db.pipeline().convertFrom(collection.whereNotIn("zip", nullList())).execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + + // With NaN. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("a"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor( + db.pipeline().convertFrom(collection.whereNotIn("zip", asList(Double.NaN))).execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + + // With NaN and a number. + expectedDocsMap = new LinkedHashMap<>(allDocs); + expectedDocsMap.remove("a"); + expectedDocsMap.remove("c"); + expectedDocsMap.remove("i"); + expectedDocsMap.remove("j"); + snapshot = + waitFor( + db.pipeline() + .convertFrom(collection.whereNotIn("zip", asList(Float.NaN, 98101L))) + .execute()); + assertEquals(Lists.newArrayList(expectedDocsMap.values()), pipelineSnapshotToValues(snapshot)); + } + + @Test + public void testQueriesCanUseNotInFiltersWithDocIds() { + Map docA = map("key", "aa"); + Map docB = map("key", "ab"); + Map docC = map("key", "ba"); + Map docD = map("key", "bb"); + Map> testDocs = + map( + "aa", docA, + "ab", docB, + "ba", docC, + "bb", docD); + CollectionReference collection = testCollectionWithDocs(testDocs); + FirebaseFirestore db = collection.firestore; + PipelineSnapshot docs = + waitFor( + db.pipeline() + .convertFrom(collection.whereNotIn(FieldPath.documentId(), asList("aa", "ab"))) + .execute()); + assertEquals(asList(docC, docD), pipelineSnapshotToValues(docs)); + } + + @Test + public void testQueriesCanUseArrayContainsAnyFilters() { + Map docA = map("array", asList(42L)); + Map docB = map("array", asList("a", 42L, "c")); + Map docC = map("array", asList(41.999, "42", map("a", asList(42)))); + Map docD = map("array", asList(42L), "array2", asList("bingo")); + Map docE = map("array", asList(43L)); + Map docF = map("array", asList(map("a", 42L))); + Map docG = map("array", 42L); + Map docH = map("array", nullList()); + Map docI = map("array", asList(Double.NaN)); + + CollectionReference collection = + testCollectionWithDocs( + map( + "a", docA, "b", docB, "c", docC, "d", docD, "e", docE, "f", docF, "g", docG, "h", + docH, "i", docI)); + FirebaseFirestore db = collection.firestore; + + // Search for "array" to contain [42, 43]. + Pipeline pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", asList(42L, 43L))); + PipelineSnapshot snapshot = waitFor(pipeline.execute()); + assertEquals(asList(docA, docB, docD, docE), pipelineSnapshotToValues(snapshot)); + + // With objects. + pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", asList(map("a", 42L)))); + snapshot = waitFor(pipeline.execute()); + assertEquals(asList(docF), pipelineSnapshotToValues(snapshot)); + + // With null. + pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", nullList())); + snapshot = waitFor(pipeline.execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + + // With null and a value. + List inputList = nullList(); + inputList.add(43L); + pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", inputList)); + snapshot = waitFor(pipeline.execute()); + assertEquals(asList(docE), pipelineSnapshotToValues(snapshot)); + + // With NaN. + pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", asList(Double.NaN))); + snapshot = waitFor(pipeline.execute()); + assertEquals(new ArrayList<>(), pipelineSnapshotToValues(snapshot)); + + // With NaN and a value. + pipeline = db.pipeline() + .convertFrom(collection.whereArrayContainsAny("array", asList(Double.NaN, 43L))); + snapshot = waitFor(pipeline.execute()); + assertEquals(asList(docE), pipelineSnapshotToValues(snapshot)); + } + + @Test + public void testCollectionGroupQueries() { + FirebaseFirestore db = testFirestore(); + // Use .document() to get a random collection group name to use but ensure it starts with 'b' + // for predictable ordering. + String collectionGroup = "b" + db.collection("foo").document().getId(); + + String[] docPaths = + new String[] { + "abc/123/${collectionGroup}/cg-doc1", + "abc/123/${collectionGroup}/cg-doc2", + "${collectionGroup}/cg-doc3", + "${collectionGroup}/cg-doc4", + "def/456/${collectionGroup}/cg-doc5", + "${collectionGroup}/virtual-doc/nested-coll/not-cg-doc", + "x${collectionGroup}/not-cg-doc", + "${collectionGroup}x/not-cg-doc", + "abc/123/${collectionGroup}x/not-cg-doc", + "abc/123/x${collectionGroup}/not-cg-doc", + "abc/${collectionGroup}" + }; + WriteBatch batch = db.batch(); + for (String path : docPaths) { + batch.set(db.document(path.replace("${collectionGroup}", collectionGroup)), map("x", 1)); + } + waitFor(batch.commit()); + + PipelineSnapshot snapshot = + waitFor(db.pipeline().convertFrom(db.collectionGroup(collectionGroup)).execute()); + assertEquals( + asList("cg-doc1", "cg-doc2", "cg-doc3", "cg-doc4", "cg-doc5"), + pipelineSnapshotToIds(snapshot)); + } + + @Test + public void testCollectionGroupQueriesWithStartAtEndAtWithArbitraryDocumentIds() { + FirebaseFirestore db = testFirestore(); + // Use .document() to get a random collection group name to use but ensure it starts with 'b' + // for predictable ordering. + String collectionGroup = "b" + db.collection("foo").document().getId(); + + String[] docPaths = + new String[] { + "a/a/${collectionGroup}/cg-doc1", + "a/b/a/b/${collectionGroup}/cg-doc2", + "a/b/${collectionGroup}/cg-doc3", + "a/b/c/d/${collectionGroup}/cg-doc4", + "a/c/${collectionGroup}/cg-doc5", + "${collectionGroup}/cg-doc6", + "a/b/nope/nope" + }; + WriteBatch batch = db.batch(); + for (String path : docPaths) { + batch.set(db.document(path.replace("${collectionGroup}", collectionGroup)), map("x", 1)); + } + waitFor(batch.commit()); + + PipelineSnapshot snapshot = + waitFor( + db.pipeline() + .convertFrom( + db.collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAt("a/b") + .endAt("a/b0")) + .execute()); + assertEquals(asList("cg-doc2", "cg-doc3", "cg-doc4"), pipelineSnapshotToIds(snapshot)); + + snapshot = + waitFor( + db.pipeline() + .convertFrom( + db.collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAfter("a/b") + .endBefore("a/b/" + collectionGroup + "/cg-doc3")) + .execute()); + assertEquals(asList("cg-doc2"), pipelineSnapshotToIds(snapshot)); + } + + @Test + public void testCollectionGroupQueriesWithWhereFiltersOnArbitraryDocumentIds() { + FirebaseFirestore db = testFirestore(); + // Use .document() to get a random collection group name to use but ensure it starts with 'b' + // for predictable ordering. + String collectionGroup = "b" + db.collection("foo").document().getId(); + + String[] docPaths = + new String[] { + "a/a/${collectionGroup}/cg-doc1", + "a/b/a/b/${collectionGroup}/cg-doc2", + "a/b/${collectionGroup}/cg-doc3", + "a/b/c/d/${collectionGroup}/cg-doc4", + "a/c/${collectionGroup}/cg-doc5", + "${collectionGroup}/cg-doc6", + "a/b/nope/nope" + }; + WriteBatch batch = db.batch(); + for (String path : docPaths) { + batch.set(db.document(path.replace("${collectionGroup}", collectionGroup)), map("x", 1)); + } + waitFor(batch.commit()); + + PipelineSnapshot snapshot = + waitFor( + db.pipeline() + .convertFrom( + db.collectionGroup(collectionGroup) + .whereGreaterThanOrEqualTo(FieldPath.documentId(), "a/b") + .whereLessThanOrEqualTo(FieldPath.documentId(), "a/b0")) + .execute()); + assertEquals(asList("cg-doc2", "cg-doc3", "cg-doc4"), pipelineSnapshotToIds(snapshot)); + + snapshot = + waitFor( + db.pipeline() + .convertFrom( + db.collectionGroup(collectionGroup) + .whereGreaterThan(FieldPath.documentId(), "a/b") + .whereLessThan( + FieldPath.documentId(), "a/b/" + collectionGroup + "/cg-doc3")) + .execute()); + assertEquals(asList("cg-doc2"), pipelineSnapshotToIds(snapshot)); + } + + @Test + public void testOrQueries() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", 0), + "doc2", map("a", 2, "b", 1), + "doc3", map("a", 3, "b", 2), + "doc4", map("a", 1, "b", 3), + "doc5", map("a", 1, "b", 1)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + // Two equalities: a==1 || b==1. + checkQueryAndPipelineResultsMatch( + collection.where(or(equalTo("a", 1), equalTo("b", 1))), "doc1", "doc2", "doc4", "doc5"); + + // (a==1 && b==0) || (a==3 && b==2) + checkQueryAndPipelineResultsMatch( + collection.where( + or(and(equalTo("a", 1), equalTo("b", 0)), and(equalTo("a", 3), equalTo("b", 2)))), + "doc1", + "doc3"); + + // a==1 && (b==0 || b==3). + checkQueryAndPipelineResultsMatch( + collection.where(and(equalTo("a", 1), or(equalTo("b", 0), equalTo("b", 3)))), + "doc1", + "doc4"); + + // (a==2 || b==2) && (a==3 || b==3) + checkQueryAndPipelineResultsMatch( + collection.where( + and(or(equalTo("a", 2), equalTo("b", 2)), or(equalTo("a", 3), equalTo("b", 3)))), + "doc3"); + + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + checkQueryAndPipelineResultsMatch( + collection.where(or(equalTo("a", 2), equalTo("b", 1))).limit(1), "doc2"); + } + + @Test + public void testOrQueriesWithIn() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", 0), + "doc2", map("b", 1), + "doc3", map("a", 3, "b", 2), + "doc4", map("a", 1, "b", 3), + "doc5", map("a", 1), + "doc6", map("a", 2)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + // a==2 || b in [2,3] + checkQueryAndPipelineResultsMatch( + collection.where(or(equalTo("a", 2), inArray("b", asList(2, 3)))), "doc3", "doc4", "doc6"); + } + + @Test + public void testOrQueriesWithArrayMembership() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", asList(0)), + "doc2", map("b", asList(1)), + "doc3", map("a", 3, "b", asList(2, 7)), + "doc4", map("a", 1, "b", asList(3, 7)), + "doc5", map("a", 1), + "doc6", map("a", 2)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + // a==2 || b array-contains 7 + checkQueryAndPipelineResultsMatch( + collection.where(or(equalTo("a", 2), arrayContains("b", 7))), "doc3", "doc4", "doc6"); + + // a==2 || b array-contains-any [0, 3] + checkQueryAndPipelineResultsMatch( + collection.where(or(equalTo("a", 2), arrayContainsAny("b", asList(0, 3)))), + "doc1", + "doc4", + "doc6"); + } + + @Test + public void testMultipleInOps() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", 0), + "doc2", map("b", 1), + "doc3", map("a", 3, "b", 2), + "doc4", map("a", 1, "b", 3), + "doc5", map("a", 1), + "doc6", map("a", 2)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + // Two IN operations on different fields with disjunction. + Query query1 = collection.where(or(inArray("a", asList(2, 3)), inArray("b", asList(0, 2)))); + checkQueryAndPipelineResultsMatch(query1, "doc1", "doc3", "doc6"); + + // Two IN operations on the same field with disjunction. + // a IN [0,3] || a IN [0,2] should union them (similar to: a IN [0,2,3]). + Query query2 = collection.where(or(inArray("a", asList(0, 3)), inArray("a", asList(0, 2)))); + checkQueryAndPipelineResultsMatch(query2, "doc3", "doc6"); + } + + @Test + public void testUsingInWithArrayContainsAny() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", asList(0)), + "doc2", map("b", asList(1)), + "doc3", map("a", 3, "b", asList(2, 7), "c", 10), + "doc4", map("a", 1, "b", asList(3, 7)), + "doc5", map("a", 1), + "doc6", map("a", 2, "c", 20)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + Query query1 = + collection.where(or(inArray("a", asList(2, 3)), arrayContainsAny("b", asList(0, 7)))); + checkQueryAndPipelineResultsMatch(query1, "doc1", "doc3", "doc4", "doc6"); + + Query query2 = + collection.where( + or( + and(inArray("a", asList(2, 3)), equalTo("c", 10)), + arrayContainsAny("b", asList(0, 7)))); + checkQueryAndPipelineResultsMatch(query2, "doc1", "doc3", "doc4"); + } + + @Test + public void testUsingInWithArrayContains() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", asList(0)), + "doc2", map("b", asList(1)), + "doc3", map("a", 3, "b", asList(2, 7)), + "doc4", map("a", 1, "b", asList(3, 7)), + "doc5", map("a", 1), + "doc6", map("a", 2)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + Query query1 = collection.where(or(inArray("a", asList(2, 3)), arrayContains("b", 3))); + checkQueryAndPipelineResultsMatch(query1, "doc3", "doc4", "doc6"); + + Query query2 = collection.where(and(inArray("a", asList(2, 3)), arrayContains("b", 7))); + checkQueryAndPipelineResultsMatch(query2, "doc3"); + + Query query3 = + collection.where( + or(inArray("a", asList(2, 3)), and(arrayContains("b", 3), equalTo("a", 1)))); + checkQueryAndPipelineResultsMatch(query3, "doc3", "doc4", "doc6"); + + Query query4 = + collection.where( + and(inArray("a", asList(2, 3)), or(arrayContains("b", 7), equalTo("a", 1)))); + checkQueryAndPipelineResultsMatch(query4, "doc3"); + } + + @Test + public void testOrderByEquality() { + Map> testDocs = + map( + "doc1", map("a", 1, "b", asList(0)), + "doc2", map("b", asList(1)), + "doc3", map("a", 3, "b", asList(2, 7), "c", 10), + "doc4", map("a", 1, "b", asList(3, 7)), + "doc5", map("a", 1), + "doc6", map("a", 2, "c", 20)); + CollectionReference collection = testCollectionWithDocs(testDocs); + + Query query1 = collection.where(equalTo("a", 1)).orderBy("a"); + checkQueryAndPipelineResultsMatch(query1, "doc1", "doc4", "doc5"); + + Query query2 = collection.where(inArray("a", asList(2, 3))).orderBy("a"); + checkQueryAndPipelineResultsMatch(query2, "doc6", "doc3"); + } +} diff --git a/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/testutil/IntegrationTestUtil.java b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/testutil/IntegrationTestUtil.java index a7417d96563..717e3f02ebc 100644 --- a/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/testutil/IntegrationTestUtil.java +++ b/firebase-firestore/src/androidTest/java/com/google/firebase/firestore/testutil/IntegrationTestUtil.java @@ -38,6 +38,8 @@ import com.google.firebase.firestore.FirebaseFirestoreSettings; import com.google.firebase.firestore.ListenerRegistration; import com.google.firebase.firestore.MetadataChanges; +import com.google.firebase.firestore.PipelineResult; +import com.google.firebase.firestore.PipelineSnapshot; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.Source; @@ -98,7 +100,7 @@ public enum TargetBackend { // Set this to the desired enum value to change the target backend when running tests locally. // Note: DO NOT change this variable except for local testing. - private static final TargetBackend backendForLocalTesting = null; + private static final TargetBackend backendForLocalTesting = TargetBackend.NIGHTLY; private static final TargetBackend backend = getTargetBackend(); private static final String EMULATOR_HOST = "10.0.2.2"; @@ -465,6 +467,15 @@ public static List> querySnapshotToValues(QuerySnapshot quer return res; } + public static List> pipelineSnapshotToValues( + PipelineSnapshot pipelineSnapshot) { + List> res = new ArrayList<>(); + for (PipelineResult result : pipelineSnapshot) { + res.add(result.getData()); + } + return res; + } + public static List querySnapshotToIds(QuerySnapshot querySnapshot) { List res = new ArrayList<>(); for (DocumentSnapshot doc : querySnapshot) { @@ -473,6 +484,15 @@ public static List querySnapshotToIds(QuerySnapshot querySnapshot) { return res; } + public static List pipelineSnapshotToIds(PipelineSnapshot pipelineResults) { + List res = new ArrayList<>(); + for (PipelineResult result : pipelineResults) { + DocumentReference ref = result.getRef(); + res.add(ref == null ? null : ref.getId()); + } + return res; + } + public static void disableNetwork(FirebaseFirestore firestore) { if (firestoreStatus.get(firestore)) { waitFor(firestore.disableNetwork()); @@ -537,4 +557,33 @@ public static void checkOnlineAndOfflineResultsMatch(Query query, String... expe assertEquals(expected, querySnapshotToIds(docsFromCache)); } } + + /** + * Checks that running the query while online (against the backend/emulator) results in the same + * documents as running the query while offline. If `expectedDocs` is provided, it also checks + * that both online and offline query result is equal to the expected documents. + * + * @param query The query to check + * @param expectedDocs Ordered list of document keys that are expected to match the query + */ + public static void checkQueryAndPipelineResultsMatch(Query query, String... expectedDocs) { + QuerySnapshot docsFromQuery; + try { + docsFromQuery = waitFor(query.get(Source.SERVER)); + } catch (Exception e) { + throw new RuntimeException("Classic Query FAILED", e); + } + PipelineSnapshot docsFromPipeline; + try { + docsFromPipeline = waitFor(query.getFirestore().pipeline().convertFrom(query).execute()); + } catch (Exception e) { + throw new RuntimeException("Pipeline FAILED", e); + } + + assertEquals(querySnapshotToIds(docsFromQuery), pipelineSnapshotToIds(docsFromPipeline)); + List expected = asList(expectedDocs); + if (!expected.isEmpty()) { + assertEquals(expected, querySnapshotToIds(docsFromQuery)); + } + } } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/AggregateField.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/AggregateField.java index 902d515d86f..a053a8d038a 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/AggregateField.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/AggregateField.java @@ -14,9 +14,13 @@ package com.google.firebase.firestore; +import static com.google.firebase.firestore.pipeline.Expr.field; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; +import com.google.firebase.firestore.pipeline.AggregateFunction; +import com.google.firebase.firestore.pipeline.AggregateWithAlias; import java.util.Objects; /** Represents an aggregation that can be performed by Firestore. */ @@ -61,6 +65,9 @@ public String getOperator() { return operator; } + @NonNull + abstract AggregateWithAlias toPipeline(); + /** * Returns true if the given object is equal to this object. Two `AggregateField` objects are * considered equal if they have the same operator and operate on the same field. @@ -195,6 +202,12 @@ public static class CountAggregateField extends AggregateField { private CountAggregateField() { super(null, "count"); } + + @NonNull + @Override + AggregateWithAlias toPipeline() { + return AggregateFunction.countAll().alias(getAlias()); + } } /** Represents a "sum" aggregation that can be performed by Firestore. */ @@ -202,6 +215,12 @@ public static class SumAggregateField extends AggregateField { private SumAggregateField(@NonNull FieldPath fieldPath) { super(fieldPath, "sum"); } + + @NonNull + @Override + AggregateWithAlias toPipeline() { + return field(getFieldPath()).sum().alias(getAlias()); + } } /** Represents an "average" aggregation that can be performed by Firestore. */ @@ -209,5 +228,11 @@ public static class AverageAggregateField extends AggregateField { private AverageAggregateField(@NonNull FieldPath fieldPath) { super(fieldPath, "average"); } + + @NonNull + @Override + AggregateWithAlias toPipeline() { + return field(getFieldPath()).avg().alias(getAlias()); + } } } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentReference.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentReference.java index e3097d32b00..f31e3103060 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentReference.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentReference.java @@ -22,6 +22,7 @@ import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.annotation.RestrictTo; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.TaskCompletionSource; import com.google.android.gms.tasks.Tasks; @@ -33,6 +34,7 @@ import com.google.firebase.firestore.core.UserData.ParsedSetData; import com.google.firebase.firestore.core.UserData.ParsedUpdateData; import com.google.firebase.firestore.core.ViewSnapshot; +import com.google.firebase.firestore.model.DatabaseId; import com.google.firebase.firestore.model.Document; import com.google.firebase.firestore.model.DocumentKey; import com.google.firebase.firestore.model.ResourcePath; @@ -57,7 +59,7 @@ * in test mocks. Subclassing is not supported in production code and new SDK releases may break * code that does so. */ -public class DocumentReference { +public final class DocumentReference { private final DocumentKey key; @@ -65,9 +67,7 @@ public class DocumentReference { DocumentReference(DocumentKey key, FirebaseFirestore firestore) { this.key = checkNotNull(key); - // TODO: We should checkNotNull(firestore), but tests are currently cheating - // and setting it to null. - this.firestore = firestore; + this.firestore = checkNotNull(firestore); } /** @hide */ @@ -120,6 +120,15 @@ public String getPath() { return key.getPath().canonicalString(); } + @RestrictTo(RestrictTo.Scope.LIBRARY) + @NonNull + public String getFullPath() { + DatabaseId databaseId = firestore.getDatabaseId(); + return String.format( + "projects/%s/databases/%s/documents/%s", + databaseId.getProjectId(), databaseId.getDatabaseId(), getPath()); + } + /** * Gets a {@code CollectionReference} instance that refers to the subcollection at the specified * path relative to this document. @@ -564,6 +573,12 @@ public int hashCode() { return result; } + @NonNull + @Override + public String toString() { + return "DocumentReference{" + "key=" + key + ", firestore=" + firestore + '}'; + } + private com.google.firebase.firestore.core.Query asQuery() { return com.google.firebase.firestore.core.Query.atPath(key.getPath()); } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentSnapshot.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentSnapshot.java index 4540608fc48..5c978b8cce9 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentSnapshot.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/DocumentSnapshot.java @@ -555,6 +555,7 @@ public int hashCode() { return hash; } + @NonNull @Override public String toString() { return "DocumentSnapshot{" + "key=" + key + ", metadata=" + metadata + ", doc=" + doc + '}'; diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/FieldPath.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/FieldPath.java index 2b5302cff19..fe353b3391b 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/FieldPath.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/FieldPath.java @@ -18,6 +18,7 @@ import static com.google.firebase.firestore.util.Preconditions.checkNotNull; import androidx.annotation.NonNull; +import androidx.annotation.RestrictTo; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; @@ -33,15 +34,18 @@ public final class FieldPath { private final com.google.firebase.firestore.model.FieldPath internalPath; - private FieldPath(List segments) { + private FieldPath(@NonNull List segments) { this.internalPath = com.google.firebase.firestore.model.FieldPath.fromSegments(segments); } - private FieldPath(com.google.firebase.firestore.model.FieldPath internalPath) { + private FieldPath(@NonNull com.google.firebase.firestore.model.FieldPath internalPath) { this.internalPath = internalPath; } - com.google.firebase.firestore.model.FieldPath getInternalPath() { + /** @hide */ + @RestrictTo(RestrictTo.Scope.LIBRARY) + @NonNull + public com.google.firebase.firestore.model.FieldPath getInternalPath() { return internalPath; } @@ -78,7 +82,9 @@ public static FieldPath documentId() { } /** Parses a field path string into a {@code FieldPath}, treating dots as separators. */ - static FieldPath fromDotSeparatedPath(@NonNull String path) { + @RestrictTo(RestrictTo.Scope.LIBRARY) + @NonNull + public static FieldPath fromDotSeparatedPath(@NonNull String path) { checkNotNull(path, "Provided field path must not be null."); checkArgument( !RESERVED.matcher(path).find(), "Use FieldPath.of() for field names containing '~*/[]'."); diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/FirebaseFirestore.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/FirebaseFirestore.java index c1218829b8a..fa0ccf7f90f 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/FirebaseFirestore.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/FirebaseFirestore.java @@ -850,10 +850,12 @@ T callClient(Function call) { return clientProvider.call(call); } + @NonNull DatabaseId getDatabaseId() { return databaseId; } + @NonNull UserDataReader getUserDataReader() { return userDataReader; } @@ -881,4 +883,15 @@ void validateReference(DocumentReference docRef) { static void setClientLanguage(@NonNull String languageToken) { FirestoreChannel.setClientLanguage(languageToken); } + + /** + * Build a new Pipeline + * + * @return {@code PipelineSource} for this Firestore instance. + */ + @NonNull + public PipelineSource pipeline() { + clientProvider.ensureConfigured(); + return new PipelineSource(this); + } } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/Firestore.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/Firestore.kt index 9f5027b5e29..e2ccf89637d 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/Firestore.kt +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/Firestore.kt @@ -21,7 +21,6 @@ import com.google.firebase.Firebase import com.google.firebase.FirebaseApp import com.google.firebase.components.Component import com.google.firebase.components.ComponentRegistrar -import com.google.firebase.firestore.* import com.google.firebase.firestore.util.Executors.BACKGROUND_EXECUTOR import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.awaitClose diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/Pipeline.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/Pipeline.kt new file mode 100644 index 00000000000..fb7d8313737 --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/Pipeline.kt @@ -0,0 +1,826 @@ +// Copyright 2025 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.firebase.firestore + +import com.google.android.gms.tasks.Task +import com.google.android.gms.tasks.TaskCompletionSource +import com.google.common.collect.FluentIterable +import com.google.common.collect.ImmutableList +import com.google.firebase.Timestamp +import com.google.firebase.firestore.model.DocumentKey +import com.google.firebase.firestore.model.Values +import com.google.firebase.firestore.pipeline.AddFieldsStage +import com.google.firebase.firestore.pipeline.AggregateFunction +import com.google.firebase.firestore.pipeline.AggregateStage +import com.google.firebase.firestore.pipeline.AggregateWithAlias +import com.google.firebase.firestore.pipeline.BooleanExpr +import com.google.firebase.firestore.pipeline.CollectionGroupSource +import com.google.firebase.firestore.pipeline.CollectionSource +import com.google.firebase.firestore.pipeline.DatabaseSource +import com.google.firebase.firestore.pipeline.DistinctStage +import com.google.firebase.firestore.pipeline.DocumentsSource +import com.google.firebase.firestore.pipeline.Expr +import com.google.firebase.firestore.pipeline.ExprWithAlias +import com.google.firebase.firestore.pipeline.Field +import com.google.firebase.firestore.pipeline.FindNearestStage +import com.google.firebase.firestore.pipeline.FunctionExpr +import com.google.firebase.firestore.pipeline.Stage +import com.google.firebase.firestore.pipeline.LimitStage +import com.google.firebase.firestore.pipeline.OffsetStage +import com.google.firebase.firestore.pipeline.Ordering +import com.google.firebase.firestore.pipeline.PipelineOptions +import com.google.firebase.firestore.pipeline.RemoveFieldsStage +import com.google.firebase.firestore.pipeline.ReplaceStage +import com.google.firebase.firestore.pipeline.SampleStage +import com.google.firebase.firestore.pipeline.SelectStage +import com.google.firebase.firestore.pipeline.Selectable +import com.google.firebase.firestore.pipeline.SortStage +import com.google.firebase.firestore.pipeline.BaseStage +import com.google.firebase.firestore.pipeline.UnionStage +import com.google.firebase.firestore.pipeline.UnnestStage +import com.google.firebase.firestore.pipeline.WhereStage +import com.google.firestore.v1.ExecutePipelineRequest +import com.google.firestore.v1.StructuredPipeline +import com.google.firestore.v1.Value + +class Pipeline +internal constructor( + internal val firestore: FirebaseFirestore, + internal val userDataReader: UserDataReader, + private val stages: FluentIterable> +) { + internal constructor( + firestore: FirebaseFirestore, + userDataReader: UserDataReader, + stage: BaseStage<*> + ) : this(firestore, userDataReader, FluentIterable.of(stage)) + + private fun append(stage: BaseStage<*>): Pipeline { + return Pipeline(firestore, userDataReader, stages.append(stage)) + } + + fun execute(): Task = execute(PipelineOptions.DEFAULT) + + fun execute(options: PipelineOptions): Task { + val observerTask = ObserverSnapshotTask() + firestore.callClient { call -> call!!.executePipeline(toProto(options), observerTask) } + return observerTask.task + } + + internal fun documentReference(key: DocumentKey): DocumentReference { + return DocumentReference(key, firestore) + } + + private fun toProto(options: PipelineOptions): ExecutePipelineRequest { + val database = firestore.databaseId + val builder = ExecutePipelineRequest.newBuilder() + builder.database = "projects/${database.projectId}/databases/${database.databaseId}" + builder.structuredPipeline = toStructuredPipelineProto() + return builder.build() + } + + private fun toStructuredPipelineProto(): StructuredPipeline { + val builder = StructuredPipeline.newBuilder() + builder.pipeline = toPipelineProto() + return builder.build() + } + + internal fun toPipelineProto(): com.google.firestore.v1.Pipeline = + com.google.firestore.v1.Pipeline.newBuilder() + .addAllStages(stages.map { it.toProtoStage(userDataReader) }) + .build() + + /** + * Adds a stage to the pipeline by specifying the stage name as an argument. This does not offer + * any type safety on the stage params and requires the caller to know the order (and optionally + * names) of parameters accepted by the stage. + * + * This method provides a way to call stages that are supported by the Firestore backend but that + * are not implemented in the SDK version being used. + * + * @param stage An [Stage] object that specifies stage name and parameters. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun addStage(stage: Stage): Pipeline = append(stage) + + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous stages + * or constants. You can use this to create new fields or overwrite existing ones. + * + * The added fields are defined using [Selectable]s, which can be: + * + * - [Field]: References an existing document field. + * - [ExprWithAlias]: Represents the result of a expression with an assigned alias name using + * [Expr.alias] + * + * @param field The first field to add to the documents, specified as a [Selectable]. + * @param additionalFields The fields to add to the documents, specified as [Selectable]s. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun addFields(field: Selectable, vararg additionalFields: Selectable): Pipeline = + append(AddFieldsStage(arrayOf(field, *additionalFields))) + + /** + * Remove fields from outputs of previous stages. + * + * @param field The first [Field] to remove. + * @param additionalFields Optional additional [Field]s to remove. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun removeFields(field: Field, vararg additionalFields: Field): Pipeline = + append(RemoveFieldsStage(arrayOf(field, *additionalFields))) + + /** + * Remove fields from outputs of previous stages. + * + * @param field The first [String] name of field to remove. + * @param additionalFields Optional additional [String] name of fields to remove. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun removeFields(field: String, vararg additionalFields: String): Pipeline = + append( + RemoveFieldsStage( + arrayOf(Expr.field(field), *additionalFields.map(Expr::field).toTypedArray()) + ) + ) + + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + * The selected fields are defined using [Selectable] expressions, which can be: + * + * - [String]: Name of an existing field + * - [Field]: Reference to an existing field. + * - [ExprWithAlias]: Represents the result of a expression with an assigned alias name using + * [Expr.alias] + * + * If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields] + * instead if only additions are desired. + * + * @param selection The first field to include in the output documents, specified as a + * [Selectable] expression. + * @param additionalSelections Optional additional fields to include in the output documents, + * specified as [Selectable] expressions or string values representing field names. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun select(selection: Selectable, vararg additionalSelections: Any): Pipeline = + append( + SelectStage( + arrayOf(selection, *additionalSelections.map(Selectable::toSelectable).toTypedArray()) + ) + ) + + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + * The selected fields are defined using [Selectable] expressions, which can be: + * + * - [String]: Name of an existing field + * - [Field]: Reference to an existing field. + * - [ExprWithAlias]: Represents the result of a expression with an assigned alias name using + * [Expr.alias] + * + * If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields] + * instead if only additions are desired. + * + * @param fieldName The first field to include in the output documents, specified as a string + * value representing a field names. + * @param additionalSelections Optional additional fields to include in the output documents, + * specified as [Selectable] expressions or string values representing field names. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun select(fieldName: String, vararg additionalSelections: Any): Pipeline = + append( + SelectStage( + arrayOf( + Expr.field(fieldName), + *additionalSelections.map(Selectable::toSelectable).toTypedArray() + ) + ) + ) + + /** + * Sorts the documents from previous stages based on one or more [Ordering] criteria. + * + * This stage allows you to order the results of your pipeline. You can specify multiple + * [Ordering] instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + * @param order The first [Ordering] instance specifying the sorting criteria. + * @param additionalOrders Optional additional [Ordering] instances specifying the sorting + * criteria. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun sort(order: Ordering, vararg additionalOrders: Ordering): Pipeline = + append(SortStage(arrayOf(order, *additionalOrders))) + + /** + * Filters the documents from previous stages to only include those matching the specified + * [BooleanExpr]. + * + * This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * + * You can filter documents based on their field values, using implementations of [BooleanExpr], + * typically including but not limited to: + * + * - field comparators: [Expr.eq], [Expr.lt] (less than), [Expr.gt] (greater than), etc. + * - logical operators: [Expr.and], [Expr.or], [Expr.not], etc. + * - advanced functions: [Expr.regexMatch], [Expr.arrayContains], etc. + * + * @param condition The [BooleanExpr] to apply. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun where(condition: BooleanExpr): Pipeline = append(WhereStage(condition)) + + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + * This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with [limit] to control the size of each + * page. + * + * @param offset The number of documents to skip. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun offset(offset: Int): Pipeline = append(OffsetStage(offset)) + + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + * This stage is particularly useful when you want to retrieve a controlled subset of data from a + * potentially large result set. It's often used for: + * + * - **Pagination:** In combination with [offset] to retrieve specific pages of results. + * - **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections. + * + * @param limit The maximum number of documents to return. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun limit(limit: Int): Pipeline = append(LimitStage(limit)) + + /** + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with unique + * combinations of [Expr] values [Field], [FunctionExpr], etc). + * + * The parameters to this stage are defined using [Selectable] expressions or strings: + * + * - [String]: Name of an existing field + * - [Field]: References an existing document field. + * - [ExprWithAlias]: Represents the result of a function with an assigned alias name using + * [Expr.alias] + * + * @param group The [Selectable] expression to consider when determining distinct value + * combinations. + * @param additionalGroups The [Selectable] expressions to consider when determining distinct + * value combinations or [String]s representing field names. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun distinct(group: Selectable, vararg additionalGroups: Any): Pipeline = + append( + DistinctStage(arrayOf(group, *additionalGroups.map(Selectable::toSelectable).toTypedArray())) + ) + + /** + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with unique + * combinations of [Expr] values ([Field], [FunctionExpr], etc). + * + * The parameters to this stage are defined using [Selectable] expressions or strings: + * + * - [String]: Name of an existing field + * - [Field]: References an existing document field. + * - [ExprWithAlias]: Represents the result of a function with an assigned alias name using + * [Expr.alias] + * + * @param groupField The [String] representing field name. + * @param additionalGroups The [Selectable] expressions to consider when determining distinct + * value combinations or [String]s representing field names. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun distinct(groupField: String, vararg additionalGroups: Any): Pipeline = + append( + DistinctStage( + arrayOf( + Expr.field(groupField), + *additionalGroups.map(Selectable::toSelectable).toTypedArray() + ) + ) + ) + + /** + * Performs aggregation operations on the documents from previous stages. + * + * This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using [AggregateWithAlias] expressions which are typically results of + * calling [AggregateFunction.alias] on [AggregateFunction] instances. + * + * @param accumulator The first [AggregateWithAlias] expression, wrapping an [AggregateFunction] + * with an alias for the accumulated results. + * @param additionalAccumulators The [AggregateWithAlias] expressions, each wrapping an + * [AggregateFunction] with an alias for the accumulated results. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun aggregate( + accumulator: AggregateWithAlias, + vararg additionalAccumulators: AggregateWithAlias + ): Pipeline = append(AggregateStage.withAccumulators(accumulator, *additionalAccumulators)) + + /** + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + * This stage allows you to calculate aggregate values over a set of documents, optionally grouped + * by one or more fields or functions. You can specify: + * + * - **Grouping Fields or Expressions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. If no + * grouping fields are provided, a single group containing all documents is used. Not specifying + * groups is the same as putting the entire inputs into one group. + * + * - **AggregateFunctions:** One or more accumulation operations to perform within each group. + * These are defined using [AggregateWithAlias] expressions, which are typically created by + * calling [AggregateFunction.alias] on [AggregateFunction] instances. Each aggregation calculates + * a value (e.g., sum, average, count) based on the documents within its group. + * + * @param aggregateStage An [AggregateStage] object that specifies the grouping fields (if any) + * and the aggregation operations to perform. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun aggregate(aggregateStage: AggregateStage): Pipeline = append(aggregateStage) + + /** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + * + * @param vectorField A [Field] that contains vector to search on. + * @param vectorValue The [VectorValue] in array form that is used to measure the distance from + * [vectorField] values in the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun findNearest( + vectorField: Field, + vectorValue: DoubleArray, + distanceMeasure: FindNearestStage.DistanceMeasure, + ): Pipeline = append(FindNearestStage.of(vectorField, vectorValue, distanceMeasure)) + + /** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + * + * @param vectorField A [String] specifying the vector field to search on. + * @param vectorValue The [VectorValue] in array form that is used to measure the distance from + * [vectorField] values in the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun findNearest( + vectorField: String, + vectorValue: DoubleArray, + distanceMeasure: FindNearestStage.DistanceMeasure, + ): Pipeline = append(FindNearestStage.of(vectorField, vectorValue, distanceMeasure)) + + /** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + * + * @param vectorField A [Field] that contains vector to search on. + * @param vectorValue The [VectorValue] used to measure the distance from [vectorField] values in + * the documents. + * @param distanceMeasure specifies what type of distance is calculated. when performing the + * search. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun findNearest( + vectorField: Field, + vectorValue: VectorValue, + distanceMeasure: FindNearestStage.DistanceMeasure, + ): Pipeline = append(FindNearestStage.of(vectorField, vectorValue, distanceMeasure)) + + /** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + * + * @param vectorField A [String] specifying the vector field to search on. + * @param vectorValue The [VectorValue] used to measure the distance from [vectorField] values in + * the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun findNearest( + vectorField: String, + vectorValue: VectorValue, + distanceMeasure: FindNearestStage.DistanceMeasure, + ): Pipeline = append(FindNearestStage.of(vectorField, vectorValue, distanceMeasure)) + + /** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + * + * @param stage An [FindNearestStage] object that specifies the search parameters. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun findNearest(stage: FindNearestStage): Pipeline = append(stage) + + /** + * Fully overwrites all fields in a document with those coming from a nested map. + * + * This stage allows you to emit a map value as a document. Each key of the map becomes a field on + * the document that contains the corresponding value. + * + * @param field The [String] specifying the field name containing the nested map. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun replace(field: String): Pipeline = replace(Expr.field(field)) + + /** + * Fully overwrites all fields in a document with those coming from a nested map. + * + * This stage allows you to emit a map value as a document. Each key of the map becomes a field on + * the document that contains the corresponding value. + * + * @param mapValue The [Expr] or [Field] containing the nested map. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun replace(mapValue: Expr): Pipeline = + append(ReplaceStage(mapValue, ReplaceStage.Mode.FULL_REPLACE)) + + /** + * Performs a pseudo-random sampling of the input documents. + * + * The [documents] parameter represents the target number of documents to produce and must be a + * non-negative integer value. If the previous stage produces less than size documents, the entire + * previous results are returned. If the previous stage produces more than size, this outputs a + * sample of exactly size entries where any sample is equally likely. + * + * @param documents The number of documents to emit. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun sample(documents: Int): Pipeline = append(SampleStage.withDocLimit(documents)) + + /** + * Performs a pseudo-random sampling of the input documents. + * + * @param sample An [SampleStage] object that specifies how sampling is performed. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun sample(sample: SampleStage): Pipeline = append(sample) + + /** + * Performs union of all documents from two pipelines, including duplicates. + * + * This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` Pipeline given in parameter. The order of documents emitted + * from this stage is undefined. + * + * @param other The other [Pipeline] that is part of union. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun union(other: Pipeline): Pipeline = append(UnionStage(other)) + + /** + * Takes a specified array from the input documents and outputs a document for each element with + * the element stored in a field with name specified by the alias. + * + * For each document emitted by the prior stage, this stage will emit zero or more augmented + * documents. The input array found in the previous stage document field specified by the + * [arrayField] parameter, will for each element of the input array produce an augmented document. + * The element of the input array will be stored in a field with name specified by [alias] + * parameter on the augmented document. + * + * @param arrayField The name of the field containing the array. + * @param alias The name of field to store emitted element of array. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun unnest(arrayField: String, alias: String): Pipeline = + unnest(Expr.field(arrayField).alias(alias)) + + /** + * Takes a specified array from the input documents and outputs a document for each element with + * the element stored in a field with name specified by the alias. + * + * For each document emitted by the prior stage, this stage will emit zero or more augmented + * documents. The input array is found in parameter [arrayWithAlias], which can be an [Expr] with + * an alias specified via [Expr.alias], or a [Field] that can also have alias specified. For each + * element of the input array, an augmented document will be produced. The element of input array + * will be stored in a field with name specified by the alias of the [arrayWithAlias] parameter. + * If the [arrayWithAlias] is a [Field] with no alias, then the original array field will be + * replaced with the individual element. + * + * @param arrayWithAlias The input array with field alias to store output element of array. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun unnest(arrayWithAlias: Selectable): Pipeline = append(UnnestStage(arrayWithAlias)) + + /** + * Takes a specified array from the input documents and outputs a document for each element with + * the element stored in a field with name specified by the alias. + * + * For each document emitted by the prior stage, this stage will emit zero or more augmented + * documents. The input array specified in the [unnestStage] parameter will for each element of + * the input array produce an augmented document. The element of the input array will be stored in + * a field with a name specified by the [unnestStage] parameter. + * + * Optionally, an index field can also be added to emitted documents. See [UnnestStage] for + * further information. + * + * @param unnestStage An [UnnestStage] object that specifies the search parameters. + * @return A new [Pipeline] object with this stage appended to the stage list. + */ + fun unnest(unnestStage: UnnestStage): Pipeline = append(unnestStage) + + private inner class ObserverSnapshotTask : PipelineResultObserver { + private val userDataWriter = + UserDataWriter(firestore, DocumentSnapshot.ServerTimestampBehavior.DEFAULT) + private val taskCompletionSource = TaskCompletionSource() + private val results: ImmutableList.Builder = ImmutableList.builder() + override fun onDocument( + key: DocumentKey?, + data: Map, + createTime: Timestamp?, + updateTime: Timestamp? + ) { + results.add( + PipelineResult( + firestore, + userDataWriter, + if (key == null) null else DocumentReference(key, firestore), + data, + createTime, + updateTime + ) + ) + } + + override fun onComplete(executionTime: Timestamp) { + taskCompletionSource.setResult(PipelineSnapshot(executionTime, results.build())) + } + + override fun onError(exception: FirebaseFirestoreException) { + taskCompletionSource.setException(exception) + } + + val task: Task + get() = taskCompletionSource.task + } +} + +/** Start of a Firestore Pipeline */ +class PipelineSource internal constructor(private val firestore: FirebaseFirestore) { + + /** + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * @return A new [Pipeline] object that is equivalent to [query] + * @throws [IllegalArgumentException] Thrown if the [query] provided targets a different project + * or database than the pipeline. + */ + fun convertFrom(query: Query): Pipeline { + if (query.firestore.databaseId != firestore.databaseId) { + throw IllegalArgumentException("Provided query is from a different Firestore instance.") + } + return query.query.toPipeline(firestore, firestore.userDataReader) + } + + /** + * Convert the given Aggregate Query into an equivalent Pipeline. + * + * @param aggregateQuery An Aggregate Query to be converted into a Pipeline. + * @return A new [Pipeline] object that is equivalent to [aggregateQuery] + * @throws [IllegalArgumentException] Thrown if the [aggregateQuery] provided targets a different + * project or database than the pipeline. + */ + fun convertFrom(aggregateQuery: AggregateQuery): Pipeline { + val aggregateFields = aggregateQuery.aggregateFields + return convertFrom(aggregateQuery.query) + .aggregate( + aggregateFields.first().toPipeline(), + *aggregateFields.drop(1).map(AggregateField::toPipeline).toTypedArray() + ) + } + + /** + * Set the pipeline's source to the collection specified by the given path. + * + * @param path A path to a collection that will be the source of this pipeline. + * @return A new [Pipeline] object with documents from target collection. + */ + fun collection(path: String): Pipeline = collection(CollectionSource.of(path)) + + /** + * Set the pipeline's source to the collection specified by the given [CollectionReference]. + * + * @param ref A [CollectionReference] for a collection that will be the source of this pipeline. + * @return A new [Pipeline] object with documents from target collection. + * @throws [IllegalArgumentException] Thrown if the [ref] provided targets a different project or + * database than the pipeline. + */ + fun collection(ref: CollectionReference): Pipeline = collection(CollectionSource.of(ref)) + + /** + * Set the pipeline's source to the collection specified by CollectionSource. + * + * @param stage A [CollectionSource] that will be the source of this pipeline. + * @return Pipeline with documents from target collection. + * @throws [IllegalArgumentException] Thrown if the [stage] provided targets a different project + * or database than the pipeline. + */ + fun collection(stage: CollectionSource): Pipeline { + if (stage.firestore != null && stage.firestore.databaseId != firestore.databaseId) { + throw IllegalArgumentException("Provided collection is from a different Firestore instance.") + } + return Pipeline(firestore, firestore.userDataReader, stage) + } + + /** + * Set the pipeline's source to the collection group with the given id. + * + * @param collectionId The id of a collection group that will be the source of this pipeline. + */ + fun collectionGroup(collectionId: String): Pipeline = + pipeline(CollectionGroupSource.of((collectionId))) + + fun pipeline(stage: CollectionGroupSource): Pipeline = + Pipeline(firestore, firestore.userDataReader, stage) + + /** + * Set the pipeline's source to be all documents in this database. + * + * @return A new [Pipeline] object with all documents in this database. + */ + fun database(): Pipeline = Pipeline(firestore, firestore.userDataReader, DatabaseSource()) + + /** + * Set the pipeline's source to the documents specified by the given paths. + * + * @param documents Paths specifying the individual documents that will be the source of this + * pipeline. + * @return A new [Pipeline] object with [documents]. + */ + fun documents(vararg documents: String): Pipeline = + // Validate document path by converting to DocumentReference + documents(*documents.map(firestore::document).toTypedArray()) + + /** + * Set the pipeline's source to the documents specified by the given DocumentReferences. + * + * @param documents DocumentReferences specifying the individual documents that will be the source + * of this pipeline. + * @return Pipeline with [documents]. + * @throws [IllegalArgumentException] Thrown if the [documents] provided targets a different + * project or database than the pipeline. + */ + fun documents(vararg documents: DocumentReference): Pipeline { + val databaseId = firestore.databaseId + for (document in documents) { + if (document.firestore.databaseId != databaseId) { + throw IllegalArgumentException( + "Provided document reference is from a different Firestore instance." + ) + } + } + return Pipeline( + firestore, + firestore.userDataReader, + DocumentsSource(documents.map { docRef -> "/" + docRef.path }.toTypedArray()) + ) + } +} + +/** + */ +class PipelineSnapshot +internal constructor(executionTime: Timestamp, results: List) : + Iterable { + + /** The time at which the pipeline producing this result is executed. */ + val executionTime: Timestamp = executionTime + + /** List of all the results */ + val results: List = results + + override fun iterator() = results.iterator() +} + +class PipelineResult +internal constructor( + private val firestore: FirebaseFirestore, + private val userDataWriter: UserDataWriter, + ref: DocumentReference?, + private val fields: Map, + createTime: Timestamp?, + updateTime: Timestamp?, +) { + + /** The time the document was created. Null if this result is not a document. */ + val createTime: Timestamp? = createTime + + /** + * The time the document was last updated (at the time the snapshot was generated). Null if this + * result is not a document. + */ + val updateTime: Timestamp? = updateTime + + /** + * The reference to the document, if the query returns the `__name__` field for a document. The + * name field will be returned by default if querying a document. + * + * The `__name__` field will not be returned if the query projects away this field. For example: + * ``` + * // this query does not select the `__name__` field as part of the select stage, + * // so the __name__ field will not be in the output docs from this stage + * db.pipeline().collection("books").select("title", "desc") + * ``` + * + * The `__name__` field will not be returned from queries with aggregate or distinct stages. + * + * @return [DocumentReference] Reference to the document, if applicable. + */ + val ref: DocumentReference? = ref + + /** + * Returns the ID of the document represented by this result. Returns null if this result is not + * corresponding to a Firestore document. + * + * @return ID of document, if applicable. + */ + fun getId(): String? = ref?.id + + /** + * Retrieves all fields in the result as an object map. + * + * @return Map of field names to objects. + */ + fun getData(): Map = userDataWriter.convertObject(fields) + + private fun extractNestedValue(fieldPath: FieldPath): Value? { + val segments = fieldPath.internalPath.iterator() + if (!segments.hasNext()) { + return Values.encodeValue(fields) + } + val firstSegment = segments.next() + if (!fields.containsKey(firstSegment)) { + return null + } + var value: Value? = fields[firstSegment] + for (segment in segments) { + if (value == null || !value.hasMapValue()) { + return null + } + value = value.mapValue.getFieldsOrDefault(segment, null) + } + return value + } + + /** + * Retrieves the field specified by [field]. + * + * @param field The field path (e.g. "foo" or "foo.bar") to a specific field. + * @return The data at the specified field location or null if no such field exists. + */ + fun get(field: String): Any? = get(FieldPath.fromDotSeparatedPath(field)) + + /** + * Retrieves the field specified by [fieldPath]. + * + * @param fieldPath The field path to a specific field. + * @return The data at the specified field location or null if no such field exists. + */ + fun get(fieldPath: FieldPath): Any? = userDataWriter.convertValue(extractNestedValue(fieldPath)) + + override fun toString() = "PipelineResult{ref=$ref, updateTime=$updateTime}, data=${getData()}" +} + +internal interface PipelineResultObserver { + fun onDocument( + key: DocumentKey?, + data: Map, + createTime: Timestamp?, + updateTime: Timestamp? + ) + fun onComplete(executionTime: Timestamp) + fun onError(exception: FirebaseFirestoreException) +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataReader.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataReader.java index 297479d0262..97c9d9d33e1 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataReader.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataReader.java @@ -19,7 +19,7 @@ import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; -import com.google.firebase.Timestamp; +import com.google.common.base.Function; import com.google.firebase.firestore.FieldValue.ArrayRemoveFieldValue; import com.google.firebase.firestore.FieldValue.ArrayUnionFieldValue; import com.google.firebase.firestore.FieldValue.DeleteFieldValue; @@ -37,6 +37,7 @@ import com.google.firebase.firestore.model.mutation.FieldMask; import com.google.firebase.firestore.model.mutation.NumericIncrementTransformOperation; import com.google.firebase.firestore.model.mutation.ServerTimestampOperation; +import com.google.firebase.firestore.pipeline.Expr; import com.google.firebase.firestore.util.Assert; import com.google.firebase.firestore.util.CustomClassMapper; import com.google.firebase.firestore.util.Util; @@ -44,9 +45,7 @@ import com.google.firestore.v1.MapValue; import com.google.firestore.v1.Value; import com.google.protobuf.NullValue; -import com.google.type.LatLng; import java.util.ArrayList; -import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -231,7 +230,7 @@ private ObjectValue convertAndParseDocumentData(Object input, ParseContext conte Object converted = CustomClassMapper.convertToPlainJavaTypes(input); Value parsedValue = parseData(converted, context); - if (parsedValue.getValueTypeCase() != Value.ValueTypeCase.MAP_VALUE) { + if (!parsedValue.hasMapValue()) { throw new IllegalArgumentException(badDocReason + "of type: " + Util.typeName(input)); } return new ObjectValue(parsedValue); @@ -387,90 +386,38 @@ private void parseSentinelFieldValue( * @return The parsed value, or {@code null} if the value was a FieldValue sentinel that should * not be included in the resulting parsed data. */ - private Value parseScalarValue(Object input, ParseContext context) { + public Value parseScalarValue(Object input, ParseContext context) { if (input == null) { - return Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build(); - } else if (input instanceof Integer) { - return Value.newBuilder().setIntegerValue((Integer) input).build(); - } else if (input instanceof Long) { - return Value.newBuilder().setIntegerValue((Long) input).build(); - } else if (input instanceof Float) { - return Value.newBuilder().setDoubleValue(((Float) input).doubleValue()).build(); - } else if (input instanceof Double) { - return Value.newBuilder().setDoubleValue((Double) input).build(); - } else if (input instanceof Boolean) { - return Value.newBuilder().setBooleanValue((Boolean) input).build(); - } else if (input instanceof String) { - return Value.newBuilder().setStringValue((String) input).build(); - } else if (input instanceof Date) { - Timestamp timestamp = new Timestamp((Date) input); - return parseTimestamp(timestamp); - } else if (input instanceof Timestamp) { - Timestamp timestamp = (Timestamp) input; - return parseTimestamp(timestamp); - } else if (input instanceof GeoPoint) { - GeoPoint geoPoint = (GeoPoint) input; - return Value.newBuilder() - .setGeoPointValue( - LatLng.newBuilder() - .setLatitude(geoPoint.getLatitude()) - .setLongitude(geoPoint.getLongitude())) - .build(); - } else if (input instanceof Blob) { - return Value.newBuilder().setBytesValue(((Blob) input).toByteString()).build(); - } else if (input instanceof DocumentReference) { - DocumentReference ref = (DocumentReference) input; - // TODO: Rework once pre-converter is ported to Android. - if (ref.getFirestore() != null) { - DatabaseId otherDb = ref.getFirestore().getDatabaseId(); - if (!otherDb.equals(databaseId)) { - throw context.createError( - String.format( - "Document reference is for database %s/%s but should be for database %s/%s", - otherDb.getProjectId(), - otherDb.getDatabaseId(), - databaseId.getProjectId(), - databaseId.getDatabaseId())); - } - } - return Value.newBuilder() - .setReferenceValue( - String.format( - "projects/%s/databases/%s/documents/%s", - databaseId.getProjectId(), - databaseId.getDatabaseId(), - ((DocumentReference) input).getPath())) - .build(); - } else if (input instanceof VectorValue) { - return parseVectorValue(((VectorValue) input), context); + return Values.NULL_VALUE; } else if (input.getClass().isArray()) { throw context.createError("Arrays are not supported; use a List instead"); + } else if (input instanceof DocumentReference) { + DocumentReference ref = (DocumentReference) input; + validateDocumentReference(ref, context::createError); + return Values.encodeValue(ref); + } else if (input instanceof Expr) { + throw context.createError("Pipeline expressions are not supported user objects"); } else { - throw context.createError("Unsupported type: " + Util.typeName(input)); + try { + return Values.encodeAnyValue(input); + } catch (IllegalArgumentException e) { + throw context.createError("Unsupported type: " + Util.typeName(input)); + } } } - private Value parseVectorValue(VectorValue vector, ParseContext context) { - MapValue.Builder mapBuilder = MapValue.newBuilder(); - - mapBuilder.putFields(Values.TYPE_KEY, Values.VECTOR_VALUE_TYPE); - mapBuilder.putFields(Values.VECTOR_MAP_VECTORS_KEY, parseData(vector.toList(), context)); - - return Value.newBuilder().setMapValue(mapBuilder).build(); - } - - private Value parseTimestamp(Timestamp timestamp) { - // Firestore backend truncates precision down to microseconds. To ensure offline mode works - // the same with regards to truncation, perform the truncation immediately without waiting for - // the backend to do that. - int truncatedNanoseconds = timestamp.getNanoseconds() / 1000 * 1000; - - return Value.newBuilder() - .setTimestampValue( - com.google.protobuf.Timestamp.newBuilder() - .setSeconds(timestamp.getSeconds()) - .setNanos(truncatedNanoseconds)) - .build(); + public void validateDocumentReference( + DocumentReference ref, Function createError) { + DatabaseId otherDb = ref.getFirestore().getDatabaseId(); + if (!otherDb.equals(databaseId)) { + throw createError.apply( + String.format( + "Document reference is for database %s/%s but should be for database %s/%s", + otherDb.getProjectId(), + otherDb.getDatabaseId(), + databaseId.getProjectId(), + databaseId.getDatabaseId())); + } } private List parseArrayTransformElements(List elements) { diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataWriter.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataWriter.java index d6ac7b90bba..8c90a4d02e4 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataWriter.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/UserDataWriter.java @@ -78,7 +78,7 @@ public Object convertValue(Value value) { case TYPE_ORDER_BOOLEAN: return value.getBooleanValue(); case TYPE_ORDER_NUMBER: - return value.getValueTypeCase().equals(Value.ValueTypeCase.INTEGER_VALUE) + return value.hasIntegerValue() ? (Object) value.getIntegerValue() // Cast to Object to prevent type coercion to double : (Object) value.getDoubleValue(); case TYPE_ORDER_STRING: diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/VectorValue.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/VectorValue.java index 2f355648376..efcefd45bf4 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/VectorValue.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/VectorValue.java @@ -16,9 +16,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; /** * Represent a vector type in Firestore documents. @@ -41,21 +39,6 @@ public double[] toArray() { return this.values.clone(); } - /** - * Package private. - * Returns a representation of the vector as a List. - * - * @return A representation of the vector as an List - */ - @NonNull - List toList() { - ArrayList result = new ArrayList(this.values.length); - for (int i = 0; i < this.values.length; i++) { - result.add(i, this.values[i]); - } - return result; - } - /** * Returns true if this VectorValue is equal to the provided object. * diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/CompositeFilter.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/CompositeFilter.java index 26654f7a1ba..090ddf9c17b 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/CompositeFilter.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/CompositeFilter.java @@ -17,6 +17,7 @@ import android.text.TextUtils; import androidx.annotation.Nullable; import com.google.firebase.firestore.model.Document; +import com.google.firebase.firestore.pipeline.BooleanExpr; import com.google.firebase.firestore.util.Function; import java.util.ArrayList; import java.util.Collections; @@ -167,6 +168,23 @@ public String getCanonicalId() { return builder.toString(); } + @Override + BooleanExpr toPipelineExpr() { + BooleanExpr first = filters.get(0).toPipelineExpr(); + BooleanExpr[] additional = new BooleanExpr[filters.size() - 1]; + for (int i = 1, filtersSize = filters.size(); i < filtersSize; i++) { + additional[i - 1] = filters.get(i).toPipelineExpr(); + } + switch (operator) { + case AND: + return BooleanExpr.and(first, additional); + case OR: + return BooleanExpr.or(first, additional); + } + // Handle OPERATOR_UNSPECIFIED and UNRECOGNIZED cases as needed + throw new IllegalArgumentException("Unsupported operator: " + operator); + } + @Override public String toString() { return getCanonicalId(); diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FieldFilter.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FieldFilter.java index 6ebf26d0718..b702746f066 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FieldFilter.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FieldFilter.java @@ -14,13 +14,23 @@ package com.google.firebase.firestore.core; +import static com.google.firebase.firestore.model.Values.isNanValue; +import static com.google.firebase.firestore.pipeline.Expr.and; +import static com.google.firebase.firestore.pipeline.Expr.ifError; import static com.google.firebase.firestore.util.Assert.hardAssert; +import androidx.annotation.NonNull; + import com.google.firebase.firestore.model.Document; import com.google.firebase.firestore.model.FieldPath; import com.google.firebase.firestore.model.Values; +import com.google.firebase.firestore.pipeline.BooleanExpr; +import com.google.firebase.firestore.pipeline.Expr; +import com.google.firebase.firestore.pipeline.Field; import com.google.firebase.firestore.util.Assert; import com.google.firestore.v1.Value; + +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -172,6 +182,76 @@ public List getFilters() { return Collections.singletonList(this); } + @Override + BooleanExpr toPipelineExpr() { + Field x = new Field(field); + BooleanExpr exists = x.exists(); + switch (operator) { + case LESS_THAN: + return and(exists, x.lt(value)); + case LESS_THAN_OR_EQUAL: + return and(exists, x.lte(value)); + case EQUAL: + if (value.hasNullValue()) { + return and(exists, x.isNull()); + } else if (isNanValue(value)) { + // The isNan will error on non-numeric values. + return and(exists, ifError(x.isNan(), Expr.constant(false))); + } else { + return and(exists, x.eq(value)); + } + case NOT_EQUAL: + if (value.hasNullValue()) { + return and(exists, x.isNotNull()); + } else if (isNanValue(value)) { + // The isNotNan will error on non-numeric values. + return and(exists, ifError(x.isNotNan(), Expr.constant(true))); + } else { + return and(exists, x.neq(value)); + } + case GREATER_THAN: + return and(exists, x.gt(value)); + case GREATER_THAN_OR_EQUAL: + return and(exists, x.gte(value)); + case ARRAY_CONTAINS: + return and(exists, x.arrayContains(value)); + case ARRAY_CONTAINS_ANY: + return and(exists, x.arrayContainsAny(value.getArrayValue().getValuesList())); + case IN: + return and(exists, x.eqAny(value.getArrayValue().getValuesList())); + case NOT_IN: { + List list = value.getArrayValue().getValuesList(); + if (hasNaN(list)) { + return and(exists, x.notEqAny(filterNaN(list)), ifError(x.isNotNan(), Expr.constant(true))); + } else { + return and(exists, x.notEqAny(list)); + } + } + default: + // Handle OPERATOR_UNSPECIFIED and UNRECOGNIZED cases as needed + throw new IllegalArgumentException("Unsupported operator: " + operator); + } + } + + private static boolean hasNaN(List list) { + for (Value v : list) { + if (isNanValue(v)) { + return true; + } + } + return false; + } + + @NonNull + private static List filterNaN(List list) { + List listWithoutNan = new ArrayList<>(list.size() - 1); + for (Value v : list) { + if (isNanValue(v)) continue; + listWithoutNan.add(v); + } + return listWithoutNan; + } + @Override public String toString() { return getCanonicalId(); diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Filter.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Filter.java index 063b994f7a8..3f33bd3d5bc 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Filter.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Filter.java @@ -15,6 +15,7 @@ package com.google.firebase.firestore.core; import com.google.firebase.firestore.model.Document; +import com.google.firebase.firestore.pipeline.BooleanExpr; import java.util.List; public abstract class Filter { @@ -29,4 +30,6 @@ public abstract class Filter { /** Returns a list of all filters that are contained within this filter */ public abstract List getFilters(); + + abstract BooleanExpr toPipelineExpr(); } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FirestoreClient.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FirestoreClient.java index 6e2d9b87b84..d54e3458d52 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FirestoreClient.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/FirestoreClient.java @@ -27,6 +27,7 @@ import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.FirebaseFirestoreException.Code; import com.google.firebase.firestore.LoadBundleTask; +import com.google.firebase.firestore.PipelineResultObserver; import com.google.firebase.firestore.TransactionOptions; import com.google.firebase.firestore.auth.CredentialsProvider; import com.google.firebase.firestore.auth.User; @@ -49,6 +50,7 @@ import com.google.firebase.firestore.util.AsyncQueue; import com.google.firebase.firestore.util.Function; import com.google.firebase.firestore.util.Logger; +import com.google.firestore.v1.ExecutePipelineRequest; import com.google.firestore.v1.Value; import java.io.InputStream; import java.util.List; @@ -249,6 +251,10 @@ public Task> runAggregateQuery( return result.getTask(); } + public void executePipeline(ExecutePipelineRequest request, PipelineResultObserver observer) { + asyncQueue.enqueueAndForget(() -> remoteStore.executePipeline(request, observer)); + } + /** * Returns a task resolves when all the pending writes at the time when this method is called * received server acknowledgement. An acknowledgement can be either acceptance or rejections. diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/OrderBy.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/OrderBy.java index 8636fd0498a..1fd8a42ada5 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/OrderBy.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/OrderBy.java @@ -21,7 +21,7 @@ import com.google.firestore.v1.Value; /** Represents a sort order for a Firestore Query */ -public class OrderBy { +public final class OrderBy { /** The direction of the ordering */ public enum Direction { ASCENDING(1), diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Query.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Query.java index bf57dfdb7a3..ac4d499854f 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Query.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/core/Query.java @@ -14,14 +14,34 @@ package com.google.firebase.firestore.core; +import static com.google.firebase.firestore.pipeline.Expr.and; +import static com.google.firebase.firestore.pipeline.Expr.or; import static com.google.firebase.firestore.util.Assert.hardAssert; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.google.firebase.firestore.FirebaseFirestore; +import com.google.firebase.firestore.Pipeline; +import com.google.firebase.firestore.UserDataReader; import com.google.firebase.firestore.core.OrderBy.Direction; import com.google.firebase.firestore.model.Document; import com.google.firebase.firestore.model.DocumentKey; import com.google.firebase.firestore.model.FieldPath; import com.google.firebase.firestore.model.ResourcePath; +import com.google.firebase.firestore.pipeline.BooleanExpr; +import com.google.firebase.firestore.pipeline.CollectionGroupSource; +import com.google.firebase.firestore.pipeline.CollectionSource; +import com.google.firebase.firestore.pipeline.DocumentsSource; +import com.google.firebase.firestore.pipeline.Expr; +import com.google.firebase.firestore.pipeline.Field; +import com.google.firebase.firestore.pipeline.FunctionExpr; +import com.google.firebase.firestore.pipeline.InternalOptions; +import com.google.firebase.firestore.pipeline.Ordering; +import com.google.firebase.firestore.pipeline.BaseStage; +import com.google.firebase.firestore.util.BiFunction; +import com.google.firebase.firestore.util.Function; +import com.google.firebase.firestore.util.IntFunction; +import com.google.firestore.v1.Value; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -502,6 +522,115 @@ private synchronized Target toTarget(List orderBys) { } } + @NonNull + public Pipeline toPipeline(FirebaseFirestore firestore, UserDataReader userDataReader) { + Pipeline p = new Pipeline(firestore, userDataReader, pipelineSource(firestore)); + + // Filters + for (Filter filter : filters) { + p = p.where(filter.toPipelineExpr()); + } + + // Orders + List normalizedOrderBy = getNormalizedOrderBy(); + int size = normalizedOrderBy.size(); + List fields = new ArrayList<>(size); + List orderings = new ArrayList<>(size); + for (OrderBy order : normalizedOrderBy) { + Field field = new Field(order.getField()); + fields.add(field); + if (order.getDirection() == Direction.ASCENDING) { + orderings.add(field.ascending()); + } else { + orderings.add(field.descending()); + } + } + + if (fields.size() == 1) { + p = p.where(fields.get(0).exists()); + } else { + BooleanExpr[] conditions = skipFirstToArray(fields, BooleanExpr[]::new, Expr.Companion::exists); + p = p.where(and(fields.get(0).exists(), conditions)); + } + + if (startAt != null) { + p = p.where(whereConditionsFromCursor(startAt, fields, FunctionExpr::gt)); + } + + if (endAt != null) { + p = p.where(whereConditionsFromCursor(endAt, fields, FunctionExpr::lt)); + } + + // Cursors, Limit, Offset + if (hasLimit()) { + // TODO: Handle situation where user enters limit larger than integer. + if (limitType == LimitType.LIMIT_TO_FIRST) { + p = p.sort(orderings.get(0), skipFirstToArray(orderings, Ordering[]::new)); + p = p.limit((int) limit); + } else { + p = + p.sort( + orderings.get(0).reverse(), + skipFirstToArray(orderings, Ordering[]::new, Ordering::reverse)); + p = p.limit((int) limit); + p = p.sort(orderings.get(0), skipFirstToArray(orderings, Ordering[]::new)); + } + } else { + p = p.sort(orderings.get(0), skipFirstToArray(orderings, Ordering[]::new)); + } + + return p; + } + + // Many Pipelines require first parameter to be separated out from rest. + private static T[] skipFirstToArray(List list, IntFunction generator) { + int size = list.size(); + T[] result = generator.apply(size - 1); + for (int i = 1; i < size; i++) { + result[i-1] = list.get(i); + } + return result; + } + + // Many Pipelines require first parameter to be separated out from rest. + private static R[] skipFirstToArray(List list, IntFunction generator, Function map) { + int size = list.size(); + R[] result = generator.apply(size - 1); + for (int i = 1; i < size; i++) { + result[i-1] = map.apply(list.get(i)); + } + return result; + } + + private static BooleanExpr whereConditionsFromCursor( + Bound bound, List fields, BiFunction cmp) { + List boundPosition = bound.getPosition(); + int size = boundPosition.size(); + hardAssert(size <= fields.size(), "Bound positions must not exceed order fields."); + int last = size - 1; + BooleanExpr condition = cmp.apply(fields.get(last), boundPosition.get(last)); + if (bound.isInclusive()) { + condition = or(condition, Expr.eq(fields.get(last), boundPosition.get(last))); + } + for (int i = size - 2; i >= 0; i--) { + final Field field = fields.get(i); + final Value value = boundPosition.get(i); + condition = or(cmp.apply(field, value), and(field.eq(value), condition)); + } + return condition; + } + + @NonNull + private BaseStage pipelineSource(FirebaseFirestore firestore) { + if (isDocumentQuery()) { + return new DocumentsSource(path.canonicalString()); + } else if (isCollectionGroupQuery()) { + return CollectionGroupSource.of(collectionGroup); + } else { + return new CollectionSource(path.canonicalString(), firestore, InternalOptions.EMPTY); + } + } + /** * This method is marked as synchronized because it modifies the internal state in some cases. * diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/BasePath.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/BasePath.java index 66356e12595..6d800de05d4 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/BasePath.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/BasePath.java @@ -19,19 +19,26 @@ import androidx.annotation.NonNull; import com.google.firebase.firestore.util.Util; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; /** * BasePath represents a path sequence in the Firestore database. It is composed of an ordered * sequence of string segments. */ -public abstract class BasePath> implements Comparable { +public abstract class BasePath> implements Comparable, Iterable { final List segments; BasePath(List segments) { this.segments = segments; } + @NonNull + @Override + public Iterator iterator() { + return segments.iterator(); + } + public String getSegment(int index) { return segments.get(index); } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/FieldPath.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/FieldPath.java index c1de25410fe..051dfce922b 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/FieldPath.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/FieldPath.java @@ -14,6 +14,7 @@ package com.google.firebase.firestore.model; +import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -34,7 +35,8 @@ public static FieldPath fromSingleSegment(String fieldName) { } /** Creates a {@code FieldPath} from a list of parsed field path segments. */ - public static FieldPath fromSegments(List segments) { + @NonNull + public static FieldPath fromSegments(@NonNull List segments) { return segments.isEmpty() ? FieldPath.EMPTY_PATH : new FieldPath(segments); } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ObjectValue.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ObjectValue.java index a7ea2997618..581bbf8481b 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ObjectValue.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ObjectValue.java @@ -47,9 +47,7 @@ public static ObjectValue fromMap(Map value) { } public ObjectValue(Value value) { - hardAssert( - value.getValueTypeCase() == Value.ValueTypeCase.MAP_VALUE, - "ObjectValues should be backed by a MapValue"); + hardAssert(value.hasMapValue(), "ObjectValues should be backed by a MapValue"); hardAssert( !ServerTimestamps.isServerTimestamp(value), "ServerTimestamps should not be used as an ObjectValue"); @@ -103,7 +101,7 @@ private FieldMask extractFieldMask(MapValue value) { } @Nullable - private Value extractNestedValue(Value value, FieldPath fieldPath) { + private static Value extractNestedValue(Value value, FieldPath fieldPath) { if (fieldPath.isEmpty()) { return value; } else { @@ -180,8 +178,7 @@ private void setOverlay(FieldPath path, @Nullable Value value) { if (currentValue instanceof Map) { // Re-use a previously created map currentLevel = (Map) currentValue; - } else if (currentValue instanceof Value - && ((Value) currentValue).getValueTypeCase() == Value.ValueTypeCase.MAP_VALUE) { + } else if (currentValue instanceof Value && ((Value) currentValue).hasMapValue()) { // Convert the existing Protobuf MapValue into a Java map Map nextLevel = new HashMap<>(((Value) currentValue).getMapValue().getFieldsMap()); diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ResourcePath.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ResourcePath.java index c96fcbdc3ee..776953d55d2 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ResourcePath.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/ResourcePath.java @@ -14,6 +14,7 @@ package com.google.firebase.firestore.model; +import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -36,7 +37,7 @@ public static ResourcePath fromSegments(List segments) { return segments.isEmpty() ? ResourcePath.EMPTY : new ResourcePath(segments); } - public static ResourcePath fromString(String path) { + public static ResourcePath fromString(@NonNull String path) { // NOTE: The client is ignorant of any path segments containing escape // sequences (for example, __id123__) and just passes them through raw (they exist // for legacy reasons and should not be used frequently). @@ -65,13 +66,6 @@ public String canonicalString() { // NOTE: The client is ignorant of any path segments containing escape // sequences (for example, __id123__) and just passes them through raw (they exist // for legacy reasons and should not be used frequently). - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < segments.size(); i++) { - if (i > 0) { - builder.append("/"); - } - builder.append(segments.get(i)); - } - return builder.toString(); + return String.join("/", segments); } } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.java deleted file mode 100644 index 834fb2454a3..00000000000 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.java +++ /dev/null @@ -1,615 +0,0 @@ -// Copyright 2020 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.firebase.firestore.model; - -import static com.google.firebase.firestore.model.ServerTimestamps.getLocalWriteTime; -import static com.google.firebase.firestore.model.ServerTimestamps.isServerTimestamp; -import static com.google.firebase.firestore.util.Assert.fail; -import static com.google.firebase.firestore.util.Assert.hardAssert; - -import androidx.annotation.Nullable; -import com.google.firebase.firestore.util.Util; -import com.google.firestore.v1.ArrayValue; -import com.google.firestore.v1.ArrayValueOrBuilder; -import com.google.firestore.v1.MapValue; -import com.google.firestore.v1.Value; -import com.google.protobuf.ByteString; -import com.google.protobuf.NullValue; -import com.google.protobuf.Timestamp; -import com.google.type.LatLng; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -public class Values { - public static final String TYPE_KEY = "__type__"; - public static final Value NAN_VALUE = Value.newBuilder().setDoubleValue(Double.NaN).build(); - public static final Value NULL_VALUE = - Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build(); - public static final Value MIN_VALUE = NULL_VALUE; - public static final Value MAX_VALUE_TYPE = Value.newBuilder().setStringValue("__max__").build(); - public static final Value MAX_VALUE = - Value.newBuilder() - .setMapValue(MapValue.newBuilder().putFields(TYPE_KEY, MAX_VALUE_TYPE)) - .build(); - - public static final Value VECTOR_VALUE_TYPE = - Value.newBuilder().setStringValue("__vector__").build(); - public static final String VECTOR_MAP_VECTORS_KEY = "value"; - private static final Value MIN_VECTOR_VALUE = - Value.newBuilder() - .setMapValue( - MapValue.newBuilder() - .putFields(TYPE_KEY, VECTOR_VALUE_TYPE) - .putFields( - VECTOR_MAP_VECTORS_KEY, - Value.newBuilder().setArrayValue(ArrayValue.newBuilder()).build())) - .build(); - - /** - * The order of types in Firestore. This order is based on the backend's ordering, but modified to - * support server timestamps and {@link #MAX_VALUE}. - */ - public static final int TYPE_ORDER_NULL = 0; - - public static final int TYPE_ORDER_BOOLEAN = 1; - public static final int TYPE_ORDER_NUMBER = 2; - public static final int TYPE_ORDER_TIMESTAMP = 3; - public static final int TYPE_ORDER_SERVER_TIMESTAMP = 4; - public static final int TYPE_ORDER_STRING = 5; - public static final int TYPE_ORDER_BLOB = 6; - public static final int TYPE_ORDER_REFERENCE = 7; - public static final int TYPE_ORDER_GEOPOINT = 8; - public static final int TYPE_ORDER_ARRAY = 9; - public static final int TYPE_ORDER_VECTOR = 10; - public static final int TYPE_ORDER_MAP = 11; - - public static final int TYPE_ORDER_MAX_VALUE = Integer.MAX_VALUE; - - /** Returns the backend's type order of the given Value type. */ - public static int typeOrder(Value value) { - switch (value.getValueTypeCase()) { - case NULL_VALUE: - return TYPE_ORDER_NULL; - case BOOLEAN_VALUE: - return TYPE_ORDER_BOOLEAN; - case INTEGER_VALUE: - return TYPE_ORDER_NUMBER; - case DOUBLE_VALUE: - return TYPE_ORDER_NUMBER; - case TIMESTAMP_VALUE: - return TYPE_ORDER_TIMESTAMP; - case STRING_VALUE: - return TYPE_ORDER_STRING; - case BYTES_VALUE: - return TYPE_ORDER_BLOB; - case REFERENCE_VALUE: - return TYPE_ORDER_REFERENCE; - case GEO_POINT_VALUE: - return TYPE_ORDER_GEOPOINT; - case ARRAY_VALUE: - return TYPE_ORDER_ARRAY; - case MAP_VALUE: - if (isServerTimestamp(value)) { - return TYPE_ORDER_SERVER_TIMESTAMP; - } else if (isMaxValue(value)) { - return TYPE_ORDER_MAX_VALUE; - } else if (isVectorValue(value)) { - return TYPE_ORDER_VECTOR; - } else { - return TYPE_ORDER_MAP; - } - default: - throw fail("Invalid value type: " + value.getValueTypeCase()); - } - } - - public static boolean equals(Value left, Value right) { - if (left == right) { - return true; - } - - if (left == null || right == null) { - return false; - } - - int leftType = typeOrder(left); - int rightType = typeOrder(right); - if (leftType != rightType) { - return false; - } - - switch (leftType) { - case TYPE_ORDER_NUMBER: - return numberEquals(left, right); - case TYPE_ORDER_ARRAY: - return arrayEquals(left, right); - case TYPE_ORDER_VECTOR: - case TYPE_ORDER_MAP: - return objectEquals(left, right); - case TYPE_ORDER_SERVER_TIMESTAMP: - return getLocalWriteTime(left).equals(getLocalWriteTime(right)); - case TYPE_ORDER_MAX_VALUE: - return true; - default: - return left.equals(right); - } - } - - private static boolean numberEquals(Value left, Value right) { - if (left.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE - && right.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE) { - return left.getIntegerValue() == right.getIntegerValue(); - } else if (left.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE - && right.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE) { - return Double.doubleToLongBits(left.getDoubleValue()) - == Double.doubleToLongBits(right.getDoubleValue()); - } - - return false; - } - - private static boolean arrayEquals(Value left, Value right) { - ArrayValue leftArray = left.getArrayValue(); - ArrayValue rightArray = right.getArrayValue(); - - if (leftArray.getValuesCount() != rightArray.getValuesCount()) { - return false; - } - - for (int i = 0; i < leftArray.getValuesCount(); ++i) { - if (!equals(leftArray.getValues(i), rightArray.getValues(i))) { - return false; - } - } - - return true; - } - - private static boolean objectEquals(Value left, Value right) { - MapValue leftMap = left.getMapValue(); - MapValue rightMap = right.getMapValue(); - - if (leftMap.getFieldsCount() != rightMap.getFieldsCount()) { - return false; - } - - for (Map.Entry entry : leftMap.getFieldsMap().entrySet()) { - Value otherEntry = rightMap.getFieldsMap().get(entry.getKey()); - if (!equals(entry.getValue(), otherEntry)) { - return false; - } - } - - return true; - } - - /** Returns true if the Value list contains the specified element. */ - public static boolean contains(ArrayValueOrBuilder haystack, Value needle) { - for (Value haystackElement : haystack.getValuesList()) { - if (equals(haystackElement, needle)) { - return true; - } - } - return false; - } - - public static int compare(Value left, Value right) { - int leftType = typeOrder(left); - int rightType = typeOrder(right); - - if (leftType != rightType) { - return Util.compareIntegers(leftType, rightType); - } - - switch (leftType) { - case TYPE_ORDER_NULL: - case TYPE_ORDER_MAX_VALUE: - return 0; - case TYPE_ORDER_BOOLEAN: - return Util.compareBooleans(left.getBooleanValue(), right.getBooleanValue()); - case TYPE_ORDER_NUMBER: - return compareNumbers(left, right); - case TYPE_ORDER_TIMESTAMP: - return compareTimestamps(left.getTimestampValue(), right.getTimestampValue()); - case TYPE_ORDER_SERVER_TIMESTAMP: - return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); - case TYPE_ORDER_STRING: - return Util.compareUtf8Strings(left.getStringValue(), right.getStringValue()); - case TYPE_ORDER_BLOB: - return Util.compareByteStrings(left.getBytesValue(), right.getBytesValue()); - case TYPE_ORDER_REFERENCE: - return compareReferences(left.getReferenceValue(), right.getReferenceValue()); - case TYPE_ORDER_GEOPOINT: - return compareGeoPoints(left.getGeoPointValue(), right.getGeoPointValue()); - case TYPE_ORDER_ARRAY: - return compareArrays(left.getArrayValue(), right.getArrayValue()); - case TYPE_ORDER_MAP: - return compareMaps(left.getMapValue(), right.getMapValue()); - case TYPE_ORDER_VECTOR: - return compareVectors(left.getMapValue(), right.getMapValue()); - default: - throw fail("Invalid value type: " + leftType); - } - } - - public static int lowerBoundCompare( - Value left, boolean leftInclusive, Value right, boolean rightInclusive) { - int cmp = compare(left, right); - if (cmp != 0) { - return cmp; - } - - if (leftInclusive && !rightInclusive) { - return -1; - } else if (!leftInclusive && rightInclusive) { - return 1; - } - - return 0; - } - - public static int upperBoundCompare( - Value left, boolean leftInclusive, Value right, boolean rightInclusive) { - int cmp = compare(left, right); - if (cmp != 0) { - return cmp; - } - - if (leftInclusive && !rightInclusive) { - return 1; - } else if (!leftInclusive && rightInclusive) { - return -1; - } - - return 0; - } - - private static int compareNumbers(Value left, Value right) { - if (left.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE) { - double leftDouble = left.getDoubleValue(); - if (right.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE) { - return Util.compareDoubles(leftDouble, right.getDoubleValue()); - } else if (right.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE) { - return Util.compareMixed(leftDouble, right.getIntegerValue()); - } - } else if (left.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE) { - long leftLong = left.getIntegerValue(); - if (right.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE) { - return Util.compareLongs(leftLong, right.getIntegerValue()); - } else if (right.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE) { - return -1 * Util.compareMixed(right.getDoubleValue(), leftLong); - } - } - - throw fail("Unexpected values: %s vs %s", left, right); - } - - private static int compareTimestamps(Timestamp left, Timestamp right) { - int cmp = Util.compareLongs(left.getSeconds(), right.getSeconds()); - if (cmp != 0) { - return cmp; - } - return Util.compareIntegers(left.getNanos(), right.getNanos()); - } - - private static int compareReferences(String leftPath, String rightPath) { - String[] leftSegments = leftPath.split("/", -1); - String[] rightSegments = rightPath.split("/", -1); - - int minLength = Math.min(leftSegments.length, rightSegments.length); - for (int i = 0; i < minLength; i++) { - int cmp = leftSegments[i].compareTo(rightSegments[i]); - if (cmp != 0) { - return cmp; - } - } - return Util.compareIntegers(leftSegments.length, rightSegments.length); - } - - private static int compareGeoPoints(LatLng left, LatLng right) { - int comparison = Util.compareDoubles(left.getLatitude(), right.getLatitude()); - if (comparison == 0) { - return Util.compareDoubles(left.getLongitude(), right.getLongitude()); - } - return comparison; - } - - private static int compareArrays(ArrayValue left, ArrayValue right) { - int minLength = Math.min(left.getValuesCount(), right.getValuesCount()); - for (int i = 0; i < minLength; i++) { - int cmp = compare(left.getValues(i), right.getValues(i)); - if (cmp != 0) { - return cmp; - } - } - return Util.compareIntegers(left.getValuesCount(), right.getValuesCount()); - } - - private static int compareMaps(MapValue left, MapValue right) { - Iterator> iterator1 = - new TreeMap<>(left.getFieldsMap()).entrySet().iterator(); - Iterator> iterator2 = - new TreeMap<>(right.getFieldsMap()).entrySet().iterator(); - while (iterator1.hasNext() && iterator2.hasNext()) { - Map.Entry entry1 = iterator1.next(); - Map.Entry entry2 = iterator2.next(); - int keyCompare = Util.compareUtf8Strings(entry1.getKey(), entry2.getKey()); - if (keyCompare != 0) { - return keyCompare; - } - int valueCompare = compare(entry1.getValue(), entry2.getValue()); - if (valueCompare != 0) { - return valueCompare; - } - } - - // Only equal if both iterators are exhausted. - return Util.compareBooleans(iterator1.hasNext(), iterator2.hasNext()); - } - - private static int compareVectors(MapValue left, MapValue right) { - Map leftMap = left.getFieldsMap(); - Map rightMap = right.getFieldsMap(); - - // The vector is a map, but only vector value is compared. - ArrayValue leftArrayValue = leftMap.get(Values.VECTOR_MAP_VECTORS_KEY).getArrayValue(); - ArrayValue rightArrayValue = rightMap.get(Values.VECTOR_MAP_VECTORS_KEY).getArrayValue(); - - int lengthCompare = - Util.compareIntegers(leftArrayValue.getValuesCount(), rightArrayValue.getValuesCount()); - if (lengthCompare != 0) { - return lengthCompare; - } - - return compareArrays(leftArrayValue, rightArrayValue); - } - - /** Generate the canonical ID for the provided field value (as used in Target serialization). */ - public static String canonicalId(Value value) { - StringBuilder builder = new StringBuilder(); - canonifyValue(builder, value); - return builder.toString(); - } - - private static void canonifyValue(StringBuilder builder, Value value) { - switch (value.getValueTypeCase()) { - case NULL_VALUE: - builder.append("null"); - break; - case BOOLEAN_VALUE: - builder.append(value.getBooleanValue()); - break; - case INTEGER_VALUE: - builder.append(value.getIntegerValue()); - break; - case DOUBLE_VALUE: - builder.append(value.getDoubleValue()); - break; - case TIMESTAMP_VALUE: - canonifyTimestamp(builder, value.getTimestampValue()); - break; - case STRING_VALUE: - builder.append(value.getStringValue()); - break; - case BYTES_VALUE: - builder.append(Util.toDebugString(value.getBytesValue())); - break; - case REFERENCE_VALUE: - canonifyReference(builder, value); - break; - case GEO_POINT_VALUE: - canonifyGeoPoint(builder, value.getGeoPointValue()); - break; - case ARRAY_VALUE: - canonifyArray(builder, value.getArrayValue()); - break; - case MAP_VALUE: - canonifyObject(builder, value.getMapValue()); - break; - default: - throw fail("Invalid value type: " + value.getValueTypeCase()); - } - } - - private static void canonifyTimestamp(StringBuilder builder, Timestamp timestamp) { - builder.append(String.format("time(%s,%s)", timestamp.getSeconds(), timestamp.getNanos())); - } - - private static void canonifyGeoPoint(StringBuilder builder, LatLng latLng) { - builder.append(String.format("geo(%s,%s)", latLng.getLatitude(), latLng.getLongitude())); - } - - private static void canonifyReference(StringBuilder builder, Value value) { - hardAssert(isReferenceValue(value), "Value should be a ReferenceValue"); - builder.append(DocumentKey.fromName(value.getReferenceValue())); - } - - private static void canonifyObject(StringBuilder builder, MapValue mapValue) { - // Even though MapValue are likely sorted correctly based on their insertion order (for example, - // when received from the backend), local modifications can bring elements out of order. We need - // to re-sort the elements to ensure that canonical IDs are independent of insertion order. - List keys = new ArrayList<>(mapValue.getFieldsMap().keySet()); - Collections.sort(keys); - - builder.append("{"); - boolean first = true; - for (String key : keys) { - if (!first) { - builder.append(","); - } else { - first = false; - } - builder.append(key).append(":"); - canonifyValue(builder, mapValue.getFieldsOrThrow(key)); - } - builder.append("}"); - } - - private static void canonifyArray(StringBuilder builder, ArrayValue arrayValue) { - builder.append("["); - for (int i = 0; i < arrayValue.getValuesCount(); ++i) { - canonifyValue(builder, arrayValue.getValues(i)); - if (i != arrayValue.getValuesCount() - 1) { - builder.append(","); - } - } - builder.append("]"); - } - - /** Returns true if `value` is a INTEGER_VALUE. */ - public static boolean isInteger(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.INTEGER_VALUE; - } - - /** Returns true if `value` is a DOUBLE_VALUE. */ - public static boolean isDouble(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.DOUBLE_VALUE; - } - - /** Returns true if `value` is either a INTEGER_VALUE or a DOUBLE_VALUE. */ - public static boolean isNumber(@Nullable Value value) { - return isInteger(value) || isDouble(value); - } - - /** Returns true if `value` is an ARRAY_VALUE. */ - public static boolean isArray(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.ARRAY_VALUE; - } - - public static boolean isReferenceValue(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.REFERENCE_VALUE; - } - - public static boolean isNullValue(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.NULL_VALUE; - } - - public static boolean isNanValue(@Nullable Value value) { - return value != null && Double.isNaN(value.getDoubleValue()); - } - - public static boolean isMapValue(@Nullable Value value) { - return value != null && value.getValueTypeCase() == Value.ValueTypeCase.MAP_VALUE; - } - - public static Value refValue(DatabaseId databaseId, DocumentKey key) { - Value value = - Value.newBuilder() - .setReferenceValue( - String.format( - "projects/%s/databases/%s/documents/%s", - databaseId.getProjectId(), databaseId.getDatabaseId(), key.toString())) - .build(); - return value; - } - - public static Value MIN_BOOLEAN = Value.newBuilder().setBooleanValue(false).build(); - public static Value MIN_NUMBER = Value.newBuilder().setDoubleValue(Double.NaN).build(); - public static Value MIN_TIMESTAMP = - Value.newBuilder() - .setTimestampValue(Timestamp.newBuilder().setSeconds(Long.MIN_VALUE)) - .build(); - public static Value MIN_STRING = Value.newBuilder().setStringValue("").build(); - public static Value MIN_BYTES = Value.newBuilder().setBytesValue(ByteString.EMPTY).build(); - public static Value MIN_REFERENCE = refValue(DatabaseId.EMPTY, DocumentKey.empty()); - public static Value MIN_GEO_POINT = - Value.newBuilder() - .setGeoPointValue(LatLng.newBuilder().setLatitude(-90.0).setLongitude(-180.0)) - .build(); - public static Value MIN_ARRAY = - Value.newBuilder().setArrayValue(ArrayValue.getDefaultInstance()).build(); - public static Value MIN_MAP = - Value.newBuilder().setMapValue(MapValue.getDefaultInstance()).build(); - - /** Returns the lowest value for the given value type (inclusive). */ - public static Value getLowerBound(Value value) { - switch (value.getValueTypeCase()) { - case NULL_VALUE: - return Values.NULL_VALUE; - case BOOLEAN_VALUE: - return MIN_BOOLEAN; - case INTEGER_VALUE: - case DOUBLE_VALUE: - return MIN_NUMBER; - case TIMESTAMP_VALUE: - return MIN_TIMESTAMP; - case STRING_VALUE: - return MIN_STRING; - case BYTES_VALUE: - return MIN_BYTES; - case REFERENCE_VALUE: - return MIN_REFERENCE; - case GEO_POINT_VALUE: - return MIN_GEO_POINT; - case ARRAY_VALUE: - return MIN_ARRAY; - case MAP_VALUE: - // VectorValue sorts after ArrayValue and before an empty MapValue - if (isVectorValue(value)) { - return MIN_VECTOR_VALUE; - } - return MIN_MAP; - default: - throw new IllegalArgumentException("Unknown value type: " + value.getValueTypeCase()); - } - } - - /** Returns the largest value for the given value type (exclusive). */ - public static Value getUpperBound(Value value) { - switch (value.getValueTypeCase()) { - case NULL_VALUE: - return MIN_BOOLEAN; - case BOOLEAN_VALUE: - return MIN_NUMBER; - case INTEGER_VALUE: - case DOUBLE_VALUE: - return MIN_TIMESTAMP; - case TIMESTAMP_VALUE: - return MIN_STRING; - case STRING_VALUE: - return MIN_BYTES; - case BYTES_VALUE: - return MIN_REFERENCE; - case REFERENCE_VALUE: - return MIN_GEO_POINT; - case GEO_POINT_VALUE: - return MIN_ARRAY; - case ARRAY_VALUE: - return MIN_VECTOR_VALUE; - case MAP_VALUE: - // VectorValue sorts after ArrayValue and before an empty MapValue - if (isVectorValue(value)) { - return MIN_MAP; - } - return MAX_VALUE; - default: - throw new IllegalArgumentException("Unknown value type: " + value.getValueTypeCase()); - } - } - - /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ - public static boolean isMaxValue(Value value) { - return MAX_VALUE_TYPE.equals(value.getMapValue().getFieldsMap().get(TYPE_KEY)); - } - - /** Returns true if the Value represents a VectorValue . */ - public static boolean isVectorValue(Value value) { - return VECTOR_VALUE_TYPE.equals(value.getMapValue().getFieldsMap().get(TYPE_KEY)); - } -} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.kt new file mode 100644 index 00000000000..568a64899ec --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/model/Values.kt @@ -0,0 +1,670 @@ +// Copyright 2020 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.firebase.firestore.model + +import com.google.firebase.firestore.Blob +import com.google.firebase.firestore.DocumentReference +import com.google.firebase.firestore.GeoPoint +import com.google.firebase.firestore.VectorValue +import com.google.firebase.firestore.util.Assert +import com.google.firebase.firestore.util.Util +import com.google.firestore.v1.ArrayValue +import com.google.firestore.v1.ArrayValueOrBuilder +import com.google.firestore.v1.MapValue +import com.google.firestore.v1.Value +import com.google.firestore.v1.Value.ValueTypeCase +import com.google.protobuf.ByteString +import com.google.protobuf.NullValue +import com.google.protobuf.Timestamp +import com.google.type.LatLng +import java.lang.Double.doubleToLongBits +import java.util.Date +import java.util.TreeMap +import kotlin.math.min + +internal object Values { + const val TYPE_KEY: String = "__type__" + @JvmField val NAN_VALUE: Value = Value.newBuilder().setDoubleValue(Double.NaN).build() + @JvmField val NULL_VALUE: Value = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build() + @JvmField val MIN_VALUE: Value = NULL_VALUE + @JvmField val MAX_VALUE_TYPE: Value = Value.newBuilder().setStringValue("__max__").build() + @JvmField + val MAX_VALUE: Value = + Value.newBuilder() + .setMapValue(MapValue.newBuilder().putFields(TYPE_KEY, MAX_VALUE_TYPE)) + .build() + + @JvmField val VECTOR_VALUE_TYPE: Value = Value.newBuilder().setStringValue("__vector__").build() + const val VECTOR_MAP_VECTORS_KEY: String = "value" + private val MIN_VECTOR_VALUE: Value = + Value.newBuilder() + .setMapValue( + MapValue.newBuilder() + .putFields(TYPE_KEY, VECTOR_VALUE_TYPE) + .putFields( + VECTOR_MAP_VECTORS_KEY, + Value.newBuilder().setArrayValue(ArrayValue.newBuilder()).build() + ) + ) + .build() + + /** + * The order of types in Firestore. This order is based on the backend's ordering, but modified to + * support server timestamps and [.MAX_VALUE]. + */ + const val TYPE_ORDER_NULL: Int = 0 + + const val TYPE_ORDER_BOOLEAN: Int = 1 + const val TYPE_ORDER_NUMBER: Int = 2 + const val TYPE_ORDER_TIMESTAMP: Int = 3 + const val TYPE_ORDER_SERVER_TIMESTAMP: Int = 4 + const val TYPE_ORDER_STRING: Int = 5 + const val TYPE_ORDER_BLOB: Int = 6 + const val TYPE_ORDER_REFERENCE: Int = 7 + const val TYPE_ORDER_GEOPOINT: Int = 8 + const val TYPE_ORDER_ARRAY: Int = 9 + const val TYPE_ORDER_VECTOR: Int = 10 + const val TYPE_ORDER_MAP: Int = 11 + + const val TYPE_ORDER_MAX_VALUE: Int = Int.MAX_VALUE + + /** Returns the backend's type order of the given Value type. */ + @JvmStatic + fun typeOrder(value: Value): Int { + return when (value.valueTypeCase) { + ValueTypeCase.NULL_VALUE -> TYPE_ORDER_NULL + ValueTypeCase.BOOLEAN_VALUE -> TYPE_ORDER_BOOLEAN + ValueTypeCase.INTEGER_VALUE -> TYPE_ORDER_NUMBER + ValueTypeCase.DOUBLE_VALUE -> TYPE_ORDER_NUMBER + ValueTypeCase.TIMESTAMP_VALUE -> TYPE_ORDER_TIMESTAMP + ValueTypeCase.STRING_VALUE -> TYPE_ORDER_STRING + ValueTypeCase.BYTES_VALUE -> TYPE_ORDER_BLOB + ValueTypeCase.REFERENCE_VALUE -> TYPE_ORDER_REFERENCE + ValueTypeCase.GEO_POINT_VALUE -> TYPE_ORDER_GEOPOINT + ValueTypeCase.ARRAY_VALUE -> TYPE_ORDER_ARRAY + ValueTypeCase.MAP_VALUE -> + if (ServerTimestamps.isServerTimestamp(value)) { + TYPE_ORDER_SERVER_TIMESTAMP + } else if (isMaxValue(value)) { + TYPE_ORDER_MAX_VALUE + } else if (isVectorValue(value)) { + TYPE_ORDER_VECTOR + } else { + TYPE_ORDER_MAP + } + else -> throw Assert.fail("Invalid value type: " + value.valueTypeCase) + } + } + + @JvmStatic + fun equals(left: Value?, right: Value?): Boolean { + if (left === right) { + return true + } + + if (left == null || right == null) { + return false + } + + val leftType = typeOrder(left) + val rightType = typeOrder(right) + if (leftType != rightType) { + return false + } + + return when (leftType) { + TYPE_ORDER_NUMBER -> numberEquals(left, right) + TYPE_ORDER_ARRAY -> arrayEquals(left, right) + TYPE_ORDER_VECTOR, + TYPE_ORDER_MAP -> objectEquals(left, right) + TYPE_ORDER_SERVER_TIMESTAMP -> + ServerTimestamps.getLocalWriteTime(left) == ServerTimestamps.getLocalWriteTime(right) + TYPE_ORDER_MAX_VALUE -> true + else -> left == right + } + } + + private fun numberEquals(left: Value, right: Value): Boolean { + if (left.valueTypeCase != right.valueTypeCase) { + return false + } + return when (left.valueTypeCase) { + ValueTypeCase.INTEGER_VALUE -> left.integerValue == right.integerValue + ValueTypeCase.DOUBLE_VALUE -> + doubleToLongBits(left.doubleValue) == doubleToLongBits(right.doubleValue) + else -> false + } + } + + private fun arrayEquals(left: Value, right: Value): Boolean { + val leftArray = left.arrayValue + val rightArray = right.arrayValue + + if (leftArray.valuesCount != rightArray.valuesCount) { + return false + } + + for (i in 0 until leftArray.valuesCount) { + if (!equals(leftArray.getValues(i), rightArray.getValues(i))) { + return false + } + } + + return true + } + + private fun objectEquals(left: Value, right: Value): Boolean { + val leftMap = left.mapValue + val rightMap = right.mapValue + + if (leftMap.fieldsCount != rightMap.fieldsCount) { + return false + } + + for ((key, value) in leftMap.fieldsMap) { + val otherEntry = rightMap.fieldsMap[key] + if (!equals(value, otherEntry)) { + return false + } + } + + return true + } + + /** Returns true if the Value list contains the specified element. */ + @JvmStatic + fun contains(haystack: ArrayValueOrBuilder, needle: Value?): Boolean { + for (haystackElement in haystack.valuesList) { + if (equals(haystackElement, needle)) { + return true + } + } + return false + } + + @JvmStatic + fun compare(left: Value, right: Value): Int { + val leftType = typeOrder(left) + val rightType = typeOrder(right) + + if (leftType != rightType) { + return Util.compareIntegers(leftType, rightType) + } + + return when (leftType) { + TYPE_ORDER_NULL, + TYPE_ORDER_MAX_VALUE -> 0 + TYPE_ORDER_BOOLEAN -> Util.compareBooleans(left.booleanValue, right.booleanValue) + TYPE_ORDER_NUMBER -> compareNumbers(left, right) + TYPE_ORDER_TIMESTAMP -> compareTimestamps(left.timestampValue, right.timestampValue) + TYPE_ORDER_SERVER_TIMESTAMP -> + compareTimestamps( + ServerTimestamps.getLocalWriteTime(left), + ServerTimestamps.getLocalWriteTime(right) + ) + TYPE_ORDER_STRING -> Util.compareUtf8Strings(left.stringValue, right.stringValue) + TYPE_ORDER_BLOB -> Util.compareByteStrings(left.bytesValue, right.bytesValue) + TYPE_ORDER_REFERENCE -> compareReferences(left.referenceValue, right.referenceValue) + TYPE_ORDER_GEOPOINT -> compareGeoPoints(left.geoPointValue, right.geoPointValue) + TYPE_ORDER_ARRAY -> compareArrays(left.arrayValue, right.arrayValue) + TYPE_ORDER_MAP -> compareMaps(left.mapValue, right.mapValue) + TYPE_ORDER_VECTOR -> compareVectors(left.mapValue, right.mapValue) + else -> throw Assert.fail("Invalid value type: $leftType") + } + } + + @JvmStatic + fun lowerBoundCompare( + left: Value, + leftInclusive: Boolean, + right: Value, + rightInclusive: Boolean + ): Int { + val cmp = compare(left, right) + if (cmp != 0) { + return cmp + } + + if (leftInclusive && !rightInclusive) { + return -1 + } else if (!leftInclusive && rightInclusive) { + return 1 + } + + return 0 + } + + @JvmStatic + fun upperBoundCompare( + left: Value, + leftInclusive: Boolean, + right: Value, + rightInclusive: Boolean + ): Int { + val cmp = compare(left, right) + if (cmp != 0) { + return cmp + } + + if (leftInclusive && !rightInclusive) { + return 1 + } else if (!leftInclusive && rightInclusive) { + return -1 + } + + return 0 + } + + private fun compareNumbers(left: Value, right: Value): Int { + if (left.hasDoubleValue()) { + if (right.hasDoubleValue()) { + return Util.compareDoubles(left.doubleValue, right.doubleValue) + } else if (right.hasIntegerValue()) { + return Util.compareMixed(left.doubleValue, right.integerValue) + } + } else if (left.hasIntegerValue()) { + if (right.hasIntegerValue()) { + return Util.compareLongs(left.integerValue, right.integerValue) + } else if (right.hasDoubleValue()) { + return -1 * Util.compareMixed(right.doubleValue, left.integerValue) + } + } + + throw Assert.fail("Unexpected values: %s vs %s", left, right) + } + + private fun compareTimestamps(left: Timestamp, right: Timestamp): Int { + val cmp = Util.compareLongs(left.seconds, right.seconds) + if (cmp != 0) { + return cmp + } + return Util.compareIntegers(left.nanos, right.nanos) + } + + private fun compareReferences(leftPath: String, rightPath: String): Int { + val leftSegments = leftPath.split("/".toRegex()).toTypedArray() + val rightSegments = rightPath.split("/".toRegex()).toTypedArray() + + val minLength = min(leftSegments.size.toDouble(), rightSegments.size.toDouble()).toInt() + for (i in 0 until minLength) { + val cmp = leftSegments[i].compareTo(rightSegments[i]) + if (cmp != 0) { + return cmp + } + } + return Util.compareIntegers(leftSegments.size, rightSegments.size) + } + + private fun compareGeoPoints(left: LatLng, right: LatLng): Int { + val comparison = Util.compareDoubles(left.latitude, right.latitude) + if (comparison == 0) { + return Util.compareDoubles(left.longitude, right.longitude) + } + return comparison + } + + private fun compareArrays(left: ArrayValue, right: ArrayValue): Int { + val minLength = min(left.valuesCount.toDouble(), right.valuesCount.toDouble()).toInt() + for (i in 0 until minLength) { + val cmp = compare(left.getValues(i), right.getValues(i)) + if (cmp != 0) { + return cmp + } + } + return Util.compareIntegers(left.valuesCount, right.valuesCount) + } + + private fun compareMaps(left: MapValue, right: MapValue): Int { + val iterator1: Iterator> = TreeMap(left.fieldsMap).entries.iterator() + val iterator2: Iterator> = TreeMap(right.fieldsMap).entries.iterator() + while (iterator1.hasNext() && iterator2.hasNext()) { + val entry1 = iterator1.next() + val entry2 = iterator2.next() + val keyCompare = Util.compareUtf8Strings(entry1.key, entry2.key) + if (keyCompare != 0) { + return keyCompare + } + val valueCompare = compare(entry1.value, entry2.value) + if (valueCompare != 0) { + return valueCompare + } + } + + // Only equal if both iterators are exhausted. + return Util.compareBooleans(iterator1.hasNext(), iterator2.hasNext()) + } + + private fun compareVectors(left: MapValue, right: MapValue): Int { + val leftMap = left.fieldsMap + val rightMap = right.fieldsMap + + // The vector is a map, but only vector value is compared. + val leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]!!.arrayValue + val rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]!!.arrayValue + + val lengthCompare = + Util.compareIntegers(leftArrayValue.valuesCount, rightArrayValue.valuesCount) + if (lengthCompare != 0) { + return lengthCompare + } + + return compareArrays(leftArrayValue, rightArrayValue) + } + + /** Generate the canonical ID for the provided field value (as used in Target serialization). */ + @JvmStatic + fun canonicalId(value: Value): String { + val builder = StringBuilder() + canonifyValue(builder, value) + return builder.toString() + } + + private fun canonifyValue(builder: StringBuilder, value: Value) { + when (value.valueTypeCase) { + ValueTypeCase.NULL_VALUE -> builder.append("null") + ValueTypeCase.BOOLEAN_VALUE -> builder.append(value.booleanValue) + ValueTypeCase.INTEGER_VALUE -> builder.append(value.integerValue) + ValueTypeCase.DOUBLE_VALUE -> builder.append(value.doubleValue) + ValueTypeCase.TIMESTAMP_VALUE -> canonifyTimestamp(builder, value.timestampValue) + ValueTypeCase.STRING_VALUE -> builder.append(value.stringValue) + ValueTypeCase.BYTES_VALUE -> builder.append(Util.toDebugString(value.bytesValue)) + ValueTypeCase.REFERENCE_VALUE -> canonifyReference(builder, value) + ValueTypeCase.GEO_POINT_VALUE -> canonifyGeoPoint(builder, value.geoPointValue) + ValueTypeCase.ARRAY_VALUE -> canonifyArray(builder, value.arrayValue) + ValueTypeCase.MAP_VALUE -> canonifyObject(builder, value.mapValue) + else -> throw Assert.fail("Invalid value type: " + value.valueTypeCase) + } + } + + private fun canonifyTimestamp(builder: StringBuilder, timestamp: Timestamp) { + builder.append(String.format("time(%s,%s)", timestamp.seconds, timestamp.nanos)) + } + + private fun canonifyGeoPoint(builder: StringBuilder, latLng: LatLng) { + builder.append(String.format("geo(%s,%s)", latLng.latitude, latLng.longitude)) + } + + private fun canonifyReference(builder: StringBuilder, value: Value) { + Assert.hardAssert(isReferenceValue(value), "Value should be a ReferenceValue") + builder.append(DocumentKey.fromName(value.referenceValue)) + } + + private fun canonifyObject(builder: StringBuilder, mapValue: MapValue) { + // Even though MapValue are likely sorted correctly based on their insertion order (for example, + // when received from the backend), local modifications can bring elements out of order. We need + // to re-sort the elements to ensure that canonical IDs are independent of insertion order. + val keys = ArrayList(mapValue.fieldsMap.keys) + keys.sort() + + builder.append("{") + val iterator = keys.iterator() + while (iterator.hasNext()) { + val key = iterator.next() + builder.append(key).append(":") + canonifyValue(builder, mapValue.getFieldsOrThrow(key)) + if (iterator.hasNext()) { + builder.append(",") + } + } + builder.append("}") + } + + private fun canonifyArray(builder: StringBuilder, arrayValue: ArrayValue) { + builder.append("[") + if (arrayValue.valuesCount > 0) { + canonifyValue(builder, arrayValue.getValues(0)) + for (i in 1 until arrayValue.valuesCount) { + builder.append(",") + canonifyValue(builder, arrayValue.getValues(i)) + } + } + builder.append("]") + } + + /** Returns true if `value` is a INTEGER_VALUE. */ + @JvmStatic + fun isInteger(value: Value?): Boolean { + return value != null && value.hasIntegerValue() + } + + /** Returns true if `value` is a DOUBLE_VALUE. */ + @JvmStatic + fun isDouble(value: Value?): Boolean { + return value != null && value.hasDoubleValue() + } + + /** Returns true if `value` is either a INTEGER_VALUE or a DOUBLE_VALUE. */ + @JvmStatic + fun isNumber(value: Value?): Boolean { + return isInteger(value) || isDouble(value) + } + + /** Returns true if `value` is an ARRAY_VALUE. */ + @JvmStatic + fun isArray(value: Value?): Boolean { + return value != null && value.hasArrayValue() + } + + @JvmStatic + fun isReferenceValue(value: Value?): Boolean { + return value != null && value.hasReferenceValue() + } + + @JvmStatic + fun isNullValue(value: Value?): Boolean { + return value != null && value.hasNullValue() + } + + @JvmStatic + fun isNanValue(value: Value?): Boolean { + return value != null && java.lang.Double.isNaN(value.doubleValue) + } + + @JvmStatic + fun isMapValue(value: Value?): Boolean { + return value != null && value.hasMapValue() + } + + @JvmStatic + fun refValue(databaseId: DatabaseId, key: DocumentKey): Value { + val value = + Value.newBuilder() + .setReferenceValue( + String.format( + "projects/%s/databases/%s/documents/%s", + databaseId.projectId, + databaseId.databaseId, + key.toString() + ) + ) + .build() + return value + } + + private val MIN_BOOLEAN: Value = Value.newBuilder().setBooleanValue(false).build() + private val MIN_NUMBER: Value = Value.newBuilder().setDoubleValue(Double.NaN).build() + private val MIN_TIMESTAMP: Value = + Value.newBuilder().setTimestampValue(Timestamp.newBuilder().setSeconds(Long.MIN_VALUE)).build() + private val MIN_STRING: Value = Value.newBuilder().setStringValue("").build() + private val MIN_BYTES: Value = Value.newBuilder().setBytesValue(ByteString.EMPTY).build() + private val MIN_REFERENCE: Value = refValue(DatabaseId.EMPTY, DocumentKey.empty()) + private val MIN_GEO_POINT: Value = + Value.newBuilder() + .setGeoPointValue(LatLng.newBuilder().setLatitude(-90.0).setLongitude(-180.0)) + .build() + private val MIN_ARRAY: Value = + Value.newBuilder().setArrayValue(ArrayValue.getDefaultInstance()).build() + private val MIN_MAP: Value = Value.newBuilder().setMapValue(MapValue.getDefaultInstance()).build() + + /** Returns the lowest value for the given value type (inclusive). */ + @JvmStatic + fun getLowerBound(value: Value): Value { + return when (value.valueTypeCase) { + ValueTypeCase.NULL_VALUE -> NULL_VALUE + ValueTypeCase.BOOLEAN_VALUE -> MIN_BOOLEAN + ValueTypeCase.INTEGER_VALUE, + ValueTypeCase.DOUBLE_VALUE -> MIN_NUMBER + ValueTypeCase.TIMESTAMP_VALUE -> MIN_TIMESTAMP + ValueTypeCase.STRING_VALUE -> MIN_STRING + ValueTypeCase.BYTES_VALUE -> MIN_BYTES + ValueTypeCase.REFERENCE_VALUE -> MIN_REFERENCE + ValueTypeCase.GEO_POINT_VALUE -> MIN_GEO_POINT + ValueTypeCase.ARRAY_VALUE -> MIN_ARRAY + // VectorValue sorts after ArrayValue and before an empty MapValue + ValueTypeCase.MAP_VALUE -> if (isVectorValue(value)) MIN_VECTOR_VALUE else MIN_MAP + else -> throw IllegalArgumentException("Unknown value type: " + value.valueTypeCase) + } + } + + /** Returns the largest value for the given value type (exclusive). */ + @JvmStatic + fun getUpperBound(value: Value): Value { + return when (value.valueTypeCase) { + ValueTypeCase.NULL_VALUE -> MIN_BOOLEAN + ValueTypeCase.BOOLEAN_VALUE -> MIN_NUMBER + ValueTypeCase.INTEGER_VALUE, + ValueTypeCase.DOUBLE_VALUE -> MIN_TIMESTAMP + ValueTypeCase.TIMESTAMP_VALUE -> MIN_STRING + ValueTypeCase.STRING_VALUE -> MIN_BYTES + ValueTypeCase.BYTES_VALUE -> MIN_REFERENCE + ValueTypeCase.REFERENCE_VALUE -> MIN_GEO_POINT + ValueTypeCase.GEO_POINT_VALUE -> MIN_ARRAY + ValueTypeCase.ARRAY_VALUE -> MIN_VECTOR_VALUE + // VectorValue sorts after ArrayValue and before an empty MapValue + ValueTypeCase.MAP_VALUE -> if (isVectorValue(value)) MIN_MAP else MAX_VALUE + else -> throw IllegalArgumentException("Unknown value type: " + value.valueTypeCase) + } + } + + /** Returns true if the Value represents the canonical [.MAX_VALUE] . */ + @JvmStatic + fun isMaxValue(value: Value): Boolean { + return MAX_VALUE_TYPE == value.mapValue.fieldsMap[TYPE_KEY] + } + + /** Returns true if the Value represents a VectorValue . */ + @JvmStatic + fun isVectorValue(value: Value): Boolean { + return VECTOR_VALUE_TYPE == value.mapValue.fieldsMap[TYPE_KEY] + } + + @JvmStatic fun encodeValue(value: Long): Value = Value.newBuilder().setIntegerValue(value).build() + + @JvmStatic + fun encodeValue(value: Int): Value = Value.newBuilder().setIntegerValue(value.toLong()).build() + + @JvmStatic + fun encodeValue(value: Double): Value = Value.newBuilder().setDoubleValue(value).build() + + @JvmStatic + fun encodeValue(value: Float): Value = Value.newBuilder().setDoubleValue(value.toDouble()).build() + + @JvmStatic + fun encodeValue(value: Number): Value = + when (value) { + is Long -> encodeValue(value) + is Int -> encodeValue(value) + is Double -> encodeValue(value) + is Float -> encodeValue(value) + else -> throw IllegalArgumentException("Unexpected number type: $value") + } + + @JvmStatic + fun encodeValue(value: String): Value = Value.newBuilder().setStringValue(value).build() + + @JvmStatic fun encodeValue(date: Date): Value = encodeValue(com.google.firebase.Timestamp((date))) + + @JvmStatic + fun encodeValue(timestamp: com.google.firebase.Timestamp): Value { + // Firestore backend truncates precision down to microseconds. To ensure offline mode works + // the same with regards to truncation, perform the truncation immediately without waiting for + // the backend to do that. + val truncatedNanoseconds: Int = timestamp.nanoseconds / 1000 * 1000 + + return Value.newBuilder() + .setTimestampValue( + Timestamp.newBuilder().setSeconds(timestamp.seconds).setNanos(truncatedNanoseconds) + ) + .build() + } + + @JvmField + val TRUE: Value = Value.newBuilder().setBooleanValue(true).build() + + @JvmField + val FALSE: Value = Value.newBuilder().setBooleanValue(false).build() + + @JvmStatic + fun encodeValue(value: Boolean): Value = if (value) TRUE else FALSE + + @JvmStatic + fun encodeValue(geoPoint: GeoPoint): Value = + Value.newBuilder() + .setGeoPointValue( + LatLng.newBuilder().setLatitude(geoPoint.latitude).setLongitude(geoPoint.longitude) + ) + .build() + + @JvmStatic + fun encodeValue(value: ByteArray): Value = + Value.newBuilder().setBytesValue(ByteString.copyFrom(value)).build() + + @JvmStatic + fun encodeValue(value: Blob): Value = + Value.newBuilder().setBytesValue(value.toByteString()).build() + + @JvmStatic + fun encodeValue(docRef: DocumentReference): Value = + Value.newBuilder().setReferenceValue(docRef.fullPath).build() + + @JvmStatic fun encodeValue(vector: VectorValue): Value = encodeVectorValue(vector.toArray()) + + @JvmStatic + fun encodeVectorValue(vector: DoubleArray): Value { + val listBuilder = ArrayValue.newBuilder() + for (value in vector) { + listBuilder.addValues(encodeValue(value)) + } + return Value.newBuilder() + .setMapValue( + MapValue.newBuilder() + .putFields(TYPE_KEY, VECTOR_VALUE_TYPE) + .putFields(VECTOR_MAP_VECTORS_KEY, Value.newBuilder().setArrayValue(listBuilder).build()) + ) + .build() + } + + @JvmStatic + fun encodeValue(map: Map): Value = + Value.newBuilder().setMapValue(MapValue.newBuilder().putAllFields(map)).build() + + @JvmStatic + fun encodeValue(values: Iterable): Value = + Value.newBuilder().setArrayValue(ArrayValue.newBuilder().addAllValues(values)).build() + + @JvmStatic + fun encodeAnyValue(value: Any?): Value = + when (value) { + null -> NULL_VALUE + is String -> encodeValue(value) + is Number -> encodeValue(value) + is Date -> encodeValue(value) + is com.google.firebase.Timestamp -> encodeValue(value) + is Boolean -> encodeValue(value) + is GeoPoint -> encodeValue(value) + is Blob -> encodeValue(value) + is VectorValue -> encodeValue(value) + else -> throw IllegalArgumentException("Unexpected type: $value") + } +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/aggregates.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/aggregates.kt new file mode 100644 index 00000000000..0ce88ce385b --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/aggregates.kt @@ -0,0 +1,160 @@ +// Copyright 2025 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.firebase.firestore.pipeline + +import com.google.firebase.firestore.UserDataReader +import com.google.firestore.v1.Value + +class AggregateWithAlias +internal constructor(internal val alias: String, internal val expr: AggregateFunction) + +/** A class that represents an aggregate function. */ +class AggregateFunction +private constructor( + private val name: String, + private val params: Array, + private val options: InternalOptions = InternalOptions.EMPTY +) { + private constructor(name: String) : this(name, emptyArray()) + private constructor(name: String, expr: Expr) : this(name, arrayOf(expr)) + private constructor(name: String, fieldName: String) : this(name, Expr.field(fieldName)) + + companion object { + + @JvmStatic fun generic(name: String, vararg expr: Expr) = AggregateFunction(name, expr) + + /** + * Creates an aggregation that counts the total number of stage inputs. + * + * @return A new [AggregateFunction] representing the countAll aggregation. + */ + @JvmStatic fun countAll() = AggregateFunction("count") + + /** + * Creates an aggregation that counts the number of stage inputs where the input field exists. + * + * @param fieldName The name of the field to count. + * @return A new [AggregateFunction] representing the 'count' aggregation. + */ + @JvmStatic fun count(fieldName: String) = AggregateFunction("count", fieldName) + + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided [expression]. + * + * @param expression The expression to count. + * @return A new [AggregateFunction] representing the 'count' aggregation. + */ + @JvmStatic fun count(expression: Expr) = AggregateFunction("count", expression) + + /** + * Creates an aggregation that counts the number of stage inputs where the provided boolean + * expression evaluates to true. + * + * @param condition The boolean expression to evaluate on each input. + * @return A new [AggregateFunction] representing the count aggregation. + */ + @JvmStatic fun countIf(condition: BooleanExpr) = AggregateFunction("countIf", condition) + + /** + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * @param fieldName The name of the field containing numeric values to sum up. + * @return A new [AggregateFunction] representing the average aggregation. + */ + @JvmStatic fun sum(fieldName: String) = AggregateFunction("sum", fieldName) + + /** + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * @param expression The expression to sum up. + * @return A new [AggregateFunction] representing the sum aggregation. + */ + @JvmStatic fun sum(expression: Expr) = AggregateFunction("sum", expression) + + /** + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * @param fieldName The name of the field containing numeric values to average. + * @return A new [AggregateFunction] representing the average aggregation. + */ + @JvmStatic fun avg(fieldName: String) = AggregateFunction("avg", fieldName) + + /** + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * @param expression The expression representing the values to average. + * @return A new [AggregateFunction] representing the average aggregation. + */ + @JvmStatic fun avg(expression: Expr) = AggregateFunction("avg", expression) + + /** + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * @param fieldName The name of the field to find the minimum value of. + * @return A new [AggregateFunction] representing the minimum aggregation. + */ + @JvmStatic fun minimum(fieldName: String) = AggregateFunction("min", fieldName) + + /** + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * @param expression The expression to find the minimum value of. + * @return A new [AggregateFunction] representing the minimum aggregation. + */ + @JvmStatic fun minimum(expression: Expr) = AggregateFunction("min", expression) + + /** + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * @param fieldName The name of the field to find the maximum value of. + * @return A new [AggregateFunction] representing the maximum aggregation. + */ + @JvmStatic fun maximum(fieldName: String) = AggregateFunction("max", fieldName) + + /** + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * @param expression The expression to find the maximum value of. + * @return A new [AggregateFunction] representing the maximum aggregation. + */ + @JvmStatic fun maximum(expression: Expr) = AggregateFunction("max", expression) + } + + /** + * Assigns an alias to this aggregate. + * + * @param alias The alias to assign to this aggregate. + * @return A new [AggregateWithAlias] that wraps this aggregate and associates it with the + * provided alias. + */ + fun alias(alias: String) = AggregateWithAlias(alias, this) + + internal fun toProto(userDataReader: UserDataReader): Value { + val builder = com.google.firestore.v1.Function.newBuilder() + builder.setName(name) + for (param in params) { + builder.addArgs(param.toProto(userDataReader)) + } + options.forEach(builder::putOptions) + return Value.newBuilder().setFunctionValue(builder).build() + } +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/expressions.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/expressions.kt new file mode 100644 index 00000000000..5eb5e6c3698 --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/expressions.kt @@ -0,0 +1,4207 @@ +// Copyright 2025 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.firebase.firestore.pipeline + +import com.google.firebase.Timestamp +import com.google.firebase.firestore.Blob +import com.google.firebase.firestore.DocumentReference +import com.google.firebase.firestore.FieldPath +import com.google.firebase.firestore.GeoPoint +import com.google.firebase.firestore.Pipeline +import com.google.firebase.firestore.UserDataReader +import com.google.firebase.firestore.VectorValue +import com.google.firebase.firestore.model.DocumentKey +import com.google.firebase.firestore.model.FieldPath as ModelFieldPath +import com.google.firebase.firestore.model.Values +import com.google.firebase.firestore.model.Values.encodeValue +import com.google.firebase.firestore.pipeline.Expr.Companion.field +import com.google.firebase.firestore.util.CustomClassMapper +import com.google.firestore.v1.MapValue +import com.google.firestore.v1.Value +import java.util.Date +import kotlin.reflect.KFunction1 + +/** + * Represents an expression that can be evaluated to a value within the execution of a [Pipeline]. + * + * Expressions are the building blocks for creating complex queries and transformations in Firestore + * pipelines. They can represent: + * + * - **Field references:** Access values from document fields. + * - **Literals:** Represent constant values (strings, numbers, booleans). + * - **Function calls:** Apply functions to one or more expressions. + * + * The [Expr] class provides a fluent API for building expressions. You can chain together method + * calls to create complex expressions. + */ +abstract class Expr internal constructor() { + + private class ValueConstant(val value: Value) : Expr() { + override fun toProto(userDataReader: UserDataReader): Value = value + } + + companion object { + internal fun toExprOrConstant(value: Any?): Expr = + toExpr(value, ::toExprOrConstant) + ?: pojoToExprOrConstant(CustomClassMapper.convertToPlainJavaTypes(value)) + + private fun pojoToExprOrConstant(value: Any?): Expr = + toExpr(value, ::pojoToExprOrConstant) + ?: throw IllegalArgumentException("Unknown type: $value") + + private fun toExpr(value: Any?, toExpr: KFunction1): Expr? { + if (value == null) return NULL + return when (value) { + is Expr -> value + is String -> constant(value) + is Number -> constant(value) + is Date -> constant(value) + is Timestamp -> constant(value) + is Boolean -> constant(value) + is GeoPoint -> constant(value) + is Blob -> constant(value) + is DocumentReference -> constant(value) + is ByteArray -> constant(value) + is VectorValue -> constant(value) + is Value -> ValueConstant(value) + is Map<*, *> -> + map( + value + .flatMap { + val key = it.key + if (key is String) listOf(constant(key), toExpr(it.value)) + else throw IllegalArgumentException("Maps with non-string keys are not supported") + } + .toTypedArray() + ) + is List<*> -> ListOfExprs(value.map(toExpr).toTypedArray()) + else -> null + } + } + + internal fun toArrayOfExprOrConstant(others: Iterable): Array = + others.map(::toExprOrConstant).toTypedArray() + + internal fun toArrayOfExprOrConstant(others: Array): Array = + others.map(::toExprOrConstant).toTypedArray() + + private val NULL: Expr = ValueConstant(Values.NULL_VALUE) + + /** + * Create a constant for a [String] value. + * + * @param value The [String] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: String): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [Number] value. + * + * @param value The [Number] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: Number): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [Date] value. + * + * @param value The [Date] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: Date): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [Timestamp] value. + * + * @param value The [Timestamp] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: Timestamp): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [Boolean] value. + * + * @param value The [Boolean] value. + * @return A new [BooleanExpr] constant instance. + */ + @JvmStatic + fun constant(value: Boolean): BooleanExpr { + val encodedValue = encodeValue(value) + return object : BooleanExpr("N/A", emptyArray()) { + override fun toProto(userDataReader: UserDataReader): Value { + return encodedValue + } + + override fun hashCode(): Int { + return encodedValue.hashCode() + } + + override fun toString(): String { + return "constant($value)" + } + } + } + + /** + * Create a constant for a [GeoPoint] value. + * + * @param value The [GeoPoint] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: GeoPoint): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a bytes value. + * + * @param value The bytes value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: ByteArray): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [Blob] value. + * + * @param value The [Blob] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: Blob): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Create a constant for a [DocumentReference] value. + * + * @param ref The [DocumentReference] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(ref: DocumentReference): Expr { + return object : Expr() { + override fun toProto(userDataReader: UserDataReader): Value { + userDataReader.validateDocumentReference(ref, ::IllegalArgumentException) + return encodeValue(ref) + } + } + } + + /** + * Create a constant for a [VectorValue] value. + * + * @param value The [VectorValue] value. + * @return A new [Expr] constant instance. + */ + @JvmStatic + fun constant(value: VectorValue): Expr { + return ValueConstant(encodeValue(value)) + } + + /** + * Constant for a null value. + * + * @return A [Expr] constant instance. + */ + @JvmStatic + fun nullValue(): Expr { + return NULL + } + + /** + * Create a vector constant for a [DoubleArray] value. + * + * @param vector The [VectorValue] value. + * @return A [Expr] constant instance. + */ + @JvmStatic + fun vector(vector: DoubleArray): Expr { + return ValueConstant(Values.encodeVectorValue(vector)) + } + + /** + * Create a vector constant for a [VectorValue] value. + * + * @param vector The [VectorValue] value. + * @return A [Expr] constant instance. + */ + @JvmStatic + fun vector(vector: VectorValue): Expr { + return ValueConstant(encodeValue(vector)) + } + + /** + * Creates a [Field] instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * @param name The path to the field. + * @return A new [Field] instance representing the specified path. + */ + @JvmStatic + fun field(name: String): Field { + if (name == DocumentKey.KEY_FIELD_NAME) { + return Field(ModelFieldPath.KEY_PATH) + } + return Field(FieldPath.fromDotSeparatedPath(name).internalPath) + } + + /** + * Creates a [Field] instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * @param fieldPath The [FieldPath] to the field. + * @return A new [Field] instance representing the specified path. + */ + @JvmStatic + fun field(fieldPath: FieldPath): Field { + return Field(fieldPath.internalPath) + } + + @JvmStatic fun generic(name: String, vararg expr: Expr): Expr = FunctionExpr(name, expr) + + /** + * Creates an expression that performs a logical 'AND' operation. + * + * @param condition The first [BooleanExpr]. + * @param conditions Addition [BooleanExpr]s. + * @return A new [BooleanExpr] representing the logical 'AND' operation. + */ + @JvmStatic + fun and(condition: BooleanExpr, vararg conditions: BooleanExpr) = + BooleanExpr("and", condition, *conditions) + + /** + * Creates an expression that performs a logical 'OR' operation. + * + * @param condition The first [BooleanExpr]. + * @param conditions Addition [BooleanExpr]s. + * @return A new [BooleanExpr] representing the logical 'OR' operation. + */ + @JvmStatic + fun or(condition: BooleanExpr, vararg conditions: BooleanExpr) = + BooleanExpr("or", condition, *conditions) + + /** + * Creates an expression that performs a logical 'XOR' operation. + * + * @param condition The first [BooleanExpr]. + * @param conditions Addition [BooleanExpr]s. + * @return A new [BooleanExpr] representing the logical 'XOR' operation. + */ + @JvmStatic + fun xor(condition: BooleanExpr, vararg conditions: BooleanExpr) = + BooleanExpr("xor", condition, *conditions) + + /** + * Creates an expression that negates a boolean expression. + * + * @param condition The boolean expression to negate. + * @return A new [BooleanExpr] representing the not operation. + */ + @JvmStatic fun not(condition: BooleanExpr): BooleanExpr = BooleanExpr("not", condition) + + /** + * Creates an expression that applies a bitwise AND operation between two expressions. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise AND operation. + */ + @JvmStatic + fun bitAnd(bits: Expr, bitsOther: Expr): Expr = FunctionExpr("bit_and", bits, bitsOther) + + /** + * Creates an expression that applies a bitwise AND operation between an expression and a + * constant. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise AND operation. + */ + @JvmStatic + fun bitAnd(bits: Expr, bitsOther: ByteArray): Expr = + FunctionExpr("bit_and", bits, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise AND operation between an field and an + * expression. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise AND operation. + */ + @JvmStatic + fun bitAnd(bitsFieldName: String, bitsOther: Expr): Expr = + FunctionExpr("bit_and", bitsFieldName, bitsOther) + + /** + * Creates an expression that applies a bitwise AND operation between an field and constant. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise AND operation. + */ + @JvmStatic + fun bitAnd(bitsFieldName: String, bitsOther: ByteArray): Expr = + FunctionExpr("bit_and", bitsFieldName, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise OR operation between two expressions. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise OR operation. + */ + @JvmStatic + fun bitOr(bits: Expr, bitsOther: Expr): Expr = FunctionExpr("bit_or", bits, bitsOther) + + /** + * Creates an expression that applies a bitwise OR operation between an expression and a + * constant. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise OR operation. + */ + @JvmStatic + fun bitOr(bits: Expr, bitsOther: ByteArray): Expr = + FunctionExpr("bit_or", bits, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise OR operation between an field and an expression. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise OR operation. + */ + @JvmStatic + fun bitOr(bitsFieldName: String, bitsOther: Expr): Expr = + FunctionExpr("bit_or", bitsFieldName, bitsOther) + + /** + * Creates an expression that applies a bitwise OR operation between an field and constant. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise OR operation. + */ + @JvmStatic + fun bitOr(bitsFieldName: String, bitsOther: ByteArray): Expr = + FunctionExpr("bit_or", bitsFieldName, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise XOR operation. + */ + @JvmStatic + fun bitXor(bits: Expr, bitsOther: Expr): Expr = FunctionExpr("bit_xor", bits, bitsOther) + + /** + * Creates an expression that applies a bitwise XOR operation between an expression and a + * constant. + * + * @param bits An expression that returns bits when evaluated. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise XOR operation. + */ + @JvmStatic + fun bitXor(bits: Expr, bitsOther: ByteArray): Expr = + FunctionExpr("bit_xor", bits, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise XOR operation between an field and an + * expression. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise XOR operation. + */ + @JvmStatic + fun bitXor(bitsFieldName: String, bitsOther: Expr): Expr = + FunctionExpr("bit_xor", bitsFieldName, bitsOther) + + /** + * Creates an expression that applies a bitwise XOR operation between an field and constant. + * + * @param bitsFieldName Name of field that contains bits data. + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise XOR operation. + */ + @JvmStatic + fun bitXor(bitsFieldName: String, bitsOther: ByteArray): Expr = + FunctionExpr("bit_xor", bitsFieldName, constant(bitsOther)) + + /** + * Creates an expression that applies a bitwise NOT operation to an expression. + * + * @param bits An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise NOT operation. + */ + @JvmStatic fun bitNot(bits: Expr): Expr = FunctionExpr("bit_not", bits) + + /** + * Creates an expression that applies a bitwise NOT operation to a field. + * + * @param bitsFieldName Name of field that contains bits data. + * @return A new [Expr] representing the bitwise NOT operation. + */ + @JvmStatic fun bitNot(bitsFieldName: String): Expr = FunctionExpr("bit_not", bitsFieldName) + + /** + * Creates an expression that applies a bitwise left shift operation between two expressions. + * + * @param bits An expression that returns bits when evaluated. + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + @JvmStatic + fun bitLeftShift(bits: Expr, numberExpr: Expr): Expr = + FunctionExpr("bit_left_shift", bits, numberExpr) + + /** + * Creates an expression that applies a bitwise left shift operation between an expression and a + * constant. + * + * @param bits An expression that returns bits when evaluated. + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + @JvmStatic + fun bitLeftShift(bits: Expr, number: Int): Expr = FunctionExpr("bit_left_shift", bits, number) + + /** + * Creates an expression that applies a bitwise left shift operation between a field and an + * expression. + * + * @param bitsFieldName Name of field that contains bits data. + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + @JvmStatic + fun bitLeftShift(bitsFieldName: String, numberExpr: Expr): Expr = + FunctionExpr("bit_left_shift", bitsFieldName, numberExpr) + + /** + * Creates an expression that applies a bitwise left shift operation between a field and a + * constant. + * + * @param bitsFieldName Name of field that contains bits data. + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + @JvmStatic + fun bitLeftShift(bitsFieldName: String, number: Int): Expr = + FunctionExpr("bit_left_shift", bitsFieldName, number) + + /** + * Creates an expression that applies a bitwise right shift operation between two expressions. + * + * @param bits An expression that returns bits when evaluated. + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + @JvmStatic + fun bitRightShift(bits: Expr, numberExpr: Expr): Expr = + FunctionExpr("bit_right_shift", bits, numberExpr) + + /** + * Creates an expression that applies a bitwise right shift operation between an expression and + * a constant. + * + * @param bits An expression that returns bits when evaluated. + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + @JvmStatic + fun bitRightShift(bits: Expr, number: Int): Expr = FunctionExpr("bit_right_shift", bits, number) + + /** + * Creates an expression that applies a bitwise right shift operation between a field and an + * expression. + * + * @param bitsFieldName Name of field that contains bits data. + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + @JvmStatic + fun bitRightShift(bitsFieldName: String, numberExpr: Expr): Expr = + FunctionExpr("bit_right_shift", bitsFieldName, numberExpr) + + /** + * Creates an expression that applies a bitwise right shift operation between a field and a + * constant. + * + * @param bitsFieldName Name of field that contains bits data. + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + @JvmStatic + fun bitRightShift(bitsFieldName: String, number: Int): Expr = + FunctionExpr("bit_right_shift", bitsFieldName, number) + + /** + * Creates an expression that rounds [numericExpr] to nearest integer. + * + * Rounds away from zero in halfway cases. + * + * @param numericExpr An expression that returns number when evaluated. + * @return A new [Expr] representing an integer result from the round operation. + */ + @JvmStatic fun round(numericExpr: Expr): Expr = FunctionExpr("round", numericExpr) + + /** + * Creates an expression that rounds [numericField] to nearest integer. + * + * Rounds away from zero in halfway cases. + * + * @param numericField Name of field that returns number when evaluated. + * @return A new [Expr] representing an integer result from the round operation. + */ + @JvmStatic fun round(numericField: String): Expr = FunctionExpr("round", numericField) + + /** + * Creates an expression that rounds off [numericExpr] to [decimalPlace] decimal places if + * [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param numericExpr An expression that returns number when evaluated. + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + @JvmStatic + fun roundToPrecision(numericExpr: Expr, decimalPlace: Int): Expr = + FunctionExpr("round", numericExpr, constant(decimalPlace)) + + /** + * Creates an expression that rounds off [numericField] to [decimalPlace] decimal places if + * [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param numericField Name of field that returns number when evaluated. + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + @JvmStatic + fun roundToPrecision(numericField: String, decimalPlace: Int): Expr = + FunctionExpr("round", numericField, constant(decimalPlace)) + + /** + * Creates an expression that rounds off [numericExpr] to [decimalPlace] decimal places if + * [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param numericExpr An expression that returns number when evaluated. + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + @JvmStatic + fun roundToPrecision(numericExpr: Expr, decimalPlace: Expr): Expr = + FunctionExpr("round", numericExpr, decimalPlace) + + /** + * Creates an expression that rounds off [numericField] to [decimalPlace] decimal places if + * [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param numericField Name of field that returns number when evaluated. + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + @JvmStatic + fun roundToPrecision(numericField: String, decimalPlace: Expr): Expr = + FunctionExpr("round", numericField, decimalPlace) + + /** + * Creates an expression that returns the smalled integer that isn't less than [numericExpr]. + * + * @param numericExpr An expression that returns number when evaluated. + * @return A new [Expr] representing an integer result from the ceil operation. + */ + @JvmStatic fun ceil(numericExpr: Expr): Expr = FunctionExpr("ceil", numericExpr) + + /** + * Creates an expression that returns the smalled integer that isn't less than [numericField]. + * + * @param numericField Name of field that returns number when evaluated. + * @return A new [Expr] representing an integer result from the ceil operation. + */ + @JvmStatic fun ceil(numericField: String): Expr = FunctionExpr("ceil", numericField) + + /** + * Creates an expression that returns the largest integer that isn't less than [numericExpr]. + * + * @param numericExpr An expression that returns number when evaluated. + * @return A new [Expr] representing an integer result from the floor operation. + */ + @JvmStatic fun floor(numericExpr: Expr): Expr = FunctionExpr("floor", numericExpr) + + /** + * Creates an expression that returns the largest integer that isn't less than [numericField]. + * + * @param numericField Name of field that returns number when evaluated. + * @return A new [Expr] representing an integer result from the floor operation. + */ + @JvmStatic fun floor(numericField: String): Expr = FunctionExpr("floor", numericField) + + /** + * Creates an expression that returns the [numericExpr] raised to the power of the [exponent]. + * Returns infinity on overflow and zero on underflow. + * + * @param numericExpr An expression that returns number when evaluated. + * @param exponent The numeric power to raise the [numericExpr]. + * @return A new [Expr] representing a numeric result from raising [numericExpr] to the power of + * [exponent]. + */ + @JvmStatic + fun pow(numericExpr: Expr, exponent: Number): Expr = + FunctionExpr("pow", numericExpr, constant(exponent)) + + /** + * Creates an expression that returns the [numericField] raised to the power of the [exponent]. + * Returns infinity on overflow and zero on underflow. + * + * @param numericField Name of field that returns number when evaluated. + * @param exponent The numeric power to raise the [numericField]. + * @return A new [Expr] representing a numeric result from raising [numericField] to the power + * of [exponent]. + */ + @JvmStatic + fun pow(numericField: String, exponent: Number): Expr = + FunctionExpr("pow", numericField, constant(exponent)) + + /** + * Creates an expression that returns the [numericExpr] raised to the power of the [exponent]. + * Returns infinity on overflow and zero on underflow. + * + * @param numericExpr An expression that returns number when evaluated. + * @param exponent The numeric power to raise the [numericExpr]. + * @return A new [Expr] representing a numeric result from raising [numericExpr] to the power of + * [exponent]. + */ + @JvmStatic + fun pow(numericExpr: Expr, exponent: Expr): Expr = FunctionExpr("pow", numericExpr, exponent) + + /** + * Creates an expression that returns the [numericField] raised to the power of the [exponent]. + * Returns infinity on overflow and zero on underflow. + * + * @param numericField Name of field that returns number when evaluated. + * @param exponent The numeric power to raise the [numericField]. + * @return A new [Expr] representing a numeric result from raising [numericField] to the power + * of [exponent]. + */ + @JvmStatic + fun pow(numericField: String, exponent: Expr): Expr = + FunctionExpr("pow", numericField, exponent) + + /** + * Creates an expression that returns the square root of [numericExpr]. + * + * @param numericExpr An expression that returns number when evaluated. + * @return A new [Expr] representing the numeric result of the square root operation. + */ + @JvmStatic fun sqrt(numericExpr: Expr): Expr = FunctionExpr("sqrt", numericExpr) + + /** + * Creates an expression that returns the square root of [numericField]. + * + * @param numericField Name of field that returns number when evaluated. + * @return A new [Expr] representing the numeric result of the square root operation. + */ + @JvmStatic fun sqrt(numericField: String): Expr = FunctionExpr("sqrt", numericField) + + /** + * Creates an expression that adds numeric expressions. + * + * @param first Numeric expression to add. + * @param second Numeric expression to add. + * @return A new [Expr] representing the addition operation. + */ + @JvmStatic + fun add(first: Expr, second: Expr): Expr = + FunctionExpr("add", first, second) + + /** + * Creates an expression that adds numeric expressions with a constant. + * + * @param first Numeric expression to add. + * @param second Constant to add. + * @return A new [Expr] representing the addition operation. + */ + @JvmStatic + fun add(first: Expr, second: Number): Expr = + FunctionExpr("add", first, second) + + /** + * Creates an expression that adds a numeric field with a numeric expression. + * + * @param numericFieldName Numeric field to add. + * @param second Numeric expression to add to field value. + * @return A new [Expr] representing the addition operation. + */ + @JvmStatic + fun add(numericFieldName: String, second: Expr): Expr = + FunctionExpr("add", numericFieldName, second) + + /** + * Creates an expression that adds a numeric field with constant. + * + * @param numericFieldName Numeric field to add. + * @param second Constant to add. + * @return A new [Expr] representing the addition operation. + */ + @JvmStatic + fun add(numericFieldName: String, second: Number): Expr = + FunctionExpr("add", numericFieldName, second) + + /** + * Creates an expression that subtracts two expressions. + * + * @param minuend Numeric expression to subtract from. + * @param subtrahend Numeric expression to subtract. + * @return A new [Expr] representing the subtract operation. + */ + @JvmStatic + fun subtract(minuend: Expr, subtrahend: Expr): Expr = + FunctionExpr("subtract", minuend, subtrahend) + + /** + * Creates an expression that subtracts a constant value from a numeric expression. + * + * @param minuend Numeric expression to subtract from. + * @param subtrahend Constant to subtract. + * @return A new [Expr] representing the subtract operation. + */ + @JvmStatic + fun subtract(minuend: Expr, subtrahend: Number): Expr = + FunctionExpr("subtract", minuend, subtrahend) + + /** + * Creates an expression that subtracts a numeric expressions from numeric field. + * + * @param numericFieldName Numeric field to subtract from. + * @param subtrahend Numeric expression to subtract. + * @return A new [Expr] representing the subtract operation. + */ + @JvmStatic + fun subtract(numericFieldName: String, subtrahend: Expr): Expr = + FunctionExpr("subtract", numericFieldName, subtrahend) + + /** + * Creates an expression that subtracts a constant from numeric field. + * + * @param numericFieldName Numeric field to subtract from. + * @param subtrahend Constant to subtract. + * @return A new [Expr] representing the subtract operation. + */ + @JvmStatic + fun subtract(numericFieldName: String, subtrahend: Number): Expr = + FunctionExpr("subtract", numericFieldName, subtrahend) + + /** + * Creates an expression that multiplies numeric expressions. + * + * @param first Numeric expression to multiply. + * @param second Numeric expression to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + @JvmStatic + fun multiply(first: Expr, second: Expr): Expr = + FunctionExpr("multiply", first, second) + + /** + * Creates an expression that multiplies numeric expressions with a constant. + * + * @param first Numeric expression to multiply. + * @param second Constant to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + @JvmStatic + fun multiply(first: Expr, second: Number): Expr = + FunctionExpr("multiply", first, second) + + /** + * Creates an expression that multiplies a numeric field with a numeric expression. + * + * @param numericFieldName Numeric field to multiply. + * @param second Numeric expression to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + @JvmStatic + fun multiply(numericFieldName: String, second: Expr): Expr = + FunctionExpr("multiply", numericFieldName, second) + + /** + * Creates an expression that multiplies a numeric field with a constant. + * + * @param numericFieldName Numeric field to multiply. + * @param second Constant to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + @JvmStatic + fun multiply(numericFieldName: String, second: Number): Expr = + FunctionExpr("multiply", numericFieldName, second) + + /** + * Creates an expression that divides two numeric expressions. + * + * @param dividend The numeric expression to be divided. + * @param divisor The numeric expression to divide by. + * @return A new [Expr] representing the division operation. + */ + @JvmStatic + fun divide(dividend: Expr, divisor: Expr): Expr = FunctionExpr("divide", dividend, divisor) + + /** + * Creates an expression that divides a numeric expression by a constant. + * + * @param dividend The numeric expression to be divided. + * @param divisor The constant to divide by. + * @return A new [Expr] representing the division operation. + */ + @JvmStatic + fun divide(dividend: Expr, divisor: Number): Expr = FunctionExpr("divide", dividend, divisor) + + /** + * Creates an expression that divides numeric field by a numeric expression. + * + * @param dividendFieldName The numeric field name to be divided. + * @param divisor The numeric expression to divide by. + * @return A new [Expr] representing the divide operation. + */ + @JvmStatic + fun divide(dividendFieldName: String, divisor: Expr): Expr = + FunctionExpr("divide", dividendFieldName, divisor) + + /** + * Creates an expression that divides a numeric field by a constant. + * + * @param dividendFieldName The numeric field name to be divided. + * @param divisor The constant to divide by. + * @return A new [Expr] representing the divide operation. + */ + @JvmStatic + fun divide(dividendFieldName: String, divisor: Number): Expr = + FunctionExpr("divide", dividendFieldName, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing two numeric + * expressions. + * + * @param dividend The numeric expression to be divided. + * @param divisor The numeric expression to divide by. + * @return A new [Expr] representing the modulo operation. + */ + @JvmStatic fun mod(dividend: Expr, divisor: Expr): Expr = FunctionExpr("mod", dividend, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing a numeric expression + * by a constant. + * + * @param dividend The numeric expression to be divided. + * @param divisor The constant to divide by. + * @return A new [Expr] representing the modulo operation. + */ + @JvmStatic + fun mod(dividend: Expr, divisor: Number): Expr = FunctionExpr("mod", dividend, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing a numeric field by a + * constant. + * + * @param dividendFieldName The numeric field name to be divided. + * @param divisor The numeric expression to divide by. + * @return A new [Expr] representing the modulo operation. + */ + @JvmStatic + fun mod(dividendFieldName: String, divisor: Expr): Expr = + FunctionExpr("mod", dividendFieldName, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing a numeric field by a + * constant. + * + * @param dividendFieldName The numeric field name to be divided. + * @param divisor The constant to divide by. + * @return A new [Expr] representing the modulo operation. + */ + @JvmStatic + fun mod(dividendFieldName: String, divisor: Number): Expr = + FunctionExpr("mod", dividendFieldName, divisor) + + /** + * Creates an expression that checks if an [expression], when evaluated, is equal to any of the + * provided [values]. + * + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + @JvmStatic + fun eqAny(expression: Expr, values: List): BooleanExpr = + eqAny(expression, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if an [expression], when evaluated, is equal to any of the + * elements of [arrayExpression]. + * + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + @JvmStatic + fun eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr = + BooleanExpr("eq_any", expression, arrayExpression) + + /** + * Creates an expression that checks if a field's value is equal to any of the provided [values] + * . + * + * @param fieldName The field to compare. + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + @JvmStatic + fun eqAny(fieldName: String, values: List): BooleanExpr = + eqAny(fieldName, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if a field's value is equal to any of the elements of + * [arrayExpression]. + * + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + @JvmStatic + fun eqAny(fieldName: String, arrayExpression: Expr): BooleanExpr = + BooleanExpr("eq_any", fieldName, arrayExpression) + + /** + * Creates an expression that checks if an [expression], when evaluated, is not equal to all the + * provided [values]. + * + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + @JvmStatic + fun notEqAny(expression: Expr, values: List): BooleanExpr = + notEqAny(expression, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if an [expression], when evaluated, is not equal to all the + * elements of [arrayExpression]. + * + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + @JvmStatic + fun notEqAny(expression: Expr, arrayExpression: Expr): BooleanExpr = + BooleanExpr("not_eq_any", expression, arrayExpression) + + /** + * Creates an expression that checks if a field's value is not equal to all of the provided + * [values]. + * + * @param fieldName The field to compare. + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + @JvmStatic + fun notEqAny(fieldName: String, values: List): BooleanExpr = + notEqAny(fieldName, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if a field's value is not equal to all of the elements of + * [arrayExpression]. + * + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + @JvmStatic + fun notEqAny(fieldName: String, arrayExpression: Expr): BooleanExpr = + BooleanExpr("not_eq_any", fieldName, arrayExpression) + + /** + * Creates an expression that returns true if a value is absent. Otherwise, returns false even + * if the value is null. + * + * @param value The expression to check. + * @return A new [BooleanExpr] representing the isAbsent operation. + */ + @JvmStatic fun isAbsent(value: Expr): BooleanExpr = BooleanExpr("is_absent", value) + + /** + * Creates an expression that returns true if a field is absent. Otherwise, returns false even + * if the field value is null. + * + * @param fieldName The field to check. + * @return A new [BooleanExpr] representing the isAbsent operation. + */ + @JvmStatic fun isAbsent(fieldName: String): BooleanExpr = BooleanExpr("is_absent", fieldName) + + /** + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * @param expr The expression to check. + * @return A new [BooleanExpr] representing the isNan operation. + */ + @JvmStatic fun isNan(expr: Expr): BooleanExpr = BooleanExpr("is_nan", expr) + + /** + * Creates an expression that checks if [expr] evaluates to 'NaN' (Not a Number). + * + * @param fieldName The field to check. + * @return A new [BooleanExpr] representing the isNan operation. + */ + @JvmStatic fun isNan(fieldName: String): BooleanExpr = BooleanExpr("is_nan", fieldName) + + /** + * Creates an expression that checks if the results of [expr] is NOT 'NaN' (Not a Number). + * + * @param expr The expression to check. + * @return A new [BooleanExpr] representing the isNotNan operation. + */ + @JvmStatic fun isNotNan(expr: Expr): BooleanExpr = BooleanExpr("is_not_nan", expr) + + /** + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a + * Number). + * + * @param fieldName The field to check. + * @return A new [BooleanExpr] representing the isNotNan operation. + */ + @JvmStatic fun isNotNan(fieldName: String): BooleanExpr = BooleanExpr("is_not_nan", fieldName) + + /** + * Creates an expression that checks if tbe result of [expr] is null. + * + * @param expr The expression to check. + * @return A new [BooleanExpr] representing the isNull operation. + */ + @JvmStatic fun isNull(expr: Expr): BooleanExpr = BooleanExpr("is_null", expr) + + /** + * Creates an expression that checks if tbe value of a field is null. + * + * @param fieldName The field to check. + * @return A new [BooleanExpr] representing the isNull operation. + */ + @JvmStatic fun isNull(fieldName: String): BooleanExpr = BooleanExpr("is_null", fieldName) + + /** + * Creates an expression that checks if tbe result of [expr] is not null. + * + * @param expr The expression to check. + * @return A new [BooleanExpr] representing the isNotNull operation. + */ + @JvmStatic fun isNotNull(expr: Expr): BooleanExpr = BooleanExpr("is_not_null", expr) + + /** + * Creates an expression that checks if tbe value of a field is not null. + * + * @param fieldName The field to check. + * @return A new [BooleanExpr] representing the isNotNull operation. + */ + @JvmStatic fun isNotNull(fieldName: String): BooleanExpr = BooleanExpr("is_not_null", fieldName) + + /** + * Creates an expression that replaces the first occurrence of a substring within the + * [stringExpression]. + * + * @param stringExpression The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for in [stringExpression]. + * @param replace The expression representing the replacement for the first occurrence of [find] + * . + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + @JvmStatic + fun replaceFirst(stringExpression: Expr, find: Expr, replace: Expr): Expr = + FunctionExpr("replace_first", stringExpression, find, replace) + + /** + * Creates an expression that replaces the first occurrence of a substring within the + * [stringExpression]. + * + * @param stringExpression The expression representing the string to perform the replacement on. + * @param find The substring to search for in [stringExpression]. + * @param replace The replacement for the first occurrence of [find] with. + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + @JvmStatic + fun replaceFirst(stringExpression: Expr, find: String, replace: String): Expr = + FunctionExpr("replace_first", stringExpression, find, replace) + + /** + * Creates an expression that replaces the first occurrence of a substring within the specified + * string field. + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The expression representing the substring to search for in specified string + * field. + * @param replace The expression representing the replacement for the first occurrence of [find] + * with. + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + @JvmStatic + fun replaceFirst(fieldName: String, find: Expr, replace: Expr): Expr = + FunctionExpr("replace_first", fieldName, find, replace) + + /** + * Creates an expression that replaces the first occurrence of a substring within the specified + * string field. + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The substring to search for in specified string field. + * @param replace The replacement for the first occurrence of [find] with. + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + @JvmStatic + fun replaceFirst(fieldName: String, find: String, replace: String): Expr = + FunctionExpr("replace_first", fieldName, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within the + * [stringExpression]. + * + * @param stringExpression The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for in [stringExpression]. + * @param replace The expression representing the replacement for all occurrences of [find]. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + @JvmStatic + fun replaceAll(stringExpression: Expr, find: Expr, replace: Expr): Expr = + FunctionExpr("replace_all", stringExpression, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within the + * [stringExpression]. + * + * @param stringExpression The expression representing the string to perform the replacement on. + * @param find The substring to search for in [stringExpression]. + * @param replace The replacement for all occurrences of [find] with. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + @JvmStatic + fun replaceAll(stringExpression: Expr, find: String, replace: String): Expr = + FunctionExpr("replace_all", stringExpression, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within the specified + * string field. + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The expression representing the substring to search for in specified string + * field. + * @param replace The expression representing the replacement for all occurrences of [find] + * with. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + @JvmStatic + fun replaceAll(fieldName: String, find: Expr, replace: Expr): Expr = + FunctionExpr("replace_all", fieldName, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within the specified + * string field. + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The substring to search for in specified string field. + * @param replace The replacement for all occurrences of [find] with. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + @JvmStatic + fun replaceAll(fieldName: String, find: String, replace: String): Expr = + FunctionExpr("replace_all", fieldName, find, replace) + + /** + * Creates an expression that calculates the character length of a string expression in UTF8. + * + * @param expr The expression representing the string. + * @return A new [Expr] representing the charLength operation. + */ + @JvmStatic fun charLength(expr: Expr): Expr = FunctionExpr("char_length", expr) + + /** + * Creates an expression that calculates the character length of a string field in UTF8. + * + * @param fieldName The name of the field containing the string. + * @return A new [Expr] representing the charLength operation. + */ + @JvmStatic fun charLength(fieldName: String): Expr = FunctionExpr("char_length", fieldName) + + /** + * Creates an expression that calculates the length of a string in UTF-8 bytes, or just the + * length of a Blob. + * + * @param value The expression representing the string. + * @return A new [Expr] representing the length of the string in bytes. + */ + @JvmStatic fun byteLength(value: Expr): Expr = FunctionExpr("byte_length", value) + + /** + * Creates an expression that calculates the length of a string represented by a field in UTF-8 + * bytes, or just the length of a Blob. + * + * @param fieldName The name of the field containing the string. + * @return A new [Expr] representing the length of the string in bytes. + */ + @JvmStatic fun byteLength(fieldName: String): Expr = FunctionExpr("byte_length", fieldName) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like operation. + */ + @JvmStatic + fun like(stringExpression: Expr, pattern: Expr): BooleanExpr = + BooleanExpr("like", stringExpression, pattern) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like operation. + */ + @JvmStatic + fun like(stringExpression: Expr, pattern: String): BooleanExpr = + BooleanExpr("like", stringExpression, pattern) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like comparison. + */ + @JvmStatic + fun like(fieldName: String, pattern: Expr): BooleanExpr = + BooleanExpr("like", fieldName, pattern) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like comparison. + */ + @JvmStatic + fun like(fieldName: String, pattern: String): BooleanExpr = + BooleanExpr("like", fieldName, pattern) + + /** + * Creates an expression that return a pseudo-random number of type double in the range of [0, + * 1), inclusive of 0 and exclusive of 1. + * + * @return A new [Expr] representing the random number operation. + */ + @JvmStatic fun rand(): Expr = FunctionExpr("rand") + + /** + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + @JvmStatic + fun regexContains(stringExpression: Expr, pattern: Expr): BooleanExpr = + BooleanExpr("regex_contains", stringExpression, pattern) + + /** + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + @JvmStatic + fun regexContains(stringExpression: Expr, pattern: String): BooleanExpr = + BooleanExpr("regex_contains", stringExpression, pattern) + + /** + * Creates an expression that checks if a string field contains a specified regular expression + * as a substring. + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + @JvmStatic + fun regexContains(fieldName: String, pattern: Expr) = + BooleanExpr("regex_contains", fieldName, pattern) + + /** + * Creates an expression that checks if a string field contains a specified regular expression + * as a substring. + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + @JvmStatic + fun regexContains(fieldName: String, pattern: String) = + BooleanExpr("regex_contains", fieldName, pattern) + + /** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + @JvmStatic + fun regexMatch(stringExpression: Expr, pattern: Expr): BooleanExpr = + BooleanExpr("regex_match", stringExpression, pattern) + + /** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + @JvmStatic + fun regexMatch(stringExpression: Expr, pattern: String): BooleanExpr = + BooleanExpr("regex_match", stringExpression, pattern) + + /** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + @JvmStatic + fun regexMatch(fieldName: String, pattern: Expr) = + BooleanExpr("regex_match", fieldName, pattern) + + /** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + @JvmStatic + fun regexMatch(fieldName: String, pattern: String) = + BooleanExpr("regex_match", fieldName, pattern) + + /** + * Creates an expression that returns the largest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param expr The first operand expression. + * @param others Optional additional expressions or literals. + * @return A new [Expr] representing the logical maximum operation. + */ + @JvmStatic + fun logicalMaximum(expr: Expr, vararg others: Any): Expr = + FunctionExpr("logical_max", expr, *others) + + /** + * Creates an expression that returns the largest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param fieldName The first operand field name. + * @param others Optional additional expressions or literals. + * @return A new [Expr] representing the logical maximum operation. + */ + @JvmStatic + fun logicalMaximum(fieldName: String, vararg others: Any): Expr = + FunctionExpr("logical_max", fieldName, *others) + + /** + * Creates an expression that returns the smallest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param expr The first operand expression. + * @param others Optional additional expressions or literals. + * @return A new [Expr] representing the logical minimum operation. + */ + @JvmStatic + fun logicalMinimum(expr: Expr, vararg others: Any): Expr = + FunctionExpr("logical_min", expr, *others) + + /** + * Creates an expression that returns the smallest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param fieldName The first operand field name. + * @param others Optional additional expressions or literals. + * @return A new [Expr] representing the logical minimum operation. + */ + @JvmStatic + fun logicalMinimum(fieldName: String, vararg others: Any): Expr = + FunctionExpr("logical_min", fieldName, *others) + + /** + * Creates an expression that reverses a string. + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @return A new [Expr] representing the reversed string. + */ + @JvmStatic fun reverse(stringExpression: Expr): Expr = FunctionExpr("reverse", stringExpression) + + /** + * Creates an expression that reverses a string value from the specified field. + * + * @param fieldName The name of the field that contains the string to reverse. + * @return A new [Expr] representing the reversed string. + */ + @JvmStatic fun reverse(fieldName: String): Expr = FunctionExpr("reverse", fieldName) + + /** + * Creates an expression that checks if a string expression contains a specified substring. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + @JvmStatic + fun strContains(stringExpression: Expr, substring: Expr): BooleanExpr = + BooleanExpr("str_contains", stringExpression, substring) + + /** + * Creates an expression that checks if a string expression contains a specified substring. + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + @JvmStatic + fun strContains(stringExpression: Expr, substring: String): BooleanExpr = + BooleanExpr("str_contains", stringExpression, substring) + + /** + * Creates an expression that checks if a string field contains a specified substring. + * + * @param fieldName The name of the field to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + @JvmStatic + fun strContains(fieldName: String, substring: Expr): BooleanExpr = + BooleanExpr("str_contains", fieldName, substring) + + /** + * Creates an expression that checks if a string field contains a specified substring. + * + * @param fieldName The name of the field to perform the comparison on. + * @param substring The substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + @JvmStatic + fun strContains(fieldName: String, substring: String): BooleanExpr = + BooleanExpr("str_contains", fieldName, substring) + + /** + * Creates an expression that checks if a string expression starts with a given [prefix]. + * + * @param stringExpr The expression to check. + * @param prefix The prefix string expression to check for. + * @return A new [BooleanExpr] representing the 'starts with' comparison. + */ + @JvmStatic + fun startsWith(stringExpr: Expr, prefix: Expr): BooleanExpr = + BooleanExpr("starts_with", stringExpr, prefix) + + /** + * Creates an expression that checks if a string expression starts with a given [prefix]. + * + * @param stringExpr The expression to check. + * @param prefix The prefix string to check for. + * @return A new [BooleanExpr] representing the 'starts with' comparison. + */ + @JvmStatic + fun startsWith(stringExpr: Expr, prefix: String): BooleanExpr = + BooleanExpr("starts_with", stringExpr, prefix) + + /** + * Creates an expression that checks if a string expression starts with a given [prefix]. + * + * @param fieldName The name of field that contains a string to check. + * @param prefix The prefix string expression to check for. + * @return A new [BooleanExpr] representing the 'starts with' comparison. + */ + @JvmStatic + fun startsWith(fieldName: String, prefix: Expr): BooleanExpr = + BooleanExpr("starts_with", fieldName, prefix) + + /** + * Creates an expression that checks if a string expression starts with a given [prefix]. + * + * @param fieldName The name of field that contains a string to check. + * @param prefix The prefix string to check for. + * @return A new [BooleanExpr] representing the 'starts with' comparison. + */ + @JvmStatic + fun startsWith(fieldName: String, prefix: String): BooleanExpr = + BooleanExpr("starts_with", fieldName, prefix) + + /** + * Creates an expression that checks if a string expression ends with a given [suffix]. + * + * @param stringExpr The expression to check. + * @param suffix The suffix string expression to check for. + * @return A new [BooleanExpr] representing the 'ends with' comparison. + */ + @JvmStatic + fun endsWith(stringExpr: Expr, suffix: Expr): BooleanExpr = + BooleanExpr("ends_with", stringExpr, suffix) + + /** + * Creates an expression that checks if a string expression ends with a given [suffix]. + * + * @param stringExpr The expression to check. + * @param suffix The suffix string to check for. + * @return A new [BooleanExpr] representing the 'ends with' comparison. + */ + @JvmStatic + fun endsWith(stringExpr: Expr, suffix: String): BooleanExpr = + BooleanExpr("ends_with", stringExpr, suffix) + + /** + * Creates an expression that checks if a string expression ends with a given [suffix]. + * + * @param fieldName The name of field that contains a string to check. + * @param suffix The suffix string expression to check for. + * @return A new [BooleanExpr] representing the 'ends with' comparison. + */ + @JvmStatic + fun endsWith(fieldName: String, suffix: Expr): BooleanExpr = + BooleanExpr("ends_with", fieldName, suffix) + + /** + * Creates an expression that checks if a string expression ends with a given [suffix]. + * + * @param fieldName The name of field that contains a string to check. + * @param suffix The suffix string to check for. + * @return A new [BooleanExpr] representing the 'ends with' comparison. + */ + @JvmStatic + fun endsWith(fieldName: String, suffix: String): BooleanExpr = + BooleanExpr("ends_with", fieldName, suffix) + + /** + * Creates an expression that converts a string expression to lowercase. + * + * @param stringExpression The expression representing the string to convert to lowercase. + * @return A new [Expr] representing the lowercase string. + */ + @JvmStatic + fun toLower(stringExpression: Expr): Expr = FunctionExpr("to_lower", stringExpression) + + /** + * Creates an expression that converts a string field to lowercase. + * + * @param fieldName The name of the field containing the string to convert to lowercase. + * @return A new [Expr] representing the lowercase string. + */ + @JvmStatic fun toLower(fieldName: String): Expr = FunctionExpr("to_lower", fieldName) + + /** + * Creates an expression that converts a string expression to uppercase. + * + * @param stringExpression The expression representing the string to convert to uppercase. + * @return A new [Expr] representing the lowercase string. + */ + @JvmStatic + fun toUpper(stringExpression: Expr): Expr = FunctionExpr("to_upper", stringExpression) + + /** + * Creates an expression that converts a string field to uppercase. + * + * @param fieldName The name of the field containing the string to convert to uppercase. + * @return A new [Expr] representing the lowercase string. + */ + @JvmStatic fun toUpper(fieldName: String): Expr = FunctionExpr("to_upper", fieldName) + + /** + * Creates an expression that removes leading and trailing whitespace from a string expression. + * + * @param stringExpression The expression representing the string to trim. + * @return A new [Expr] representing the trimmed string. + */ + @JvmStatic fun trim(stringExpression: Expr): Expr = FunctionExpr("trim", stringExpression) + + /** + * Creates an expression that removes leading and trailing whitespace from a string field. + * + * @param fieldName The name of the field containing the string to trim. + * @return A new [Expr] representing the trimmed string. + */ + @JvmStatic fun trim(fieldName: String): Expr = FunctionExpr("trim", fieldName) + + /** + * Creates an expression that concatenates string expressions together. + * + * @param firstString The expression representing the initial string value. + * @param otherStrings Optional additional string expressions to concatenate. + * @return A new [Expr] representing the concatenated string. + */ + @JvmStatic + fun strConcat(firstString: Expr, vararg otherStrings: Expr): Expr = + FunctionExpr("str_concat", firstString, *otherStrings) + + /** + * Creates an expression that concatenates string expressions together. + * + * @param firstString The expression representing the initial string value. + * @param otherStrings Optional additional string expressions or string constants to + * concatenate. + * @return A new [Expr] representing the concatenated string. + */ + @JvmStatic + fun strConcat(firstString: Expr, vararg otherStrings: Any): Expr = + FunctionExpr("str_concat", firstString, *otherStrings) + + /** + * Creates an expression that concatenates string expressions together. + * + * @param fieldName The field name containing the initial string value. + * @param otherStrings Optional additional string expressions to concatenate. + * @return A new [Expr] representing the concatenated string. + */ + @JvmStatic + fun strConcat(fieldName: String, vararg otherStrings: Expr): Expr = + FunctionExpr("str_concat", fieldName, *otherStrings) + + /** + * Creates an expression that concatenates string expressions together. + * + * @param fieldName The field name containing the initial string value. + * @param otherStrings Optional additional string expressions or string constants to + * concatenate. + * @return A new [Expr] representing the concatenated string. + */ + @JvmStatic + fun strConcat(fieldName: String, vararg otherStrings: Any): Expr = + FunctionExpr("str_concat", fieldName, *otherStrings) + + internal fun map(elements: Array): Expr = FunctionExpr("map", elements) + + /** + * Creates an expression that creates a Firestore map value from an input object. + * + * @param elements The input map to evaluate in the expression. + * @return A new [Expr] representing the map function. + */ + @JvmStatic + fun map(elements: Map): Expr = + map(elements.flatMap { listOf(constant(it.key), toExprOrConstant(it.value)) }.toTypedArray()) + + /** + * Accesses a value from a map (object) field using the provided [key]. + * + * @param mapExpression The expression representing the map. + * @param key The key to access in the map. + * @return A new [Expr] representing the value associated with the given key in the map. + */ + @JvmStatic + fun mapGet(mapExpression: Expr, key: String): Expr = FunctionExpr("map_get", mapExpression, key) + + /** + * Accesses a value from a map (object) field using the provided [key]. + * + * @param fieldName The field name of the map field. + * @param key The key to access in the map. + * @return A new [Expr] representing the value associated with the given key in the map. + */ + @JvmStatic + fun mapGet(fieldName: String, key: String): Expr = FunctionExpr("map_get", fieldName, key) + + /** + * Creates an expression that merges multiple maps into a single map. If multiple maps have the + * same key, the later value is used. + * + * @param firstMap First map expression that will be merged. + * @param secondMap Second map expression that will be merged. + * @param otherMaps Additional maps to merge. + * @return A new [Expr] representing the mapMerge operation. + */ + @JvmStatic + fun mapMerge(firstMap: Expr, secondMap: Expr, vararg otherMaps: Expr): Expr = + FunctionExpr("map_merge", firstMap, secondMap, *otherMaps) + + /** + * Creates an expression that merges multiple maps into a single map. If multiple maps have the + * same key, the later value is used. + * + * @param firstMapFieldName First map field name that will be merged. + * @param secondMap Second map expression that will be merged. + * @param otherMaps Additional maps to merge. + * @return A new [Expr] representing the mapMerge operation. + */ + @JvmStatic + fun mapMerge(firstMapFieldName: String, secondMap: Expr, vararg otherMaps: Expr): Expr = + FunctionExpr("map_merge", firstMapFieldName, secondMap, *otherMaps) + + /** + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * @param mapExpr An expression that evaluates to a map. + * @param key The name of the key to remove from the input map. + * @return A new [Expr] that evaluates to a modified map. + */ + @JvmStatic + fun mapRemove(mapExpr: Expr, key: Expr): Expr = FunctionExpr("map_remove", mapExpr, key) + + /** + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. + * @return A new [Expr] that evaluates to a modified map. + */ + @JvmStatic + fun mapRemove(mapField: String, key: Expr): Expr = FunctionExpr("map_remove", mapField, key) + + /** + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * @param mapExpr An expression that evaluates to a map. + * @param key The name of the key to remove from the input map. + * @return A new [Expr] that evaluates to a modified map. + */ + @JvmStatic + fun mapRemove(mapExpr: Expr, key: String): Expr = FunctionExpr("map_remove", mapExpr, key) + + /** + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. + * @return A new [Expr] that evaluates to a modified map. + */ + @JvmStatic + fun mapRemove(mapField: String, key: String): Expr = FunctionExpr("map_remove", mapField, key) + + /** + * Calculates the Cosine distance between two vector expressions. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vector1: Expr, vector2: Expr): Expr = + FunctionExpr("cosine_distance", vector1, vector2) + + /** + * Calculates the Cosine distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vector1: Expr, vector2: DoubleArray): Expr = + FunctionExpr("cosine_distance", vector1, vector(vector2)) + + /** + * Calculates the Cosine distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an [Expr]) to compare against. + * @param vector2 The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vector1: Expr, vector2: VectorValue): Expr = + FunctionExpr("cosine_distance", vector1, vector2) + + /** + * Calculates the Cosine distance between a vector field and a vector expression. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vectorFieldName: String, vector: Expr): Expr = + FunctionExpr("cosine_distance", vectorFieldName, vector) + + /** + * Calculates the Cosine distance between a vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vectorFieldName: String, vector: DoubleArray): Expr = + FunctionExpr("cosine_distance", vectorFieldName, vector(vector)) + + /** + * Calculates the Cosine distance between a vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + @JvmStatic + fun cosineDistance(vectorFieldName: String, vector: VectorValue): Expr = + FunctionExpr("cosine_distance", vectorFieldName, vector) + + /** + * Calculates the dot product distance between two vector expressions. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vector1: Expr, vector2: Expr): Expr = + FunctionExpr("dot_product", vector1, vector2) + + /** + * Calculates the dot product distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vector1: Expr, vector2: DoubleArray): Expr = + FunctionExpr("dot_product", vector1, vector(vector2)) + + /** + * Calculates the dot product distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an [Expr]) to compare against. + * @param vector2 The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vector1: Expr, vector2: VectorValue): Expr = + FunctionExpr("dot_product", vector1, vector2) + + /** + * Calculates the dot product distance between a vector field and a vector expression. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vectorFieldName: String, vector: Expr): Expr = + FunctionExpr("dot_product", vectorFieldName, vector) + + /** + * Calculates the dot product distance between vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vectorFieldName: String, vector: DoubleArray): Expr = + FunctionExpr("dot_product", vectorFieldName, vector(vector)) + + /** + * Calculates the dot product distance between a vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + @JvmStatic + fun dotProduct(vectorFieldName: String, vector: VectorValue): Expr = + FunctionExpr("dot_product", vectorFieldName, vector) + + /** + * Calculates the Euclidean distance between two vector expressions. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vector1: Expr, vector2: Expr): Expr = + FunctionExpr("euclidean_distance", vector1, vector2) + + /** + * Calculates the Euclidean distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an Expr) to compare against. + * @param vector2 The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vector1: Expr, vector2: DoubleArray): Expr = + FunctionExpr("euclidean_distance", vector1, vector(vector2)) + + /** + * Calculates the Euclidean distance between vector expression and a vector literal. + * + * @param vector1 The first vector (represented as an [Expr]) to compare against. + * @param vector2 The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vector1: Expr, vector2: VectorValue): Expr = + FunctionExpr("euclidean_distance", vector1, vector2) + + /** + * Calculates the Euclidean distance between a vector field and a vector expression. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vectorFieldName: String, vector: Expr): Expr = + FunctionExpr("euclidean_distance", vectorFieldName, vector) + + /** + * Calculates the Euclidean distance between a vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vectorFieldName: String, vector: DoubleArray): Expr = + FunctionExpr("euclidean_distance", vectorFieldName, vector(vector)) + + /** + * Calculates the Euclidean distance between a vector field and a vector literal. + * + * @param vectorFieldName The name of the field containing the first vector. + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + @JvmStatic + fun euclideanDistance(vectorFieldName: String, vector: VectorValue): Expr = + FunctionExpr("euclidean_distance", vectorFieldName, vector) + + /** + * Creates an expression that calculates the length (dimension) of a Firestore Vector. + * + * @param vectorExpression The expression representing the Firestore Vector. + * @return A new [Expr] representing the length (dimension) of the vector. + */ + @JvmStatic + fun vectorLength(vectorExpression: Expr): Expr = FunctionExpr("vector_length", vectorExpression) + + /** + * Creates an expression that calculates the length (dimension) of a Firestore Vector. + * + * @param fieldName The name of the field containing the Firestore Vector. + * @return A new [Expr] representing the length (dimension) of the vector. + */ + @JvmStatic fun vectorLength(fieldName: String): Expr = FunctionExpr("vector_length", fieldName) + + /** + * Creates an expression that interprets an expression as the number of microseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param expr The expression representing the number of microseconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixMicrosToTimestamp(expr: Expr): Expr = FunctionExpr("unix_micros_to_timestamp", expr) + + /** + * Creates an expression that interprets a field's value as the number of microseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param fieldName The name of the field containing the number of microseconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixMicrosToTimestamp(fieldName: String): Expr = + FunctionExpr("unix_micros_to_timestamp", fieldName) + + /** + * Creates an expression that converts a timestamp expression to the number of microseconds + * since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @param expr The expression representing the timestamp. + * @return A new [Expr] representing the number of microseconds since epoch. + */ + @JvmStatic + fun timestampToUnixMicros(expr: Expr): Expr = FunctionExpr("timestamp_to_unix_micros", expr) + + /** + * Creates an expression that converts a timestamp field to the number of microseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC). + * + * @param fieldName The name of the field that contains the timestamp. + * @return A new [Expr] representing the number of microseconds since epoch. + */ + @JvmStatic + fun timestampToUnixMicros(fieldName: String): Expr = + FunctionExpr("timestamp_to_unix_micros", fieldName) + + /** + * Creates an expression that interprets an expression as the number of milliseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param expr The expression representing the number of milliseconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixMillisToTimestamp(expr: Expr): Expr = FunctionExpr("unix_millis_to_timestamp", expr) + + /** + * Creates an expression that interprets a field's value as the number of milliseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param fieldName The name of the field containing the number of milliseconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixMillisToTimestamp(fieldName: String): Expr = + FunctionExpr("unix_millis_to_timestamp", fieldName) + + /** + * Creates an expression that converts a timestamp expression to the number of milliseconds + * since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @param expr The expression representing the timestamp. + * @return A new [Expr] representing the number of milliseconds since epoch. + */ + @JvmStatic + fun timestampToUnixMillis(expr: Expr): Expr = FunctionExpr("timestamp_to_unix_millis", expr) + + /** + * Creates an expression that converts a timestamp field to the number of milliseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC). + * + * @param fieldName The name of the field that contains the timestamp. + * @return A new [Expr] representing the number of milliseconds since epoch. + */ + @JvmStatic + fun timestampToUnixMillis(fieldName: String): Expr = + FunctionExpr("timestamp_to_unix_millis", fieldName) + + /** + * Creates an expression that interprets an expression as the number of seconds since the Unix + * epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param expr The expression representing the number of seconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixSecondsToTimestamp(expr: Expr): Expr = FunctionExpr("unix_seconds_to_timestamp", expr) + + /** + * Creates an expression that interprets a field's value as the number of seconds since the Unix + * epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @param fieldName The name of the field containing the number of seconds since epoch. + * @return A new [Expr] representing the timestamp. + */ + @JvmStatic + fun unixSecondsToTimestamp(fieldName: String): Expr = + FunctionExpr("unix_seconds_to_timestamp", fieldName) + + /** + * Creates an expression that converts a timestamp expression to the number of seconds since the + * Unix epoch (1970-01-01 00:00:00 UTC). + * + * @param expr The expression representing the timestamp. + * @return A new [Expr] representing the number of seconds since epoch. + */ + @JvmStatic + fun timestampToUnixSeconds(expr: Expr): Expr = FunctionExpr("timestamp_to_unix_seconds", expr) + + /** + * Creates an expression that converts a timestamp field to the number of seconds since the Unix + * epoch (1970-01-01 00:00:00 UTC). + * + * @param fieldName The name of the field that contains the timestamp. + * @return A new [Expr] representing the number of seconds since epoch. + */ + @JvmStatic + fun timestampToUnixSeconds(fieldName: String): Expr = + FunctionExpr("timestamp_to_unix_seconds", fieldName) + + /** + * Creates an expression that adds a specified amount of time to a timestamp. + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression representing the unit of time to add. Valid units include + * "microsecond", "millisecond", "second", "minute", "hour" and "day". + * @param amount The expression representing the amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampAdd(timestamp: Expr, unit: Expr, amount: Expr): Expr = + FunctionExpr("timestamp_add", timestamp, unit, amount) + + /** + * Creates an expression that adds a specified amount of time to a timestamp. + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampAdd(timestamp: Expr, unit: String, amount: Double): Expr = + FunctionExpr("timestamp_add", timestamp, unit, amount) + + /** + * Creates an expression that adds a specified amount of time to a timestamp. + * + * @param fieldName The name of the field that contains the timestamp. + * @param unit The expression representing the unit of time to add. Valid units include + * "microsecond", "millisecond", "second", "minute", "hour" and "day". + * @param amount The expression representing the amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampAdd(fieldName: String, unit: Expr, amount: Expr): Expr = + FunctionExpr("timestamp_add", fieldName, unit, amount) + + /** + * Creates an expression that adds a specified amount of time to a timestamp. + * + * @param fieldName The name of the field that contains the timestamp. + * @param unit The unit of time to add. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampAdd(fieldName: String, unit: String, amount: Double): Expr = + FunctionExpr("timestamp_add", fieldName, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to a timestamp. + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression representing the unit of time to subtract. Valid units include + * "microsecond", "millisecond", "second", "minute", "hour" and "day". + * @param amount The expression representing the amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampSub(timestamp: Expr, unit: Expr, amount: Expr): Expr = + FunctionExpr("timestamp_sub", timestamp, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to a timestamp. + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampSub(timestamp: Expr, unit: String, amount: Double): Expr = + FunctionExpr("timestamp_sub", timestamp, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to a timestamp. + * + * @param fieldName The name of the field that contains the timestamp. + * @param unit The unit of time to subtract. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampSub(fieldName: String, unit: Expr, amount: Expr): Expr = + FunctionExpr("timestamp_sub", fieldName, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to a timestamp. + * + * @param fieldName The name of the field that contains the timestamp. + * @param unit The unit of time to subtract. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + @JvmStatic + fun timestampSub(fieldName: String, unit: String, amount: Double): Expr = + FunctionExpr("timestamp_sub", fieldName, unit, amount) + + /** + * Creates an expression that checks if two expressions are equal. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + @JvmStatic fun eq(left: Expr, right: Expr): BooleanExpr = BooleanExpr("eq", left, right) + + /** + * Creates an expression that checks if an expression is equal to a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + @JvmStatic fun eq(left: Expr, right: Any): BooleanExpr = BooleanExpr("eq", left, right) + + /** + * Creates an expression that checks if a field's value is equal to an expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + @JvmStatic + fun eq(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("eq", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is equal to another value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + @JvmStatic + fun eq(fieldName: String, value: Any): BooleanExpr = BooleanExpr("eq", fieldName, value) + + /** + * Creates an expression that checks if two expressions are not equal. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + @JvmStatic fun neq(left: Expr, right: Expr): BooleanExpr = BooleanExpr("neq", left, right) + + /** + * Creates an expression that checks if an expression is not equal to a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + @JvmStatic fun neq(left: Expr, right: Any): BooleanExpr = BooleanExpr("neq", left, right) + + /** + * Creates an expression that checks if a field's value is not equal to an expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + @JvmStatic + fun neq(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("neq", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is not equal to another value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + @JvmStatic + fun neq(fieldName: String, value: Any): BooleanExpr = BooleanExpr("neq", fieldName, value) + + /** + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + @JvmStatic fun gt(left: Expr, right: Expr): BooleanExpr = BooleanExpr("gt", left, right) + + /** + * Creates an expression that checks if an expression is greater than a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + @JvmStatic fun gt(left: Expr, right: Any): BooleanExpr = BooleanExpr("gt", left, right) + + /** + * Creates an expression that checks if a field's value is greater than an expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + @JvmStatic + fun gt(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("gt", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is greater than another value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + @JvmStatic + fun gt(fieldName: String, value: Any): BooleanExpr = BooleanExpr("gt", fieldName, value) + + /** + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + @JvmStatic fun gte(left: Expr, right: Expr): BooleanExpr = BooleanExpr("gte", left, right) + + /** + * Creates an expression that checks if an expression is greater than or equal to a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + @JvmStatic fun gte(left: Expr, right: Any): BooleanExpr = BooleanExpr("gte", left, right) + + /** + * Creates an expression that checks if a field's value is greater than or equal to an + * expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + @JvmStatic + fun gte(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("gte", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is greater than or equal to another + * value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + @JvmStatic + fun gte(fieldName: String, value: Any): BooleanExpr = BooleanExpr("gte", fieldName, value) + + /** + * Creates an expression that checks if the first expression is less than the second expression. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + @JvmStatic fun lt(left: Expr, right: Expr): BooleanExpr = BooleanExpr("lt", left, right) + + /** + * Creates an expression that checks if an expression is less than a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + @JvmStatic fun lt(left: Expr, right: Any): BooleanExpr = BooleanExpr("lt", left, right) + + /** + * Creates an expression that checks if a field's value is less than an expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + @JvmStatic + fun lt(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("lt", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is less than another value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + @JvmStatic + fun lt(fieldName: String, right: Any): BooleanExpr = BooleanExpr("lt", fieldName, right) + + /** + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * @param left The first expression to compare. + * @param right The second expression to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + @JvmStatic fun lte(left: Expr, right: Expr): BooleanExpr = BooleanExpr("lte", left, right) + + /** + * Creates an expression that checks if an expression is less than or equal to a value. + * + * @param left The first expression to compare. + * @param right The value to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + @JvmStatic fun lte(left: Expr, right: Any): BooleanExpr = BooleanExpr("lte", left, right) + + /** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + @JvmStatic + fun lte(fieldName: String, expression: Expr): BooleanExpr = + BooleanExpr("lte", fieldName, expression) + + /** + * Creates an expression that checks if a field's value is less than or equal to another value. + * + * @param fieldName The field name to compare. + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + @JvmStatic + fun lte(fieldName: String, value: Any): BooleanExpr = BooleanExpr("lte", fieldName, value) + + /** + * Creates an expression that concatenates an array with other arrays. + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray An expression that evaluates to array to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + @JvmStatic + fun arrayConcat(firstArray: Expr, secondArray: Expr, vararg otherArrays: Any): Expr = + FunctionExpr("array_concat", firstArray, secondArray, *otherArrays) + + /** + * Creates an expression that concatenates an array with other arrays. + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray An array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + @JvmStatic + fun arrayConcat(firstArray: Expr, secondArray: Any, vararg otherArrays: Any): Expr = + FunctionExpr("array_concat", firstArray, secondArray, *otherArrays) + + /** + * Creates an expression that concatenates a field's array value with other arrays. + * + * @param firstArrayField The name of field that contains first array to concatenate to. + * @param secondArray An expression that evaluates to array to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + @JvmStatic + fun arrayConcat(firstArrayField: String, secondArray: Expr, vararg otherArrays: Any): Expr = + FunctionExpr("array_concat", firstArrayField, secondArray, *otherArrays) + + /** + * Creates an expression that concatenates a field's array value with other arrays. + * + * @param firstArrayField The name of field that contains first array to concatenate to. + * @param secondArray An array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + @JvmStatic + fun arrayConcat(firstArrayField: String, secondArray: Any, vararg otherArrays: Any): Expr = + FunctionExpr("array_concat", firstArrayField, secondArray, *otherArrays) + + /** + * Reverses the order of elements in the [array]. + * + * @param array The array expression to reverse. + * @return A new [Expr] representing the arrayReverse operation. + */ + @JvmStatic fun arrayReverse(array: Expr): Expr = FunctionExpr("array_reverse", array) + + /** + * Reverses the order of elements in the array field. + * + * @param arrayFieldName The name of field that contains the array to reverse. + * @return A new [Expr] representing the arrayReverse operation. + */ + @JvmStatic + fun arrayReverse(arrayFieldName: String): Expr = FunctionExpr("array_reverse", arrayFieldName) + + /** + * Creates an expression that checks if the array contains a specific [element]. + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + @JvmStatic + fun arrayContains(array: Expr, element: Expr): BooleanExpr = + BooleanExpr("array_contains", array, element) + + /** + * Creates an expression that checks if the array field contains a specific [element]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + @JvmStatic + fun arrayContains(arrayFieldName: String, element: Expr) = + BooleanExpr("array_contains", arrayFieldName, element) + + /** + * Creates an expression that checks if the [array] contains a specific [element]. + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + @JvmStatic + fun arrayContains(array: Expr, element: Any): BooleanExpr = + BooleanExpr("array_contains", array, element) + + /** + * Creates an expression that checks if the array field contains a specific [element]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + @JvmStatic + fun arrayContains(arrayFieldName: String, element: Any) = + BooleanExpr("array_contains", arrayFieldName, element) + + /** + * Creates an expression that checks if [array] contains all the specified [values]. + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + @JvmStatic + fun arrayContainsAll(array: Expr, values: List) = + arrayContainsAll(array, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if [array] contains all elements of [arrayExpression]. + * + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + @JvmStatic + fun arrayContainsAll(array: Expr, arrayExpression: Expr) = + BooleanExpr("array_contains_all", array, arrayExpression) + + /** + * Creates an expression that checks if array field contains all the specified [values]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + @JvmStatic + fun arrayContainsAll(arrayFieldName: String, values: List) = + BooleanExpr( + "array_contains_all", + arrayFieldName, + ListOfExprs(toArrayOfExprOrConstant(values)) + ) + + /** + * Creates an expression that checks if array field contains all elements of [arrayExpression]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + @JvmStatic + fun arrayContainsAll(arrayFieldName: String, arrayExpression: Expr) = + BooleanExpr("array_contains_all", arrayFieldName, arrayExpression) + + /** + * Creates an expression that checks if [array] contains any of the specified [values]. + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + @JvmStatic + fun arrayContainsAny(array: Expr, values: List) = + BooleanExpr("array_contains_any", array, ListOfExprs(toArrayOfExprOrConstant(values))) + + /** + * Creates an expression that checks if [array] contains any elements of [arrayExpression]. + * + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + @JvmStatic + fun arrayContainsAny(array: Expr, arrayExpression: Expr) = + BooleanExpr("array_contains_any", array, arrayExpression) + + /** + * Creates an expression that checks if array field contains any of the specified [values]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + @JvmStatic + fun arrayContainsAny(arrayFieldName: String, values: List) = + BooleanExpr( + "array_contains_any", + arrayFieldName, + ListOfExprs(toArrayOfExprOrConstant(values)) + ) + + /** + * Creates an expression that checks if array field contains any elements of [arrayExpression]. + * + * @param arrayFieldName The name of field that contains array to check. + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + @JvmStatic + fun arrayContainsAny(arrayFieldName: String, arrayExpression: Expr) = + BooleanExpr("array_contains_any", arrayFieldName, arrayExpression) + + /** + * Creates an expression that calculates the length of an [array] expression. + * + * @param array The array expression to calculate the length of. + * @return A new [Expr] representing the length of the array. + */ + @JvmStatic fun arrayLength(array: Expr): Expr = FunctionExpr("array_length", array) + + /** + * Creates an expression that calculates the length of an array field. + * + * @param arrayFieldName The name of the field containing an array to calculate the length of. + * @return A new [Expr] representing the length of the array. + */ + @JvmStatic + fun arrayLength(arrayFieldName: String): Expr = FunctionExpr("array_length", arrayFieldName) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param array An [Expr] evaluating to an array. + * @param offset An Expr evaluating to the index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + @JvmStatic + fun arrayOffset(array: Expr, offset: Expr): Expr = FunctionExpr("array_offset", array, offset) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param array An [Expr] evaluating to an array. + * @param offset The index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + @JvmStatic + fun arrayOffset(array: Expr, offset: Int): Expr = + FunctionExpr("array_offset", array, constant(offset)) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param arrayFieldName The name of an array field. + * @param offset An Expr evaluating to the index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + @JvmStatic + fun arrayOffset(arrayFieldName: String, offset: Expr): Expr = + FunctionExpr("array_offset", arrayFieldName, offset) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param arrayFieldName The name of an array field. + * @param offset The index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + @JvmStatic + fun arrayOffset(arrayFieldName: String, offset: Int): Expr = + FunctionExpr("array_offset", arrayFieldName, constant(offset)) + + /** + * Creates a conditional expression that evaluates to a [thenExpr] expression if a condition is + * true or an [elseExpr] expression if the condition is false. + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new [Expr] representing the conditional operation. + */ + @JvmStatic + fun cond(condition: BooleanExpr, thenExpr: Expr, elseExpr: Expr): Expr = + FunctionExpr("cond", condition, thenExpr, elseExpr) + + /** + * Creates a conditional expression that evaluates to a [thenValue] if a condition is true or an + * [elseValue] if the condition is false. + * + * @param condition The condition to evaluate. + * @param thenValue Value if the condition is true. + * @param elseValue Value if the condition is false. + * @return A new [Expr] representing the conditional operation. + */ + @JvmStatic + fun cond(condition: BooleanExpr, thenValue: Any, elseValue: Any): Expr = + FunctionExpr("cond", condition, thenValue, elseValue) + + /** + * Creates an expression that checks if a field exists. + * + * @param value An expression evaluates to the name of the field to check. + * @return A new [Expr] representing the exists check. + */ + @JvmStatic fun exists(value: Expr): BooleanExpr = BooleanExpr("exists", value) + + /** + * Creates an expression that checks if a field exists. + * + * @param fieldName The field name to check. + * @return A new [Expr] representing the exists check. + */ + @JvmStatic fun exists(fieldName: String): BooleanExpr = BooleanExpr("exists", fieldName) + + /** + * Creates an expression that returns the [catchExpr] argument if there is an error, else return + * the result of the [tryExpr] argument evaluation. + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and returned if the [tryExpr] + * produces an error. + * @return A new [Expr] representing the ifError operation. + */ + @JvmStatic + fun ifError(tryExpr: Expr, catchExpr: Expr): Expr = FunctionExpr("if_error", tryExpr, catchExpr) + + /** + * Creates an expression that returns the [catchExpr] argument if there is an error, else return + * the result of the [tryExpr] argument evaluation. + * + * This overload will return [BooleanExpr] when both parameters are also [BooleanExpr]. + * + * @param tryExpr The try boolean expression. + * @param catchExpr The catch boolean expression that will be evaluated and returned if the [tryExpr] + * produces an error. + * @return A new [BooleanExpr] representing the ifError operation. + */ + @JvmStatic + fun ifError(tryExpr: BooleanExpr, catchExpr: BooleanExpr): BooleanExpr = BooleanExpr("if_error", tryExpr, catchExpr) + + /** + * Creates an expression that returns the [catchValue] argument if there is an error, else + * return the result of the [tryExpr] argument evaluation. + * + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the [tryExpr] produces an error. + * @return A new [Expr] representing the ifError operation. + */ + @JvmStatic + fun ifError(tryExpr: Expr, catchValue: Any): Expr = + FunctionExpr("if_error", tryExpr, catchValue) + + /** + * Creates an expression that returns the document ID from a path. + * + * @param documentPath An expression the evaluates to document path. + * @return A new [Expr] representing the documentId operation. + */ + @JvmStatic fun documentId(documentPath: Expr): Expr = FunctionExpr("document_id", documentPath) + + /** + * Creates an expression that returns the document ID from a path. + * + * @param documentPath The string representation of the document path. + * @return A new [Expr] representing the documentId operation. + */ + @JvmStatic fun documentId(documentPath: String): Expr = documentId(constant(documentPath)) + + /** + * Creates an expression that returns the document ID from a [DocumentReference]. + * + * @param docRef The [DocumentReference]. + * @return A new [Expr] representing the documentId operation. + */ + @JvmStatic fun documentId(docRef: DocumentReference): Expr = documentId(constant(docRef)) + } + + /** + * Creates an expression that applies a bitwise AND operation with other expression. + * + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise AND operation. + */ + fun bitAnd(bitsOther: Expr): Expr = Companion.bitAnd(this, bitsOther) + + /** + * Creates an expression that applies a bitwise AND operation with a constant. + * + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise AND operation. + */ + fun bitAnd(bitsOther: ByteArray): Expr = Companion.bitAnd(this, bitsOther) + + /** + * Creates an expression that applies a bitwise OR operation with other expression. + * + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise OR operation. + */ + fun bitOr(bitsOther: Expr): Expr = Companion.bitOr(this, bitsOther) + + /** + * Creates an expression that applies a bitwise OR operation with a constant. + * + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise OR operation. + */ + fun bitOr(bitsOther: ByteArray): Expr = Companion.bitOr(this, bitsOther) + + /** + * Creates an expression that applies a bitwise XOR operation with an expression. + * + * @param bitsOther An expression that returns bits when evaluated. + * @return A new [Expr] representing the bitwise XOR operation. + */ + fun bitXor(bitsOther: Expr): Expr = Companion.bitXor(this, bitsOther) + + /** + * Creates an expression that applies a bitwise XOR operation with a constant. + * + * @param bitsOther A constant byte array. + * @return A new [Expr] representing the bitwise XOR operation. + */ + fun bitXor(bitsOther: ByteArray): Expr = Companion.bitXor(this, bitsOther) + + /** + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * @return A new [Expr] representing the bitwise NOT operation. + */ + fun bitNot(): Expr = Companion.bitNot(this) + + /** + * Creates an expression that applies a bitwise left shift operation with an expression. + * + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + fun bitLeftShift(numberExpr: Expr): Expr = Companion.bitLeftShift(this, numberExpr) + + /** + * Creates an expression that applies a bitwise left shift operation with a constant. + * + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise left shift operation. + */ + fun bitLeftShift(number: Int): Expr = Companion.bitLeftShift(this, number) + + /** + * Creates an expression that applies a bitwise right shift operation with an expression. + * + * @param numberExpr The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + fun bitRightShift(numberExpr: Expr): Expr = Companion.bitRightShift(this, numberExpr) + + /** + * Creates an expression that applies a bitwise right shift operation with a constant. + * + * @param number The number of bits to shift. + * @return A new [Expr] representing the bitwise right shift operation. + */ + fun bitRightShift(number: Int): Expr = Companion.bitRightShift(this, number) + + /** + * Assigns an alias to this expression. + * + * Aliases are useful for renaming fields in the output of a stage or for giving meaningful names + * to calculated values. + * + * @param alias The alias to assign to this expression. + * @return A new [Selectable] (typically an [ExprWithAlias]) that wraps this expression and + * associates it with the provided alias. + */ + open fun alias(alias: String) = ExprWithAlias(alias, this) + + /** + * Creates an expression that returns the document ID from this path expression. + * + * @return A new [Expr] representing the documentId operation. + */ + fun documentId(): Expr = Companion.documentId(this) + + /** + * Creates an expression that adds this numeric expression to another numeric expression. + * + * @param second Numeric expression to add. + * @return A new [Expr] representing the addition operation. + */ + fun add(second: Expr): Expr = Companion.add(this, second) + + /** + * Creates an expression that adds this numeric expression to a constants. + * + * @param second Constant to add. + * @return A new [Expr] representing the addition operation. + */ + fun add(second: Number): Expr = Companion.add(this, second) + + /** + * Creates an expression that subtracts a constant from this numeric expression. + * + * @param subtrahend Numeric expression to subtract. + * @return A new [Expr] representing the subtract operation. + */ + fun subtract(subtrahend: Expr): Expr = Companion.subtract(this, subtrahend) + + /** + * Creates an expression that subtracts a numeric expressions from this numeric expression. + * + * @param subtrahend Constant to subtract. + * @return A new [Expr] representing the subtract operation. + */ + fun subtract(subtrahend: Number): Expr = Companion.subtract(this, subtrahend) + + /** + * Creates an expression that multiplies this numeric expression with another numeric expression. + * + * @param second Numeric expression to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + fun multiply(second: Expr): Expr = Companion.multiply(this, second) + + /** + * Creates an expression that multiplies this numeric expression with a constant. + * + * @param second Constant to multiply. + * @return A new [Expr] representing the multiplication operation. + */ + fun multiply(second: Number): Expr = Companion.multiply(this, second) + + /** + * Creates an expression that divides this numeric expression by another numeric expression. + * + * @param divisor Numeric expression to divide this numeric expression by. + * @return A new [Expr] representing the division operation. + */ + fun divide(divisor: Expr): Expr = Companion.divide(this, divisor) + + /** + * Creates an expression that divides this numeric expression by a constant. + * + * @param divisor Constant to divide this expression by. + * @return A new [Expr] representing the division operation. + */ + fun divide(divisor: Number): Expr = Companion.divide(this, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this numeric + * expressions by another numeric expression. + * + * @param divisor The numeric expression to divide this expression by. + * @return A new [Expr] representing the modulo operation. + */ + fun mod(divisor: Expr): Expr = Companion.mod(this, divisor) + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this numeric + * expressions by a constant. + * + * @param divisor The constant to divide this expression by. + * @return A new [Expr] representing the modulo operation. + */ + fun mod(divisor: Number): Expr = Companion.mod(this, divisor) + + /** + * Creates an expression that rounds this numeric expression to nearest integer. + * + * Rounds away from zero in halfway cases. + * + * @return A new [Expr] representing an integer result from the round operation. + */ + fun round(): Expr = Companion.round(this) + + /** + * Creates an expression that rounds off this numeric expression to [decimalPlace] decimal places + * if [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + fun roundToPrecision(decimalPlace: Int): Expr = Companion.roundToPrecision(this, decimalPlace) + + /** + * Creates an expression that rounds off this numeric expression to [decimalPlace] decimal places + * if [decimalPlace] is positive, rounds off digits to the left of the decimal point if + * [decimalPlace] is negative. Rounds away from zero in halfway cases. + * + * @param decimalPlace The number of decimal places to round. + * @return A new [Expr] representing the round operation. + */ + fun roundToPrecision(decimalPlace: Expr): Expr = Companion.roundToPrecision(this, decimalPlace) + + /** + * Creates an expression that returns the smalled integer that isn't less than this numeric + * expression. + * + * @return A new [Expr] representing an integer result from the ceil operation. + */ + fun ceil(): Expr = Companion.ceil(this) + + /** + * Creates an expression that returns the largest integer that isn't less than this numeric + * expression. + * + * @return A new [Expr] representing an integer result from the floor operation. + */ + fun floor(): Expr = Companion.floor(this) + + /** + * Creates an expression that returns this numeric expression raised to the power of the + * [exponent]. Returns infinity on overflow and zero on underflow. + * + * @param exponent The numeric power to raise this numeric expression. + * @return A new [Expr] representing a numeric result from raising this numeric expression to the + * power of [exponent]. + */ + fun pow(exponent: Number): Expr = Companion.pow(this, exponent) + + /** + * Creates an expression that returns this numeric expression raised to the power of the + * [exponent]. Returns infinity on overflow and zero on underflow. + * + * @param exponent The numeric power to raise this numeric expression. + * @return A new [Expr] representing a numeric result from raising this numeric expression to the + * power of [exponent]. + */ + fun pow(exponent: Expr): Expr = Companion.pow(this, exponent) + + /** + * Creates an expression that returns the square root of this numeric expression. + * + * @return A new [Expr] representing the numeric result of the square root operation. + */ + fun sqrt(): Expr = Companion.sqrt(this) + + /** + * Creates an expression that checks if this expression, when evaluated, is equal to any of the + * provided [values]. + * + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + fun eqAny(values: List): BooleanExpr = Companion.eqAny(this, values) + + /** + * Creates an expression that checks if this expression, when evaluated, is equal to any of the + * elements of [arrayExpression]. + * + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'IN' comparison. + */ + fun eqAny(arrayExpression: Expr): BooleanExpr = Companion.eqAny(this, arrayExpression) + + /** + * Creates an expression that checks if this expression, when evaluated, is not equal to all the + * provided [values]. + * + * @param values The values to check against. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + fun notEqAny(values: List): BooleanExpr = Companion.notEqAny(this, values) + + /** + * Creates an expression that checks if this expression, when evaluated, is not equal to all the + * elements of [arrayExpression]. + * + * @param arrayExpression An expression that evaluates to an array, whose elements to check for + * equality to the input. + * @return A new [BooleanExpr] representing the 'NOT IN' comparison. + */ + fun notEqAny(arrayExpression: Expr): BooleanExpr = Companion.notEqAny(this, arrayExpression) + + /** + * Creates an expression that returns true if yhe result of this expression is absent. Otherwise, + * returns false even if the value is null. + * + * @return A new [BooleanExpr] representing the isAbsent operation. + */ + fun isAbsent(): BooleanExpr = Companion.isAbsent(this) + + /** + * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). + * + * @return A new [BooleanExpr] representing the isNan operation. + */ + fun isNan(): BooleanExpr = Companion.isNan(this) + + /** + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a + * Number). + * + * @return A new [BooleanExpr] representing the isNotNan operation. + */ + fun isNotNan(): BooleanExpr = Companion.isNotNan(this) + + /** + * Creates an expression that checks if tbe result of this expression is null. + * + * @return A new [BooleanExpr] representing the isNull operation. + */ + fun isNull(): BooleanExpr = Companion.isNull(this) + + /** + * Creates an expression that checks if tbe result of this expression is not null. + * + * @return A new [BooleanExpr] representing the isNotNull operation. + */ + fun isNotNull(): BooleanExpr = Companion.isNotNull(this) + + /** + * Creates an expression that replaces the first occurrence of a substring within this string + * expression. + * + * @param find The expression representing the substring to search for in this expressions. + * @param replace The expression representing the replacement for the first occurrence of [find]. + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + fun replaceFirst(find: Expr, replace: Expr) = Companion.replaceFirst(this, find, replace) + + /** + * Creates an expression that replaces the first occurrence of a substring within this string + * expression. + * + * @param find The substring to search for in this string expression. + * @param replace The replacement for the first occurrence of [find] with. + * @return A new [Expr] representing the string with the first occurrence replaced. + */ + fun replaceFirst(find: String, replace: String) = Companion.replaceFirst(this, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within this string + * expression. + * + * @param find The expression representing the substring to search for in this string expression. + * @param replace The expression representing the replacement for all occurrences of [find]. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + fun replaceAll(find: Expr, replace: Expr) = Companion.replaceAll(this, find, replace) + + /** + * Creates an expression that replaces all occurrences of a substring within this string + * expression. + * + * @param find The substring to search for in this string expression. + * @param replace The replacement for all occurrences of [find] with. + * @return A new [Expr] representing the string with all occurrences replaced. + */ + fun replaceAll(find: String, replace: String) = Companion.replaceAll(this, find, replace) + + /** + * Creates an expression that calculates the character length of this string expression in UTF8. + * + * @return A new [Expr] representing the charLength operation. + */ + fun charLength(): Expr = Companion.charLength(this) + + /** + * Creates an expression that calculates the length of a string in UTF-8 bytes, or just the length + * of a Blob. + * + * @return A new [Expr] representing the length of the string in bytes. + */ + fun byteLength(): Expr = Companion.byteLength(this) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like operation. + */ + fun like(pattern: Expr): BooleanExpr = Companion.like(this, pattern) + + /** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new [BooleanExpr] representing the like operation. + */ + fun like(pattern: String): BooleanExpr = Companion.like(this, pattern) + + /** + * Creates an expression that checks if this string expression contains a specified regular + * expression as a substring. + * + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + fun regexContains(pattern: Expr): BooleanExpr = Companion.regexContains(this, pattern) + + /** + * Creates an expression that checks if this string expression contains a specified regular + * expression as a substring. + * + * @param pattern The regular expression to use for the search. + * @return A new [BooleanExpr] representing the contains regular expression comparison. + */ + fun regexContains(pattern: String): BooleanExpr = Companion.regexContains(this, pattern) + + /** + * Creates an expression that checks if this string expression matches a specified regular + * expression. + * + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + fun regexMatch(pattern: Expr): BooleanExpr = Companion.regexMatch(this, pattern) + + /** + * Creates an expression that checks if this string expression matches a specified regular + * expression. + * + * @param pattern The regular expression to use for the match. + * @return A new [BooleanExpr] representing the regular expression match comparison. + */ + fun regexMatch(pattern: String): BooleanExpr = Companion.regexMatch(this, pattern) + + /** + * Creates an expression that returns the largest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param others Expressions or literals. + * @return A new [Expr] representing the logical maximum operation. + */ + fun logicalMaximum(vararg others: Expr): Expr = Companion.logicalMaximum(this, *others) + + /** + * Creates an expression that returns the largest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param others Expressions or literals. + * @return A new [Expr] representing the logical maximum operation. + */ + fun logicalMaximum(vararg others: Any): Expr = Companion.logicalMaximum(this, *others) + + /** + * Creates an expression that returns the smallest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param others Expressions or literals. + * @return A new [Expr] representing the logical minimum operation. + */ + fun logicalMinimum(vararg others: Expr): Expr = Companion.logicalMinimum(this, *others) + + /** + * Creates an expression that returns the smallest value between multiple input expressions or + * literal values. Based on Firestore's value type ordering. + * + * @param others Expressions or literals. + * @return A new [Expr] representing the logical minimum operation. + */ + fun logicalMinimum(vararg others: Any): Expr = Companion.logicalMinimum(this, *others) + + /** + * Creates an expression that reverses this string expression. + * + * @return A new [Expr] representing the reversed string. + */ + fun reverse(): Expr = Companion.reverse(this) + + /** + * Creates an expression that checks if this string expression contains a specified substring. + * + * @param substring The expression representing the substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + fun strContains(substring: Expr): BooleanExpr = Companion.strContains(this, substring) + + /** + * Creates an expression that checks if this string expression contains a specified substring. + * + * @param substring The substring to search for. + * @return A new [BooleanExpr] representing the contains comparison. + */ + fun strContains(substring: String): BooleanExpr = Companion.strContains(this, substring) + + /** + * Creates an expression that checks if this string expression starts with a given [prefix]. + * + * @param prefix The prefix string expression to check for. + * @return A new [Expr] representing the the 'starts with' comparison. + */ + fun startsWith(prefix: Expr): BooleanExpr = Companion.startsWith(this, prefix) + + /** + * Creates an expression that checks if this string expression starts with a given [prefix]. + * + * @param prefix The prefix string expression to check for. + * @return A new [Expr] representing the 'starts with' comparison. + */ + fun startsWith(prefix: String): BooleanExpr = Companion.startsWith(this, prefix) + + /** + * Creates an expression that checks if this string expression ends with a given [suffix]. + * + * @param suffix The suffix string expression to check for. + * @return A new [Expr] representing the 'ends with' comparison. + */ + fun endsWith(suffix: Expr): BooleanExpr = Companion.endsWith(this, suffix) + + /** + * Creates an expression that checks if this string expression ends with a given [suffix]. + * + * @param suffix The suffix string to check for. + * @return A new [Expr] representing the the 'ends with' comparison. + */ + fun endsWith(suffix: String) = Companion.endsWith(this, suffix) + + /** + * Creates an expression that converts this string expression to lowercase. + * + * @return A new [Expr] representing the lowercase string. + */ + fun toLower() = Companion.toLower(this) + + /** + * Creates an expression that converts this string expression to uppercase. + * + * @return A new [Expr] representing the lowercase string. + */ + fun toUpper() = Companion.toUpper(this) + + /** + * Creates an expression that removes leading and trailing whitespace from this string expression. + * + * @return A new [Expr] representing the trimmed string. + */ + fun trim() = Companion.trim(this) + + /** + * Creates an expression that concatenates string expressions together. + * + * @param stringExpressions The string expressions to concatenate. + * @return A new [Expr] representing the concatenated string. + */ + fun strConcat(vararg stringExpressions: Expr): Expr = + Companion.strConcat(this, *stringExpressions) + + /** + * Creates an expression that concatenates this string expression with string constants. + * + * @param strings The string constants to concatenate. + * @return A new [Expr] representing the concatenated string. + */ + fun strConcat(vararg strings: String): Expr = Companion.strConcat(this, *strings) + + /** + * Creates an expression that concatenates string expressions and string constants together. + * + * @param strings The string expressions or string constants to concatenate. + * @return A new [Expr] representing the concatenated string. + */ + fun strConcat(vararg strings: Any): Expr = Companion.strConcat(this, *strings) + + /** + * Accesses a map (object) value using the provided [key]. + * + * @param key The key to access in the map. + * @return A new [Expr] representing the value associated with the given key in the map. + */ + fun mapGet(key: String) = Companion.mapGet(this, key) + + /** + * Creates an expression that merges multiple maps into a single map. If multiple maps have the + * same key, the later value is used. + * + * @param mapExpr Map expression that will be merged. + * @param otherMaps Additional maps to merge. + * @return A new [Expr] representing the mapMerge operation. + */ + fun mapMerge(mapExpr: Expr, vararg otherMaps: Expr) = + Companion.mapMerge(this, mapExpr, *otherMaps) + + /** + * Creates an expression that removes a key from this map expression. + * + * @param key The name of the key to remove from this map expression. + * @return A new [Expr] that evaluates to a modified map. + */ + fun mapRemove(key: Expr) = Companion.mapRemove(this, key) + + /** + * Creates an expression that removes a key from this map expression. + * + * @param key The name of the key to remove from this map expression. + * @return A new [Expr] that evaluates to a modified map. + */ + fun mapRemove(key: String) = Companion.mapRemove(this, key) + + /** + * Calculates the Cosine distance between this and another vector expressions. + * + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + fun cosineDistance(vector: Expr): Expr = Companion.cosineDistance(this, vector) + + /** + * Calculates the Cosine distance between this vector expression and a vector literal. + * + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + fun cosineDistance(vector: DoubleArray): Expr = Companion.cosineDistance(this, vector) + + /** + * Calculates the Cosine distance between this vector expression and a vector literal. + * + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the cosine distance between the two vectors. + */ + fun cosineDistance(vector: VectorValue): Expr = Companion.cosineDistance(this, vector) + + /** + * Calculates the dot product distance between this and another vector expression. + * + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + fun dotProduct(vector: Expr): Expr = Companion.dotProduct(this, vector) + + /** + * Calculates the dot product distance between this vector expression and a vector literal. + * + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + fun dotProduct(vector: DoubleArray): Expr = Companion.dotProduct(this, vector) + + /** + * Calculates the dot product distance between this vector expression and a vector literal. + * + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the dot product distance between the two vectors. + */ + fun dotProduct(vector: VectorValue): Expr = Companion.dotProduct(this, vector) + + /** + * Calculates the Euclidean distance between this and another vector expression. + * + * @param vector The other vector (represented as an Expr) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + fun euclideanDistance(vector: Expr): Expr = Companion.euclideanDistance(this, vector) + + /** + * Calculates the Euclidean distance between this vector expression and a vector literal. + * + * @param vector The other vector (as an array of doubles) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + fun euclideanDistance(vector: DoubleArray): Expr = Companion.euclideanDistance(this, vector) + + /** + * Calculates the Euclidean distance between this vector expression and a vector literal. + * + * @param vector The other vector (represented as an [VectorValue]) to compare against. + * @return A new [Expr] representing the Euclidean distance between the two vectors. + */ + fun euclideanDistance(vector: VectorValue): Expr = Companion.euclideanDistance(this, vector) + + /** + * Creates an expression that calculates the length (dimension) of a Firestore Vector. + * + * @return A new [Expr] representing the length (dimension) of the vector. + */ + fun vectorLength() = Companion.vectorLength(this) + + /** + * Creates an expression that interprets this expression as the number of microseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @return A new [Expr] representing the timestamp. + */ + fun unixMicrosToTimestamp() = Companion.unixMicrosToTimestamp(this) + + /** + * Creates an expression that converts this timestamp expression to the number of microseconds + * since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @return A new [Expr] representing the number of microseconds since epoch. + */ + fun timestampToUnixMicros() = Companion.timestampToUnixMicros(this) + + /** + * Creates an expression that interprets this expression as the number of milliseconds since the + * Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @return A new [Expr] representing the timestamp. + */ + fun unixMillisToTimestamp() = Companion.unixMillisToTimestamp(this) + + /** + * Creates an expression that converts this timestamp expression to the number of milliseconds + * since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @return A new [Expr] representing the number of milliseconds since epoch. + */ + fun timestampToUnixMillis() = Companion.timestampToUnixMillis(this) + + /** + * Creates an expression that interprets this expression as the number of seconds since the Unix + * epoch (1970-01-01 00:00:00 UTC) and returns a timestamp. + * + * @return A new [Expr] representing the timestamp. + */ + fun unixSecondsToTimestamp() = Companion.unixSecondsToTimestamp(this) + + /** + * Creates an expression that converts this timestamp expression to the number of seconds since + * the Unix epoch (1970-01-01 00:00:00 UTC). + * + * @return A new [Expr] representing the number of seconds since epoch. + */ + fun timestampToUnixSeconds() = Companion.timestampToUnixSeconds(this) + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @param unit The expression representing the unit of time to add. Valid units include + * "microsecond", "millisecond", "second", "minute", "hour" and "day". + * @param amount The expression representing the amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + fun timestampAdd(unit: Expr, amount: Expr): Expr = Companion.timestampAdd(this, unit, amount) + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * @param unit The unit of time to add. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to add. + * @return A new [Expr] representing the resulting timestamp. + */ + fun timestampAdd(unit: String, amount: Double): Expr = Companion.timestampAdd(this, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to this timestamp expression. + * + * @param unit The expression representing the unit of time to subtract. Valid units include + * "microsecond", "millisecond", "second", "minute", "hour" and "day". + * @param amount The expression representing the amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + fun timestampSub(unit: Expr, amount: Expr): Expr = Companion.timestampSub(this, unit, amount) + + /** + * Creates an expression that subtracts a specified amount of time to this timestamp expression. + * + * @param unit The unit of time to subtract. Valid units include "microsecond", "millisecond", + * "second", "minute", "hour" and "day". + * @param amount The amount of time to subtract. + * @return A new [Expr] representing the resulting timestamp. + */ + fun timestampSub(unit: String, amount: Double): Expr = Companion.timestampSub(this, unit, amount) + + /** + * Creates an expression that concatenates a field's array value with other arrays. + * + * @param secondArray An expression that evaluates to array to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + fun arrayConcat(secondArray: Expr, vararg otherArrays: Any) = + Companion.arrayConcat(this, secondArray, *otherArrays) + + /** + * Creates an expression that concatenates a field's array value with other arrays. + * + * @param secondArray An array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new [Expr] representing the arrayConcat operation. + */ + fun arrayConcat(secondArray: Any, vararg otherArrays: Any) = + Companion.arrayConcat(this, secondArray, *otherArrays) + + /** + * Reverses the order of elements in the array. + * + * @return A new [Expr] representing the arrayReverse operation. + */ + fun arrayReverse() = Companion.arrayReverse(this) + + /** + * Creates an expression that checks if array contains a specific [element]. + * + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + fun arrayContains(element: Expr): BooleanExpr = Companion.arrayContains(this, element) + + /** + * Creates an expression that checks if array contains a specific [element]. + * + * @param element The element to search for in the array. + * @return A new [BooleanExpr] representing the arrayContains operation. + */ + fun arrayContains(element: Any): BooleanExpr = Companion.arrayContains(this, element) + + /** + * Creates an expression that checks if array contains all the specified [values]. + * + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + fun arrayContainsAll(values: List): BooleanExpr = Companion.arrayContainsAll(this, values) + + /** + * Creates an expression that checks if array contains all elements of [arrayExpression]. + * + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAll operation. + */ + fun arrayContainsAll(arrayExpression: Expr): BooleanExpr = + Companion.arrayContainsAll(this, arrayExpression) + + /** + * Creates an expression that checks if array contains any of the specified [values]. + * + * @param values The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + fun arrayContainsAny(values: List): BooleanExpr = Companion.arrayContainsAny(this, values) + + /** + * Creates an expression that checks if array contains any elements of [arrayExpression]. + * + * @param arrayExpression The elements to check for in the array. + * @return A new [BooleanExpr] representing the arrayContainsAny operation. + */ + fun arrayContainsAny(arrayExpression: Expr): BooleanExpr = + Companion.arrayContainsAny(this, arrayExpression) + + /** + * Creates an expression that calculates the length of an array expression. + * + * @return A new [Expr] representing the length of the array. + */ + fun arrayLength() = Companion.arrayLength(this) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param offset An Expr evaluating to the index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + fun arrayOffset(offset: Expr) = Companion.arrayOffset(this, offset) + + /** + * Creates an expression that indexes into an array from the beginning or end and return the + * element. If the offset exceeds the array length, an error is returned. A negative offset, + * starts from the end. + * + * @param offset An Expr evaluating to the index of the element to return. + * @return A new [Expr] representing the arrayOffset operation. + */ + fun arrayOffset(offset: Int) = Companion.arrayOffset(this, offset) + + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * this expression. + * + * @return A new [AggregateFunction] representing the count aggregation. + */ + fun count(): AggregateFunction = AggregateFunction.count(this) + + /** + * Creates an aggregation that calculates the sum of this numeric expression across multiple stage + * inputs. + * + * @return A new [AggregateFunction] representing the sum aggregation. + */ + fun sum(): AggregateFunction = AggregateFunction.sum(this) + + /** + * Creates an aggregation that calculates the average (mean) of this numeric expression across + * multiple stage inputs. + * + * @return A new [AggregateFunction] representing the average aggregation. + */ + fun avg(): AggregateFunction = AggregateFunction.avg(this) + + /** + * Creates an aggregation that finds the minimum value of this expression across multiple stage + * inputs. + * + * @return A new [AggregateFunction] representing the minimum aggregation. + */ + fun minimum(): AggregateFunction = AggregateFunction.minimum(this) + + /** + * Creates an aggregation that finds the maximum value of this expression across multiple stage + * inputs. + * + * @return A new [AggregateFunction] representing the maximum aggregation. + */ + fun maximum(): AggregateFunction = AggregateFunction.maximum(this) + + /** + * Create an [Ordering] that sorts documents in ascending order based on value of this expression + * + * @return A new [Ordering] object with ascending sort by this expression. + */ + fun ascending(): Ordering = Ordering.ascending(this) + + /** + * Create an [Ordering] that sorts documents in descending order based on value of this expression + * + * @return A new [Ordering] object with descending sort by this expression. + */ + fun descending(): Ordering = Ordering.descending(this) + + /** + * Creates an expression that checks if this and [other] expression are equal. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + fun eq(other: Expr): BooleanExpr = Companion.eq(this, other) + + /** + * Creates an expression that checks if this expression is equal to a [value]. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the equality comparison. + */ + fun eq(value: Any): BooleanExpr = Companion.eq(this, value) + + /** + * Creates an expression that checks if this expressions is not equal to the [other] expression. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + fun neq(other: Expr): BooleanExpr = Companion.neq(this, other) + + /** + * Creates an expression that checks if this expression is not equal to a [value]. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the inequality comparison. + */ + fun neq(value: Any): BooleanExpr = Companion.neq(this, value) + + /** + * Creates an expression that checks if this expression is greater than the [other] expression. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + fun gt(other: Expr): BooleanExpr = Companion.gt(this, other) + + /** + * Creates an expression that checks if this expression is greater than a [value]. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the greater than comparison. + */ + fun gt(value: Any): BooleanExpr = Companion.gt(this, value) + + /** + * Creates an expression that checks if this expression is greater than or equal to the [other] + * expression. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + fun gte(other: Expr): BooleanExpr = Companion.gte(this, other) + + /** + * Creates an expression that checks if this expression is greater than or equal to a [value]. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the greater than or equal to comparison. + */ + fun gte(value: Any): BooleanExpr = Companion.gte(this, value) + + /** + * Creates an expression that checks if this expression is less than the [other] expression. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + fun lt(other: Expr): BooleanExpr = Companion.lt(this, other) + + /** + * Creates an expression that checks if this expression is less than a value. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the less than comparison. + */ + fun lt(value: Any): BooleanExpr = Companion.lt(this, value) + + /** + * Creates an expression that checks if this expression is less than or equal to the [other] + * expression. + * + * @param other The expression to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + fun lte(other: Expr): BooleanExpr = Companion.lte(this, other) + + /** + * Creates an expression that checks if this expression is less than or equal to a [value]. + * + * @param value The value to compare to. + * @return A new [BooleanExpr] representing the less than or equal to comparison. + */ + fun lte(value: Any): BooleanExpr = Companion.lte(this, value) + + /** + * Creates an expression that checks if this expression evaluates to a name of the field that + * exists. + * + * @return A new [Expr] representing the exists check. + */ + fun exists(): BooleanExpr = Companion.exists(this) + + /** + * Creates an expression that returns the [catchExpr] argument if there is an error, else return + * the result of this expression. + * + * @param catchExpr The catch expression that will be evaluated and returned if the this + * expression produces an error. + * @return A new [Expr] representing the ifError operation. + */ + fun ifError(catchExpr: Expr): Expr = Companion.ifError(this, catchExpr) + + /** + * Creates an expression that returns the [catchValue] argument if there is an error, else return + * the result of this expression. + * + * @param catchValue The value that will be returned if this expression produces an error. + * @return A new [Expr] representing the ifError operation. + */ + fun ifError(catchValue: Any): Expr = Companion.ifError(this, catchValue) + + internal abstract fun toProto(userDataReader: UserDataReader): Value +} + +/** Expressions that have an alias are [Selectable] */ +abstract class Selectable : Expr() { + internal abstract fun getAlias(): String + internal abstract fun getExpr(): Expr + + internal companion object { + fun toSelectable(o: Any): Selectable { + return when (o) { + is Selectable -> o + is String -> field(o) + is FieldPath -> field(o) + else -> throw IllegalArgumentException("Unknown Selectable type: $o") + } + } + } +} + +/** Represents an expression that will be given the alias in the output document. */ +class ExprWithAlias internal constructor(private val alias: String, private val expr: Expr) : + Selectable() { + override fun getAlias() = alias + override fun getExpr() = expr + override fun toProto(userDataReader: UserDataReader): Value = expr.toProto(userDataReader) +} + +/** + * Represents a reference to a field in a Firestore document. + * + * [Field] references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + * You can create a [Field] instance using the static [Expr.field] method: + */ +class Field internal constructor(private val fieldPath: ModelFieldPath) : Selectable() { + companion object { + + /** + * An expression that returns the document ID. + * + * @return An [Field] representing the document ID. + */ + @JvmField val DOCUMENT_ID: Field = field(FieldPath.documentId()) + } + + override fun getAlias(): String = fieldPath.canonicalString() + + override fun getExpr(): Expr = this + + override fun toProto(userDataReader: UserDataReader) = toProto() + + internal fun toProto(): Value = + Value.newBuilder().setFieldReferenceValue(fieldPath.canonicalString()).build() +} + +internal class ListOfExprs(private val expressions: Array) : Expr() { + override fun toProto(userDataReader: UserDataReader): Value = + encodeValue(expressions.map { it.toProto(userDataReader) }) +} + +/** + * This class defines the base class for Firestore [Pipeline] functions, which can be evaluated + * within pipeline execution. + * + * Typically, you would not use this class or its children directly. Use either the functions like + * [and], [eq], or the methods on [Expr] ([Expr.eq]), [Expr.lt], etc) to construct new + * [FunctionExpr] instances. + */ +open class FunctionExpr +internal constructor( + private val name: String, + private val params: Array, + private val options: InternalOptions = InternalOptions.EMPTY +) : Expr() { + internal constructor(name: String) : this(name, emptyArray()) + internal constructor(name: String, param: Expr) : this(name, arrayOf(param)) + internal constructor( + name: String, + param: Expr, + vararg params: Any + ) : this(name, arrayOf(param, *toArrayOfExprOrConstant(params))) + internal constructor( + name: String, + param1: Expr, + param2: Expr + ) : this(name, arrayOf(param1, param2)) + internal constructor( + name: String, + param1: Expr, + param2: Expr, + vararg params: Any + ) : this(name, arrayOf(param1, param2, *toArrayOfExprOrConstant(params))) + internal constructor(name: String, fieldName: String) : this(name, arrayOf(field(fieldName))) + internal constructor( + name: String, + fieldName: String, + vararg params: Any + ) : this(name, arrayOf(field(fieldName), *toArrayOfExprOrConstant(params))) + + override fun toProto(userDataReader: UserDataReader): Value { + val builder = com.google.firestore.v1.Function.newBuilder() + builder.setName(name) + for (param in params) { + builder.addArgs(param.toProto(userDataReader)) + } + options.forEach(builder::putOptions) + return Value.newBuilder().setFunctionValue(builder).build() + } +} + +/** A class that represents a filter condition. */ +open class BooleanExpr internal constructor(name: String, params: Array) : + FunctionExpr(name, params, InternalOptions.EMPTY) { + internal constructor(name: String, param: Expr) : this(name, arrayOf(param)) + internal constructor( + name: String, + param1: Expr, + param2: Any + ) : this(name, arrayOf(param1, toExprOrConstant(param2))) + internal constructor( + name: String, + param: Expr, + vararg params: Any + ) : this(name, arrayOf(param, *toArrayOfExprOrConstant(params))) + internal constructor( + name: String, + param1: Expr, + param2: Expr + ) : this(name, arrayOf(param1, param2)) + internal constructor(name: String, fieldName: String) : this(name, arrayOf(field(fieldName))) + internal constructor( + name: String, + fieldName: String, + vararg params: Any + ) : this(name, arrayOf(field(fieldName), *toArrayOfExprOrConstant(params))) + + companion object { + + /** + */ + @JvmStatic fun generic(name: String, vararg expr: Expr): BooleanExpr = BooleanExpr(name, expr) + } + + /** + * Creates an aggregation that counts the number of stage inputs where the this boolean expression + * evaluates to true. + * + * @return A new [AggregateFunction] representing the count aggregation. + */ + fun countIf(): AggregateFunction = AggregateFunction.countIf(this) + + /** + * Creates a conditional expression that evaluates to a [thenExpr] expression if this condition is + * true or an [elseExpr] expression if the condition is false. + * + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new [Expr] representing the conditional operation. + */ + fun cond(thenExpr: Expr, elseExpr: Expr): Expr = Expr.Companion.cond(this, thenExpr, elseExpr) + + /** + * Creates a conditional expression that evaluates to a [thenValue] if this condition is true or + * an [elseValue] if the condition is false. + * + * @param thenValue Value if the condition is true. + * @param elseValue Value if the condition is false. + * @return A new [Expr] representing the conditional operation. + */ + fun cond(thenValue: Any, elseValue: Any): Expr = Expr.Companion.cond(this, thenValue, elseValue) + + /** + * Creates an expression that negates this boolean expression. + * + * @return A new [BooleanExpr] representing the not operation. + */ + fun not(): BooleanExpr = Expr.Companion.not(this) +} + +/** + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create [Ordering] instances using the [ascending] and [descending] helper methods. + */ +class Ordering private constructor(val expr: Expr, private val dir: Direction) { + companion object { + + /** + * Create an [Ordering] that sorts documents in ascending order based on value of [expr]. + * + * @param expr The order is based on the evaluation of the [Expr]. + * @return A new [Ordering] object with ascending sort by [expr]. + */ + @JvmStatic fun ascending(expr: Expr): Ordering = Ordering(expr, Direction.ASCENDING) + + /** + * Creates an [Ordering] that sorts documents in ascending order based on field. + * + * @param fieldName The name of field to sort documents. + * @return A new [Ordering] object with ascending sort by field. + */ + @JvmStatic + fun ascending(fieldName: String): Ordering = Ordering(field(fieldName), Direction.ASCENDING) + + /** + * Create an [Ordering] that sorts documents in descending order based on value of [expr]. + * + * @param expr The order is based on the evaluation of the [Expr]. + * @return A new [Ordering] object with descending sort by [expr]. + */ + @JvmStatic fun descending(expr: Expr): Ordering = Ordering(expr, Direction.DESCENDING) + + /** + * Creates an [Ordering] that sorts documents in descending order based on field. + * + * @param fieldName The name of field to sort documents. + * @return A new [Ordering] object with descending sort by field. + */ + @JvmStatic + fun descending(fieldName: String): Ordering = Ordering(field(fieldName), Direction.DESCENDING) + } + + private class Direction private constructor(val proto: Value) { + private constructor(protoString: String) : this(encodeValue(protoString)) + companion object { + val ASCENDING = Direction("ascending") + val DESCENDING = Direction("descending") + } + } + + internal fun toProto(userDataReader: UserDataReader): Value = + Value.newBuilder() + .setMapValue( + MapValue.newBuilder() + .putFields("direction", dir.proto) + .putFields("expression", expr.toProto(userDataReader)) + ) + .build() + + /** + * Create an order that is in reverse. + * + * If the previous [Ordering] was ascending, then the new [Ordering] will be descending. Likewise, + * if the previous [Ordering] was descending, then the new [Ordering] will be ascending. + * + * @return New [Ordering] object that is has order reversed. + */ + fun reverse(): Ordering = + Ordering(expr, if (dir == Direction.ASCENDING) Direction.DESCENDING else Direction.ASCENDING) +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/options.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/options.kt new file mode 100644 index 00000000000..27d5375f3ab --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/options.kt @@ -0,0 +1,219 @@ +// Copyright 2025 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.firebase.firestore.pipeline + +import com.google.common.collect.ImmutableMap +import com.google.firebase.firestore.model.Values +import com.google.firestore.v1.ArrayValue +import com.google.firestore.v1.MapValue +import com.google.firestore.v1.Value + +/** + * Wither style Key/Value options object. + * + * Basic `wither` functionality built upon `ImmutableMap, Value>`. Exposes methods + * to construct, augment, and encode Kay/Value pairs. The wrapped collection + * `ImmutableMap, Value>` is an implementation detail, not to be exposed, since + * more efficient implementations are possible. + */ +class InternalOptions internal constructor(private val options: ImmutableMap) { + internal fun with(key: String, value: Value): InternalOptions { + val builder = ImmutableMap.builderWithExpectedSize(options.size + 1) + builder.putAll(options) + builder.put(key, value) + return InternalOptions(builder.buildKeepingLast()) + } + + internal fun with(key: String, values: Iterable): InternalOptions { + val arrayValue = ArrayValue.newBuilder().addAllValues(values).build() + return with(key, Value.newBuilder().setArrayValue(arrayValue).build()) + } + + internal fun with(key: String, value: InternalOptions): InternalOptions { + return with(key, value.toValue()) + } + + internal fun forEach(f: (String, Value) -> Unit) { + for (entry in options.entries) { + f(entry.key, entry.value) + } + } + + private fun toValue(): Value { + val mapValue = MapValue.newBuilder().putAllFields(options).build() + return Value.newBuilder().setMapValue(mapValue).build() + } + + companion object { + @JvmField val EMPTY: InternalOptions = InternalOptions(ImmutableMap.of()) + + fun of(key: String, value: Value): InternalOptions { + return InternalOptions(ImmutableMap.of(key, value)) + } + } +} + +abstract class AbstractOptions> +internal constructor(internal val options: InternalOptions) { + + internal abstract fun self(options: InternalOptions): T + + protected fun with(key: String, value: InternalOptions): T = self(options.with(key, value)) + + protected fun with(key: String, value: Value): T = self(options.with(key, value)) + + /** + * Specify generic [String] option + * + * @param key The option key + * @param value The [String] value of option + * @return A new options object. + */ + fun with(key: String, value: String): T = with(key, Values.encodeValue(value)) + + /** + * Specify generic [Boolean] option + * + * @param key The option key + * @param value The [Boolean] value of option + * @return A new options object. + */ + fun with(key: String, value: Boolean): T = with(key, Values.encodeValue(value)) + + /** + * Specify generic [Long] option + * + * @param key The option key + * @param value The [Long] value of option + * @return A new options object. + */ + fun with(key: String, value: Long): T = with(key, Values.encodeValue(value)) + + /** + * Specify generic [Double] option + * + * @param key The option key + * @param value The [Double] value of option + * @return A new options object. + */ + fun with(key: String, value: Double): T = with(key, Values.encodeValue(value)) + + /** + * Specify generic [Field] option + * + * @param key The option key + * @param value The [Field] value of option + * @return A new options object. + */ + fun with(key: String, value: Field): T = with(key, value.toProto()) + + /** + * Specify [GenericOptions] object + * + * @param key The option key + * @param value The [GenericOptions] object + * @return A new options object. + */ + fun with(key: String, value: GenericOptions): T = with(key, value.options) +} + +class GenericOptions private constructor(options: InternalOptions) : + AbstractOptions(options) { + override fun self(options: InternalOptions) = GenericOptions(options) + + companion object { + @JvmField val DEFAULT: GenericOptions = GenericOptions(InternalOptions.EMPTY) + } +} + +class PipelineOptions private constructor(options: InternalOptions) : + AbstractOptions(options) { + + override fun self(options: InternalOptions) = PipelineOptions(options) + + companion object { + @JvmField val DEFAULT: PipelineOptions = PipelineOptions(InternalOptions.EMPTY) + } + + class IndexMode private constructor(internal val value: String) { + companion object { + @JvmField val RECOMMENDED = IndexMode("recommended") + } + } + + fun withIndexMode(indexMode: IndexMode): PipelineOptions = with("index_mode", indexMode.value) + + fun withExplainOptions(options: ExplainOptions): PipelineOptions = + with("explain_options", options.options) +} + +class ExplainOptions private constructor(options: InternalOptions) : + AbstractOptions(options) { + override fun self(options: InternalOptions) = ExplainOptions(options) + + companion object { + @JvmField val DEFAULT = ExplainOptions(InternalOptions.EMPTY) + } + + fun withMode(value: ExplainMode) = with("mode", value.value) + + fun withOutputFormat(value: OutputFormat) = with("output_format", value.value) + + fun withVerbosity(value: Verbosity) = with("verbosity", value.value) + + fun withIndexRecommendation(value: Boolean) = with("index_recommendation", value) + + fun withProfiles(value: Profiles) = with("profiles", value.value) + + fun withRedact(value: Boolean) = with("redact", value) + + class ExplainMode private constructor(internal val value: String) { + companion object { + @JvmField val EXECUTE = ExplainMode("execute") + + @JvmField val EXPLAIN = ExplainMode("explain") + + @JvmField val ANALYZE = ExplainMode("analyze") + } + } + + class OutputFormat private constructor(internal val value: String) { + companion object { + @JvmField val TEXT = OutputFormat("text") + + @JvmField val JSON = OutputFormat("json") + + @JvmField val STRUCT = OutputFormat("struct") + } + } + + class Verbosity private constructor(internal val value: String) { + companion object { + @JvmField val SUMMARY_ONLY = Verbosity("summary_only") + + @JvmField val EXECUTION_TREE = Verbosity("execution_tree") + } + } + + class Profiles private constructor(internal val value: String) { + companion object { + @JvmField val LATENCY = Profiles("latency") + + @JvmField val RECORDS_COUNT = Profiles("records_count") + + @JvmField val BYTES_THROUGHPUT = Profiles("bytes_throughput") + } + } +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/stage.kt b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/stage.kt new file mode 100644 index 00000000000..6b7e4546557 --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/pipeline/stage.kt @@ -0,0 +1,671 @@ +// Copyright 2025 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.firebase.firestore.pipeline + +import com.google.firebase.firestore.CollectionReference +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.UserDataReader +import com.google.firebase.firestore.VectorValue +import com.google.firebase.firestore.model.ResourcePath +import com.google.firebase.firestore.model.Values +import com.google.firebase.firestore.model.Values.encodeValue +import com.google.firebase.firestore.pipeline.Expr.Companion.constant +import com.google.firebase.firestore.pipeline.Expr.Companion.field +import com.google.firebase.firestore.util.Preconditions +import com.google.firestore.v1.Pipeline +import com.google.firestore.v1.Value + +abstract class BaseStage> +internal constructor(protected val name: String, internal val options: InternalOptions) { + internal fun toProtoStage(userDataReader: UserDataReader): Pipeline.Stage { + val builder = Pipeline.Stage.newBuilder() + builder.setName(name) + args(userDataReader).forEach(builder::addArgs) + options.forEach(builder::putOptions) + return builder.build() + } + internal abstract fun args(userDataReader: UserDataReader): Sequence + + internal abstract fun self(options: InternalOptions): T + + protected fun with(key: String, value: Value): T = self(options.with(key, value)) + + /** + * Specify named [String] parameter + * + * @param key The name of parameter + * @param value The [String] value of parameter + * @return New stage with named parameter. + */ + fun with(key: String, value: String): T = with(key, Values.encodeValue(value)) + + /** + * Specify named [Boolean] parameter + * + * @param key The name of parameter + * @param value The [Boolean] value of parameter + * @return New stage with named parameter. + */ + fun with(key: String, value: Boolean): T = with(key, Values.encodeValue(value)) + + /** + * Specify named [Long] parameter + * + * @param key The name of parameter + * @param value The [Long] value of parameter + * @return New stage with named parameter. + */ + fun with(key: String, value: Long): T = with(key, Values.encodeValue(value)) + + /** + * Specify named [Double] parameter + * + * @param key The name of parameter + * @param value The [Double] value of parameter + * @return New stage with named parameter. + */ + fun with(key: String, value: Double): T = with(key, Values.encodeValue(value)) + + /** + * Specify named [Field] parameter + * + * @param key The name of parameter + * @param value The [Field] value of parameter + * @return New stage with named parameter. + */ + fun with(key: String, value: Field): T = with(key, value.toProto()) +} + +/** + * Adds a stage to the pipeline by specifying the stage name as an argument. This does not offer any + * type safety on the stage params and requires the caller to know the order (and optionally names) + * of parameters accepted by the stage. + * + * This class provides a way to call stages that are supported by the Firestore backend but that are + * not implemented in the SDK version being used. + */ +class Stage +private constructor( + name: String, + private val arguments: List, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage(name, options) { + companion object { + /** + * Specify name of stage + * + * @param name The unique name of the stage to add. + * @return [Stage] with specified parameters. + */ + @JvmStatic fun ofName(name: String) = Stage(name, emptyList(), InternalOptions.EMPTY) + } + + override fun self(options: InternalOptions) = Stage(name, arguments, options) + + /** + * Specify arguments to stage. + * + * @param arguments A list of ordered parameters to configure the stage's behavior. + * @return [Stage] with specified parameters. + */ + fun withArguments(vararg arguments: Any): Stage = + Stage(name, arguments.map(GenericArg::from), options) + + override fun args(userDataReader: UserDataReader): Sequence = + arguments.asSequence().map { it.toProto(userDataReader) } +} + +internal sealed class GenericArg { + companion object { + fun from(arg: Any?): GenericArg = + when (arg) { + is AggregateFunction -> AggregateArg(arg) + is Ordering -> OrderingArg(arg) + is Map<*, *> -> + MapArg(arg.asIterable().associate { (key, value) -> key as String to from(value) }) + is List<*> -> ListArg(arg.map(::from)) + else -> ExprArg(Expr.toExprOrConstant(arg)) + } + } + abstract fun toProto(userDataReader: UserDataReader): Value + + data class AggregateArg(val aggregate: AggregateFunction) : GenericArg() { + override fun toProto(userDataReader: UserDataReader) = aggregate.toProto(userDataReader) + } + + data class ExprArg(val expr: Expr) : GenericArg() { + override fun toProto(userDataReader: UserDataReader) = expr.toProto(userDataReader) + } + + data class OrderingArg(val ordering: Ordering) : GenericArg() { + override fun toProto(userDataReader: UserDataReader) = ordering.toProto(userDataReader) + } + + data class MapArg(val args: Map) : GenericArg() { + override fun toProto(userDataReader: UserDataReader) = + encodeValue(args.mapValues { it.value.toProto(userDataReader) }) + } + + data class ListArg(val args: List) : GenericArg() { + override fun toProto(userDataReader: UserDataReader) = + encodeValue(args.map { it.toProto(userDataReader) }) + } +} + +internal class DatabaseSource +@JvmOverloads +internal constructor(options: InternalOptions = InternalOptions.EMPTY) : + BaseStage("database", options) { + override fun self(options: InternalOptions) = DatabaseSource(options) + override fun args(userDataReader: UserDataReader): Sequence = emptySequence() +} + +class CollectionSource +internal constructor( + private val path: String, + // We validate [firestore.databaseId] when adding to pipeline. + internal val firestore: FirebaseFirestore?, + options: InternalOptions +) : BaseStage("collection", options) { + override fun self(options: InternalOptions): CollectionSource = + CollectionSource(path, firestore, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf( + Value.newBuilder().setReferenceValue(if (path.startsWith("/")) path else "/" + path).build() + ) + companion object { + /** + * Set the pipeline's source to the collection specified by the given path. + * + * @param path A path to a collection that will be the source of this pipeline. + * @return Pipeline with documents from target collection. + */ + @JvmStatic + fun of(path: String): CollectionSource { + // Validate path by converting to ResourcePath + val resourcePath = ResourcePath.fromString(path) + return CollectionSource(resourcePath.canonicalString(), null, InternalOptions.EMPTY) + } + + /** + * Set the pipeline's source to the collection specified by the given CollectionReference. + * + * @param ref A CollectionReference for a collection that will be the source of this pipeline. + * @return Pipeline with documents from target collection. + */ + @JvmStatic + fun of(ref: CollectionReference): CollectionSource { + return CollectionSource(ref.path, ref.firestore, InternalOptions.EMPTY) + } + } + + fun withForceIndex(value: String) = with("force_index", value) +} + +class CollectionGroupSource +private constructor(private val collectionId: String, options: InternalOptions) : + BaseStage("collection_group", options) { + override fun self(options: InternalOptions) = CollectionGroupSource(collectionId, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(Value.newBuilder().setReferenceValue("").build(), encodeValue(collectionId)) + + companion object { + + /** + * Set the pipeline's source to the collection group with the given id. + * + * @param collectionId The id of a collection group that will be the source of this pipeline. + */ + @JvmStatic + fun of(collectionId: String): CollectionGroupSource { + Preconditions.checkNotNull(collectionId, "Provided collection ID must not be null.") + require(!collectionId.contains("/")) { + "Invalid collectionId '$collectionId'. Collection IDs must not contain '/'." + } + return CollectionGroupSource(collectionId, InternalOptions.EMPTY) + } + } + + fun withForceIndex(value: String) = with("force_index", value) +} + +internal class DocumentsSource +@JvmOverloads +internal constructor( + private val documents: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("documents", options) { + internal constructor(document: String) : this(arrayOf(document)) + override fun self(options: InternalOptions) = DocumentsSource(documents, options) + override fun args(userDataReader: UserDataReader): Sequence = + documents.asSequence().map { if (it.startsWith("/")) it else "/" + it }.map(::encodeValue) +} + +internal class AddFieldsStage +internal constructor( + private val fields: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("add_fields", options) { + override fun self(options: InternalOptions) = AddFieldsStage(fields, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(fields.associate { it.getAlias() to it.toProto(userDataReader) })) +} + +/** + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + * This stage allows you to calculate aggregate values over a set of documents, optionally grouped + * by one or more fields or functions. You can specify: + * + * - **Grouping Fields or Expressions:** One or more fields or functions to group the documents by. + * For each distinct combination of values in these fields, a separate group is created. If no + * grouping fields are provided, a single group containing all documents is used. Not specifying + * groups is the same as putting the entire inputs into one group. + * + * - **AggregateFunctions:** One or more accumulation operations to perform within each group. These + * are defined using [AggregateWithAlias] expressions, which are typically created by calling + * [AggregateFunction.alias] on [AggregateFunction] instances. Each aggregation calculates a value + * (e.g., sum, average, count) based on the documents within its group. + */ +class AggregateStage +internal constructor( + private val accumulators: Map, + private val groups: Map, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("aggregate", options) { + private constructor(accumulators: Map) : this(accumulators, emptyMap()) + companion object { + + /** + * Create [AggregateStage] with one or more accumulators. + * + * @param accumulator The first [AggregateWithAlias] expression, wrapping an {@link + * AggregateFunction} with an alias for the accumulated results. + * @param additionalAccumulators The [AggregateWithAlias] expressions, each wrapping an + * [AggregateFunction] with an alias for the accumulated results. + * @return [AggregateStage] with specified accumulators. + */ + @JvmStatic + fun withAccumulators( + accumulator: AggregateWithAlias, + vararg additionalAccumulators: AggregateWithAlias + ): AggregateStage { + return AggregateStage( + mapOf(accumulator.alias to accumulator.expr) + .plus(additionalAccumulators.associate { it.alias to it.expr }) + ) + } + } + + override fun self(options: InternalOptions) = AggregateStage(accumulators, groups, options) + + /** + * Add one or more groups to [AggregateStage] + * + * @param groupField The [String] representing field name. + * @param additionalGroups The [Selectable] expressions to consider when determining group value + * combinations or [String]s representing field names. + * @return [AggregateStage] with specified groups. + */ + fun withGroups(groupField: String, vararg additionalGroups: Any) = + withGroups(Expr.field(groupField), additionalGroups) + + /** + * Add one or more groups to [AggregateStage] + * + * @param groupField The [Selectable] expression to consider when determining group value + * combinations. + * @param additionalGroups The [Selectable] expressions to consider when determining group value + * combinations or [String]s representing field names. + * @return [AggregateStage] with specified groups. + */ + fun withGroups(group: Selectable, vararg additionalGroups: Any) = + AggregateStage( + accumulators, + mapOf(group.getAlias() to group.getExpr()) + .plus(additionalGroups.map(Selectable::toSelectable).associateBy(Selectable::getAlias)) + ) + + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf( + encodeValue(accumulators.mapValues { entry -> entry.value.toProto(userDataReader) }), + encodeValue(groups.mapValues { entry -> entry.value.toProto(userDataReader) }) + ) +} + +internal class WhereStage +internal constructor( + private val condition: BooleanExpr, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("where", options) { + override fun self(options: InternalOptions) = WhereStage(condition, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(condition.toProto(userDataReader)) +} + +/** + * Performs a vector similarity search, ordering the result set by most similar to least similar, + * and returning the first N documents in the result set. + */ +class FindNearestStage +internal constructor( + private val property: Expr, + private val vector: Expr, + private val distanceMeasure: DistanceMeasure, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("find_nearest", options) { + + companion object { + + /** + * Create [FindNearestStage]. + * + * @param vectorField A [Field] that contains vector to search on. + * @param vectorValue The [VectorValue] used to measure the distance from [vectorField] values + * in the documents. + * @param distanceMeasure specifies what type of distance is calculated. when performing the + * search. + * @return [FindNearestStage] with specified parameters. + */ + @JvmStatic + fun of(vectorField: Field, vectorValue: VectorValue, distanceMeasure: DistanceMeasure) = + FindNearestStage(vectorField, constant(vectorValue), distanceMeasure) + + /** + * Create [FindNearestStage]. + * + * @param vectorField A [Field] that contains vector to search on. + * @param vectorValue The [VectorValue] in array form that is used to measure the distance from + * [vectorField] values in the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return [FindNearestStage] with specified parameters. + */ + @JvmStatic + fun of(vectorField: Field, vectorValue: DoubleArray, distanceMeasure: DistanceMeasure) = + FindNearestStage(vectorField, Expr.vector(vectorValue), distanceMeasure) + + /** + * Create [FindNearestStage]. + * + * @param vectorField A [String] specifying the vector field to search on. + * @param vectorValue The [VectorValue] used to measure the distance from [vectorField] values + * in the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return [FindNearestStage] with specified parameters. + */ + @JvmStatic + fun of(vectorField: String, vectorValue: VectorValue, distanceMeasure: DistanceMeasure) = + FindNearestStage(constant(vectorField), constant(vectorValue), distanceMeasure) + + /** + * Create [FindNearestStage]. + * + * @param vectorField A [String] specifying the vector field to search on. + * @param vectorValue The [VectorValue] in array form that is used to measure the distance from + * [vectorField] values in the documents. + * @param distanceMeasure specifies what type of distance is calculated when performing the + * search. + * @return [FindNearestStage] with specified parameters. + */ + @JvmStatic + fun of(vectorField: String, vectorValue: DoubleArray, distanceMeasure: DistanceMeasure) = + FindNearestStage(constant(vectorField), Expr.vector(vectorValue), distanceMeasure) + } + + class DistanceMeasure private constructor(internal val proto: Value) { + private constructor(protoString: String) : this(encodeValue(protoString)) + + companion object { + @JvmField val EUCLIDEAN = DistanceMeasure("euclidean") + + @JvmField val COSINE = DistanceMeasure("cosine") + + @JvmField val DOT_PRODUCT = DistanceMeasure("dot_product") + } + } + + override fun self(options: InternalOptions) = + FindNearestStage(property, vector, distanceMeasure, options) + + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf( + property.toProto(userDataReader), + vector.toProto(userDataReader), + distanceMeasure.proto + ) + + /** + * Specifies the upper bound of documents to return. + * + * @param limit must be a positive integer. + * @return [FindNearestStage] with specified [limit]. + */ + fun withLimit(limit: Long): FindNearestStage = with("limit", limit) + + /** + * Add a field containing the distance to the result. + * + * @param distanceField The [Field] that will be added to the result. + * @return [FindNearestStage] with specified [distanceField]. + */ + fun withDistanceField(distanceField: Field): FindNearestStage = + with("distance_field", distanceField) + + /** + * Add a field containing the distance to the result. + * + * @param distanceField The name of the field that will be added to the result. + * @return [FindNearestStage] with specified [distanceField]. + */ + fun withDistanceField(distanceField: String): FindNearestStage = + withDistanceField(field(distanceField)) +} + +internal class LimitStage +internal constructor(private val limit: Int, options: InternalOptions = InternalOptions.EMPTY) : + BaseStage("limit", options) { + override fun self(options: InternalOptions) = LimitStage(limit, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(limit)) +} + +internal class OffsetStage +internal constructor(private val offset: Int, options: InternalOptions = InternalOptions.EMPTY) : + BaseStage("offset", options) { + override fun self(options: InternalOptions) = OffsetStage(offset, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(offset)) +} + +internal class SelectStage +internal constructor( + private val fields: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("select", options) { + override fun self(options: InternalOptions) = SelectStage(fields, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(fields.associate { it.getAlias() to it.toProto(userDataReader) })) +} + +internal class SortStage +internal constructor( + private val orders: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("sort", options) { + override fun self(options: InternalOptions) = SortStage(orders, options) + override fun args(userDataReader: UserDataReader): Sequence = + orders.asSequence().map { it.toProto(userDataReader) } +} + +internal class DistinctStage +internal constructor( + private val groups: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("distinct", options) { + override fun self(options: InternalOptions) = DistinctStage(groups, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(groups.associate { it.getAlias() to it.toProto(userDataReader) })) +} + +internal class RemoveFieldsStage +internal constructor( + private val fields: Array, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("remove_fields", options) { + override fun self(options: InternalOptions) = RemoveFieldsStage(fields, options) + override fun args(userDataReader: UserDataReader): Sequence = + fields.asSequence().map(Field::toProto) +} + +internal class ReplaceStage +internal constructor( + private val mapValue: Expr, + private val mode: Mode, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("replace", options) { + class Mode private constructor(internal val proto: Value) { + private constructor(protoString: String) : this(encodeValue(protoString)) + companion object { + val FULL_REPLACE = Mode("full_replace") + val MERGE_PREFER_NEXT = Mode("merge_prefer_nest") + val MERGE_PREFER_PARENT = Mode("merge_prefer_parent") + } + } + override fun self(options: InternalOptions) = ReplaceStage(mapValue, mode, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(mapValue.toProto(userDataReader), mode.proto) +} + +/** + * Performs a pseudo-random sampling of the input documents. + * + * The documents produced from this stage are non-deterministic, running the same query over the + * same dataset multiple times will produce different results. There are two different ways to + * dictate how the sample is calculated either by specifying a target output size, or by specifying + * a target percentage of the input size. + */ +class SampleStage +private constructor( + private val size: Number, + private val mode: Mode, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("sample", options) { + override fun self(options: InternalOptions) = SampleStage(size, mode, options) + class Mode private constructor(internal val proto: Value) { + private constructor(protoString: String) : this(encodeValue(protoString)) + companion object { + val DOCUMENTS = Mode("documents") + val PERCENT = Mode("percent") + } + } + companion object { + /** + * Creates [SampleStage] with size limited to percentage of prior stages results. + * + * The [percentage] parameter is the target percentage (between 0.0 & 1.0) of the number of + * input documents to produce. Each input document is independently selected against the given + * percentage. As a result the output size will be approximately documents * [percentage]. + * + * @param percentage The percentage of the prior stages documents to emit. + * @return [SampleStage] with specified [percentage]. + */ + @JvmStatic fun withPercentage(percentage: Double) = SampleStage(percentage, Mode.PERCENT) + + /** + * Creates [SampleStage] with size limited to number of documents. + * + * The [documents] parameter represents the target number of documents to produce and must be a + * non-negative integer value. If the previous stage produces less than size documents, the + * entire previous results are returned. If the previous stage produces more than size, this + * outputs a sample of exactly size entries where any sample is equally likely. + * + * @param documents The number of documents to emit. + * @return [SampleStage] with specified [documents]. + */ + @JvmStatic fun withDocLimit(documents: Int) = SampleStage(documents, Mode.DOCUMENTS) + } + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(size), mode.proto) +} + +internal class UnionStage +internal constructor( + private val other: com.google.firebase.firestore.Pipeline, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("union", options) { + override fun self(options: InternalOptions) = UnionStage(other, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(Value.newBuilder().setPipelineValue(other.toPipelineProto()).build()) +} + +/** + * Takes a specified array from the input documents and outputs a document for each element with the + * element stored in a field with name specified by the alias. + */ +class UnnestStage +internal constructor( + private val selectable: Selectable, + options: InternalOptions = InternalOptions.EMPTY +) : BaseStage("unnest", options) { + companion object { + + /** + * Creates [UnnestStage] with input array and alias specified. + * + * For each document emitted by the prior stage, this stage will emit zero or more augmented + * documents. The input array is found in parameter [arrayWithAlias], which can be an [Expr] + * with an alias specified via [Expr.alias], or a [Field] that can also have alias specified. + * For each element of the input array, an augmented document will be produced. The element of + * input array will be stored in a field with name specified by the alias of the + * [arrayWithAlias] parameter. If the [arrayWithAlias] is a [Field] with no alias, then the + * original array field will be replaced with the individual element. + * + * @param arrayWithAlias The input array with field alias to store output element of array. + * @return [SampleStage] with input array and alias specified. + */ + @JvmStatic fun withField(arrayWithAlias: Selectable) = UnnestStage(arrayWithAlias) + + /** + * Creates [UnnestStage] with input array and alias specified. + * + * For each document emitted by the prior stage, this stage will emit zero or more augmented + * documents. The input array found in the previous stage document field specified by the + * [arrayField] parameter, will for each element of the input array produce an augmented + * document. The element of the input array will be stored in a field with name specified by + * [alias] parameter on the augmented document. + * + * @return [SampleStage] with input array and alias specified. + */ + @JvmStatic + fun withField(arrayField: String, alias: String): UnnestStage = + UnnestStage(Expr.field(arrayField).alias(alias)) + } + override fun self(options: InternalOptions) = UnnestStage(selectable, options) + override fun args(userDataReader: UserDataReader): Sequence = + sequenceOf(encodeValue(selectable.getAlias()), selectable.toProto(userDataReader)) + + /** + * Adds index field to emitted documents + * + * A field with name specified in [indexField] will be added to emitted document. The index is a + * numeric value that corresponds to array index of the element from input array. + * + * @param indexField The field name of index field. + * @return [SampleStage] that includes specified index field. + */ + fun withIndexField(indexField: String): UnnestStage = with("index_field", indexField) +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/Datastore.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/Datastore.java index 87365361be4..e3a8da26217 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/Datastore.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/Datastore.java @@ -21,8 +21,11 @@ import androidx.annotation.VisibleForTesting; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.TaskCompletionSource; +import com.google.common.base.Strings; +import com.google.firebase.Timestamp; import com.google.firebase.firestore.AggregateField; import com.google.firebase.firestore.FirebaseFirestoreException; +import com.google.firebase.firestore.PipelineResultObserver; import com.google.firebase.firestore.core.Query; import com.google.firebase.firestore.model.DocumentKey; import com.google.firebase.firestore.model.MutableDocument; @@ -34,6 +37,9 @@ import com.google.firestore.v1.BatchGetDocumentsResponse; import com.google.firestore.v1.CommitRequest; import com.google.firestore.v1.CommitResponse; +import com.google.firestore.v1.Document; +import com.google.firestore.v1.ExecutePipelineRequest; +import com.google.firestore.v1.ExecutePipelineResponse; import com.google.firestore.v1.FirestoreGrpc; import com.google.firestore.v1.RunAggregationQueryRequest; import com.google.firestore.v1.RunAggregationQueryResponse; @@ -237,6 +243,48 @@ public Task> runAggregateQuery( }); } + public void executePipeline(ExecutePipelineRequest request, PipelineResultObserver observer) { + channel.runStreamingResponseRpc( + FirestoreGrpc.getExecutePipelineMethod(), + request, + new FirestoreChannel.StreamingListener() { + + private Timestamp executionTime = null; + + @Override + public void onMessage(ExecutePipelineResponse message) { + if (message.hasExecutionTime()) { + executionTime = serializer.decodeTimestamp(message.getExecutionTime()); + } + for (Document document : message.getResultsList()) { + String documentName = document.getName(); + observer.onDocument( + Strings.isNullOrEmpty(documentName) ? null : serializer.decodeKey(documentName), + document.getFieldsMap(), + document.hasCreateTime() + ? serializer.decodeTimestamp(document.getCreateTime()) + : null, + document.hasUpdateTime() + ? serializer.decodeTimestamp(document.getUpdateTime()) + : null); + } + } + + @Override + public void onClose(Status status) { + if (status.isOk()) { + observer.onComplete(executionTime); + } else { + FirebaseFirestoreException exception = exceptionFromStatus(status); + if (exception.getCode() == FirebaseFirestoreException.Code.UNAUTHENTICATED) { + channel.invalidateToken(); + } + observer.onError(exception); + } + } + }); + } + /** * Determines whether the given status has an error code that represents a permanent error when * received in response to a non-write operation. diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteSerializer.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteSerializer.java index 8e509247524..2e813ac3b98 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteSerializer.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteSerializer.java @@ -727,31 +727,39 @@ StructuredQuery.Filter encodeFilter(com.google.firebase.firestore.core.Filter fi @VisibleForTesting StructuredQuery.Filter encodeUnaryOrFieldFilter(FieldFilter filter) { - if (filter.getOperator() == FieldFilter.Operator.EQUAL - || filter.getOperator() == FieldFilter.Operator.NOT_EQUAL) { - UnaryFilter.Builder unaryProto = UnaryFilter.newBuilder(); - unaryProto.setField(encodeFieldPath(filter.getField())); - if (Values.isNanValue(filter.getValue())) { - unaryProto.setOp( - filter.getOperator() == FieldFilter.Operator.EQUAL - ? UnaryFilter.Operator.IS_NAN - : UnaryFilter.Operator.IS_NOT_NAN); - return StructuredQuery.Filter.newBuilder().setUnaryFilter(unaryProto).build(); - } else if (Values.isNullValue(filter.getValue())) { - unaryProto.setOp( - filter.getOperator() == FieldFilter.Operator.EQUAL - ? UnaryFilter.Operator.IS_NULL - : UnaryFilter.Operator.IS_NOT_NULL); - return StructuredQuery.Filter.newBuilder().setUnaryFilter(unaryProto).build(); + FieldFilter.Operator op = filter.getOperator(); + Value value = filter.getValue(); + FieldReference fieldReference = encodeFieldPath(filter.getField()); + if (op == FieldFilter.Operator.EQUAL) { + if (Values.isNanValue(value)) { + return encodeUnaryFilter(fieldReference, UnaryFilter.Operator.IS_NAN); + } + if (Values.isNullValue(value)) { + return encodeUnaryFilter(fieldReference, UnaryFilter.Operator.IS_NULL); + } + } else if (op == FieldFilter.Operator.NOT_EQUAL) { + if (Values.isNanValue(value)) { + return encodeUnaryFilter(fieldReference, UnaryFilter.Operator.IS_NOT_NAN); + } + if (Values.isNullValue(value)) { + return encodeUnaryFilter(fieldReference, UnaryFilter.Operator.IS_NOT_NULL); } } StructuredQuery.FieldFilter.Builder proto = StructuredQuery.FieldFilter.newBuilder(); - proto.setField(encodeFieldPath(filter.getField())); - proto.setOp(encodeFieldFilterOperator(filter.getOperator())); - proto.setValue(filter.getValue()); + proto.setField(fieldReference); + proto.setOp(encodeFieldFilterOperator(op)); + proto.setValue(value); return StructuredQuery.Filter.newBuilder().setFieldFilter(proto).build(); } + private StructuredQuery.Filter encodeUnaryFilter( + FieldReference fieldReference, UnaryFilter.Operator op) { + UnaryFilter.Builder unaryProto = UnaryFilter.newBuilder(); + unaryProto.setField(fieldReference); + unaryProto.setOp(op); + return StructuredQuery.Filter.newBuilder().setUnaryFilter(unaryProto).build(); + } + StructuredQuery.CompositeFilter.Operator encodeCompositeFilterOperator( com.google.firebase.firestore.core.CompositeFilter.Operator op) { switch (op) { diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteStore.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteStore.java index d2a139d4b6f..05f2bfa9837 100644 --- a/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteStore.java +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/remote/RemoteStore.java @@ -23,6 +23,7 @@ import com.google.firebase.database.collection.ImmutableSortedSet; import com.google.firebase.firestore.AggregateField; import com.google.firebase.firestore.FirebaseFirestoreException; +import com.google.firebase.firestore.PipelineResultObserver; import com.google.firebase.firestore.core.OnlineState; import com.google.firebase.firestore.core.Query; import com.google.firebase.firestore.core.Transaction; @@ -43,6 +44,7 @@ import com.google.firebase.firestore.util.AsyncQueue; import com.google.firebase.firestore.util.Logger; import com.google.firebase.firestore.util.Util; +import com.google.firestore.v1.ExecutePipelineRequest; import com.google.firestore.v1.Value; import com.google.protobuf.ByteString; import io.grpc.Status; @@ -777,4 +779,14 @@ public Task> runAggregateQuery( "Failed to get result from server.", FirebaseFirestoreException.Code.UNAVAILABLE)); } } + + public void executePipeline(ExecutePipelineRequest request, PipelineResultObserver observer) { + if (canUseNetwork()) { + datastore.executePipeline(request, observer); + } else { + observer.onError( + new FirebaseFirestoreException( + "Failed to get result from server.", FirebaseFirestoreException.Code.UNAVAILABLE)); + } + } } diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/util/BiFunction.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/util/BiFunction.java new file mode 100644 index 00000000000..1afb87fbb1d --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/util/BiFunction.java @@ -0,0 +1,7 @@ +package com.google.firebase.firestore.util; + +/** A port of {@link java.util.function.BiFunction} */ +@FunctionalInterface +public interface BiFunction { + R apply(T t, U u); +} diff --git a/firebase-firestore/src/main/java/com/google/firebase/firestore/util/IntFunction.java b/firebase-firestore/src/main/java/com/google/firebase/firestore/util/IntFunction.java new file mode 100644 index 00000000000..2407db54808 --- /dev/null +++ b/firebase-firestore/src/main/java/com/google/firebase/firestore/util/IntFunction.java @@ -0,0 +1,7 @@ +package com.google.firebase.firestore.util; + +/** A port of {@link java.util.function.IntFunction} */ +@FunctionalInterface +public interface IntFunction { + R apply(int value); +} diff --git a/firebase-firestore/src/proto/google/firestore/v1/document.proto b/firebase-firestore/src/proto/google/firestore/v1/document.proto index 52dc85ca9df..9947a289a1e 100644 --- a/firebase-firestore/src/proto/google/firestore/v1/document.proto +++ b/firebase-firestore/src/proto/google/firestore/v1/document.proto @@ -129,6 +129,50 @@ message Value { // A map value. MapValue map_value = 6; + + + // Value which references a field. + // + // This is considered relative (vs absolute) since it only refers to a field + // and not a field within a particular document. + // + // **Requires:** + // + // * Must follow [field reference][FieldReference.field_path] limitations. + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): long term, there is no reason this type should not be + // allowed to be used on the write path. --) + string field_reference_value = 19; + + // A value that represents an unevaluated expression. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): similar to above, there is no reason to not allow + // storing expressions into the database, just no plan to support in + // the near term. + // + // This would actually be an interesting way to represent user-defined + // functions or more expressive rules-based systems. --) + Function function_value = 20; + + // A value that represents an unevaluated pipeline. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): similar to above, there is no reason to not allow + // storing expressions into the database, just no plan to support in + // the near term. + // + // This would actually be an interesting way to represent user-defined + // functions or more expressive rules-based systems. --) + Pipeline pipeline_value = 21; } } @@ -148,3 +192,73 @@ message MapValue { // not exceed 1,500 bytes and cannot be empty. map fields = 1; } + +// Represents an unevaluated scalar expression. +// +// For example, the expression `like(user_name, "%alice%")` is represented as: +// +// ``` +// name: "like" +// args { field_reference: "user_name" } +// args { string_value: "%alice%" } +// ``` +// +// (-- api-linter: core::0123::resource-annotation=disabled +// aip.dev/not-precedent: this is not a One Platform API resource. --) +message Function { + // The name of the function to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + // + string name = 1; + + // Ordered list of arguments the given function expects. + repeated Value args = 2; + + // Optional named arguments that certain functions may support. + map options = 3; +} + +// A Firestore query represented as an ordered list of operations / stages. +message Pipeline { + // A single operation within a pipeline. + // + // A stage is made up of a unique name, and a list of arguments. The exact + // number of arguments & types is dependent on the stage type. + // + // To give an example, the stage `filter(state = "MD")` would be encoded as: + // + // ``` + // name: "filter" + // args { + // function_value { + // name: "eq" + // args { field_reference_value: "state" } + // args { string_value: "MD" } + // } + // } + // ``` + // + // See public documentation for the full list. + message Stage { + // The name of the stage to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + // + string name = 1; + + // Ordered list of arguments the given stage expects. + repeated Value args = 2; + + // Optional named arguments that certain functions may support. + map options = 3; + } + + // Ordered list of stages to evaluate. + repeated Stage stages = 1; +} + diff --git a/firebase-firestore/src/proto/google/firestore/v1/firestore.proto b/firebase-firestore/src/proto/google/firestore/v1/firestore.proto index 9ea56429afc..d59c9e2decb 100644 --- a/firebase-firestore/src/proto/google/firestore/v1/firestore.proto +++ b/firebase-firestore/src/proto/google/firestore/v1/firestore.proto @@ -22,6 +22,7 @@ import "google/api/field_behavior.proto"; import "google/firestore/v1/aggregation_result.proto"; import "google/firestore/v1/common.proto"; import "google/firestore/v1/document.proto"; +import "google/firestore/v1/pipeline.proto"; import "google/firestore/v1/query.proto"; import "google/firestore/v1/write.proto"; import "google/protobuf/empty.proto"; @@ -139,6 +140,15 @@ service Firestore { }; } + // Executes a pipeline query. + rpc ExecutePipeline(ExecutePipelineRequest) + returns (stream ExecutePipelineResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}:executePipeline" + body: "*" + }; + } + // Runs an aggregation query. // // Rather than producing [Document][google.firestore.v1.Document] results like @@ -574,6 +584,80 @@ message RunQueryResponse { int32 skipped_results = 4; } +// The request for [Firestore.ExecutePipeline][]. +message ExecutePipelineRequest { + // Database identifier, in the form `projects/{project}/databases/{database}`. + string database = 1; + + oneof pipeline_type { + // A pipelined operation. + StructuredPipeline structured_pipeline = 2; + } + + // Optional consistency arguments, defaults to strong consistency. + oneof consistency_selector { + // Run the query within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 5; + + // Execute the pipeline in a new transaction. + // + // The identifier of the newly created transaction will be returned in the + // first response on the stream. This defaults to a read-only transaction. + TransactionOptions new_transaction = 6; + + // Execute the pipeline in a snapshot transaction at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 7; + } + + // Explain / analyze options for the pipeline. + // ExplainOptions explain_options = 8 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for [Firestore.Execute][]. +message ExecutePipelineResponse { + // Newly created transaction identifier. + // + // This field is only specified on the first response from the server when + // the request specified [ExecuteRequest.new_transaction][]. + bytes transaction = 1; + + // An ordered batch of results returned executing a pipeline. + // + // The batch size is variable, and can even be zero for when only a partial + // progress message is returned. + // + // The fields present in the returned documents are only those that were + // explicitly requested in the pipeline, this include those like + // [`__name__`][Document.name] & [`__update_time__`][Document.update_time]. + // This is explicitly a divergence from `Firestore.RunQuery` / + // `Firestore.GetDocument` RPCs which always return such fields even when they + // are not specified in the [`mask`][DocumentMask]. + repeated Document results = 2; + + // The time at which the document(s) were read. + // + // This may be monotonically increasing; in this case, the previous documents + // in the result stream are guaranteed not to have changed between their + // `execution_time` and this one. + // + // If the query returns no results, a response with `execution_time` and no + // `results` will be sent, and this represents the time at which the operation + // was run. + google.protobuf.Timestamp execution_time = 3; + + // Query explain metrics. + // + // Set on the last response when [ExecutePipelineRequest.explain_options][] + // was specified on the request. + // ExplainMetrics explain_metrics = 4; +} + // The request for [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. message RunAggregationQueryRequest { // Required. The parent resource name. In the format: diff --git a/firebase-firestore/src/proto/google/firestore/v1/pipeline.proto b/firebase-firestore/src/proto/google/firestore/v1/pipeline.proto new file mode 100644 index 00000000000..f425ec6911a --- /dev/null +++ b/firebase-firestore/src/proto/google/firestore/v1/pipeline.proto @@ -0,0 +1,40 @@ +// Copyright 2024 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. + +syntax = "proto3"; +package google.firestore.v1; +import "google/firestore/v1/document.proto"; +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; +option java_multiple_files = true; +option java_package = "com.google.firestore.v1"; +option java_outer_classname = "PipelineProto"; +option objc_class_prefix = "GCFS"; +// A Firestore query represented as an ordered list of operations / stages. +// +// This is considered the top-level function which plans & executes a query. +// It is logically equivalent to `query(stages, options)`, but prevents the +// client from having to build a function wrapper. +message StructuredPipeline { + // The pipeline query to execute. + Pipeline pipeline = 1; + // Optional query-level arguments. + // + // (-- Think query statement hints. --) + // + // (-- TODO(batchik): define the api contract of using an unsupported hint --) + map options = 2; +} + diff --git a/firebase-firestore/src/testUtil/java/com/google/firebase/firestore/TestAccessHelper.java b/firebase-firestore/src/testUtil/java/com/google/firebase/firestore/TestAccessHelper.java index bab88979493..b62ec1b9933 100644 --- a/firebase-firestore/src/testUtil/java/com/google/firebase/firestore/TestAccessHelper.java +++ b/firebase-firestore/src/testUtil/java/com/google/firebase/firestore/TestAccessHelper.java @@ -14,14 +14,20 @@ package com.google.firebase.firestore; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.firebase.firestore.model.DatabaseId; import com.google.firebase.firestore.model.DocumentKey; public final class TestAccessHelper { /** Makes the DocumentReference constructor accessible. */ public static DocumentReference createDocumentReference(DocumentKey documentKey) { - // We can use null here because the tests only use this as a wrapper for documentKeys. - return new DocumentReference(documentKey, null); + // We can use mock here because the tests only use this as a wrapper for documentKeys. + FirebaseFirestore mock = mock(FirebaseFirestore.class); + when(mock.getDatabaseId()).thenReturn(DatabaseId.forProject("project")); + return new DocumentReference(documentKey, mock); } /** Makes the getKey() method accessible. */