示例#1
0
        public async Task BasicFlow()
        {
            //Assume
            const string insertCql   = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            const int insertCount = 1000;

            //Act
            using (var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                var executions = new Task <ICqlQueryResult> [insertCount];

                var options = new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 1
                };
                Parallel.For(0, insertCount, options, (i) =>
                {
                    var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                    cmd.Prepare();

                    var b = new BasicFlowData {
                        Id = i, Data = "Hallo " + i
                    };
                    cmd.PartitionKey.Set(b);
                    cmd.Parameters.Set(b);

                    executions[i] = cmd.ExecuteNonQueryAsync();
                });

                await Task.WhenAll(executions);

                var presence = new bool[insertCount];

                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One)
                {
                    EnableTracing = true
                };

                CqlDataReader <BasicFlowData> reader = await selectCmd.ExecuteReaderAsync <BasicFlowData>();

                while (await reader.ReadAsync())
                {
                    BasicFlowData row = reader.Current;
                    Assert.AreEqual(row.Data, "Hallo " + row.Id);
                    presence[row.Id] = true;
                }

                Assert.IsTrue(presence.All(p => p));

                var            tracer  = new QueryTraceCommand(connection, reader.TracingId.Value);
                TracingSession session = await tracer.GetTraceSessionAsync();

                Assert.IsNotNull(session);
            }
        }
示例#2
0
        /// <summary>
        ///   Updates the cart async.
        /// </summary>
        /// <param name="c"> The c. </param>
        /// <returns> </returns>
        public async Task UpdateCartAsync(Cart c)
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "update Shop.Carts set groupid=?, items=? where id=?;");
                await command.PrepareAsync();

                command.Parameters.Set(c);
                await command.ExecuteNonQueryAsync();
            }
        }
示例#3
0
        /// <summary>
        ///   Adds the items async.
        /// </summary>
        /// <param name="guid"> The GUID. </param>
        /// <param name="items"> The items. </param>
        /// <returns> </returns>
        public async Task AddItemsAsync(Guid guid, Dictionary <string, int> items)
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "update Shop.Carts set items = items + ? where id = ?;");
                await command.PrepareAsync();

                command.Parameters["id"]    = guid;
                command.Parameters["items"] = items;
                await command.ExecuteNonQueryAsync();
            }
        }
示例#4
0
        /// <summary>
        ///   Prepares the db async.
        /// </summary>
        /// <returns> </returns>
        public async Task PrepareDbAsync()
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                try
                {
                    var shopExistCommand = new CqlCommand(connection,
                                                          "select * from system.schema_keyspaces where keyspace_name='shop';");
                    using (var reader = shopExistCommand.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            var dropKs = new CqlCommand(connection, @"DROP KEYSPACE Shop;");
                            await dropKs.ExecuteNonQueryAsync();
                        }
                    }
                }
                catch (AlreadyExistsException)
                {
                    //ignore
                }

                try
                {
                    //create the keyspace if it does not exist
                    var createKs = new CqlCommand(connection,
                                                  @"CREATE KEYSPACE Shop WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';");
                    await createKs.ExecuteNonQueryAsync();

                    //create the table
                    var createTable = new CqlCommand(connection,
                                                     @"create table Shop.Carts (id uuid primary key, groupId text, items map<text, int>);");
                    await createTable.ExecuteNonQueryAsync();

                    //create corresponding index
                    var createIndex = new CqlCommand(connection, @"create index on Shop.Carts(GroupId)");
                    await createIndex.ExecuteNonQueryAsync();
                }
                catch (AlreadyExistsException)
                {
                }
            }
        }
示例#5
0
        /// <summary>
        ///   Prepares the db async.
        /// </summary>
        /// <returns> </returns>
        public async Task PrepareDbAsync()
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                try
                {
                    var shopExistCommand = new CqlCommand(connection,
                                                          "select * from system.schema_keyspaces where keyspace_name='shop';");
                    using (var reader = shopExistCommand.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            var dropKs = new CqlCommand(connection, @"DROP KEYSPACE Shop;");
                            await dropKs.ExecuteNonQueryAsync();
                        }
                    }
                }
                catch (AlreadyExistsException)
                {
                    //ignore
                }

                try
                {
                    //create the keyspace if it does not exist
                    var createKs = new CqlCommand(connection,
                                                  @"CREATE KEYSPACE Shop WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1} and durable_writes = 'false';");
                    await createKs.ExecuteNonQueryAsync();

                    //create the table
                    var createTable = new CqlCommand(connection,
                                                     @"create table Shop.Carts (id uuid primary key, groupId text, items map<text, int>);");
                    await createTable.ExecuteNonQueryAsync();

                    //create corresponding index
                    var createIndex = new CqlCommand(connection, @"create index on Shop.Carts(GroupId)");
                    await createIndex.ExecuteNonQueryAsync();
                }
                catch (AlreadyExistsException)
                {
                }
            }
        }
