Ejemplo n.º 1
0
        public void SetupFixture()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.2"), Comparison.LessThan))
            {
                Assert.Ignore("Requires Cassandra version >= 2.2");
                return;
            }

            Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;

            _testCluster = TestClusterManager.CreateNew(1, new TestClusterOptions
            {
                CassandraYaml = new[]
                {
                    "batch_size_warn_threshold_in_kb:5",
                    "batch_size_fail_threshold_in_kb:50"
                },
                //Using a mirroring handler, the server will reply providing the same payload that was sent
                JvmArgs = new[] { "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler" }
            });
            _testCluster.InitClient();
            Session = _testCluster.Session;
            Session.Execute(string.Format(TestUtils.CreateKeyspaceSimpleFormat, Keyspace, 1));
            Session.Execute(string.Format(TestUtils.CreateTableSimpleFormat, Table));
        }
Ejemplo n.º 2
0
        public void Fetch_WithConsistencyLevel_Invalids_OnlySupportedForWrites()
        {
            Table <Author> table = new Table <Author>(_session, new MappingConfiguration());

            table.Create();
            int totalInserts = 10;

            var           mapper          = new Mapper(_session, new MappingConfiguration().Define(new FluentUserMapping()));
            List <Author> expectedAuthors = Author.GetRandomList(totalInserts);

            foreach (Author expectedAuthor in expectedAuthors)
            {
                mapper.Insert(expectedAuthor);
            }

            Cql cql = new Cql("SELECT * from " + table.Name).WithOptions(c => c.SetConsistencyLevel(ConsistencyLevel.Any));
            var err = Assert.Throws <InvalidQueryException>(() => mapper.Fetch <Author>(cql).ToList());

            Assert.AreEqual("ANY ConsistencyLevel is only supported for writes", err.Message);

            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("3.0"), Comparison.LessThan))
            {
                cql = new Cql("SELECT * from " + table.Name).WithOptions(c => c.SetConsistencyLevel(ConsistencyLevel.EachQuorum));
                err = Assert.Throws <InvalidQueryException>(() => mapper.Fetch <Author>(cql).ToList());
                Assert.AreEqual("EACH_QUORUM ConsistencyLevel is only supported for writes", err.Message);
            }
        }
        public void ColumnClusteringOrderReversedTest(bool metadataSync)
        {
            if (TestClusterManager.CheckCassandraVersion(false, new Version(4, 0), Comparison.GreaterThanOrEqualsTo))
            {
                Assert.Ignore("Compact table test designed for C* 3.0");
                return;
            }
            var keyspaceName = TestUtils.GetUniqueKeyspaceName();
            var tableName    = TestUtils.GetUniqueTableName().ToLower();
            var cluster      = GetNewTemporaryCluster(builder => builder.WithMetadataSyncOptions(new MetadataSyncOptions().SetMetadataSyncEnabled(metadataSync)));
            var session      = cluster.Connect();

            session.CreateKeyspace(keyspaceName);
            session.ChangeKeyspace(keyspaceName);

            var cql = "CREATE TABLE " + tableName + " (" +
                      @"id int,
                      description text,
                      price double,
                      PRIMARY KEY(id, description, price)
                      ) WITH COMPACT STORAGE
                      AND CLUSTERING ORDER BY (description ASC, price DESC)";

            session.Execute(cql);

            var tableMeta = cluster.Metadata.GetKeyspace(keyspaceName).GetTableMetadata(tableName);

            Assert.AreEqual(new[] { "description", "price" }, tableMeta.ClusteringKeys.Select(c => c.Item1.Name));
            Assert.AreEqual(new[] { SortOrder.Ascending, SortOrder.Descending }, tableMeta.ClusteringKeys.Select(c => c.Item2));
        }
 public SchemaMetadataTests() :
     base(1, true, new TestClusterOptions
 {
     CassandraYaml =
         TestClusterManager.CheckCassandraVersion(true, new Version(4, 0), Comparison.GreaterThanOrEqualsTo)
                 ? new[] { "enable_materialized_views: true" } : new string[0]
 })
 {
 }
