/// <summary>
        /// Gets the current sum.
        /// </summary>
        /// <returns>The current sum.</returns>
        public CosmosElement GetResult()
        {
            if (double.IsNaN(this.globalSum))
            {
                return(null);
            }

            return(CosmosNumber64.Create(this.globalSum));
        }
            /// <summary>
            /// Returns the average or undefined if any of the intermediate averages resulted in an undefined value.
            /// </summary>
            /// <returns>The average or undefined if any of the intermediate averages resulted in an undefined value.</returns>
            public CosmosNumber GetAverage()
            {
                if (!this.Sum.HasValue || this.Count <= 0)
                {
                    return(null);
                }

                return(CosmosNumber64.Create(this.Sum.Value / this.Count));
            }
示例#3
0
        public void Numbers()
        {
            List <Input> inputs = new List <Input>()
            {
                new Input(
                    description: "positive zero",
                    partitionKeyValue: CosmosNumber64.Create(0.0)),
                new Input(
                    description: "negative zero",
                    partitionKeyValue: CosmosNumber64.Create(-0.0)),
                new Input(
                    description: "positive number",
                    partitionKeyValue: CosmosNumber64.Create(1)),
                new Input(
                    description: "negative number",
                    partitionKeyValue: CosmosNumber64.Create(-1)),
                new Input(
                    description: nameof(double.Epsilon),
                    partitionKeyValue: CosmosNumber64.Create(double.Epsilon)),
                new Input(
                    description: nameof(double.MaxValue),
                    partitionKeyValue: CosmosNumber64.Create(double.MaxValue)),
                new Input(
                    description: nameof(double.MinValue),
                    partitionKeyValue: CosmosNumber64.Create(double.MinValue)),
                new Input(
                    description: nameof(double.NaN),
                    partitionKeyValue: CosmosNumber64.Create(double.NaN)),
                new Input(
                    description: "long " + nameof(double.NegativeInfinity),
                    partitionKeyValue: CosmosNumber64.Create(double.NegativeInfinity)),
                new Input(
                    description: "long " + nameof(double.PositiveInfinity),
                    partitionKeyValue: CosmosNumber64.Create(double.PositiveInfinity)),
                new Input(
                    description: "long " + nameof(long.MaxValue),
                    partitionKeyValue: CosmosNumber64.Create(long.MaxValue)),
                new Input(
                    description: "long " + nameof(long.MaxValue) + " minus 1",
                    partitionKeyValue: CosmosNumber64.Create(long.MaxValue - 1)),
                new Input(
                    description: "long " + nameof(long.MinValue),
                    partitionKeyValue: CosmosNumber64.Create(long.MinValue)),
                new Input(
                    description: nameof(MaxSafeInteger),
                    partitionKeyValue: CosmosNumber64.Create(MaxSafeInteger)),
                new Input(
                    description: nameof(MaxSafeInteger) + " Minus 1",
                    partitionKeyValue: CosmosNumber64.Create(MaxSafeInteger - 1)),
                new Input(
                    description: nameof(MaxSafeInteger) + " Plus 1",
                    partitionKeyValue: CosmosNumber64.Create(MaxSafeInteger + 1)),
            };

            this.ExecuteTestSuite(inputs);
        }
示例#4
0
 public static CosmosElement ToCosmosElement(VersionedAndRidCheckedCompositeToken token)
 {
     return(CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
     {
         { PropertyNames.Version, CosmosNumber64.Create((long)token.VersionNumber) },
         { PropertyNames.Rid, CosmosString.Create(token.Rid) },
         { PropertyNames.Continuation, token.ContinuationToken },
     }));
 }
 private static QueryState CreateQueryState(int count)
 {
     return(new QueryState(
                CosmosString.Create(
                    CosmosObject.Create(
                        new Dictionary <string, CosmosElement>()
     {
         { "continuationCount", CosmosNumber64.Create(++count) },
     })
                    .ToString())));
 }
示例#6
0
 private CosmosElement CreateVertexPropertyPrimitiveValueElement(object value)
 {
     return(value switch
     {
         bool boolValue => CosmosBoolean.Create(boolValue),
         double doubleValue => CosmosNumber64.Create(doubleValue),
         float floatValue => CosmosNumber64.Create(floatValue),
         int intValue => CosmosNumber64.Create(intValue),
         long longValue => CosmosNumber64.Create(longValue),
         string stringValue => CosmosString.Create(stringValue),
         _ => throw new AssertFailedException($"Invalid Gremlin property value object type: {value.GetType().Name}."),
     });
示例#7
0
        private static CosmosElement PerformUnaryNumberOperation(
            Func <double, double> unaryOperation,
            CosmosElement operand)
        {
            if (!(operand is CosmosNumber operandAsNumber))
            {
                return(Undefined);
            }

            double result = unaryOperation(Number64.ToDouble(operandAsNumber.Value));

            return(CosmosNumber64.Create(result));
        }
            public static CosmosElement ToCosmosElement(AverageInfo averageInfo)
            {
                Dictionary <string, CosmosElement> dictionary = new Dictionary <string, CosmosElement>();

                if (averageInfo.Sum.HasValue)
                {
                    dictionary.Add(AverageInfo.SumName, CosmosNumber64.Create(averageInfo.Sum.Value));
                }

                dictionary.Add(AverageInfo.CountName, CosmosNumber64.Create(averageInfo.Count));

                return(CosmosObject.Create(dictionary));
            }
示例#9
0
                public static CosmosElement ToCosmosElement(OffsetContinuationToken offsetContinuationToken)
                {
                    Dictionary <string, CosmosElement> dictionary = new Dictionary <string, CosmosElement>()
                    {
                        {
                            OffsetContinuationToken.ProperytNames.SkipCountProperty,
                            CosmosNumber64.Create(offsetContinuationToken.Offset)
                        },
                        {
                            OffsetContinuationToken.ProperytNames.SourceTokenProperty,
                            offsetContinuationToken.SourceToken
                        }
                    };

                    return(CosmosObject.Create(dictionary));
                }
示例#10
0
                public static CosmosElement ToCosmosElement(TakeContinuationToken takeContinuationToken)
                {
                    Dictionary <string, CosmosElement> dictionary = new Dictionary <string, CosmosElement>()
                    {
                        {
                            TakeContinuationToken.PropertyNames.SourceToken,
                            takeContinuationToken.SourceToken
                        },
                        {
                            TakeContinuationToken.PropertyNames.TakeCount,
                            CosmosNumber64.Create(takeContinuationToken.TakeCount)
                        },
                    };

                    return(CosmosObject.Create(dictionary));
                }
        public void SqlCoalesceScalarExpressionTest()
        {
            SqlLiteralScalarExpression nullLiteral      = SqlLiteralScalarExpression.Create(SqlNullLiteral.Singleton);
            SqlLiteralScalarExpression undefinedLiteral = SqlLiteralScalarExpression.Create(SqlUndefinedLiteral.Create());
            SqlLiteralScalarExpression five             = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(5));
            SqlLiteralScalarExpression three            = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(3));

            SqlCoalesceScalarExpression nullCoalesceFive = SqlCoalesceScalarExpression.Create(nullLiteral, five);

            AssertEvaluation(CosmosNull.Create(), nullCoalesceFive);

            SqlCoalesceScalarExpression undefinedCoalesceFive = SqlCoalesceScalarExpression.Create(undefinedLiteral, five);

            AssertEvaluation(CosmosNumber64.Create(5), undefinedCoalesceFive);

            SqlCoalesceScalarExpression threeCoalesceFive = SqlCoalesceScalarExpression.Create(three, five);

            AssertEvaluation(CosmosNumber64.Create(3), threeCoalesceFive);
        }