示例#6
0
        /// <summary>
        ///   Creates the cart async.
        /// </summary>
        /// <returns> </returns>
        public async Task <Cart> AddCartAsync(string groupId)
        {
            var c = new Cart {
                Id = Guid.NewGuid(), GroupId = groupId
            };

            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "insert into Shop.Carts (id, groupId) values (?,?);");
                await command.PrepareAsync();

                command.Parameters.Set(c);
                await command.ExecuteNonQueryAsync();

                return(c);
            }
        }
示例#7
0
        public async Task ErrorResult()
        {
            //Assume
            const string insertCql = @"insert into Test.UnknownTable (id,value) values (1,'Hallo 1');";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                cmd.EnableTracing = true;

                try
                {
                    await cmd.ExecuteNonQueryAsync();
                    Assert.Fail("Should have thrown exception!");
                }
                catch(ProtocolException pex)
                {
                    Assert.IsInstanceOfType(pex, typeof(InvalidException));
                    Assert.IsInstanceOfType(cmd.LastQueryResult, typeof(CqlError));
                    Assert.AreEqual(((CqlError)cmd.LastQueryResult).Exception, pex,
                                    "CqlError does not contain thrown exception");
                    Assert.AreEqual(pex.TracingId, cmd.LastQueryResult.TracingId);
                }
            }
        }
示例#8
0
        public async Task BasicInsertSelectScalar()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (1001,'Hallo 1001');";
            const string retrieveCql = @"select value from Test.BasicFlow where id=1001;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);

                string value = (string)await selectCmd.ExecuteScalarAsync();
                Assert.AreEqual("Hallo 1001", value);
            }
        }
示例#9
0
        public async Task TransactionRolledBackDoesNotInsertData()
        {
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (9876, 'Transaction 9876');";
            const string retrieveCql = @"select id from Test.BasicFlow where id=9876;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //create transaction
                using(var transaction = connection.BeginTransaction())
                {
                    //insert data
                    var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                    cmd.Transaction = transaction;
                    await cmd.ExecuteNonQueryAsync();

                    transaction.Rollback();
                }

                //check if data exists
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);
                using(CqlDataReader reader = await selectCmd.ExecuteReaderAsync())
                {
                    //check if any rows are returned
                    Assert.IsFalse(reader.HasRows);
                }
            }
        }
示例#10
0
        /// <summary>
        ///   Creates the cart async.
        /// </summary>
        /// <returns> </returns>
        public async Task<Cart> AddCartAsync(string groupId)
        {
            var c = new Cart {Id = Guid.NewGuid(), GroupId = groupId};

            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "insert into Shop.Carts (id, groupId) values (?,?);");
                await command.PrepareAsync();
                command.Parameters.Set(c);
                await command.ExecuteNonQueryAsync();
                return c;
            }
        }
示例#11
0
        public async Task BasicFlow()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            const int insertCount = 1000;

            //Act
            using (var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                var executions = new Task<ICqlQueryResult>[insertCount];

                var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
                Parallel.For(0, insertCount, options, (i) =>
                {
                    var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                    cmd.Prepare();

                    var b = new BasicFlowData { Id = i, Data = "Hallo " + i };
                    cmd.PartitionKey.Set(b);
                    cmd.Parameters.Set(b);

                    executions[i] = cmd.ExecuteNonQueryAsync();
                });

                await Task.WhenAll(executions);

                var presence = new bool[insertCount];

                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One) { EnableTracing = true };

                CqlDataReader<BasicFlowData> reader = await selectCmd.ExecuteReaderAsync<BasicFlowData>();
                while (await reader.ReadAsync())
                {
                    BasicFlowData row = reader.Current;
                    Assert.AreEqual(row.Data, "Hallo " + row.Id);
                    presence[row.Id] = true;
                }

                Assert.IsTrue(presence.All(p => p));

                var tracer = new QueryTraceCommand(connection, reader.TracingId.Value);
                TracingSession session = await tracer.GetTraceSessionAsync();

                Assert.IsNotNull(session);
            }
        }