Ejemplo n.º 5
0
        public void Parallel_Insert_And_Select_Sync_With_Nodes_Failing()
        {
            var testCluster = TestClusterManager.GetNonShareableTestCluster(3, 1, true, false);

            using (var cluster = ClusterBuilder()
                                 .WithRetryPolicy(AlwaysRetryRetryPolicy.Instance)
                                 .AddContactPoint(testCluster.InitialContactPoint)
                                 .Build())
            {
                var session      = cluster.Connect();
                var uniqueKsName = "keyspace_" + Randomm.RandomAlphaNum(10);
                session.Execute(@"CREATE KEYSPACE " + uniqueKsName +
                                " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};");
                session.ChangeKeyspace(uniqueKsName);

                var tableName = "table_" + Guid.NewGuid().ToString("N").ToLower();
                session.Execute(string.Format(TestUtils.CREATE_TABLE_TIME_SERIES, tableName));

                var insertQuery         = string.Format("INSERT INTO {0} (id, event_time, text_sample) VALUES (?, ?, ?)", tableName);
                var insertQueryPrepared = session.Prepare(insertQuery);
                var selectQuery         = string.Format("SELECT * FROM {0} LIMIT 10000", tableName);

                const int rowsPerId            = 100;
                object    insertQueryStatement = new SimpleStatement(insertQuery);
                if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 0), Comparison.LessThan))
                {
                    //Use prepared statements all the way as it is not possible to bind on a simple statement with C* 1.2
                    insertQueryStatement = session.Prepare(insertQuery);
                }
                var actionInsert         = GetInsertAction(session, insertQueryStatement, ConsistencyLevel.Quorum, rowsPerId);
                var actionInsertPrepared = GetInsertAction(session, insertQueryPrepared, ConsistencyLevel.Quorum, rowsPerId);
                var actionSelect         = GetSelectAction(session, selectQuery, ConsistencyLevel.Quorum, 10);

                //Execute insert sync to have some records
                actionInsert();
                //Execute select sync to assert that everything is going OK
                actionSelect();

                var actions = new List <Action>();
                for (var i = 0; i < 10; i++)
                {
                    //Add 10 actions to execute
                    actions.AddRange(new[] { actionInsert, actionSelect, actionInsertPrepared });
                    actions.AddRange(new[] { actionSelect, actionInsert, actionInsertPrepared, actionInsert });
                    actions.AddRange(new[] { actionInsertPrepared, actionInsertPrepared, actionSelect });
                }

                actions.Insert(8, () =>
                {
                    Thread.Sleep(300);
                    testCluster.StopForce(2);
                });
                TestHelper.ParallelInvoke(actions.ToArray());
            }
        }