示例#12
0
        public void SqlSelectValueSpecTest()
        {
            CosmosObject john = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["name"] = CosmosString.Create("John"),
                ["age"]  = CosmosNumber64.Create(25)
            });

            CosmosObject johnWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"] = john
            });

            SqlScalarExpression cDotName = TestUtils.CreatePathExpression("c", "name");

            SqlSelectValueSpec valueSpec = SqlSelectValueSpec.Create(cDotName);

            AssertEvaluation(CosmosString.Create("John"), valueSpec, johnWrapped);
        }
示例#13
0
        private static CosmosElement PerformBinaryNumberOperation(
            Func <double, double, double> operation,
            CosmosElement left,
            CosmosElement right)
        {
            if (!(left is CosmosNumber leftAsNumber))
            {
                return(Undefined);
            }

            if (!(right is CosmosNumber rightAsNumber))
            {
                return(Undefined);
            }

            double result = operation(Number64.ToDouble(leftAsNumber.Value), Number64.ToDouble(rightAsNumber.Value));

            return(CosmosNumber64.Create(result));
        }
示例#14
0
        public void ROUND()
        {
            // ROUND(4.84090499760142E+15)
            // offline engine has double precision errors
            AssertEvaluation(
                expected: CosmosNumber64.Create(4.84090499760142E+15),
                sqlScalarExpression: SqlFunctionCallScalarExpression.CreateBuiltin(
                    SqlFunctionCallScalarExpression.Identifiers.Round,
                    SqlLiteralScalarExpression.Create(
                        SqlNumberLiteral.Create(
                            JToken.Parse("4840904997601420").Value <double>()))));

            // ROUND(0.5, 1)
            // -> should round up
            AssertEvaluation(
                expected: CosmosNumber64.Create(1),
                sqlScalarExpression: SqlFunctionCallScalarExpression.CreateBuiltin(
                    SqlFunctionCallScalarExpression.Identifiers.Round,
                    SqlLiteralScalarExpression.Create(
                        SqlNumberLiteral.Create(0.5))));
        }
