Ejemplo n.º 1
0
        /// <inheritdoc />
        public IGraphTypeSerializer CreateSerializer(
            IInternalSession session,
            IReadOnlyDictionary <GraphProtocol, IReadOnlyDictionary <string, IGraphSONDeserializer> > customDeserializers,
            IReadOnlyDictionary <GraphProtocol, IReadOnlyDictionary <Type, IGraphSONSerializer> > customSerializers,
            GraphProtocol graphProtocol,
            bool deserializeGraphNodes)
        {
            switch (graphProtocol)
            {
            case GraphProtocol.GraphSON1:
                return(_graphSon1TypeSerializer);

            case GraphProtocol.GraphSON2:
            case GraphProtocol.GraphSON3:
                IReadOnlyDictionary <Type, IGraphSONSerializer>     serializers   = null;
                IReadOnlyDictionary <string, IGraphSONDeserializer> deserializers = null;
                customDeserializers?.TryGetValue(graphProtocol, out deserializers);
                customSerializers?.TryGetValue(graphProtocol, out serializers);
                var cacheKey = new CacheKey(graphProtocol, serializers, deserializers, deserializeGraphNodes);
                return(_graphTypeSerializers.GetOrAdd(cacheKey, k => new GraphTypeSerializer(
                                                          session,
                                                          graphProtocol,
                                                          deserializers,
                                                          serializers,
                                                          deserializeGraphNodes)));

            default:
                throw new DriverInternalError($"Invalid graph protocol: {graphProtocol.GetInternalRepresentation()}");
            }
        }
 private static GraphNode GetGraphNode(string json, GraphProtocol protocol)
 {
     return(new GraphNode(new GraphSONNode(
                              new GraphTypeSerializer(
                                  Mock.Of <IInternalSession>(), protocol, null, null, true),
                              "{\"result\": " + json + "}")));
 }
        public void To_Should_Parse_Nullable_Values(GraphProtocol protocol)
        {
            var nodes = new[] { GraphNodeGraphSONTests.GetGraphNode("null", protocol), GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Vertex\", \"@value\": null}", protocol) };

            foreach (var node in nodes)
            {
                Assert.Null(node.To <short?>());
                Assert.Null(node.To <int?>());
                Assert.Null(node.To <long?>());
                Assert.Null(node.To <decimal?>());
                Assert.Null(node.To <float?>());
                Assert.Null(node.To <double?>());
                Assert.Null(node.To <Guid?>());
                Assert.Null(node.To <TimeUuid?>());
                Assert.Null(node.To <BigInteger?>());
                Assert.Null(node.To <Duration?>());
                Assert.Null(node.To <DateTimeOffset?>());
            }
            Assert.AreEqual(1, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"gx:Int16\", \"@value\": 1}", protocol).To <short?>());
            Assert.AreEqual(1, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Int32\", \"@value\": 1}", protocol).To <int?>());
            Assert.AreEqual(1L, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Int64\", \"@value\": 1}", protocol).To <long?>());
            Assert.AreEqual(1M, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"gx:BigDecimal\", \"@value\": 1}", protocol).To <decimal?>());
            Assert.AreEqual(1F, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Float\", \"@value\": 1}", protocol).To <float?>());
            Assert.AreEqual(1D, GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Double\", \"@value\": 1}", protocol).To <double?>());
            Assert.AreEqual(null, GraphNodeGraphSONTests.GetGraphNode(
                                "{\"@type\": \"gx:Int16\", \"@value\": null}", protocol).To <Guid?>());
            Assert.AreEqual((TimeUuid)Guid.Parse("2cc83ef0-5da4-11e7-8c51-2578d2fa5d3a"), GraphNodeGraphSONTests.GetGraphNode(
                                "{\"@type\": \"g:UUID\", \"@value\": \"2cc83ef0-5da4-11e7-8c51-2578d2fa5d3a\"}", protocol).To <TimeUuid?>());
            Assert.AreEqual(BigInteger.Parse("1"),
                            GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"gx:Int16\", \"@value\": 1}", protocol).To <BigInteger?>());
            Assert.AreEqual(Duration.Parse("12h"),
                            GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"gx:Duration\", \"@value\": \"12h\"}", protocol).To <Duration?>());
            Assert.AreEqual(DateTimeOffset.Parse("1970-01-01 00:00:01Z"),
                            GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Timestamp\", \"@value\": 1000}", protocol).To <DateTimeOffset?>());
        }