Ejemplo n.º 6
0
        public void Insert_WithMapperInsert_TwoPartitionKeys_OnlyOne()
        {
            // Setup
            var mappingConfig = new MappingConfiguration().Define(new Map <ClassWithTwoPartitionKeys>()
                                                                  .TableName(typeof(ClassWithTwoPartitionKeys).Name).CaseSensitive()
                                                                  .PartitionKey(new string[] { "PartitionKey1", "PartitionKey2" }).CaseSensitive()
                                                                  );
            var table = new Table <ClassWithTwoPartitionKeys>(_session, mappingConfig);

            table.Create();

            // Insert the data
            ClassWithTwoPartitionKeys defaultInstance = new ClassWithTwoPartitionKeys();
            ClassWithTwoPartitionKeys instance        = new ClassWithTwoPartitionKeys();
            var mapper = new Mapper(_session, mappingConfig);

            mapper.Insert(instance);

            List <ClassWithTwoPartitionKeys> instancesRetrieved = new List <ClassWithTwoPartitionKeys>();
            DateTime futureDateTime = DateTime.Now.AddSeconds(5);

            while (instancesRetrieved.Count < 1 && DateTime.Now < futureDateTime)
            {
                instancesRetrieved = mapper.Fetch <ClassWithTwoPartitionKeys>("SELECT * from \"" + table.Name + "\"").ToList();
            }
            Assert.AreEqual(1, instancesRetrieved.Count);
            Assert.AreEqual(defaultInstance.PartitionKey1, instancesRetrieved[0].PartitionKey1);
            Assert.AreEqual(defaultInstance.PartitionKey2, instancesRetrieved[0].PartitionKey2);
            instancesRetrieved.Clear();

            futureDateTime = DateTime.Now.AddSeconds(5);
            string cqlSelect = "SELECT * from \"" + table.Name + "\" where \"PartitionKey1\" = '" + instance.PartitionKey1 + "' and \"PartitionKey2\" = '" + instance.PartitionKey2 + "'";

            while (instancesRetrieved.Count < 1 && DateTime.Now < futureDateTime)
            {
                instancesRetrieved = mapper.Fetch <ClassWithTwoPartitionKeys>(cqlSelect).ToList();
            }
            Assert.AreEqual(1, instancesRetrieved.Count);
            Assert.AreEqual(defaultInstance.PartitionKey1, instancesRetrieved[0].PartitionKey1);
            Assert.AreEqual(defaultInstance.PartitionKey2, instancesRetrieved[0].PartitionKey2);

            var    err            = Assert.Throws <InvalidQueryException>(() => mapper.Fetch <ClassWithTwoPartitionKeys>("SELECT * from \"" + table.Name + "\" where \"PartitionKey1\" = '" + instance.PartitionKey1 + "'"));
            string expectedErrMsg = "Partition key part(s:)? PartitionKey2 must be restricted (since preceding part is|as other parts are)";

            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("3.10"), Comparison.GreaterThanOrEqualsTo))
            {
                expectedErrMsg = "Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING";
            }
            StringAssert.IsMatch(expectedErrMsg, err.Message);

            Assert.Throws <InvalidQueryException>(() => mapper.Fetch <ClassWithTwoPartitionKeys>("SELECT * from \"" + table.Name + "\" where \"PartitionKey2\" = '" + instance.PartitionKey2 + "'"));
        }
Ejemplo n.º 7
0
 public void Should_Use_Maximum_Protocol_Version_Provided()
 {
     var version = ProtocolVersion.V2;
     if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("3.0"), Comparison.GreaterThanOrEqualsTo))
     {
         //protocol 2 is not supported in Cassandra 3.0+
         version = ProtocolVersion.V3;
     }
     var cc = NewInstance(version);
     cc.InitAsync().Wait(InitTimeout);
     Assert.AreEqual(version, cc.ProtocolVersion);
     cc.Dispose();
 }
Ejemplo n.º 8
0
        public override void OneTimeSetUp()
        {
            base.OneTimeSetUp();
            var insertQuery = $"INSERT INTO {AllTypesTableName} (id, timeuuid_sample) VALUES (?, ?)";
            var selectQuery = $"SELECT id, timeuuid_sample, dateOf(timeuuid_sample) FROM {AllTypesTableName} WHERE id = ?";

            if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 2), Comparison.GreaterThanOrEqualsTo))
            {
                selectQuery =
                    $"SELECT id, timeuuid_sample, toTimestamp(timeuuid_sample) as timeuuid_date_value FROM {AllTypesTableName} WHERE id = ?";
            }
            _insertPrepared = Session.Prepare(insertQuery);
            _selectPrepared = Session.Prepare(selectQuery);
        }
Ejemplo n.º 9
0
        public override void OneTimeSetUp()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1.0"), Comparison.LessThan))
            {
                Assert.Ignore("Requires Cassandra version >= 2.1");
            }

            base.OneTimeSetUp();

            Session.Execute(UdtMappingsTests.CqlType1);
            Session.Execute(UdtMappingsTests.CqlType2);
            Session.Execute(UdtMappingsTests.CqlTable1);
            Session.Execute(UdtMappingsTests.CqlTable2);
        }