示例#15
0
            public override CosmosElement GetCosmosElementContinuationToken()
            {
                Dictionary <string, CosmosElement> dictionary = new Dictionary <string, CosmosElement>()
                {
                    {
                        UnorderdDistinctMap.PropertyNames.Numbers,
                        CosmosArray.Create(this.numbers.Select(x => CosmosNumber64.Create(x)))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.StringsLength4,
                        CosmosArray.Create(this.stringsLength4.Select(x => CosmosUInt32.Create(x)))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.StringsLength8,
                        CosmosArray.Create(this.stringsLength8.Select(x => CosmosInt64.Create((long)x)))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.StringsLength16,
                        CosmosArray.Create(this.stringsLength16.Select(x => CosmosBinary.Create(UInt128.ToByteArray(x))))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.StringsLength16Plus,
                        CosmosArray.Create(this.stringsLength16Plus.Select(x => CosmosBinary.Create(UInt128.ToByteArray(x))))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.Arrays,
                        CosmosArray.Create(this.arrays.Select(x => CosmosBinary.Create(UInt128.ToByteArray(x))))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.Object,
                        CosmosArray.Create(this.objects.Select(x => CosmosBinary.Create(UInt128.ToByteArray(x))))
                    },
                    {
                        UnorderdDistinctMap.PropertyNames.SimpleValues,
                        CosmosString.Create(this.simpleValues.ToString())
                    }
                };

                return(CosmosObject.Create(dictionary));
            }
        public void SqlSubqueryScalarExpressionTest()
        {
            SqlLiteralScalarExpression five  = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(5));
            SqlLiteralScalarExpression three = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(3));

            // (SELECT VALUE 5 + 3)
            SqlSubqueryScalarExpression subqueryScalarExpression = SqlSubqueryScalarExpression.Create(
                SqlQuery.Create(
                    SqlSelectClause.Create(
                        SqlSelectValueSpec.Create(
                            SqlBinaryScalarExpression.Create(
                                SqlBinaryScalarOperatorKind.Add,
                                five,
                                three))),
                    fromClause: null,
                    whereClause: null,
                    groupByClause: null,
                    orderByClause: null,
                    offsetLimitClause: null));

            AssertEvaluation(CosmosNumber64.Create(5 + 3), subqueryScalarExpression);
        }
        public void VerifyNumberSort()
        {
            List <CosmosElement> manuallySortedList = new List <CosmosElement>()
            {
                CosmosNumber64.Create(-1),
                CosmosNumber64.Create(0),
                CosmosNumber64.Create(1),

                CosmosInt8.Create(-1),
                CosmosInt8.Create(0),
                CosmosInt8.Create(1),

                CosmosInt16.Create(-1),
                CosmosInt16.Create(0),
                CosmosInt16.Create(1),

                CosmosInt32.Create(-1),
                CosmosInt32.Create(0),
                CosmosInt32.Create(1),


                CosmosInt64.Create(-1),
                CosmosInt64.Create(0),
                CosmosInt64.Create(1),

                CosmosUInt32.Create(0),
                CosmosUInt32.Create(1),

                CosmosFloat32.Create(-1),
                CosmosFloat32.Create(0),
                CosmosFloat32.Create(1),

                CosmosFloat64.Create(-1),
                CosmosFloat64.Create(0),
                CosmosFloat64.Create(1),
            };

            VerifySort(manuallySortedList);
        }
                public override SqlScalarExpression Visit(SqlFunctionCallScalarExpression sqlFunctionCallScalarExpression)
                {
                    SqlScalarExpression rewrittenExpression;

                    // If the function call is an aggregate just evaluate the aggregate first and return that
                    if (
                        !sqlFunctionCallScalarExpression.IsUdf &&
                        Enum.TryParse(value: sqlFunctionCallScalarExpression.Name.Value, ignoreCase: true, result: out Aggregate aggregate))
                    {
                        IReadOnlyList <SqlScalarExpression> arguments = sqlFunctionCallScalarExpression.Arguments;
                        if (arguments.Count != 1)
                        {
                            throw new ArgumentException("Aggregates only accept one argument.");
                        }

                        IEnumerable <CosmosElement> results = this.dataSource
                                                              .Select((element) => arguments[0].Accept(
                                                                          ScalarExpressionEvaluator.Singleton,
                                                                          element));

                        // If aggregates are pushed to the index, then we only get back defined results
                        results = results.Where((result) => result != Undefined);

                        CosmosElement aggregationResult;
                        switch (aggregate)
                        {
                        case Aggregate.Min:
                        case Aggregate.Max:
                            if (results.Count() == 0)
                            {
                                aggregationResult = Undefined;
                            }
                            else if (results.Any(result => !Utils.IsPrimitive(result)))
                            {
                                aggregationResult = Undefined;
                            }
                            else
                            {
                                aggregationResult = results.First();
                                foreach (CosmosElement result in results)
                                {
                                    // First compare the types
                                    int comparison = result.CompareTo(aggregationResult);

                                    if (aggregate == Aggregate.Min)
                                    {
                                        if (comparison < 0)
                                        {
                                            aggregationResult = result;
                                        }
                                    }
                                    else if (aggregate == Aggregate.Max)
                                    {
                                        if (comparison > 0)
                                        {
                                            aggregationResult = result;
                                        }
                                    }
                                    else
                                    {
                                        throw new InvalidOperationException("Should not get here");
                                    }
                                }
                            }

                            break;

                        case Aggregate.Avg:
                        case Aggregate.Sum:
                            CosmosNumber sum   = CosmosNumber64.Create(0);
                            double       count = 0;
                            foreach (CosmosElement result in results)
                            {
                                if ((result is CosmosNumber resultAsNumber) && (sum != Undefined))
                                {
                                    sum = CosmosNumber64.Create(Number64.ToDouble(sum.Value) + Number64.ToDouble(resultAsNumber.Value));
                                    count++;
                                }
                                else
                                {
                                    sum = Undefined;
                                }
                            }
示例#19
0
 public override CosmosElement Visit(SqlNumberLiteral literal) => CosmosNumber64.Create(literal.Value);
示例#20
0
        public void SqlSelectListSpecTest()
        {
            CosmosObject john = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["name"] = CosmosString.Create("John"),
                ["age"]  = CosmosNumber64.Create(25)
            });

            CosmosObject johnWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"] = john
            });

            // { c.name, c.age }
            SqlScalarExpression cDotName = TestUtils.CreatePathExpression("c", "name");

            SqlScalarExpression cDotAge = TestUtils.CreatePathExpression("c", "age");

            SqlSelectListSpec listSpec = SqlSelectListSpec.Create(
                SqlSelectItem.Create(cDotName),
                SqlSelectItem.Create(cDotAge));

            AssertEvaluation(john, listSpec, johnWrapped);

            // { c.name AS nameAlias }
            CosmosObject johnAliased = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["nameAlias"] = CosmosString.Create("John"),
            });

            SqlSelectListSpec listSpecWithAlias = SqlSelectListSpec.Create(SqlSelectItem.Create(cDotName, SqlIdentifier.Create("nameAlias")));

            AssertEvaluation(johnAliased, listSpecWithAlias, johnWrapped);

            // { 3 + 5 }
            CosmosObject johnNonPropertyName = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["$1"] = CosmosNumber64.Create(8)
            });

            SqlLiteralScalarExpression five          = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(5));
            SqlLiteralScalarExpression three         = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(3));
            SqlBinaryScalarExpression  fivePlusThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Add, five, three);

            SqlSelectListSpec listSpecNonMember = SqlSelectListSpec.Create(SqlSelectItem.Create(fivePlusThree));

            AssertEvaluation(johnNonPropertyName, listSpecNonMember);

            // { 3 + 5 AS Five Plus Three }
            CosmosObject johnNonPropertyNameAliased = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["Five Plus Three"] = CosmosNumber64.Create(8)
            });
            SqlSelectListSpec listSpecNonMemberAliased = SqlSelectListSpec.Create(SqlSelectItem.Create(fivePlusThree, SqlIdentifier.Create("Five Plus Three")));

            AssertEvaluation(johnNonPropertyNameAliased, listSpecNonMemberAliased);

            // { c.blah[0] }
            CosmosObject numberIndex = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["blah"] = CosmosArray.Create(
                    new List <CosmosElement>()
                {
                    CosmosNumber64.Create(0),
                    CosmosNumber64.Create(1),
                    CosmosNumber64.Create(2)
                })
            });

            CosmosObject numberIndexWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"] = numberIndex
            });

            CosmosObject numberIndexEval = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["$1"] = CosmosNumber64.Create(0)
            });

            SqlScalarExpression cDotBlah0       = TestUtils.CreatePathExpression("c", "blah", 0);
            SqlSelectListSpec   numberIndexSpec = SqlSelectListSpec.Create(SqlSelectItem.Create(cDotBlah0));

            AssertEvaluation(numberIndexEval, numberIndexSpec, numberIndexWrapped);
        }
        public void AliasedCollectionExpressionTest()
        {
            // FROM c
            SqlAliasedCollectionExpression fromC = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    relativePath: null),
                alias: null);

            CosmosObject andersenWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = AndersenFamily,
                ["_rid"] = AndersenFamily["_rid"]
            });

            CosmosObject wakeFieldWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["c"]    = WakefieldFamily,
                ["_rid"] = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenWrapped, wakeFieldWrapped }, fromC, DataSource);

            // FROM c.id
            SqlAliasedCollectionExpression fromCDotId = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    SqlIdentifierPathExpression.Create(
                        null,
                        SqlIdentifier.Create("id"))),
                alias: null);

            CosmosObject andersenId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["id"]   = CosmosString.Create("AndersenFamily"),
                ["_rid"] = AndersenFamily["_rid"]
            });

            CosmosObject wakefieldId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["id"]   = CosmosString.Create("WakefieldFamily"),
                ["_rid"] = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenId, wakefieldId }, fromCDotId, DataSource);

            // FROM c.id AS familyId
            SqlAliasedCollectionExpression fromCDotIdAsFamilyId = SqlAliasedCollectionExpression.Create(
                SqlInputPathCollection.Create(
                    SqlIdentifier.Create("c"),
                    SqlIdentifierPathExpression.Create(
                        null,
                        SqlIdentifier.Create("id"))),
                SqlIdentifier.Create("familyId"));

            CosmosObject andersenIdAsFamilyId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["familyId"] = CosmosString.Create("AndersenFamily"),
                ["_rid"]     = AndersenFamily["_rid"]
            });

            CosmosObject wakefieldIdAsFamilyId = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["familyId"] = CosmosString.Create("WakefieldFamily"),
                ["_rid"]     = WakefieldFamily["_rid"]
            });

            AssertEvaluation(new CosmosElement[] { andersenIdAsFamilyId, wakefieldIdAsFamilyId }, fromCDotIdAsFamilyId, DataSource);

            // FROM (SELECT VALUE child["grade"] FROM child IN c.children) grade
            SqlAliasedCollectionExpression fromSubqueryGrades = SqlAliasedCollectionExpression.Create(
                SqlSubqueryCollection.Create(
                    SqlQuery.Create(
                        SqlSelectClause.Create(
                            SqlSelectValueSpec.Create(
                                TestUtils.CreatePathExpression("child", "grade"))),
                        SqlFromClause.Create(
                            SqlArrayIteratorCollectionExpression.Create(
                                SqlIdentifier.Create("child"),
                                SqlInputPathCollection.Create(
                                    SqlIdentifier.Create("c"),
                                    SqlStringPathExpression.Create(
                                        null,
                                        SqlStringLiteral.Create("children"))))),
                        whereClause: null,
                        groupByClause: null,
                        orderByClause: null,
                        offsetLimitClause: null)),
                SqlIdentifier.Create("grade"));

            CosmosObject henrietteWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(5),
                ["_rid"]  = AndersenFamily["_rid"]
            });

            CosmosObject jesseWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(1),
                ["_rid"]  = WakefieldFamily["_rid"]
            });

            CosmosObject lisaWrapped = CosmosObject.Create(new Dictionary <string, CosmosElement>
            {
                ["grade"] = CosmosNumber64.Create(8),
                ["_rid"]  = WakefieldFamily["_rid"]
            });

            AssertEvaluation(
                new CosmosElement[]
            {
                henrietteWrapped,
                jesseWrapped,
                lisaWrapped
            },
                fromSubqueryGrades,
                DataSource);
        }
        public void SqlBinaryScalarExpressionTest()
        {
            SqlLiteralScalarExpression five             = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(5));
            SqlLiteralScalarExpression three            = SqlLiteralScalarExpression.Create(SqlNumberLiteral.Create(3));
            SqlLiteralScalarExpression hello            = SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("Hello"));
            SqlLiteralScalarExpression world            = SqlLiteralScalarExpression.Create(SqlStringLiteral.Create("World"));
            SqlLiteralScalarExpression trueBoolean      = SqlLiteralScalarExpression.Create(SqlBooleanLiteral.True);
            SqlLiteralScalarExpression falseBoolean     = SqlLiteralScalarExpression.Create(SqlBooleanLiteral.False);
            SqlLiteralScalarExpression nullLiteral      = SqlLiteralScalarExpression.Create(SqlNullLiteral.Singleton);
            SqlLiteralScalarExpression undefinedLiteral = SqlLiteralScalarExpression.Create(SqlUndefinedLiteral.Create());

            SqlArrayCreateScalarExpression  arrayCreateScalarExpresion1  = SqlArrayCreateScalarExpression.Create();
            SqlArrayCreateScalarExpression  arrayCreateScalarExpresion2  = SqlArrayCreateScalarExpression.Create(five);
            SqlObjectCreateScalarExpression objectCreateScalarExpression = SqlObjectCreateScalarExpression.Create();

            SqlBinaryScalarExpression fivePlusThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Add, five, three);

            AssertEvaluation(CosmosNumber64.Create(3 + 5), fivePlusThree);

            SqlBinaryScalarExpression trueAndFalse = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.And, trueBoolean, falseBoolean);

            AssertEvaluation(CosmosBoolean.Create(true && false), trueAndFalse);

            SqlBinaryScalarExpression falseAndUndefined = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.And, falseBoolean, undefinedLiteral);

            AssertEvaluation(CosmosBoolean.Create(false), falseAndUndefined);

            SqlBinaryScalarExpression trueAndUndefined = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.And, trueBoolean, undefinedLiteral);

            AssertEvaluation(Undefined, trueAndUndefined);

            try
            {
                SqlBinaryScalarExpression threeBitwiseAndFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.BitwiseAnd, three, five);
                AssertEvaluation(CosmosNumber64.Create(1), threeBitwiseAndFive);
            }
            catch (Exception)
            {
            }

            try
            {
                SqlBinaryScalarExpression threeBitwiseOrFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.BitwiseOr, three, five);
                AssertEvaluation(CosmosNumber64.Create(7), threeBitwiseOrFive);
            }
            catch (Exception)
            {
            }

            try
            {
                SqlBinaryScalarExpression threeBitwiseXorFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.BitwiseXor, three, five);
                AssertEvaluation(CosmosNumber64.Create(7), threeBitwiseXorFive);
            }
            catch (Exception)
            {
            }

            SqlBinaryScalarExpression nullCoalesceFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Coalesce, nullLiteral, five);

            AssertEvaluation(CosmosNull.Create(), nullCoalesceFive);

            SqlBinaryScalarExpression fiveDivideFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Divide, five, five);

            AssertEvaluation(CosmosNumber64.Create(5 / 5), fiveDivideFive);

            SqlBinaryScalarExpression fiveEqualFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Equal, five, five);

            AssertEvaluation(CosmosBoolean.Create(5 == 5), fiveEqualFive);

            SqlBinaryScalarExpression threeEqualFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Equal, three, five);

            AssertEvaluation(CosmosBoolean.Create(3 == 5), threeEqualFive);

            AssertEvaluation(
                CosmosBoolean.Create(true),
                SqlBinaryScalarExpression.Create(
                    SqlBinaryScalarOperatorKind.Equal,
                    arrayCreateScalarExpresion1,
                    arrayCreateScalarExpresion1));

            AssertEvaluation(
                CosmosBoolean.Create(false),
                SqlBinaryScalarExpression.Create(
                    SqlBinaryScalarOperatorKind.Equal,
                    arrayCreateScalarExpresion1,
                    arrayCreateScalarExpresion2));

            AssertEvaluation(
                CosmosBoolean.Create(false),
                SqlBinaryScalarExpression.Create(
                    SqlBinaryScalarOperatorKind.Equal,
                    arrayCreateScalarExpresion1,
                    objectCreateScalarExpression));

            SqlBinaryScalarExpression threeGreaterThanFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.GreaterThan, three, five);

            AssertEvaluation(CosmosBoolean.Create(3 > 5), threeGreaterThanFive);

            SqlBinaryScalarExpression fiveGreaterThanThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.GreaterThan, five, three);

            AssertEvaluation(CosmosBoolean.Create(5 > 3), fiveGreaterThanThree);

            SqlBinaryScalarExpression threeGreaterThanOrEqualFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.GreaterThanOrEqual, three, five);

            AssertEvaluation(CosmosBoolean.Create(3 >= 5), threeGreaterThanOrEqualFive);

            SqlBinaryScalarExpression fiveGreaterThanOrEqualThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.GreaterThanOrEqual, five, three);

            AssertEvaluation(CosmosBoolean.Create(5 >= 3), fiveGreaterThanOrEqualThree);

            SqlBinaryScalarExpression threeLessThanFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.LessThan, three, five);

            AssertEvaluation(CosmosBoolean.Create(3 < 5), threeLessThanFive);

            SqlBinaryScalarExpression fiveLessThanThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.LessThan, five, three);

            AssertEvaluation(CosmosBoolean.Create(5 < 3), fiveLessThanThree);

            SqlBinaryScalarExpression threeLessThanOrEqualFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.LessThanOrEqual, three, five);

            AssertEvaluation(CosmosBoolean.Create(3 <= 5), threeLessThanOrEqualFive);

            SqlBinaryScalarExpression fiveLessThanOrEqualThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.LessThanOrEqual, five, three);

            AssertEvaluation(CosmosBoolean.Create(5 <= 3), fiveLessThanOrEqualThree);

            SqlBinaryScalarExpression fiveModThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Modulo, five, three);

            AssertEvaluation(CosmosNumber64.Create(5 % 3), fiveModThree);

            SqlBinaryScalarExpression fiveMultiplyThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Multiply, five, three);

            AssertEvaluation(CosmosNumber64.Create(5 * 3), fiveMultiplyThree);

            SqlBinaryScalarExpression fiveNotEqualThree = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.NotEqual, five, three);

            AssertEvaluation(CosmosBoolean.Create(5 != 3), fiveNotEqualThree);

            SqlBinaryScalarExpression fiveNotEqualFive = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.NotEqual, five, five);

            AssertEvaluation(CosmosBoolean.Create(5 != 5), fiveNotEqualFive);

            SqlBinaryScalarExpression trueOrFalse = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Or, trueBoolean, falseBoolean);

            AssertEvaluation(CosmosBoolean.Create(true || false), trueOrFalse);

            SqlBinaryScalarExpression trueOrUndefined = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Or, trueBoolean, undefinedLiteral);

            AssertEvaluation(CosmosBoolean.Create(true), trueOrUndefined);

            SqlBinaryScalarExpression falseOrUndefined = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Or, falseBoolean, undefinedLiteral);

            AssertEvaluation(Undefined, falseOrUndefined);

            SqlBinaryScalarExpression helloConcatWorld = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.StringConcat, hello, world);

            AssertEvaluation(CosmosString.Create("Hello" + "World"), helloConcatWorld);

            SqlBinaryScalarExpression fiveSubtract3 = SqlBinaryScalarExpression.Create(SqlBinaryScalarOperatorKind.Subtract, five, three);

            AssertEvaluation(CosmosNumber64.Create(5 - 3), fiveSubtract3);
        }
