Example #1
0
        public void testCounters()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                Session.WaitForSchemaAgreement(QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         incdec counter
         );", tableName)));
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();

            Parallel.For(0, 100,
                         i =>
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format(@"UPDATE {0} SET incdec = incdec {2}  WHERE tweet_id = {1};", tableName,
                                                             tweet_id, (i % 2 == 0 ? "-" : "+") + i));
            });

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(),
                                        new List <object[]> {
                new object[2] {
                    tweet_id, (Int64)50
                }
            });
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
        public void Prepared_SelectOne()
        {
            var tableName = TestUtils.GetUniqueTableName();

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                    CREATE TABLE {0}(
                    tweet_id int PRIMARY KEY,
                    numb double,
                    label text);", tableName));
                TestUtils.WaitForSchemaAgreement(Session.Cluster);
            }
            catch (AlreadyExistsException)
            {
            }

            for (int i = 0; i < 10; i++)
            {
                Session.Execute(string.Format("INSERT INTO {0} (tweet_id, numb, label) VALUES({1}, 0.01,'{2}')", tableName, i, "row" + i));
            }

            var prepSelect = QueryTools.PrepareQuery(Session, string.Format("SELECT * FROM {0} WHERE tweet_id = ?;", tableName));

            var rowId  = 5;
            var result = QueryTools.ExecutePreparedSelectQuery(Session, prepSelect, new object[] { rowId });

            foreach (var row in result)
            {
                Assert.True((string)row.GetValue(typeof(int), "label") == "row" + rowId);
            }
            Assert.True(result.Columns != null);
            Assert.True(result.Columns.Length == 3);
        }
        private void ParameterizedStatement(Type type, bool testAsync = false)
        {
            var tableName             = "table" + Guid.NewGuid().ToString("N").ToLower();
            var cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(type);
            var expectedValues        = new List <object[]>(1);
            var val        = Randomm.RandomVal(type);
            var bindValues = new object[] { Guid.NewGuid(), val };

            expectedValues.Add(bindValues);

            CreateTable(tableName, cassandraDataTypeName);

            var statement = new SimpleStatement(string.Format("INSERT INTO {0} (id, val) VALUES (?, ?)", tableName), bindValues);

            if (testAsync)
            {
                Session.ExecuteAsync(statement).Wait(500);
            }
            else
            {
                Session.Execute(statement);
            }

            // Verify results
            RowSet rs = Session.Execute("SELECT * FROM " + tableName);

            VerifyData(rs, expectedValues);
        }
Example #4
0
        public void insertingSingleValue(Type tp)
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
            string tableName             = "table" + Guid.NewGuid().ToString("N").ToLower();

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         value {1}
         );", tableName, cassandraDataTypeName)));
            }
            catch (AlreadyExistsException)
            {
            }

            var    toInsert = new List <object[]>(1);
            object val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }
            var row1 = new object[2] {
                Guid.NewGuid(), val
            };

            toInsert.Add(row1);

            bool isFloatingPoint = false;

            if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
                                                             row1[1].GetType() == typeof(byte[])
                                                                 ? "0x" + CqlQueryTools.ToHex((byte[])toInsert[0][1])
                                                                 : "'" + toInsert[0][1] + "'"), null);
            }
            // rndm.GetType().GetMethod("Next" + tp.Name).Invoke(rndm, new object[] { })
            else
            {
                if (tp == typeof(Single) || tp == typeof(Double))
                {
                    isFloatingPoint = true;
                }
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id,value) VALUES ({1}, {2});", tableName, toInsert[0][0],
                                                             !isFloatingPoint
                                                                 ? toInsert[0][1]
                                                                 : toInsert[0][1].GetType()
                                                             .GetMethod("ToString", new[] { typeof(string) })
                                                             .Invoke(toInsert[0][1], new object[] { "r" })), null);
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #5
0
        public void TestCounters()
        {
            var tableName = TestUtils.GetUniqueTableName();

            try
            {
                var query = $"CREATE TABLE {tableName}(tweet_id uuid PRIMARY KEY, incdec counter);";
                QueryTools.ExecuteSyncNonQuery(Session, query);
            }
            catch (AlreadyExistsException)
            {
            }

            var tweet_id = Guid.NewGuid();

            Parallel.For(0, 100,
                         i =>
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format(@"UPDATE {0} SET incdec = incdec {2}  WHERE tweet_id = {1};", tableName,
                                                             tweet_id, (i % 2 == 0 ? "-" : "+") + i));
            });

            QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};",
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(),
                                        new List <object[]> {
                new object[2] {
                    tweet_id, (Int64)50
                }
            });
        }