Ejemplo n.º 10
0
        public void Register_For_Events()
        {
            var eventHandle = new AutoResetEvent(false);
            CassandraEventArgs eventArgs = null;

            using (var connection = CreateConnection())
            {
                connection.Open().Wait();
                Query(connection, String.Format("DROP KEYSPACE IF EXISTS test_events_kp", 1)).Wait();
                var eventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange;
                var task       = connection.Send(new RegisterForEventRequest(eventTypes));
                TaskHelper.WaitToComplete(task, 1000);
                Assert.IsInstanceOf <ReadyResponse>(task.Result);
                connection.CassandraEventResponse += (o, e) =>
                {
                    eventArgs = e;
                    eventHandle.Set();
                };
                //create a keyspace and check if gets received as an event
                Query(connection, String.Format(TestUtils.CreateKeyspaceSimpleFormat, "test_events_kp", 1)).Wait(1000);
                eventHandle.WaitOne(2000);
                Assert.IsNotNull(eventArgs);
                Assert.IsInstanceOf <SchemaChangeEventArgs>(eventArgs);
                Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
                Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
                Assert.That((eventArgs as SchemaChangeEventArgs).Table, Is.Null.Or.Empty);

                //create a table and check if gets received as an event
                Query(connection, String.Format(TestUtils.CreateTableAllTypes, "test_events_kp.test_table", 1)).Wait(1000);
                eventHandle.WaitOne(2000);
                Assert.IsNotNull(eventArgs);
                Assert.IsInstanceOf <SchemaChangeEventArgs>(eventArgs);

                Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
                Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
                Assert.AreEqual("test_table", (eventArgs as SchemaChangeEventArgs).Table);

                if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1"), Comparison.GreaterThanOrEqualsTo))
                {
                    Query(connection, "CREATE TYPE test_events_kp.test_type (street text, city text, zip int);").Wait(1000);
                    eventHandle.WaitOne(2000);
                    Assert.IsNotNull(eventArgs);
                    Assert.IsInstanceOf <SchemaChangeEventArgs>(eventArgs);
                    Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
                    Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
                    Assert.AreEqual("test_type", (eventArgs as SchemaChangeEventArgs).Type);
                }
            }
        }
Ejemplo n.º 11
0
        public void SetupFixture()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.2.0"), Comparison.LessThan))
            {
                Assert.Ignore("Requires Cassandra version >= 2.2");
                return;
            }

            Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;
            //Using a mirroring handler, the server will reply providing the same payload that was sent
            var jvmArgs     = new [] { "-Dcassandra.custom_query_handler_class=org.apache.cassandra.cql3.CustomPayloadMirroringQueryHandler" };
            var testCluster = TestClusterManager.GetTestCluster(1, 0, false, DefaultMaxClusterCreateRetries, true, true, 0, jvmArgs);

            Session = testCluster.Session;
            Session.Execute(string.Format(TestUtils.CreateKeyspaceSimpleFormat, Keyspace, 1));
            Session.Execute(string.Format(TestUtils.CreateTableSimpleFormat, Table));
        }