Ejemplo n.º 4
0
        public void Should_IgnoreProtocolOnOptionsAndStatement_When_ResolvingDefaultGraphProtocol(
            GraphProtocol expected, bool coreGraph, GraphProtocol?optionsLevel, GraphProtocol?statementLevel)
        {
            var ks      = $"ks{Guid.NewGuid().GetHashCode()}";
            var session = MockSession(ks, coreGraph);
            var factory = new GraphTypeSerializerFactory();

            var             options   = new GraphOptions().SetName(ks);
            IGraphStatement statement = new SimpleGraphStatement("");

            if (optionsLevel.HasValue)
            {
                options = options.SetGraphProtocolVersion(optionsLevel.Value);
            }
            else
            {
                Assert.IsNull(options.GraphProtocolVersion);
            }

            if (statementLevel.HasValue)
            {
                statement = statement.SetGraphProtocolVersion(statementLevel.Value);
            }
            else
            {
                Assert.IsNull(statement.GraphProtocolVersion);
            }

            var actual = factory.GetDefaultGraphProtocol(session, statement, options);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 5
0
        public void Should_UseStatementGraphNameBeforeOptions_When_ResolvingDefaultGraphProtocol(
            GraphProtocol expected, string coreGraphName, string optionsLevel, string statementLevel)
        {
            var session = MockSession(coreGraphName, true);
            var factory = new GraphTypeSerializerFactory();

            var             options   = new GraphOptions();
            IGraphStatement statement = new SimpleGraphStatement("");

            if (optionsLevel != null)
            {
                options = options.SetName(optionsLevel);
            }
            else
            {
                Assert.IsNull(options.Name);
            }

            if (statementLevel != null)
            {
                statement = statement.SetGraphName(statementLevel);
            }
            else
            {
                Assert.IsNull(statement.GraphName);
            }

            var actual = factory.GetDefaultGraphProtocol(session, statement, options);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 6
0
        public void Should_Execute_Batch_Of_Traversals(string graphName, GraphProtocol protocol)
        {
            if (graphName == BaseIntegrationTest.DefaultCoreGraphName &&
                !TestDseVersion.VersionMatch(
                    new Version(6, 8), TestClusterManager.DseVersion, Comparison.GreaterThanOrEqualsTo))
            {
                Assert.Ignore("Test requires DSE 6.8");
            }

            var g = DseGraph.Traversal(Session, new GraphOptions().SetName(graphName));

            if (graphName == BaseIntegrationTest.DefaultCoreGraphName)
            {
                g = g.With("allow-filtering");
            }
            var batch = DseGraph.Batch(new GraphOptions().SetName(graphName).SetWriteConsistencyLevel(ConsistencyLevel.LocalQuorum));

            batch
            .Add(g.AddV("character").Property("name", "Matias").Property("age", 12).Property("tag", "batch1"))
            .Add(g.AddV("character").Property("name", "Olivia").Property("age", 8).Property("tag", "batch1"));

            var rs = Session.ExecuteGraph(batch);

            Assert.AreEqual(protocol, rs.GraphProtocol);

            var list = g.V().Has("character", "tag", "batch1").Values <string>("name").ToList();

            CollectionAssert.AreEquivalent(new [] { "Matias", "Olivia" }, list);
        }
Ejemplo n.º 7
0
        public GraphTypeSerializer(
            IInternalSession session,
            GraphProtocol protocol,
            IReadOnlyDictionary <string, IGraphSONDeserializer> customDeserializers,
            IReadOnlyDictionary <Type, IGraphSONSerializer> customSerializers,
            bool deserializeGraphNodes)
        {
            _session       = session;
            _typeConverter = GraphTypeSerializer.DefaultTypeConverter;
            DefaultDeserializeGraphNodes = deserializeGraphNodes;
            GraphProtocol = protocol;

            customDeserializers = customDeserializers ?? GraphTypeSerializer.EmptyDeserializersDict;
            customSerializers   = customSerializers ?? GraphTypeSerializer.EmptySerializersDict;

            switch (protocol)
            {
            case GraphProtocol.GraphSON2:
                _reader = new CustomGraphSON2Reader(token => new GraphNode(new GraphSONNode(this, token)), customDeserializers, this);
                _writer = new CustomGraphSON2Writer(customSerializers, this);
                break;

            case GraphProtocol.GraphSON3:
                _reader = new CustomGraphSON3Reader(token => new GraphNode(new GraphSONNode(this, token)), customDeserializers, this);
                _writer = new CustomGraphSON3Writer(customSerializers, this);
                break;

            default:
                throw new ArgumentException($"Can not create graph type serializer for {protocol.GetInternalRepresentation()}");
            }

            _rowParser = row => new GraphNode(new GraphSONNode(this, row.GetValue <string>("gremlin")));
        }
        public void HasProperty_Should_Check_For_JSON_Objects(GraphProtocol protocol)
        {
            const string json = "{\"prop1\": {\"@type\": \"g:Double\", \"@value\": 789}}";
            var          node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            Assert.True(node.HasProperty("prop1"));
            Assert.False(node.HasProperty("propZ"));
        }
        public void Get_T_Should_Navigate_Properties_Of_Json_Objects(GraphProtocol protocol)
        {
            const string json = "{\"prop1\": {\"@type\": \"g:Double\", \"@value\": 789}," +
                                "  \"prop2\": true}";
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            Assert.AreEqual(789D, node.Get <double>("prop1"));
            Assert.AreEqual(true, node.Get <bool>("prop2"));
        }
        public void To_Should_Parse_Null_Vertex_Edge_Or_Path(GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode("null", protocol);

            Assert.Null(node.To <Vertex>());
            Assert.Null(node.To <Edge>());
            Assert.Null(node.To <Path>());
            Assert.Null(node.To <IVertex>());
            Assert.Null(node.To <IEdge>());
            Assert.Null(node.To <IPath>());
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Clone a graph options object, replacing the graph protocol version.
 /// </summary>
 internal GraphOptions(GraphOptions other, GraphProtocol version)
 {
     _language              = other._language;
     _name                  = other._name;
     _source                = other._source;
     _readConsistencyLevel  = Interlocked.Read(ref other._readConsistencyLevel);
     _writeConsistencyLevel = Interlocked.Read(ref other._writeConsistencyLevel);
     _readTimeout           = other._readTimeout;
     _nullableGraphProtocol = version;
     RebuildDefaultPayload();
 }
Ejemplo n.º 12
0
 public CacheKey(
     GraphProtocol protocol,
     IReadOnlyDictionary <Type, IGraphSONSerializer> serializers,
     IReadOnlyDictionary <string, IGraphSONDeserializer> deserializers,
     bool deserializeGraphNodes)
 {
     GraphProtocol         = protocol;
     Serializers           = serializers;
     Deserializers         = deserializers;
     DeserializeGraphNodes = deserializeGraphNodes;
 }
        public void Dynamic_Should_Navigate_Properties_Of_GraphSON_Objects(GraphProtocol protocol)
        {
            dynamic node = GraphNodeGraphSONTests.GetGraphNode(
                "{\"@type\": \"g:MyObject\", \"@value\": {" +
                "\"id\":{\"@type\":\"g:Int32\",\"@value\":150}," +
                "\"label\":\"topic\"" +
                "}}", protocol);
            int id = node.id;

            Assert.AreEqual(150, id);
            Assert.AreEqual("topic", node.label.ToString());
        }
        public void HasProperty_Should_Check_For_TypedGraphSON_Objects(GraphProtocol protocol)
        {
            const string json = "{\"@type\": \"gex:ObjectTree\", \"@value\": " +
                                "  {" +
                                "    \"prop1\": {\"@type\": \"g:Int32\", \"@value\": 789}," +
                                "    \"prop2\": \"prop2 value\"" +
                                "  }" +
                                "}";
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            Assert.True(node.HasProperty("prop1"));
            Assert.False(node.HasProperty("propZ"));
        }
        public void To_Should_Parse_Instant_Values(string json, string stringValue, GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            if (stringValue == null)
            {
                Assert.AreEqual(null, node.To <DateTimeOffset?>());
            }
            else
            {
                Assert.AreEqual(DateTimeOffset.Parse(stringValue, CultureInfo.InvariantCulture), node.To <DateTimeOffset>());
                Assert.AreEqual(DateTimeOffset.Parse(stringValue, CultureInfo.InvariantCulture), node.To <DateTimeOffset?>());
            }
        }
        public void To_Should_Throw_For_Structs_With_Null(GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode("null", protocol);

            Assert.Throws <InvalidOperationException>(() => node.To <short>());
            Assert.Throws <InvalidOperationException>(() => node.To <int>());
            Assert.Throws <InvalidOperationException>(() => node.To <long>());
            Assert.Throws <InvalidOperationException>(() => node.To <decimal>());
            Assert.Throws <InvalidOperationException>(() => node.To <float>());
            Assert.Throws <InvalidOperationException>(() => node.To <double>());
            Assert.Throws <InvalidOperationException>(() => node.To <Guid>());
            Assert.Throws <InvalidOperationException>(() => node.To <TimeUuid>());
            Assert.Throws <InvalidOperationException>(() => node.To <BigInteger>());
            Assert.Throws <InvalidOperationException>(() => node.To <Duration>());
        }
        public void To_Should_Not_Throw_For_Nullables_With_Null(GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode("null", protocol);

            Assert.IsNull(node.To <short?>());
            Assert.IsNull(node.To <int?>());
            Assert.IsNull(node.To <long?>());
            Assert.IsNull(node.To <decimal?>());
            Assert.IsNull(node.To <float?>());
            Assert.IsNull(node.To <double?>());
            Assert.IsNull(node.To <Guid?>());
            Assert.IsNull(node.To <TimeUuid?>());
            Assert.IsNull(node.To <BigInteger?>());
            Assert.IsNull(node.To <Duration?>());
        }
        public void Get_T_Should_Navigate_Properties_Of_TypedGraphSON_Objects(GraphProtocol protocol)
        {
            const string json = "{\"@type\": \"gex:ObjectTree\", \"@value\": " +
                                "  {" +
                                "    \"prop1\": {\"@type\": \"g:Int32\", \"@value\": 789}," +
                                "    \"prop2\": \"prop2 value\"" +
                                "  }" +
                                "}";
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            Assert.AreEqual(789, node.Get <int>("prop1"));
            Assert.AreEqual("prop2 value", node.Get <string>("prop2"));
            var prop = node.Get <IGraphNode>("prop1");

            Assert.AreEqual(789, prop.To <int>());
            Assert.AreEqual("prop2 value", node.Get <IGraphNode>("prop2").ToString());
        }
        public void Implicit_Conversion_Operators_Test(GraphProtocol protocol)
        {
            var intNode = GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"gx:Int16\", \"@value\": 123}", protocol);

            Assert.AreEqual(123, (int)intNode);
            Assert.AreEqual(123L, (long)intNode);
            Assert.AreEqual((short)123, (short)intNode);
            string stringValue = GraphNodeGraphSONTests.GetGraphNode("\"something\"", protocol);

            Assert.AreEqual("something", stringValue);
            bool boolValue = GraphNodeGraphSONTests.GetGraphNode("true", protocol);

            Assert.True(boolValue);
            var floatNode = GraphNodeGraphSONTests.GetGraphNode("{\"@type\": \"g:Float\", \"@value\": 123.1}", protocol);

            Assert.AreEqual(123.1f, (float)floatNode);
            Assert.AreEqual((double)123.1f, (double)floatNode);
        }
Ejemplo n.º 20
0
 private GraphResultSet(RowSet rs, GraphProtocol protocol, Func <Row, GraphNode> factory)
 {
     _rs           = rs ?? throw new ArgumentNullException(nameof(rs));
     _factory      = factory ?? throw new ArgumentNullException(nameof(factory));
     GraphProtocol = protocol;
 }
Ejemplo n.º 21
0
 public IGraphStatement SetGraphProtocolVersion(GraphProtocol graphProtocol)
 {
     GraphProtocolVersion = graphProtocol;
     return(this);
 }
Ejemplo n.º 22
0
        public async Task Should_Execute_Batch_Of_Traversals_Asynchronously_With_Edges(string graphName, GraphProtocol protocol)
        {
            if (graphName == BaseIntegrationTest.DefaultCoreGraphName &&
                !TestDseVersion.VersionMatch(
                    new Version(6, 8), TestClusterManager.DseVersion, Comparison.GreaterThanOrEqualsTo))
            {
                Assert.Ignore("Test requires DSE 6.8");
            }

            var g = DseGraph.Traversal(Session, new GraphOptions().SetName(graphName));

            if (graphName == BaseIntegrationTest.DefaultCoreGraphName)
            {
                g = g.With("allow-filtering");
            }
            var batch = DseGraph.Batch(new GraphOptions().SetName(graphName).SetWriteConsistencyLevel(ConsistencyLevel.LocalQuorum));

            batch
            .Add(g.AddV("character").Property("name", "Matias").Property("age", 12).Property("tag", "batch2"))
            .Add(g.AddV("character").Property("name", "Olivia").Property("age", 8).Property("tag", "batch2"))
            .Add(g.V().Has("name", "Matias").Has("tag", "batch2").AddE("knows").To(
                     __.V().Has("name", "Olivia").Has("tag", "batch2")));

            var rs = await Session.ExecuteGraphAsync(batch).ConfigureAwait(false);

            Assert.AreEqual(protocol, rs.GraphProtocol);

            var characters = g.V().Has("character", "tag", "batch2").Values <string>("name").ToList();

            CollectionAssert.AreEquivalent(new [] { "Matias", "Olivia" }, characters);

            var knowsOut = g.V().Has("name", "Matias").Has("tag", "batch2")
                           .Out("knows").Values <string>("name").ToList();

            Assert.AreEqual(new [] { "Olivia" }, knowsOut);
        }
Ejemplo n.º 23
0
        private ConvertedStatementResult ConvertGraphStatement(
            IGraphStatement graphStmt, GraphOptions options, GraphProtocol graphProtocol)
        {
            string jsonParams;
            string query;
            IGraphTypeSerializer serializer;

            if (graphStmt is SimpleGraphStatement simpleGraphStatement)
            {
                serializer = _graphTypeSerializerFactory.CreateSerializer(_session, null, null, graphProtocol, true);
                query      = simpleGraphStatement.Query;
                if (simpleGraphStatement.ValuesDictionary != null)
                {
                    jsonParams = serializer.ToDb(simpleGraphStatement.ValuesDictionary);
                }
                else if (simpleGraphStatement.Values != null)
                {
                    jsonParams = serializer.ToDb(Utils.GetValues(simpleGraphStatement.Values));
                }
                else
                {
                    jsonParams = null;
                }
            }
            else if (graphStmt is FluentGraphStatement fluentGraphStatement)
            {
                serializer = _graphTypeSerializerFactory.CreateSerializer(
                    _session,
                    fluentGraphStatement.CustomDeserializers,
                    fluentGraphStatement.CustomSerializers,
                    graphProtocol,
                    fluentGraphStatement.DeserializeGraphNodes);
                query      = serializer.ToDb(fluentGraphStatement.QueryBytecode);
                jsonParams = null;
            }
            else
            {
                throw new NotSupportedException("Statement of type " + graphStmt.GetType().FullName + " not supported");
            }

            IStatement stmt = jsonParams != null
                ? new TargettedSimpleStatement(query, jsonParams)
                : new TargettedSimpleStatement(query);

            //Set Cassandra.Statement properties
            if (graphStmt.Timestamp != null)
            {
                stmt.SetTimestamp(graphStmt.Timestamp.Value);
            }
            var readTimeout = graphStmt.ReadTimeoutMillis != 0 ? graphStmt.ReadTimeoutMillis : options.ReadTimeoutMillis;

            if (readTimeout <= 0)
            {
                // Infinite (-1) is not supported in the core driver, set an arbitrarily large int
                readTimeout = int.MaxValue;
            }

            stmt = stmt
                   .SetIdempotence(false)
                   .SetConsistencyLevel(graphStmt.ConsistencyLevel)
                   .SetReadTimeoutMillis(readTimeout)
                   .SetOutgoingPayload(options.BuildPayload(graphStmt));

            return(new ConvertedStatementResult
            {
                Serializer = serializer,
                Statement = stmt
            });
        }
 public static string GetInternalRepresentation(this GraphProtocol version)
 {
     return(GraphProtocolExtensions.EnumToNameMap[version]);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Sets the graph protocol version to use in graph queries. See <see cref="GraphProtocolVersion"/>.
 /// </summary>
 public GraphOptions SetGraphProtocolVersion(GraphProtocol version)
 {
     _nullableGraphProtocol = version;
     RebuildDefaultPayload();
     return(this);
 }
        public void To_Should_Parse_Blob_Values(string json, string stringValue, GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            CollectionAssert.AreEqual(Encoding.UTF8.GetBytes(stringValue), node.To <byte[]>());
        }
        public void To_Should_Parse_LocalTime_Values(string json, string stringValue, GraphProtocol protocol)
        {
            var node = GraphNodeGraphSONTests.GetGraphNode(json, protocol);

            Assert.AreEqual(LocalTime.Parse(stringValue), node.To <LocalTime>());
        }
Ejemplo n.º 28
0
 internal static GraphResultSet CreateNew(RowSet rs, GraphProtocol protocol, Func <Row, GraphNode> rowParser)
 {
     return(new GraphResultSet(rs, protocol, rowParser));
 }