示例#23
0
 public CosmosElement GetCosmosElementContinuationToken()
 {
     return(CosmosNumber64.Create(this.globalSum));
 }
        public override ValueTask <bool> MoveNextAsync(ITrace trace)
        {
            if (this.PageIndex == this.pages.Count)
            {
                this.Current = default;
                return(new ValueTask <bool>(false));
            }

            IReadOnlyList <CosmosElement> documents = this.pages[(int)this.PageIndex++];
            QueryState state = this.PageIndex == this.pages.Count ? null : new QueryState(CosmosNumber64.Create(this.PageIndex));
            QueryPage  page  = new QueryPage(
                documents: documents,
                requestCharge: default,
示例#25
0
        internal void DeserializeModifyAndSerializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName            = "id";
            const string idValue           = "v_0";
            const string pkValue           = "pk_0";
            const string labelName         = "label";
            const string labelValue        = "l_0";
            const string property1Name     = "p_0";
            const string property1Value1Id = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const string property1Value1   = "p_0_v_0";
            const string property1Value2Id = "7546f541-a003-4e69-a25c-608372ed1321";
            const long   property1Value2   = 1234;
            const string property2Name     = "p_1";
            const string property2Value1Id = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const double property2Value1   = 34.56;
            const string property3Name     = "p_2";
            const string property3Value1Id = "98d27280-70ee-4edd-8461-7633a328539a";
            const bool   property3Value1   = true;
            const string property4Name     = "p_3";
            const string property4Value1Id = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const string property4Value1   = "p_3_v_0";

            // Compose the initial vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> initialVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value1Id), CosmosString.Create(property1Value1)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property3Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property3Value1Id), CosmosBoolean.Create(property3Value1)),
                    }
                        )
                },
            };

            CosmosObject initialVertexEagerObject = CosmosObject.Create(initialVertexDocumentProperties);

            // Serialize the initial vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            initialVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> initialJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(initialJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(initialJsonWriterResult);

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(initialVertexDocumentProperties.Count, vertexLazyObject.Count);

            CosmosString idLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);
            CosmosString pkLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);
            CosmosArray  property2Array  = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, property2Name);

            // Compose a new vertex document using a combination of lazy and eager CosmosElements
            Dictionary <string, CosmosElement> modifiedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, idLazyString },
                { GremlinScenarioTests.PartitionKeyPropertyName, pkLazyString },
                { labelName, labelLazyString },

                // Property 1 is modified with a new value
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },

                // Property 2 is unmodified
                { property2Name, property2Array },

                // Property 3 is deleted

                // Property 4 is newly added
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject modifiedVertexEagerObject = CosmosObject.Create(modifiedVertexDocumentProperties);

            // Serialize the modified vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            modifiedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> modifiedJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(modifiedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Compose an expected vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> expectedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject expectedVertexEagerObject = CosmosObject.Create(expectedVertexDocumentProperties);

            // Serialize the initial vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            expectedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> expectedJsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(expectedJsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Verify that the modified serialized document matches the expected serialized document
            Assert.IsTrue(modifiedJsonWriterResult.Span.SequenceEqual(expectedJsonWriterResult.Span));
        }