示例#12
0
        /// <summary>
        ///   Adds the items async.
        /// </summary>
        /// <param name="guid"> The GUID. </param>
        /// <param name="items"> The items. </param>
        /// <returns> </returns>
        public async Task AddItemsAsync(Guid guid, Dictionary<string, int> items)
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "update Shop.Carts set items = items + ? where id = ?;");
                await command.PrepareAsync();
                command.Parameters["id"] = guid;
                command.Parameters["items"] = items;
                await command.ExecuteNonQueryAsync();
            }
        }
示例#13
0
        public async Task SelectScalarNullValue()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id) values (2001);";
            const string retrieveCql = @"select value from Test.BasicFlow where id=2001;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);

                object value = await selectCmd.ExecuteScalarAsync();
                Assert.AreEqual(DBNull.Value, value);
            }
        }
示例#14
0
        private async Task BatchInsertInternal(CqlBatchType batchType)
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select id,value,ignored from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();
                var transaction = connection.BeginTransaction();
                transaction.BatchType = batchType;

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                cmd.Transaction = transaction;

                await cmd.PrepareAsync();

                for(int i = 0; i < 10; i++)
                {
                    cmd.Parameters[0].Value = i;
                    cmd.Parameters[1].Value = "Hello " + i;
                    await cmd.ExecuteNonQueryAsync();
                }

                var cmd2 = new CqlCommand(connection, insertCql, CqlConsistency.One);
                cmd2.Transaction = transaction;
                cmd2.Parameters.Add("id", CqlType.Int);
                cmd2.Parameters.Add("value", CqlType.Text);

                for(int i = 10; i < 20; i++)
                {
                    cmd2.Parameters[0].Value = i;
                    cmd2.Parameters[1].Value = "Hello " + i;
                    await cmd2.ExecuteNonQueryAsync();
                }

                try
                {
                    await transaction.CommitAsync();
                }
                catch(ProtocolException pex)
                {
                    //skip when server version is below 2.0.0
                    if(pex.Code == ErrorCode.Protocol &&
                       String.Compare(connection.ServerVersion, "2.0.0", StringComparison.Ordinal) < 0)
                        return;

                    throw;
                }

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);
                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();
                Assert.AreEqual(20, reader.Count);

                var results = new bool[20];
                for(int i = 0; i < 20; i++)
                {
                    if(await reader.ReadAsync())
                    {
                        results[(int)reader["id"]] = true;
                        Assert.AreEqual("Hello " + reader["id"], reader["value"]);
                    }
                    else
                        Assert.Fail("Read should have succeeded");
                    }

                Assert.IsTrue(results.All(p => p));

                Assert.IsNotNull(transaction.LastBatchResult);
            }
        }
示例#15
0
        /// <summary>
        ///   Updates the cart async.
        /// </summary>
        /// <param name="c"> The c. </param>
        /// <returns> </returns>
        public async Task UpdateCartAsync(Cart c)
        {
            using (var connection = new CqlConnection("cartDB"))
            {
                await connection.OpenAsync();

                var command = new CqlCommand(connection, "update Shop.Carts set groupid=?, items=? where id=?;");
                await command.PrepareAsync();
                command.Parameters.Set(c);
                await command.ExecuteNonQueryAsync();
            }
        }
示例#16
0
        public async Task InsertSelectCustomParameters()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                cmd.Parameters.Add("myKey", CqlType.Int);
                cmd.Parameters.Add("myValue", CqlType.Text);
                await cmd.PrepareAsync();

                cmd.Parameters["myKey"].Value = 1234;
                cmd.Parameters["myValue"].Value = "Hallo 1234";
                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);

                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();
                Assert.AreEqual(1, reader.Count);
                if(await reader.ReadAsync())
                {
                    Assert.AreEqual(1234, reader["id"]);
                    Assert.AreEqual("Hallo 1234", reader["value"]);
                    Assert.AreEqual(DBNull.Value, reader["ignored"]);
                }
                else
                    Assert.Fail("Read should have succeeded");
                }
            }
示例#17
0
        public async Task BasicPrepareInsertSelect()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.PrepareAsync();

                var b = new BasicFlowData {Id = 123, Data = "Hallo", Ignored = "none"};
                cmd.PartitionKey.Set(b);
                cmd.Parameters.Set(b);

                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One) {EnableTracing = true};
                await selectCmd.PrepareAsync();

                CqlDataReader<BasicFlowData> reader = await selectCmd.ExecuteReaderAsync<BasicFlowData>();
                Assert.AreEqual(1, reader.Count);
                if(await reader.ReadAsync())
                {
                    BasicFlowData row = reader.Current;
                    Assert.AreEqual(123, row.Id);
                    Assert.AreEqual("Hallo", row.Data);
                    Assert.IsNull(row.Ignored);
                }
                else
                    Assert.Fail("Read should have succeeded");
                }
            }