Example #6
0
        public void DecimalWithNegativeScaleTest()
        {
            const string query = "CREATE TABLE decimal_neg_scale(id uuid PRIMARY KEY, value decimal);";

            QueryTools.ExecuteSyncNonQuery(Session, query);

            const string insertQuery       = @"INSERT INTO decimal_neg_scale (id, value) VALUES (?, ?)";
            var          preparedStatement = Session.Prepare(insertQuery);

            const int scale      = -1;
            var       scaleBytes = BitConverter.GetBytes(scale);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(scaleBytes);
            }
            var bytes = new byte[scaleBytes.Length + 1];

            Array.Copy(scaleBytes, bytes, scaleBytes.Length);

            bytes[scaleBytes.Length] = 5;

            var firstRowValues = new object[] { Guid.NewGuid(), bytes };

            Session.Execute(preparedStatement.Bind(firstRowValues));

            var row      = Session.Execute("SELECT * FROM decimal_neg_scale").First();
            var decValue = row.GetValue <decimal>("value");

            Assert.AreEqual(50, decValue);

            const string dropQuery = "DROP TABLE decimal_neg_scale;";

            QueryTools.ExecuteSyncNonQuery(Session, dropQuery);
        }
Example #7
0
        public void BigInsertTest(int RowsNo = 5000)
        {
            string tableName = TestUtils.GetUniqueTableName();

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                     tweet_id uuid,
                     author text,
                     body text,
                     isok boolean,
		             fval float,
		             dval double,
                     PRIMARY KEY(tweet_id))", tableName));
            }
            catch (AlreadyExistsException)
            {
            }

            var longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            for (int i = 0; i < RowsNo; i++)
            {
                longQ.AppendFormat(@"INSERT INTO {0} (
                            tweet_id, author, isok, body, fval, dval)
                    VALUES ({1},'test{2}',{3},'body{2}',{4},{5});",
                                   tableName, Guid.NewGuid(), i, i % 2 == 0 ? "false" : "true", Randomm.Instance.NextSingle(), Randomm.Instance.NextDouble());
            }
            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");
            QueryTools.ExecuteSyncQuery(Session, string.Format(@"SELECT * from {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
Example #8
0
        public void ExceedingCassandraType(Type toExceed, Type toExceedWith, bool sameOutput = true)
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(toExceed);
            string tableName             = TestUtils.GetUniqueTableName();
            var    query = String.Format("CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, label text, number {1});", tableName, cassandraDataTypeName);

            QueryTools.ExecuteSyncNonQuery(Session, query);

            object Minimum = toExceedWith.GetField("MinValue").GetValue(this);
            object Maximum = toExceedWith.GetField("MaxValue").GetValue(this);

            var row1 = new object[3] {
                Guid.NewGuid(), "Minimum", Minimum
            };
            var row2 = new object[3] {
                Guid.NewGuid(), "Maximum", Maximum
            };
            var toInsert_and_Check = new List <object[]>(2)
            {
                row1, row2
            };

            if (toExceedWith == typeof(Double) || toExceedWith == typeof(Single))
            {
                Minimum = Minimum.GetType().GetMethod("ToString", new[] { typeof(string) }).Invoke(Minimum, new object[1] {
                    "r"
                });
                Maximum = Maximum.GetType().GetMethod("ToString", new[] { typeof(string) }).Invoke(Maximum, new object[1] {
                    "r"
                });

                if (!sameOutput) //for ExceedingCassandra_FLOAT() test case
                {
                    toInsert_and_Check[0][2] = Single.NegativeInfinity;
                    toInsert_and_Check[1][2] = Single.PositiveInfinity;
                }
            }

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
                                                             toInsert_and_Check[0][0], toInsert_and_Check[0][1], Minimum), null);
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format("INSERT INTO {0}(tweet_id, label, number) VALUES ({1}, '{2}', {3});", tableName,
                                                             toInsert_and_Check[1][0], toInsert_and_Check[1][1], Maximum), null);
            }
            catch (InvalidQueryException)
            {
                if (!sameOutput && toExceed == typeof(Int32)) //for ExceedingCassandra_INT() test case
                {
                    return;
                }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert_and_Check);
        }
Example #9
0
 private void CreateTable(string tableName)
 {
     Session.WaitForSchemaAgreement(
         QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                                                             id int PRIMARY KEY,
                                                             label text,
                                                             number int
                                                             );", tableName)));
 }
 private void CreateTable(ISession session, string tableName)
 {
     QueryTools.ExecuteSyncNonQuery(session, $@"CREATE TABLE {tableName}(
                                                         id int PRIMARY KEY,
                                                         label text,
                                                         number int
                                                         );");
     TestUtils.WaitForSchemaAgreement(session.Cluster);
 }