示例#26
0
        internal void SerializeAndDeserializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName             = "id";
            const string idValue            = "v_0";
            const string pkValue            = "pk_0";
            const string labelName          = "label";
            const string labelValue         = "l_0";
            const string boolName           = "myBool";
            const string boolId             = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const bool   boolValue          = true;
            const string intName            = "myInteger";
            const string intId              = "7546f541-a003-4e69-a25c-608372ed1321";
            const int    intValue           = 12345;
            const string longId             = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const long   longValue          = 67890L;
            const string floatName          = "myFloatingPoint";
            const string floatId            = "98d27280-70ee-4edd-8461-7633a328539a";
            const float  floatValue         = 123.4f;
            const string doubleId           = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const double doubleValue        = 56.78;
            const string stringName         = "myString";
            const string stringId           = "6bb8ae5b-19ca-450e-b369-922a34c02729";
            const string stringValue        = "str_0";
            const string metaProperty0Name  = "myMetaProperty0";
            const string metaProperty0Value = "m_0";
            const string metaProperty1Name  = "myMetaProperty1";
            const int    metaProperty1Value = 123;

            // Compose the vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> vertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    boolName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(boolId), CosmosBoolean.Create(boolValue)),
                    }
                        )
                },
                {
                    intName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(intId), CosmosNumber64.Create(intValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(longId), CosmosNumber64.Create(longValue)),
                    }
                        )
                },
                {
                    floatName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(floatId), CosmosNumber64.Create(floatValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(doubleId), CosmosNumber64.Create(doubleValue)),
                    }
                        )
                },
                {
                    stringName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(
                            CosmosString.Create(stringId),
                            CosmosString.Create(stringValue),
                            Tuple.Create <string, CosmosElement>(metaProperty0Name, CosmosString.Create(metaProperty0Value)),
                            Tuple.Create <string, CosmosElement>(metaProperty1Name, CosmosNumber64.Create(metaProperty1Value))),
                    }
                        )
                },
            };

            CosmosObject vertexEagerObject = CosmosObject.Create(vertexDocumentProperties);

            // Serialize the vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            vertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

            Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected vertex document structure/values

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(vertexDocumentProperties.Count, vertexLazyObject.Count);

            // Vertex system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            // Vertex user properties
            CosmosArray boolLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, boolName);

            Assert.AreEqual(1, boolLazyArray.Count);

            // Bool value(s)
            CosmosObject boolValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(boolLazyArray, 0);
            CosmosString boolValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(boolId, boolValue0IdLazyString.Value);
            CosmosBoolean boolValue0ValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(boolValue, boolValue0ValueLazyBool.Value);

            CosmosArray intLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, intName);

            Assert.AreEqual(2, intLazyArray.Count);

            // Integer value(s)
            CosmosObject intValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 0);
            CosmosString intValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(intId, intValue0IdLazyString.Value);
            CosmosNumber intValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, intValue0ValueLazyNumber.NumberType);
            Assert.IsTrue(intValue0ValueLazyNumber.IsInteger);
            Assert.AreEqual((long)intValue, intValue0ValueLazyNumber.AsInteger().Value);

            CosmosObject intValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 1);
            CosmosString intValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(longId, intValue1IdLazyString.Value);
            CosmosNumber intValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, intValue1ValueLazyNumber.NumberType);
            Assert.IsTrue(intValue1ValueLazyNumber.IsInteger);
            Assert.AreEqual(longValue, intValue1ValueLazyNumber.AsInteger().Value);

            // Floating point value(s)
            CosmosArray floatLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, floatName);

            Assert.AreEqual(2, floatLazyArray.Count);

            CosmosObject floatValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 0);
            CosmosString floatValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(floatId, floatValue0IdLazyString.Value);
            CosmosNumber floatValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, floatValue0ValueLazyNumber.NumberType);
            Assert.IsTrue(floatValue0ValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)floatValue, floatValue0ValueLazyNumber.AsFloatingPoint().Value);

            CosmosObject floatValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 1);
            CosmosString floatValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(doubleId, floatValue1IdLazyString.Value);
            CosmosNumber floatValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, floatValue1ValueLazyNumber.NumberType);
            Assert.IsTrue(floatValue1ValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual(doubleValue, floatValue1ValueLazyNumber.AsFloatingPoint().Value);

            // String value(s)
            CosmosArray stringLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, stringName);

            Assert.AreEqual(1, stringLazyArray.Count);

            CosmosObject stringValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(stringLazyArray, 0);
            CosmosString stringValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(stringId, stringValue0IdLazyString.Value);
            CosmosString stringValue0ValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(stringValue, stringValue0ValueLazyString.Value);

            // String value meta-properties
            CosmosObject stringValue0MetaLazyObject = this.GetAndAssertObjectProperty <CosmosObject>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_META);

            Assert.AreEqual(2, stringValue0MetaLazyObject.Count);

            CosmosString stringValue0MetaValue0LazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0MetaLazyObject, metaProperty0Name);

            Assert.AreEqual(metaProperty0Value, stringValue0MetaValue0LazyString.Value);

            CosmosNumber stringValue0MetaValue1LazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(stringValue0MetaLazyObject, metaProperty1Name);

            Assert.AreEqual(CosmosNumberType.Number64, stringValue0MetaValue1LazyNumber.NumberType);
            Assert.IsTrue(stringValue0MetaValue1LazyNumber.IsInteger);
            Assert.AreEqual((long)metaProperty1Value, stringValue0MetaValue1LazyNumber.AsInteger().Value);
        }