Ejemplo n.º 12
0
        public void TestFixtureSetup()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.2"), Comparison.LessThan))
            {
                return;
            }
            _testCluster = TestClusterManager.GetTestCluster(1, 0, false, DefaultMaxClusterCreateRetries, false, false);
            _testCluster.UpdateConfig("enable_user_defined_functions: true");
            _testCluster.Start(1);
            using (var cluster = ClusterBuilder().AddContactPoint(_testCluster.InitialContactPoint).Build())
            {
                var session = cluster.Connect();
                var queries = new List <string>
                {
                    "CREATE KEYSPACE  ks_udf WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}",
                    "CREATE FUNCTION  ks_udf.return_one() RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return 1;'",
                    "CREATE FUNCTION  ks_udf.plus(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return s+v;'",
                    "CREATE FUNCTION  ks_udf.plus(s bigint, v bigint) RETURNS NULL ON NULL INPUT RETURNS bigint LANGUAGE java AS 'return s+v;'",
                    "CREATE AGGREGATE ks_udf.sum(int) SFUNC plus STYPE int INITCOND 1",
                    "CREATE AGGREGATE ks_udf.sum(bigint) SFUNC plus STYPE bigint INITCOND 2"
                };

                if (TestClusterManager.CheckDseVersion(new Version(6, 0), Comparison.GreaterThanOrEqualsTo))
                {
                    queries.Add("CREATE FUNCTION ks_udf.deterministic(dividend int, divisor int) " +
                                "CALLED ON NULL INPUT RETURNS int DETERMINISTIC LANGUAGE java AS " +
                                "'return dividend / divisor;'");
                    queries.Add("CREATE FUNCTION ks_udf.monotonic(dividend int, divisor int) " +
                                "CALLED ON NULL INPUT RETURNS int MONOTONIC LANGUAGE java AS " +
                                "'return dividend / divisor;'");
                    queries.Add("CREATE FUNCTION ks_udf.md(dividend int, divisor int) " +
                                "CALLED ON NULL INPUT RETURNS int DETERMINISTIC MONOTONIC LANGUAGE java AS " +
                                "'return dividend / divisor;'");
                    queries.Add("CREATE FUNCTION ks_udf.monotonic_on(dividend int, divisor int) " +
                                "CALLED ON NULL INPUT RETURNS int MONOTONIC ON dividend LANGUAGE java AS " +
                                "'return dividend / divisor;'");
                    queries.Add("CREATE AGGREGATE ks_udf.deta(int) SFUNC plus STYPE int INITCOND 0 DETERMINISTIC;");
                }

                foreach (var q in queries)
                {
                    session.Execute(q);
                }
            }
        }
Ejemplo n.º 13
0
        public async Task Cluster_Should_Honor_MaxProtocolVersion_Set(bool asyncConnect)
        {
            _testCluster = SimulacronCluster.CreateNew(2);

            // Default MaxProtocolVersion
            using (var clusterDefault = Cluster.Builder()
                                        .AddContactPoint(_testCluster.InitialContactPoint)
                                        .Build())
            {
                Assert.AreEqual(Cluster.MaxProtocolVersion, clusterDefault.Configuration.ProtocolOptions.MaxProtocolVersion);

                // MaxProtocolVersion set
                var clusterMax = Cluster.Builder()
                                 .AddContactPoint(_testCluster.InitialContactPoint)
                                 .WithMaxProtocolVersion(3)
                                 .Build();
                Assert.AreEqual(3, clusterMax.Configuration.ProtocolOptions.MaxProtocolVersion);
                await Connect(clusterMax, asyncConnect, session =>
                {
                    if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1"), Comparison.LessThan))
                    {
                        Assert.AreEqual(2, session.BinaryProtocolVersion);
                    }
                    else
                    {
                        Assert.AreEqual(3, session.BinaryProtocolVersion);
                    }
                }).ConfigureAwait(false);

                // Arbitary MaxProtocolVersion set, will negotiate down upon connect
                var clusterNegotiate = Cluster.Builder()
                                       .AddContactPoint(_testCluster.InitialContactPoint)
                                       .WithMaxProtocolVersion(10)
                                       .Build();
                Assert.AreEqual(10, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion);
                await Connect(clusterNegotiate, asyncConnect, session =>
                {
                    Assert.LessOrEqual(4, clusterNegotiate.Configuration.ProtocolOptions.MaxProtocolVersion);
                }).ConfigureAwait(false);

                // ProtocolVersion 0 does not exist
                Assert.Throws <ArgumentException>(
                    () => Cluster.Builder().AddContactPoint("127.0.0.1").WithMaxProtocolVersion((byte)0));
            }
        }
        public void SimpleStatement_With_No_Compact_Disabled_Should_Not_Reveal_Non_Schema_Columns()
        {
            if (TestClusterManager.CheckCassandraVersion(false, new Version(4, 0), Comparison.GreaterThanOrEqualsTo))
            {
                Assert.Ignore("COMPACT STORAGE is only supported by C* versions prior to 4.0");
                return;
            }

            var builder = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint);

            using (var cluster = builder.Build())
            {
                var session = cluster.Connect(KeyspaceName);
                var rs      = session.Execute($"SELECT * FROM {TableCompactStorage} LIMIT 1");
                Assert.AreEqual(3, rs.Columns.Length);
                Assert.Null(rs.Columns.FirstOrDefault(c => c.Name == "column1"));
                Assert.Null(rs.Columns.FirstOrDefault(c => c.Name == "value"));
            }
        }