Example #11
0
        public void InsertingSingleValue(Type tp)
        {
            var tableName = TestUtils.GetUniqueTableName();

            var toInsert = new List <object[]>(1);
            var val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }

            var row1 = new object[2] {
                Guid.NewGuid(), val
            };

            toInsert.Add(row1);

            var isFloatingPoint = false;

            if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
            {
                var query =
                    $"INSERT INTO {tableName}(tweet_id,value) VALUES (" +
                    $"{toInsert[0][0]}, " +
                    $"{(row1[1].GetType() == typeof(byte[]) ? "0x" + CqlQueryTools.ToHex((byte[]) toInsert[0][1]) : "'" + toInsert[0][1] + "'")}" +
                    ");";
                QueryTools.ExecuteSyncNonQuery(Session, query, null);
                VerifyStatement(QueryType.Query, query, 1);
            }
            else
            {
                if (tp == typeof(Single) || tp == typeof(Double))
                {
                    isFloatingPoint = true;
                }

                var query =
                    $"INSERT INTO {tableName}(tweet_id,value) VALUES (" +
                    $"{toInsert[0][0]}, " +
                    $"{(!isFloatingPoint ? toInsert[0][1] : toInsert[0][1].GetType().GetMethod("ToString", new[] { typeof(string) }).Invoke(toInsert[0][1], new object[] { "r" }))}" +
                    ");";
                QueryTools.ExecuteSyncNonQuery(Session, query, null);
                VerifyStatement(QueryType.Query, query, 1);
            }

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.LocalOne))
                .ThenRowsSuccess(new[] { "tweet_id", "value" }, r => r.WithRow(toInsert[0][0], toInsert[0][1])));

            QueryTools.ExecuteSyncQuery(
                Session, $"SELECT * FROM {tableName};", Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
        }
 private void CreateTable(string tableName, string type)
 {
     try
     {
         QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
                                                                 id uuid PRIMARY KEY,
                                                                 val {1}
                                                                 );", tableName, type));
     }
     catch (AlreadyExistsException)
     {
     }
 }
        private void CreateTwoTableTestEnv(string table1, string table2)
        {
            QueryTools.ExecuteSyncNonQuery(Session, $@"CREATE TABLE {table1} (
                                                                          id int PRIMARY KEY,
                                                                          label text,
                                                                          number int
                                                                          );");

            QueryTools.ExecuteSyncNonQuery(Session, $@"CREATE TABLE {table2} (
                                                                        id int PRIMARY KEY,
                                                                        label text,
                                                                        number int
                                                                        );");
            TestUtils.WaitForSchemaAgreement(Session.Cluster);
        }
Example #14
0
        /// <summary>
        /// Creates a table and inserts a number of records synchronously.
        /// </summary>
        /// <returns>The name of the table</returns>
        private string CreateSimpleTableAndInsert(int rowsInTable)
        {
            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            Session.WaitForSchemaAgreement(QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                CREATE TABLE {0}(
                id uuid PRIMARY KEY,
                label text);", tableName)));
            for (int i = 0; i < rowsInTable; i++)
            {
                Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", Guid.NewGuid(), "LABEL" + i, tableName));
            }

            return(tableName);
        }
Example #15
0
        ////////////////////////////////////
        /// Test Helpers
        ////////////////////////////////////

        /// <summary>
        /// Creates a table and inserts a number of records synchronously.
        /// </summary>
        /// <returns>The name of the table</returns>
        private string CreateSimpleTableAndInsert(int rowsInTable)
        {
            string tableName = TestUtils.GetUniqueTableName();

            QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                CREATE TABLE {0}(
                id uuid PRIMARY KEY,
                label text);", tableName));
            for (int i = 0; i < rowsInTable; i++)
            {
                Session.Execute(string.Format("INSERT INTO {2} (id, label) VALUES({0},'{1}')", Guid.NewGuid(), "LABEL" + i, tableName));
            }

            return(tableName);
        }
Example #16
0
        public void InsertingSingleValue(Type tp)
        {
            var cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
            var tableName             = TestUtils.GetUniqueTableName();

            try
            {
                var query = $@"CREATE TABLE {tableName}(tweet_id uuid PRIMARY KEY, value {cassandraDataTypeName});";
                QueryTools.ExecuteSyncNonQuery(Session, query);
            }
            catch (AlreadyExistsException)
            {
            }

            var toInsert = new List <object[]>(1);
            var val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }
            var row1 = new object[2] {
                Guid.NewGuid(), val
            };

            toInsert.Add(row1);

            var isFloatingPoint = false;

            if (row1[1].GetType() == typeof(string) || row1[1].GetType() == typeof(byte[]))
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               $"INSERT INTO {tableName}(tweet_id,value) VALUES ({toInsert[0][0]}, {(row1[1].GetType() == typeof(byte[]) ? "0x" + CqlQueryTools.ToHex((byte[]) toInsert[0][1]) : "'" + toInsert[0][1] + "'")});", null);
            }
            else
            {
                if (tp == typeof(Single) || tp == typeof(Double))
                {
                    isFloatingPoint = true;
                }
                QueryTools.ExecuteSyncNonQuery(Session,
                                               $"INSERT INTO {tableName}(tweet_id,value) VALUES ({toInsert[0][0]}, {(!isFloatingPoint ? toInsert[0][1] : toInsert[0][1].GetType().GetMethod("ToString", new[] {typeof(string)}).Invoke(toInsert[0][1], new object[] {"r"}))});", null);
            }

            QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};",
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(), toInsert);
        }