示例#18
0
        public async Task InsertTracing()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (567,'Hallo 567');";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                cmd.EnableTracing = true;
                await cmd.ExecuteNonQueryAsync();

                Assert.IsInstanceOfType(cmd.LastQueryResult, typeof(CqlVoid));
                Assert.IsTrue(cmd.LastQueryResult.TracingId.HasValue, "Expected a tracing id");

                var tracer = new QueryTraceCommand(connection, cmd.LastQueryResult.TracingId.Value);
                TracingSession session = await tracer.GetTraceSessionAsync(CancellationToken.None);

                Assert.IsNotNull(session);
            }
        }
示例#19
0
        public async Task SelectWithPagingAsync()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.PrepareAsync();

                for(int i = 0; i < 100; i++)
                {
                    cmd.Parameters[0].Value = i;
                    cmd.Parameters[1].Value = "Hello " + i;
                    await cmd.ExecuteNonQueryAsync();
                }

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);
                selectCmd.PageSize = 10;

                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();

                //no paging when version < 2.0.0 is used...
                var expectedCount = String.Compare(connection.ServerVersion, "2.0.0", StringComparison.Ordinal) < 0
                                        ? 100
                                        : 10;
                Assert.AreEqual(expectedCount, reader.Count);

                var results = new bool[100];
                for(int i = 0; i < 100; i++)
                {
                    if(await reader.ReadAsync())
                    {
                        results[(int)reader["id"]] = true;
                        Assert.AreEqual("Hello " + reader["id"], reader["value"]);
                    }
                    else
                        Assert.Fail("Read should have succeeded");
                    }
                Assert.IsFalse(reader.Read());
                Assert.IsTrue(results.All(p => p));
            }
        }
示例#20
0
        public async Task CASInsertSelect()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (901,'Hallo 901') if not exists;";
            const string insertCql2 = @"insert into Test.BasicFlow (id,value) values (901,'Hallo 901.2') if not exists;";

            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //skip when server version is below 2.0.0
                if(String.Compare(connection.ServerVersion, "2.0.0", StringComparison.Ordinal) < 0)
                    return;

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.Any);
                cmd.UseCASLocalSerial = true;
                await cmd.ExecuteNonQueryAsync();
                var result = cmd.LastQueryResult as CqlDataReader;
                Assert.IsNotNull(result);
                Assert.IsTrue(await result.ReadAsync());
                Assert.IsTrue((bool)result["[applied]"]);

                var cmd2 = new CqlCommand(connection, insertCql2, CqlConsistency.Any);
                await cmd2.ExecuteNonQueryAsync();
                var result2 = cmd2.LastQueryResult as CqlDataReader;
                Assert.IsNotNull(result2);
                Assert.IsTrue(await result2.ReadAsync());
                Assert.IsFalse((bool)result2["[applied]"]);
                Assert.AreEqual("Hallo 901", result2["value"]);

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);
                await selectCmd.PrepareAsync();

                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();
                Assert.AreEqual(1, reader.Count);
                if(await reader.ReadAsync())
                {
                    Assert.AreEqual(901, reader["id"]);
                    Assert.AreEqual("Hallo 901", reader["value"]);
                    Assert.AreEqual(DBNull.Value, reader["ignored"]);
                }
                else
                    Assert.Fail("Read should have succeeded");
                }
            }
示例#21
0
        public async Task ChangeDatabaseThenInsertSelect()
        {
            //Assume
            const string insertCql = @"insert into BasicFlow (id,value) values (901,'Hallo 901');";
            const string retrieveCql = @"select * from BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                Assert.AreEqual("", connection.Database);

                await connection.OpenAsync();

                //change database
                connection.ChangeDatabase("test");

                Assert.AreEqual("test", connection.Database);

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);
                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();

                Assert.AreEqual(1, reader.Count);
                if(await reader.ReadAsync())
                {
                    Assert.AreEqual(901, reader["id"]);
                    Assert.AreEqual("Hallo 901", reader["value"]);
                    Assert.AreEqual(DBNull.Value, reader["ignored"]);
                }
                else
                    Assert.Fail("Read should have succeeded");
                }
            }