Ejemplo n.º 15
0
        public void Insert_MislabledClusteringKey()
        {
            string tableName      = typeof(PocoWithAdditionalField).Name.ToLower();
            string createTableCql = "Create table " + tableName + "(somestring text PRIMARY KEY)";

            _session.Execute(createTableCql);
            var cqlClient = new Mapper(_session, new MappingConfiguration());
            PocoWithAdditionalField pocoWithCustomAttributes = new PocoWithAdditionalField();

            // Validate expected exception
            var ex = Assert.Throws <InvalidQueryException>(() => cqlClient.Insert(pocoWithCustomAttributes));
            var expectedMessage = "Unknown identifier someotherstring";

            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("3.10"), Comparison.GreaterThanOrEqualsTo))
            {
                expectedMessage = "Undefined column name someotherstring";
            }
            StringAssert.Contains(expectedMessage, ex.Message);
        }
Ejemplo n.º 16
0
        public void TableMetadataCassandra22Types()
        {
            if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 2), Comparison.LessThan))
            {
                Assert.Ignore("Date, Time, SmallInt and TinyInt are supported in 2.2 and above");
            }
            var          keyspaceName = TestUtils.GetUniqueKeyspaceName();
            const string tableName    = "tbl_cass22_types";
            ITestCluster testCluster  = TestClusterManager.GetNonShareableTestCluster(DefaultNodeCount);
            var          cluster      = testCluster.Cluster;
            var          session      = testCluster.Session;

            session.CreateKeyspaceIfNotExists(keyspaceName);
            session.ChangeKeyspace(keyspaceName);

            session.Execute(string.Format("CREATE TABLE {0} (" +
                                          "id uuid primary key, " +
                                          "map1 map<smallint, date>," +
                                          "s smallint," +
                                          "b tinyint," +
                                          "d date," +
                                          "t time)", tableName));
            var table = cluster.Metadata
                        .GetKeyspace(keyspaceName)
                        .GetTableMetadata(tableName);

            Assert.AreEqual(6, table.TableColumns.Length);
            CollectionAssert.AreEqual(table.PartitionKeys, new[] { table.TableColumns.First(c => c.Name == "id") });
            var map1 = table.TableColumns.First(c => c.Name == "map1");

            Assert.AreEqual(ColumnTypeCode.Map, map1.TypeCode);
            Assert.IsInstanceOf <MapColumnInfo>(map1.TypeInfo);
            var map1Info = (MapColumnInfo)map1.TypeInfo;

            Assert.AreEqual(ColumnTypeCode.SmallInt, map1Info.KeyTypeCode);
            Assert.AreEqual(ColumnTypeCode.Date, map1Info.ValueTypeCode);

            Assert.AreEqual(ColumnTypeCode.SmallInt, table.TableColumns.First(c => c.Name == "s").TypeCode);
            Assert.AreEqual(ColumnTypeCode.TinyInt, table.TableColumns.First(c => c.Name == "b").TypeCode);
            Assert.AreEqual(ColumnTypeCode.Date, table.TableColumns.First(c => c.Name == "d").TypeCode);
            Assert.AreEqual(ColumnTypeCode.Time, table.TableColumns.First(c => c.Name == "t").TypeCode);
        }