Example #17
0
        public void TimestampTest()
        {
            var tableName   = TestUtils.GetUniqueTableName();
            var createQuery = $@"CREATE TABLE {tableName}(tweet_id uuid PRIMARY KEY, ts timestamp);";

            QueryTools.ExecuteSyncNonQuery(Session, createQuery);

            QueryTools.ExecuteSyncNonQuery(Session,
                                           $"INSERT INTO {tableName}(tweet_id,ts) VALUES ({Guid.NewGuid()}, '2011-02-03 04:05+0000');", null);
            QueryTools.ExecuteSyncNonQuery(Session,
                                           $"INSERT INTO {tableName}(tweet_id,ts) VALUES ({Guid.NewGuid()}, '{220898707200000}');", null);
            QueryTools.ExecuteSyncNonQuery(Session, $"INSERT INTO {tableName}(tweet_id,ts) VALUES ({Guid.NewGuid()}, '{0}');",
                                           null);

            QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};",
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
Example #18
0
        /// <summary>
        /// Creates a table with a composite index and inserts a number of records synchronously.
        /// </summary>
        /// <returns>The name of the table</returns>
        private Tuple <string, string> CreateTableWithCompositeIndexAndInsert(ISession session, int rowsInTable)
        {
            var tableName           = TestUtils.GetUniqueTableName();
            var staticClusterKeyStr = "staticClusterKeyStr";

            QueryTools.ExecuteSyncNonQuery(session, $@"
                CREATE TABLE {tableName} (
                id text,
                label text,
                PRIMARY KEY (label, id));");
            for (var i = 0; i < rowsInTable; i++)
            {
                session.Execute(string.Format("INSERT INTO {2} (label, id) VALUES('{0}','{1}')", staticClusterKeyStr, Guid.NewGuid().ToString(), tableName));
            }
            var infoTuple = new Tuple <string, string>(tableName, staticClusterKeyStr);

            return(infoTuple);
        }
        public void massivePreparedStatementTest()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         numb1 double,
         numb2 int
         );", tableName))
                    );
            }
            catch (AlreadyExistsException)
            {
            }
            int numberOfPrepares = 100;

            var values   = new List <object[]>(numberOfPrepares);
            var prepares = new List <PreparedStatement>();

            Parallel.For(0, numberOfPrepares, i =>
            {
                PreparedStatement prep = QueryTools.PrepareQuery(Session,
                                                                 string.Format("INSERT INTO {0}(tweet_id, numb1, numb2) VALUES ({1}, ?, ?);",
                                                                               tableName, Guid.NewGuid()));

                lock (prepares)
                    prepares.Add(prep);
            });

            Parallel.ForEach(prepares,
                             prep =>
            {
                QueryTools.ExecutePreparedQuery(Session, prep,
                                                new object[]
                                                { (double)Randomm.RandomVal(typeof(double)), (int)Randomm.RandomVal(typeof(int)) });
            });

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
Example #20
0
        public void TimestampTest()
        {
            string tableName   = TestUtils.GetUniqueTableName();
            var    createQuery = string.Format(@"CREATE TABLE {0}(tweet_id uuid PRIMARY KEY, ts timestamp);", tableName);

            QueryTools.ExecuteSyncNonQuery(Session, createQuery);

            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         "2011-02-03 04:05+0000"), null);
            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         220898707200000), null);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(), 0),
                                           null);

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
        }
        public void InsertingSingleValuePrepared(Type tp, object value = null)
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(tp);
            string tableName             = "table" + Guid.NewGuid().ToString("N");

            Session.WaitForSchemaAgreement(
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         value {1}
         );", tableName, cassandraDataTypeName))
                );

            var    toInsert = new List <object[]>(1);
            object val      = Randomm.RandomVal(tp);

            if (tp == typeof(string))
            {
                val = "'" + val.ToString().Replace("'", "''") + "'";
            }

            var row1 = new object[2] {
                Guid.NewGuid(), val
            };

            toInsert.Add(row1);

            PreparedStatement prep = QueryTools.PrepareQuery(Session,
                                                             string.Format("INSERT INTO {0}(tweet_id, value) VALUES ({1}, ?);", tableName,
                                                                           toInsert[0][0]));

            if (value == null)
            {
                QueryTools.ExecutePreparedQuery(Session, prep, new object[] { toInsert[0][1] });
            }
            else
            {
                QueryTools.ExecutePreparedQuery(Session, prep, new object[] { value });
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.One, toInsert);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #22
0
        public void TestCounters()
        {
            var tableName = TestUtils.GetUniqueTableName();

            var tweet_id = Guid.NewGuid();

            var tasks = Enumerable.Range(0, 100).Select(i => Task.Factory.StartNew(
                                                            () =>
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               string.Format(@"UPDATE {0} SET incdec = incdec {2}  WHERE tweet_id = {1};", tableName,
                                                             tweet_id, (i % 2 == 0 ? "-" : "+") + i));
            },
                                                            TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler));

            Task.WaitAll(tasks.ToArray());

            var logs = TestCluster.GetQueries(null, QueryType.Query).Where(l => l.Query.StartsWith("UPDATE")).ToList();

            Assert.AreEqual(100, logs.Count);
            foreach (var i in Enumerable.Range(0, 100))
            {
                var query = string.Format(@"UPDATE {0} SET incdec = incdec {2}  WHERE tweet_id = {1};", tableName,
                                          tweet_id, (i % 2 == 0 ? "-" : "+") + i);
                VerifyStatement(logs, query, 1);
            }

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.LocalOne))
                .ThenRowsSuccess(new[] { "tweet_id", "incdec" }, r => r.WithRow(tweet_id, (Int64)50)));

            QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};",
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel(),
                                        new List <object[]> {
                new object[2] {
                    tweet_id, (Int64)50
                }
            });
        }
        public void PreparedSelectOneTest()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"
                        CREATE TABLE {0}(
                        tweet_id int PRIMARY KEY,
                        numb double,
                        label text);", tableName))
                    );
            }
            catch (AlreadyExistsException)
            {
            }

            for (int i = 0; i < 10; i++)
            {
                Session.Execute(string.Format("INSERT INTO {0} (tweet_id, numb, label) VALUES({1}, 0.01,'{2}')", tableName, i, "row" + i));
            }

            PreparedStatement prep_select = QueryTools.PrepareQuery(Session, string.Format("SELECT * FROM {0} WHERE tweet_id = ?;", tableName));

            int rowID  = 5;
            var result = QueryTools.ExecutePreparedSelectQuery(Session, prep_select, new object[1] {
                rowID
            });

            foreach (var row in result)
            {
                Assert.True((string)row.GetValue(typeof(int), "label") == "row" + rowID);
            }
            Assert.True(result.Columns != null);
            Assert.True(result.Columns.Length == 3);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #24