示例#27
0
        internal void SerializeAndDeserializeEdgeDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName                = "id";
            const string idValue               = "e_0";
            const string pkValue               = "pk_0";
            const string labelName             = "label";
            const string labelValue            = "l_0";
            const string vertexIdValue         = "v_0";
            const string vertexLabelValue      = "l_1";
            const string sinkIdValue           = "v_1";
            const string sinkLabelValue        = "l_2";
            const string sinkPartitionValue    = "pk_1";
            const bool   isEdgeValue           = true;
            const bool   isPkEdgePropertyValue = true;
            const string boolName              = "myBool";
            const bool   boolValue             = true;
            const string intName               = "myInteger";
            const int    intValue              = 12345;
            const string longName              = "myLong";
            const long   longValue             = 67890L;
            const string floatName             = "myFloatingPoint";
            const float  floatValue            = 123.4f;
            const string doubleName            = "myDouble";
            const double doubleValue           = 56.78;
            const string stringName            = "myString";
            const string stringValue           = "str_0";

            Dictionary <string, CosmosElement> edgeDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXID, CosmosString.Create(vertexIdValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXLABEL, CosmosString.Create(vertexLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV, CosmosString.Create(sinkIdValue) },
                { GremlinKeywords.KW_EDGE_SINKV_LABEL, CosmosString.Create(sinkLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV_PARTITION, CosmosString.Create(sinkPartitionValue) },
                { GremlinKeywords.KW_EDGEDOC_IDENTIFIER, CosmosBoolean.Create(isEdgeValue) },
                { GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY, CosmosBoolean.Create(isPkEdgePropertyValue) },
                { boolName, CosmosBoolean.Create(boolValue) },
                { intName, CosmosNumber64.Create(intValue) },
                { longName, CosmosNumber64.Create(longValue) },
                { floatName, CosmosNumber64.Create(floatValue) },
                { doubleName, CosmosNumber64.Create(doubleValue) },
                { stringName, CosmosString.Create(stringValue) },
            };

            CosmosObject edgeEagerObject = CosmosObject.Create(edgeDocumentProperties);

            // Serialize the edge object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            edgeEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

            Assert.IsTrue(jsonResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized edge document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected edge document structure/values

            // Root edge document object
            CosmosObject edgeLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(edgeLazyObject, $"Edge document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(edgeDocumentProperties.Count, edgeLazyObject.Count);

            // Edge system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            CosmosString vertexIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXID);

            Assert.AreEqual(vertexIdValue, vertexIdLazyString.Value);

            CosmosString vertexLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXLABEL);

            Assert.AreEqual(vertexLabelValue, vertexLabelLazyString.Value);

            CosmosString sinkIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV);

            Assert.AreEqual(sinkIdValue, sinkIdLazyString.Value);

            CosmosString sinkLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_LABEL);

            Assert.AreEqual(sinkLabelValue, sinkLabelLazyString.Value);

            CosmosString sinkPartitionLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_PARTITION);

            Assert.AreEqual(sinkPartitionValue, sinkPartitionLazyString.Value);

            CosmosBoolean isEdgeLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_IDENTIFIER);

            Assert.AreEqual(isEdgeValue, isEdgeLazyBool.Value);

            CosmosBoolean isPkEdgePropertyLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY);

            Assert.AreEqual(isPkEdgePropertyValue, isPkEdgePropertyLazyBool.Value);

            // Edge user properties

            CosmosBoolean boolValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, boolName);

            Assert.AreEqual(boolValue, boolValueLazyBool.Value);

            CosmosNumber intValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, intName);

            Assert.AreEqual(CosmosNumberType.Number64, intValueLazyNumber.NumberType);
            Assert.IsTrue(intValueLazyNumber.IsInteger);
            Assert.AreEqual((long)intValue, intValueLazyNumber.AsInteger().Value);

            CosmosNumber longValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, longName);

            Assert.AreEqual(CosmosNumberType.Number64, intValueLazyNumber.NumberType);
            Assert.IsTrue(intValueLazyNumber.IsInteger);
            Assert.AreEqual(longValue, longValueLazyNumber.AsInteger().Value);

            CosmosNumber floatValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, floatName);

            Assert.AreEqual(CosmosNumberType.Number64, floatValueLazyNumber.NumberType);
            Assert.IsTrue(floatValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)floatValue, floatValueLazyNumber.AsFloatingPoint().Value);

            CosmosNumber doubleValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, doubleName);

            Assert.AreEqual(CosmosNumberType.Number64, doubleValueLazyNumber.NumberType);
            Assert.IsTrue(doubleValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)doubleValue, doubleValueLazyNumber.AsFloatingPoint().Value);

            CosmosString stringValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, stringName);

            Assert.AreEqual(stringValue, stringValueLazyString.Value);
        }