Ejemplo n.º 17
0
        public void Insert_TableNameLowerCase_PartitionKeyCamelCase()
        {
            // Setup
            var mappingConfig = new MappingConfiguration().Define(new Map <lowercaseclassnamepkcamelcase>().PartitionKey(c => c.SomePartitionKey));
            Table <lowercaseclassnamepkcamelcase> table = new Table <lowercaseclassnamepkcamelcase>(_session, mappingConfig);

            Assert.AreEqual(table.Name, table.Name.ToLower());
            table.Create();
            var mapper = new Mapper(_session, new MappingConfiguration());
            lowercaseclassnamepkcamelcase privateClassInstance = new lowercaseclassnamepkcamelcase();

            // Validate state of table
            mapper.Insert(privateClassInstance);
            List <lowercaseclassnamepkcamelcase> instancesQueried = mapper.Fetch <lowercaseclassnamepkcamelcase>("SELECT * from " + table.Name).ToList();

            Assert.AreEqual(1, instancesQueried.Count);
            lowercaseclassnamepkcamelcase defaultPocoInstance = new lowercaseclassnamepkcamelcase();

            Assert.AreEqual(defaultPocoInstance.SomePartitionKey, instancesQueried[0].SomePartitionKey);

            // Attempt to select from Camel Case partition key
            string cqlCamelCasePartitionKey = "SELECT * from " + typeof(lowercaseclassnamepkcamelcase).Name + " where \"SomePartitionKey\" = 'doesntmatter'";
            var    ex             = Assert.Throws <InvalidQueryException>(() => _session.Execute(cqlCamelCasePartitionKey));
            var    expectedErrMsg = "Undefined name SomePartitionKey in where clause";

            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("3.10"), Comparison.GreaterThanOrEqualsTo))
            {
                expectedErrMsg = "Undefined column name \"SomePartitionKey\"";
            }
            StringAssert.Contains(expectedErrMsg, ex.Message);

            // Validate that select on lower case key does not fail
            string     cqlLowerCasePartitionKey = "SELECT * from " + typeof(lowercaseclassnamepkcamelcase).Name + " where \"somepartitionkey\" = '" + defaultPocoInstance.SomePartitionKey + "'";
            List <Row> rows = _session.Execute(cqlLowerCasePartitionKey).GetRows().ToList();

            Assert.AreEqual(1, rows.Count);
            Assert.AreEqual(defaultPocoInstance.SomePartitionKey, rows[0].GetValue <string>("somepartitionkey"));
        }
Ejemplo n.º 18
0
        public void Register_For_Events()
        {
            var receivedEvents = new CopyOnWriteList <CassandraEventArgs>();

            using (var connection = CreateConnection())
            {
                connection.Open().Wait();
                Query(connection, string.Format("DROP KEYSPACE IF EXISTS test_events_kp", 1)).Wait();
                var eventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange;
                var task       = connection.Send(new RegisterForEventRequest(eventTypes));
                TaskHelper.WaitToComplete(task, 1000);
                Assert.IsInstanceOf <ReadyResponse>(task.Result);
                connection.CassandraEventResponse += (o, e) =>
                {
                    receivedEvents.Add(e);
                };
                //create a keyspace and check if gets received as an event
                Query(connection, string.Format(TestUtils.CreateKeyspaceSimpleFormat, "test_events_kp", 1)).Wait(1000);

                TestHelper.RetryAssert(
                    () =>
                {
                    Assert.Greater(receivedEvents.Count, 0);
                    var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                    var createdEvent = evs.SingleOrDefault(
                        e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                        string.IsNullOrEmpty(e.Table));
                    Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                },
                    100,
                    50);

                //create a table and check if gets received as an event
                Query(connection, string.Format(TestUtils.CreateTableAllTypes, "test_events_kp.test_table", 1)).Wait(1000);
                TestHelper.RetryAssert(
                    () =>
                {
                    Assert.Greater(receivedEvents.Count, 0);
                    var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                    var createdEvent = evs.SingleOrDefault(
                        e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                        e.Table == "test_table");
                    Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                },
                    100,
                    50);

                if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1"), Comparison.GreaterThanOrEqualsTo))
                {
                    Query(connection, "CREATE TYPE test_events_kp.test_type (street text, city text, zip int);").Wait(1000);
                    TestHelper.RetryAssert(
                        () =>
                    {
                        Assert.Greater(receivedEvents.Count, 0);
                        var evs          = receivedEvents.Select(e => e as SchemaChangeEventArgs).Where(e => e != null);
                        var createdEvent = evs.SingleOrDefault(
                            e => e.What == SchemaChangeEventArgs.Reason.Created && e.Keyspace == "test_events_kp" &&
                            e.Type == "test_type");
                        Assert.IsNotNull(createdEvent, JsonConvert.SerializeObject(receivedEvents.ToArray()));
                    },
                        100,
                        50);
                }
            }
        }