0
        public void TimestampTest()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            Session.WaitForSchemaAgreement(
                QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         ts timestamp
         );", tableName)));

            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         "2011-02-03 04:05+0000"), null);
            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(),
                                                         220898707200000), null);
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("INSERT INTO {0}(tweet_id,ts) VALUES ({1}, '{2}');", tableName, Guid.NewGuid(), 0),
                                           null);

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #25
0
        public void insertingSingleCollectionPrepared(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null)
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";
            string mapSyntax = "";

            object valueCollection = null;

            int Cnt = 10;

            if (CassandraCollectionType == "list" || CassandraCollectionType == "set")
            {
                Type openType = CassandraCollectionType == "list" ? typeof(List <>) : typeof(HashSet <>);
                Type listType = openType.MakeGenericType(TypeOfDataToBeInputed);
                valueCollection = Activator.CreateInstance(listType);
                MethodInfo addM = listType.GetMethod("Add");
                for (int i = 0; i < Cnt; i++)
                {
                    object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed);
                    addM.Invoke(valueCollection, new[] { randomValue });
                }
            }
            else if (CassandraCollectionType == "map")
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                Type openType = typeof(SortedDictionary <,>);
                Type dicType  = openType.MakeGenericType(TypeOfKeyForMap, TypeOfDataToBeInputed);
                valueCollection = Activator.CreateInstance(dicType);
                MethodInfo addM = dicType.GetMethod("Add");
                for (int i = 0; i < Cnt; i++)
                {
RETRY:
                    try
                    {
                        object randomKey   = Randomm.RandomVal(TypeOfKeyForMap);
                        object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed);
                        addM.Invoke(valueCollection, new[] { randomKey, randomValue });
                    }
                    catch
                    {
                        goto RETRY;
                    }
                }
            }

            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         some_collection {1}<{2}{3}>
         );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName))
                    );
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();
            PreparedStatement prepInsert = QueryTools.PrepareQuery(Session,
                                                                   string.Format("INSERT INTO {0}(tweet_id,some_collection) VALUES (?, ?);", tableName));

            Session.Execute(prepInsert.Bind(tweet_id, valueCollection).SetConsistencyLevel(ConsistencyLevel.Quorum));
            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #26