示例#22
0
        public async Task BatchPreparedWithNamedParameters()
        {
            //Assume
            const string insertCql =
                @"begin batch insert into Test.BasicFlow (id,value) values (:id1,:value1); insert into Test.BasicFlow (id,value) values (:id2,:value2); apply batch;";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //skip if cqlversion too low
                if(string.CompareOrdinal(connection.CqlVersion, "3.1.1") < 0)
                    return;

                //insert data
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);
                await cmd.PrepareAsync();

                cmd.Parameters["id1"].Value = 0;
                cmd.Parameters["value1"].Value = "Hello 0";
                cmd.Parameters["id2"].Value = 1;
                cmd.Parameters["value2"].Value = "Hello 1";
                await cmd.ExecuteNonQueryAsync();

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);

                CqlDataReader reader = await selectCmd.ExecuteReaderAsync();
                Assert.AreEqual(2, reader.Count);

                var results = new bool[2];
                for(int i = 0; i < 2; i++)
                {
                    if(await reader.ReadAsync())
                    {
                        results[(int)reader["id"]] = true;
                        Assert.AreEqual("Hello " + reader["id"], reader["value"]);
                    }
                    else
                        Assert.Fail("Read should have succeeded");
                    }

                Assert.IsTrue(results.All(p => p));
            }
        }
示例#23
0
        public async Task QueryWithBoundParameters()
        {
            //Assume
            const string insertCql = @"insert into Test.BasicFlow (id,value) values (?,?);";
            const string retrieveCql = @"select * from Test.BasicFlow;";

            //Act
            using(var connection = new CqlConnection(ConnectionString))
            {
                await connection.OpenAsync();

                //define command
                var cmd = new CqlCommand(connection, insertCql, CqlConsistency.One);

                //add parameters, infer Cql types
                cmd.Parameters.Add("id", 123);
                cmd.Parameters.Add("value", "Hallo");

                try
                {
                    //execute
                    await cmd.ExecuteNonQueryAsync();
                }
                catch(InvalidException)
                {
                    Assert.IsNotNull(connection.ServerVersion);
                    if(String.Compare(connection.ServerVersion, "2.0.0", StringComparison.Ordinal) < 0)
                        return;

                    throw;
                }

                //select data
                var selectCmd = new CqlCommand(connection, retrieveCql, CqlConsistency.One);

                CqlDataReader<BasicFlowData> reader = await selectCmd.ExecuteReaderAsync<BasicFlowData>();
                Assert.AreEqual(1, reader.Count);
                if(await reader.ReadAsync())
                {
                    BasicFlowData row = reader.Current;
                    Assert.AreEqual(123, row.Id);
                    Assert.AreEqual("Hallo", row.Data);
                    Assert.IsNull(row.Ignored);
                }
                else
                    Assert.Fail("Read should have succeeded");
                }
            }
示例#24
0
        /// <summary>
        /// Creates the database.
        /// </summary>
        public static void CreateDatabase()
        {
            using(var connection = new CqlConnection(ConnectionString))
            {
                connection.Open();

                var existCommand = new CqlCommand(connection,
                                                  "select * from system.schema_keyspaces where keyspace_name='cqlsharptest';");
                using(var reader = existCommand.ExecuteReader())
                {
                    //check if database exists, if so, use it, otherwise create it
                    if(!reader.Read())
                    {
                        //create the keyspace 
                        var createKs = new CqlCommand(connection,
                                                      @"CREATE KEYSPACE cqlsharptest WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1};");
                        createKs.ExecuteNonQuery();

                        //create the table
                        var createTable = new CqlCommand(connection,
                                                         @"CREATE TABLE cqlsharptest.measurements (id int PRIMARY KEY, customer text, values map<text, int>);");
                        createTable.ExecuteNonQuery();

                        //fill table with dummy data
                        var inserts = new List<Task>(25000);
                        for(int i = 0; i < 25000; i++)
                        {
                            //create and prepare the insert command
                            var insertCommand = new CqlCommand(connection,
                                                               "insert into cqlsharptest.measurements (id, customer, values) values (?,?,?)");
                            insertCommand.Prepare();

                            //create new measurement
                            var measurement = new Measurement
                            {
                                Id = i,
                                Customer = Customers[Random.Next(0, Customers.Count)],
                                Values = new Dictionary<string, int>
                                {
                                    {"Temp", Random.Next(0, 101)},
                                    {"Humidity", Random.Next(0, 101)},
                                    {"Clouds", Random.Next(0, 101)},
                                    {"Pressure", Random.Next(0, 101)},
                                    {"Rain", Random.Next(0, 101)},
                                    {"Sunshine", Random.Next(0, 101)},
                                    {"Overall", Random.Next(0, 101)}
                                }
                            };

                            //set insert parameters
                            insertCommand.Parameters.Set(measurement);

                            //add the insert as task to list
                            inserts.Add(insertCommand.ExecuteNonQueryAsync());
                        }

                        //wait for all inserts to complete
                        Task.WaitAll(inserts.ToArray());
                    }
                }
            }
        }