Ejemplo n.º 19
0
        public void TableMetadataNestedCollectionsTest()
        {
            if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1.3"), Comparison.LessThan))
            {
                Assert.Ignore("Nested frozen collections are supported in 2.1.3 and above");
                return;
            }
            var          keyspaceName = TestUtils.GetUniqueKeyspaceName();
            const string tableName    = "tbl_nested_cols_meta";
            ITestCluster testCluster  = TestClusterManager.GetNonShareableTestCluster(DefaultNodeCount);
            var          cluster      = testCluster.Cluster;
            var          session      = testCluster.Session;

            session.CreateKeyspaceIfNotExists(keyspaceName);
            session.ChangeKeyspace(keyspaceName);

            session.Execute(string.Format("CREATE TABLE {0} (" +
                                          "id uuid primary key, " +
                                          "map1 map<varchar, frozen<list<timeuuid>>>," +
                                          "map2 map<int, frozen<map<uuid, bigint>>>," +
                                          "list1 list<frozen<map<uuid, int>>>)", tableName));
            var table = cluster.Metadata
                        .GetKeyspace(keyspaceName)
                        .GetTableMetadata(tableName);

            Assert.AreEqual(4, table.TableColumns.Length);
            var map1 = table.TableColumns.First(c => c.Name == "map1");

            Assert.AreEqual(ColumnTypeCode.Map, map1.TypeCode);
            Assert.IsInstanceOf <MapColumnInfo>(map1.TypeInfo);
            var map1Info = (MapColumnInfo)map1.TypeInfo;

            Assert.True(map1Info.KeyTypeCode == ColumnTypeCode.Varchar || map1Info.KeyTypeCode == ColumnTypeCode.Text,
                        "Expected {0} but was {1}", ColumnTypeCode.Varchar, map1Info.KeyTypeCode);
            Assert.AreEqual(ColumnTypeCode.List, map1Info.ValueTypeCode);
            Assert.IsInstanceOf <ListColumnInfo>(map1Info.ValueTypeInfo);
            var map1ListInfo = (ListColumnInfo)map1Info.ValueTypeInfo;

            Assert.AreEqual(ColumnTypeCode.Timeuuid, map1ListInfo.ValueTypeCode);

            var map2 = table.TableColumns.First(c => c.Name == "map2");

            Assert.AreEqual(ColumnTypeCode.Map, map2.TypeCode);
            Assert.IsInstanceOf <MapColumnInfo>(map2.TypeInfo);
            var map2Info = (MapColumnInfo)map2.TypeInfo;

            Assert.AreEqual(ColumnTypeCode.Int, map2Info.KeyTypeCode);
            Assert.AreEqual(ColumnTypeCode.Map, map2Info.ValueTypeCode);
            Assert.IsInstanceOf <MapColumnInfo>(map2Info.ValueTypeInfo);
            var map2MapInfo = (MapColumnInfo)map2Info.ValueTypeInfo;

            Assert.AreEqual(ColumnTypeCode.Uuid, map2MapInfo.KeyTypeCode);
            Assert.AreEqual(ColumnTypeCode.Bigint, map2MapInfo.ValueTypeCode);

            var list1 = table.TableColumns.First(c => c.Name == "list1");

            Assert.AreEqual(ColumnTypeCode.List, list1.TypeCode);
            Assert.IsInstanceOf <ListColumnInfo>(list1.TypeInfo);
            var list1Info = (ListColumnInfo)list1.TypeInfo;

            Assert.AreEqual(ColumnTypeCode.Map, list1Info.ValueTypeCode);
            Assert.IsInstanceOf <MapColumnInfo>(list1Info.ValueTypeInfo);
            var list1MapInfo = (MapColumnInfo)list1Info.ValueTypeInfo;

            Assert.AreEqual(ColumnTypeCode.Uuid, list1MapInfo.KeyTypeCode);
            Assert.AreEqual(ColumnTypeCode.Int, list1MapInfo.ValueTypeCode);
        }