0
        public void insertingSingleCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null)
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";

            string openBracket  = CassandraCollectionType == "list" ? "[" : "{";
            string closeBracket = CassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax    = "";

            object randomValue = Randomm.RandomVal(TypeOfDataToBeInputed);

            if (TypeOfDataToBeInputed == typeof(string))
            {
                randomValue = "'" + randomValue.ToString().Replace("'", "''") + "'";
            }

            string randomKeyValue = string.Empty;

            if (TypeOfKeyForMap != null)
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (TypeOfKeyForMap == typeof(DateTimeOffset))
                {
                    randomKeyValue = "'" +
                                     (Randomm.RandomVal(typeof(DateTimeOffset))
                                      .GetType()
                                      .GetMethod("ToString", new[] { typeof(string) })
                                      .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] {
                        "yyyy-MM-dd H:mm:sszz00"
                    }) + "'");
                }
                else if (TypeOfKeyForMap == typeof(string))
                {
                    randomKeyValue = "'" + Randomm.RandomVal(TypeOfDataToBeInputed).ToString().Replace("'", "''") + "'";
                }
                else
                {
                    randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed).ToString();
                }
            }

            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         some_collection {1}<{2}{3}>
         );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName))
                    );
            }
            catch (AlreadyExistsException)
            {
            }

            Guid tweet_id = Guid.NewGuid();


            QueryTools.ExecuteSyncNonQuery(Session,
                                           string.Format("INSERT INTO {0}(tweet_id,some_collection) VALUES ({1}, {2});", tableName, tweet_id,
                                                         openBracket + randomKeyValue + (string.IsNullOrEmpty(randomKeyValue) ? "" : " : ") +
                                                         randomValue + closeBracket));

            var longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            int    CollectionElementsNo = 100;
            object rval = Randomm.RandomVal(TypeOfDataToBeInputed);

            for (int i = 0; i < CollectionElementsNo; i++)
            {
                object val = rval;
                if (TypeOfDataToBeInputed == typeof(string))
                {
                    val = "'" + val.ToString().Replace("'", "''") + "'";
                }

                longQ.AppendFormat(@"UPDATE {0} SET some_collection = some_collection + {1} WHERE tweet_id = {2};"
                                   , tableName,
                                   openBracket + randomKeyValue + (string.IsNullOrEmpty(randomKeyValue) ? "" : " : ") + val + closeBracket, tweet_id);
            }
            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #27
0
 private void DropTable(string tableName)
 {
     QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"DROP TABLE {0};", tableName));
 }