示例#28
0
 /// <summary>
 /// Gets the global count.
 /// </summary>
 /// <returns>The global count.</returns>
 public CosmosElement GetResult()
 {
     return(CosmosNumber64.Create(this.globalCount));
 }
示例#29
0
        public async Task TestAggregateFunctionsAsync()
        {
            AggregateTestArgs args = new AggregateTestArgs()
            {
                NumberOfDocsWithSamePartitionKey       = 37,
                NumberOfDocumentsDifferentPartitionKey = 43,
                PartitionKey       = "key",
                UniquePartitionKey = "uniquePartitionKey",
                Field  = "field",
                Values = new object[] { false, true, "abc", "cdfg", "opqrs", "ttttttt", "xyz" },
            };

            List <string> documents = new List <string>(args.NumberOfDocumentsDifferentPartitionKey + args.NumberOfDocsWithSamePartitionKey);

            foreach (object val in args.Values)
            {
                Document doc;
                doc = new Document();
                doc.SetPropertyValue(args.PartitionKey, val);
                doc.SetPropertyValue("id", Guid.NewGuid().ToString());

                documents.Add(doc.ToString());
            }

            for (int i = 0; i < args.NumberOfDocsWithSamePartitionKey; ++i)
            {
                Document doc = new Document();
                doc.SetPropertyValue(args.PartitionKey, args.UniquePartitionKey);
                documents.Add(doc.ToString());
            }

            Random random = new Random();

            for (int i = 0; i < args.NumberOfDocumentsDifferentPartitionKey; ++i)
            {
                Document doc = new Document();
                doc.SetPropertyValue(args.PartitionKey, random.NextDouble());
                documents.Add(doc.ToString());
            }

            await this.CreateIngestQueryDeleteAsync <AggregateTestArgs>(
                ConnectionModes.Direct | ConnectionModes.Gateway,
                CollectionTypes.SinglePartition | CollectionTypes.MultiPartition,
                documents,
                ImplementationAsync,
                args,
                "/" + args.PartitionKey);

            async Task ImplementationAsync(
                Container container,
                IReadOnlyList <CosmosObject> inputDocuments,
                AggregateTestArgs aggregateTestArgs)
            {
                IReadOnlyList <CosmosObject> documentsWherePkIsANumber = inputDocuments
                                                                         .Where(doc =>
                {
                    return(double.TryParse(
                               doc[aggregateTestArgs.PartitionKey].ToString(),
                               out double result));
                })
                                                                         .ToList();
                double numberSum = documentsWherePkIsANumber
                                   .Sum(doc =>
                {
                    if (!doc.TryGetValue(aggregateTestArgs.PartitionKey, out CosmosNumber number))
                    {
                        Assert.Fail("Failed to get partition key from document");
                    }

                    return(Number64.ToDouble(number.Value));
                });
                double count = documentsWherePkIsANumber.Count();

                AggregateQueryArguments[] aggregateQueryArgumentsList = new AggregateQueryArguments[]
                {
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "AVG",
                        ExpectedValue     = CosmosNumber64.Create(numberSum / count),
                        Predicate         = $"IS_NUMBER(r.{aggregateTestArgs.PartitionKey})",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "AVG",
                        ExpectedValue     = null,
                        Predicate         = "true",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "COUNT",
                        ExpectedValue     = CosmosNumber64.Create(documents.Count()),
                        Predicate         = "true",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "MAX",
                        ExpectedValue     = CosmosString.Create("xyz"),
                        Predicate         = "true",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "MIN",
                        ExpectedValue     = CosmosBoolean.Create(false),
                        Predicate         = "true",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "SUM",
                        ExpectedValue     = CosmosNumber64.Create(numberSum),
                        Predicate         = $"IS_NUMBER(r.{aggregateTestArgs.PartitionKey})",
                    },
                    new AggregateQueryArguments()
                    {
                        AggregateOperator = "SUM",
                        ExpectedValue     = null,
                        Predicate         = $"true",
                    },
                };

                foreach (int maxDoP in new[] { 0, 10 })
                {
                    foreach (AggregateQueryArguments argument in aggregateQueryArgumentsList)
                    {
                        string[] queryFormats = new[]
                        {
                            "SELECT VALUE {0}(r.{1}) FROM r WHERE {2}",
                            "SELECT VALUE {0}(r.{1}) FROM r WHERE {2} ORDER BY r.{1}"
                        };

                        foreach (string queryFormat in queryFormats)
                        {
                            string query = string.Format(
                                CultureInfo.InvariantCulture,
                                queryFormat,
                                argument.AggregateOperator,
                                aggregateTestArgs.PartitionKey,
                                argument.Predicate);
                            string message = string.Format(
                                CultureInfo.InvariantCulture,
                                "query: {0}, data: {1}",
                                query,
                                JsonConvert.SerializeObject(argument));

                            List <CosmosElement> items = await QueryTestsBase.RunQueryAsync(
                                container,
                                query,
                                new QueryRequestOptions()
                            {
                                MaxConcurrency = maxDoP,
                            });

                            if (argument.ExpectedValue == null)
                            {
                                Assert.AreEqual(0, items.Count, message);
                            }
                            else
                            {
                                Assert.AreEqual(1, items.Count, message);
                                CosmosElement expected = argument.ExpectedValue;
                                CosmosElement actual   = items.Single();

                                if ((expected is CosmosNumber expectedNumber) && (actual is CosmosNumber actualNumber))
                                {
                                    Assert.AreEqual(Number64.ToDouble(expectedNumber.Value), Number64.ToDouble(actualNumber.Value), .01);
                                }
        public void TestOrderByQueryLiterals()
        {
            StringBuilder sb      = new StringBuilder();
            CosmosElement element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosString.Create("asdf") }
            });

            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":""asdf""}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosBoolean.Create(true) }
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":true}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosBoolean.Create(false) }
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":false}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosNull.Create() }
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":null}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosNumber64.Create(1.0) }
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":1}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosNumber64.Create(1L) }
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":1}",
                sb.ToString());

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosInt8.Create(3) },
                { "item2", CosmosInt16.Create(4) },
                { "item3", CosmosInt32.Create(5) },
                { "item5", CosmosUInt32.Create(7) },
                { "item6", CosmosInt64.Create(8) },
                { "item7", CosmosFloat32.Create(9.1f) },
                { "item8", CosmosFloat64.Create(10.2) },
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                @"{""item"":C_Int8(3),""item2"":C_Int16(4),""item3"":C_Int32(5),""item5"":C_UInt32(7),""item6"":C_Int64(8)," +
                @"""item7"":C_Float32(9.1),""item8"":C_Float64(10.2)}",
                sb.ToString());

            Guid guid = Guid.NewGuid();

            byte[] randomBytes = Guid.NewGuid().ToByteArray();
            string hexString   = PartitionKeyInternal.HexConvert.ToHex(randomBytes, 0, randomBytes.Length);

            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosGuid.Create(guid) },
                { "item2", CosmosBinary.Create(new ReadOnlyMemory <byte>(randomBytes)) },
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                $@"{{""item"":C_Guid(""{guid.ToString()}""),""item2"":C_Binary(""0x{hexString}"")}}",
                sb.ToString());

            // deeply nested arrays and objects
            element = CosmosObject.Create(
                new Dictionary <string, CosmosElement>()
            {
                { "item", CosmosGuid.Create(guid) },

                // empty array
                { "item2", CosmosArray.Create(new CosmosElement[] { }) },

                // empty object
                { "item3", CosmosObject.Create(new Dictionary <string, CosmosElement>()) },

                // array of objects with numbers
                { "item4", CosmosArray.Create(new CosmosElement[]
                    {
                        CosmosObject.Create(new Dictionary <string, CosmosElement>()
                        {
                            { "a", CosmosInt8.Create(3) },
                            { "b", CosmosString.Create("adf") },
                        }),
                        CosmosInt16.Create(25)
                    }) },
            });
            sb.Clear();
            element.Accept(new CosmosElementToQueryLiteral(sb));
            Assert.AreEqual(
                $@"{{""item"":C_Guid(""{guid.ToString()}""),""item2"":[],""item3"":{{}},""item4"":[{{""a"":C_Int8(3),""b"":""adf""}},C_Int16(25)]}}",
                sb.ToString());
        }