Example #28
0
        public void checkingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null,
                                              string pendingMode = "")
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";

            string openBracket  = CassandraCollectionType == "list" ? "[" : "{";
            string closeBracket = CassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax    = "";

            string randomKeyValue = string.Empty;

            if (TypeOfKeyForMap != null)
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (TypeOfKeyForMap == typeof(DateTimeOffset))
                {
                    randomKeyValue =
                        Randomm.RandomVal(typeof(DateTimeOffset))
                        .GetType()
                        .GetMethod("ToString", new[] { typeof(string) })
                        .Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] {
                        "yyyy-MM-dd H:mm:sszz00"
                    }) + "' : '";
                }
                else
                {
                    randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed) + "' : '";
                }
            }


            string tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         some_collection {1}<{2}{3}>
         );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName)));
            }
            catch (AlreadyExistsException)
            {
            }
            Guid tweet_id = Guid.NewGuid();

            var longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            int CollectionElementsNo = 100;
            var orderedAsInputed     = new List <Int32>(CollectionElementsNo);

            string inputSide = "some_collection + {1}";

            if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                inputSide = "{1} + some_collection";
            }

            for (int i = 0; i < CollectionElementsNo; i++)
            {
                int data = i * (i % 2);
                longQ.AppendFormat(@"UPDATE {0} SET some_collection = " + inputSide + " WHERE tweet_id = {2};"
                                   , tableName, openBracket + randomKeyValue + data + closeBracket, tweet_id);
                orderedAsInputed.Add(data);
            }

            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            if (CassandraCollectionType == "set")
            {
                orderedAsInputed.Sort();
                orderedAsInputed.RemoveRange(0, orderedAsInputed.LastIndexOf(0));
            }
            else if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                orderedAsInputed.Reverse();
            }

            var rs = Session.Execute(string.Format("SELECT * FROM {0};", tableName),
                                     Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());

            {
                int ind = 0;
                foreach (Row row in rs.GetRows())
                {
                    foreach (object value in row[1] as IEnumerable)
                    {
                        Assert.True(orderedAsInputed[ind] == (int)value);
                        ind++;
                    }
                }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName),
                                        Session.Cluster.Configuration.QueryOptions.GetConsistencyLevel());
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #29
0
        private void CheckPureMetadata(string tableName = null, string keyspaceName = null, TableOptions tableOptions = null)
        {
            var columns = new Dictionary
                          <string, ColumnTypeCode>
            {
                { "q0uuid", ColumnTypeCode.Uuid },
                { "q1timestamp", ColumnTypeCode.Timestamp },
                { "q2double", ColumnTypeCode.Double },
                { "q3int32", ColumnTypeCode.Int },
                { "q4int64", ColumnTypeCode.Bigint },
                { "q5float", ColumnTypeCode.Float },
                { "q6inet", ColumnTypeCode.Inet },
                { "q7boolean", ColumnTypeCode.Boolean },
                { "q8inet", ColumnTypeCode.Inet },
                { "q9blob", ColumnTypeCode.Blob },
                { "q10varint", ColumnTypeCode.Varint },
                { "q11decimal", ColumnTypeCode.Decimal },
                { "q12list", ColumnTypeCode.List },
                { "q13set", ColumnTypeCode.Set },
                { "q14map", ColumnTypeCode.Map }
                //{"q12counter", Metadata.ColumnTypeCode.Counter}, A table that contains a counter can only contain counters
            };

            tableName = tableName ?? "table" + Guid.NewGuid().ToString("N");
            var sb = new StringBuilder(@"CREATE TABLE " + tableName + " (");

            foreach (KeyValuePair <string, ColumnTypeCode> col in columns)
            {
                sb.Append(col.Key + " " + col.Value +
                          (((col.Value == ColumnTypeCode.List) ||
                            (col.Value == ColumnTypeCode.Set) ||
                            (col.Value == ColumnTypeCode.Map))
                               ? "<int" + (col.Value == ColumnTypeCode.Map ? ",varchar>" : ">")
                               : "") + ", ");
            }

            sb.Append("PRIMARY KEY(");
            int rowKeys = Randomm.Instance.Next(1, columns.Count - 3);

            for (int i = 0; i < rowKeys; i++)
            {
                sb.Append(columns.Keys.First(key => key.StartsWith("q" + i.ToString(CultureInfo.InvariantCulture))) + ((i == rowKeys - 1) ? "" : ", "));
            }

            string opt = tableOptions != null ? " WITH " + tableOptions : "";

            sb.Append("))" + opt + ";");

            Session.WaitForSchemaAgreement(
                QueryTools.ExecuteSyncNonQuery(Session, sb.ToString())
                );

            var table = Cluster.Metadata.GetTable(keyspaceName ?? Keyspace, tableName);

            Assert.AreEqual(tableName, table.Name);
            foreach (TableColumn metaCol in table.TableColumns)
            {
                Assert.True(columns.Keys.Contains(metaCol.Name));
                Assert.True(metaCol.TypeCode == columns.First(tpc => tpc.Key == metaCol.Name).Value);
                Assert.True(metaCol.Table == tableName);
                Assert.True(metaCol.Keyspace == (keyspaceName ?? Keyspace));
            }

            if (tableOptions != null)
            {
                Assert.AreEqual(tableOptions.Comment, table.Options.Comment);
                Assert.AreEqual(tableOptions.ReadRepairChance, table.Options.ReadRepairChance);
                Assert.AreEqual(tableOptions.LocalReadRepairChance, table.Options.LocalReadRepairChance);
                Assert.AreEqual(tableOptions.ReplicateOnWrite, table.Options.replicateOnWrite);
                Assert.AreEqual(tableOptions.GcGraceSeconds, table.Options.GcGraceSeconds);
                Assert.AreEqual(tableOptions.bfFpChance, table.Options.bfFpChance);
                if (tableOptions.Caching == "ALL")
                {
                    //The string returned can be more complete than the provided
                    Assert.That(table.Options.Caching == "ALL" || table.Options.Caching.Contains("ALL"), "Caching returned does not match");
                }
                else
                {
                    Assert.AreEqual(tableOptions.Caching, table.Options.Caching);
                }
                Assert.AreEqual(tableOptions.CompactionOptions, table.Options.CompactionOptions);
                Assert.AreEqual(tableOptions.CompressionParams, table.Options.CompressionParams);
            }
        }
Example #30
0
        ////////////////////////////////////
        /// Test Helpers
        ////////////////////////////////////

        public void ExceedingCassandraType(Type toExceed, Type toExceedWith, bool sameOutput = true)
        {
            var cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(toExceed);
            var tableName             = TestUtils.GetUniqueTableName();
            var query = $"CREATE TABLE {tableName}(tweet_id uuid PRIMARY KEY, label text, number {cassandraDataTypeName});";

            QueryTools.ExecuteSyncNonQuery(Session, query);

            var minimum = toExceedWith.GetTypeInfo().GetField("MinValue").GetValue(this);
            var maximum = toExceedWith.GetTypeInfo().GetField("MaxValue").GetValue(this);

            var row1 = new object[3] {
                Guid.NewGuid(), "Minimum", minimum
            };
            var row2 = new object[3] {
                Guid.NewGuid(), "Maximum", maximum
            };
            var toInsertAndCheck = new List <object[]>(2)
            {
                row1, row2
            };

            if (toExceedWith == typeof(double) || toExceedWith == typeof(Single))
            {
                minimum = minimum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(minimum, new object[1] {
                    "r"
                });
                maximum = maximum.GetType().GetTypeInfo().GetMethod("ToString", new[] { typeof(string) }).Invoke(maximum, new object[1] {
                    "r"
                });

                toInsertAndCheck[0][2] = minimum;
                toInsertAndCheck[1][2] = maximum;

                if (!sameOutput) //for ExceedingCassandra_FLOAT() test case
                {
                    toInsertAndCheck[0][2] = Single.NegativeInfinity;
                    toInsertAndCheck[1][2] = Single.PositiveInfinity;
                }
            }

            try
            {
                QueryTools.ExecuteSyncNonQuery(Session,
                                               $"INSERT INTO {tableName}(tweet_id, label, number) VALUES ({toInsertAndCheck[0][0]}, '{toInsertAndCheck[0][1]}', {toInsertAndCheck[0][2]});", null);
                QueryTools.ExecuteSyncNonQuery(Session,
                                               $"INSERT INTO {tableName}(tweet_id, label, number) VALUES ({toInsertAndCheck[1][0]}, '{toInsertAndCheck[1][1]}', {toInsertAndCheck[1][2]});", null);
            }
            catch (InvalidQueryException)
            {
                if (!sameOutput && toExceed == typeof(Int32)) //for ExceedingCassandra_INT() test case
                {
                    return;
                }

                throw;
            }

            VerifyStatement(
                QueryType.Query,
                $"INSERT INTO {tableName}(tweet_id, label, number) VALUES ({toInsertAndCheck[0][0]}, '{toInsertAndCheck[0][1]}', {toInsertAndCheck[0][2]});",
                1);

            VerifyStatement(
                QueryType.Query,
                $"INSERT INTO {tableName}(tweet_id, label, number) VALUES ({toInsertAndCheck[1][0]}, '{toInsertAndCheck[1][1]}', {toInsertAndCheck[1][2]});",
                1);

            TestCluster.PrimeFluent(
                b => b.WhenQuery($"SELECT * FROM {tableName};", when => when.WithConsistency(ConsistencyLevel.One))
                .ThenRowsSuccess(
                    new[] { "tweet_id", "label", "number" },
                    r => r.WithRow(toInsertAndCheck[0][0], toInsertAndCheck[0][1], toInsertAndCheck[0][2])
                    .WithRow(toInsertAndCheck[1][0], toInsertAndCheck[1][1], toInsertAndCheck[1][2])));

            QueryTools.ExecuteSyncQuery(Session, $"SELECT * FROM {tableName};", ConsistencyLevel.One, toInsertAndCheck);
        }