示例#1
0
        public void BatchMixedStatements()
        {
            foreach (var protocolVersion in ProtocolVersionSupported)
            {
                //Use all possible protocol versions
                Cluster.MaxProtocolVersion = protocolVersion;
                //Use a local cluster
                var localCluster = Cluster.Builder().AddContactPoint(IpPrefix + "1").Build();
                var localSession = localCluster.Connect("tester");
                var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
                CreateTable(tableName);

                var simpleStatement =
                    new SimpleStatement(String.Format("INSERT INTO {0} (id, label, number) VALUES ({1}, {2}, {3})", tableName, 1, "label", 2));
                var ps = localSession.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
                var batchStatement = new BatchStatement();
                var expectedValues = new List<object[]> {new object[] {1, "label", 2}, new object[] {1, "test", 2}};

                batchStatement.Add(ps.Bind(new object[] {1, "test", 2}));
                batchStatement.Add(simpleStatement);

                var rs = localSession.Execute("SELECT * FROM " + tableName);
                VerifyData(rs, expectedValues);
            }
        }
        public void RequestHandler_GetRequest_BatchStatement_Default_QueryOptions_Are_Used()
        {
            var stmt = new BatchStatement();

            Assert.Null(stmt.ConsistencyLevel);
            var request = (BatchRequest)RequestHandler <RowSet> .GetRequest(stmt, new Serializer(2), GetConfig());

            Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
        }
        public void BatchStatement_Bind_SetsRoutingValues_Single()
        {
            var batch = new BatchStatement();

            Assert.Null(batch.RoutingKey);
            batch.SetRoutingValues("id1-value");
            batch.Serializer = new SerializerManager(ProtocolVersion.MaxSupported).GetCurrentSerializer();
            CollectionAssert.AreEqual(batch.Serializer.Serialize("id1-value"), batch.RoutingKey.RawRoutingKey);
        }
 public BatchStatement GetBatchStatement(ISession session, IEnumerable<Cql> cqlToBatch)
 {
     var batch = new BatchStatement();
     foreach (var cql in cqlToBatch)
     {
         batch.Add(GetStatement(session, cql));
     }
     return batch;
 }
示例#5
0
        public void Batch_UsingTwoTables_OneInvalidTable()
        {
            var batch = new BatchStatement();

            batch.Add(new SimpleStatement($@"INSERT INTO {_tableName} (id, label, number) VALUES ({400}, '{"label1"}', {1})"));
            batch.Add(new SimpleStatement($@"INSERT INTO table_randomnonexistent (id, label, number) VALUES ({2}, '{"label2"}', {2})"));

            Assert.Throws <InvalidQueryException>(() => Session.Execute(batch));
        }
示例#6
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Cassandra World!");

            var cluster = Cluster.Builder()
                          .AddContactPoint("192.168.0.40")
                          .Build();
            //new TemperatureRepository()
            var session = cluster.Connect("peiuhub");

            System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
            int rowCount = 0;

            using (StreamReader reader = new StreamReader(sampleFile))
            {
                var track = session.Prepare("INSERT INTO peiuhub.pcs_log2(id, timestamp, pcs_meter, pcs_volt, pcs_current, pcs_status, pv_meter, soc, soh, rcc, source, deviceid) VALUES " +
                                            "(?,?,?,?,?,?,?,?,?,?,?,?)");
                reader.ReadLine();

                var    batch      = new BatchStatement();
                ushort batchCount = 0;
                while (reader.EndOfStream == false)
                {
                    string   line        = reader.ReadLine();
                    string[] columns     = line.Split(',');
                    DateTime time        = DateTime.Parse(columns[0]);
                    float    pcs_meter   = float.Parse(columns[1]);
                    float    pcs_volt    = float.Parse(columns[2]);
                    float    pcs_current = float.Parse(columns[3]);
                    int      pcs_status  = int.Parse(columns[4]);
                    float    pv_meter    = float.Parse(columns[5]);
                    float    soc         = float.Parse(columns[6]);
                    float    soh         = float.Parse(columns[7]);
                    int      rcc         = int.Parse(columns[8]);
                    int      source      = 0;
                    string   deviceid    = columns[10];
                    //Int32 unixTimestamp = (Int32)(time.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    Guid id = Guid.NewGuid();

                    batch.Add(track.Bind(id, time, pcs_meter, pcs_volt, pcs_current, pcs_status, pv_meter, soc, soh, rcc, source, deviceid));
                    batchCount++;
                    rowCount++;

                    if (rowCount % 200 == 0)
                    {
                        session.Execute(batch);
                        batch      = new BatchStatement();
                        batchCount = 0;
                    }
                }
                session.Execute(batch);
            }

            Console.WriteLine($"완료. 걸린시간:{watch.Elapsed} row갯수:{rowCount}");
            Console.ReadKey();
        }
        public void RequestHandler_GetRequest_BatchStatement_Statement_Level_Settings_Are_Used()
        {
            var stmt = new BatchStatement();

            stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
            Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
            var request = (BatchRequest)RequestHandler.GetRequest(stmt, Serializer, GetConfig());

            Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
        }
示例#8
0
        public void BatchStatement_Bind_SetsRoutingValues_Single()
        {
            const int protocolVersion = 2;
            var       batch           = new BatchStatement();

            Assert.Null(batch.RoutingKey);
            batch.SetRoutingValues("id1-value");
            batch.ProtocolVersion = protocolVersion;
            CollectionAssert.AreEqual(TypeCodec.Encode(protocolVersion, "id1-value"), batch.RoutingKey.RawRoutingKey);
        }
        public BatchStatement GetBatchStatement(ISession session, IEnumerable <Cql> cqlToBatch, BatchType batchType)
        {
            var batch = new BatchStatement().SetBatchType(batchType);

            foreach (var cql in cqlToBatch)
            {
                batch.Add(GetStatement(session, cql));
            }
            return(batch);
        }
示例#10
0
        public void RequestHandler_GetRequest_BatchStatement_Statement_Level_Settings_Are_Used()
        {
            var stmt = new BatchStatement();

            stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
            Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
            var request = (BatchRequest)RequestHandler <RowSet> .GetRequest(stmt, new Serializer(ProtocolVersion.MaxSupported), GetConfig());

            Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
        }
        public void BatchStatement_Bind_SetsRoutingValues_Single()
        {
            const int protocolVersion = 2;
            var       batch           = new BatchStatement();

            Assert.Null(batch.RoutingKey);
            batch.SetRoutingValues("id1-value");
            batch.Serializer = new Serializer(protocolVersion);
            CollectionAssert.AreEqual(batch.Serializer.Serialize("id1-value"), batch.RoutingKey.RawRoutingKey);
        }
        public void RequestHandler_GetRequest_BatchStatement_QueryOptions_Are_Used()
        {
            var stmt = new BatchStatement();

            Assert.Null(stmt.ConsistencyLevel);
            var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
            var request      = (BatchRequest)RequestHandler.GetRequest(stmt, Serializer, GetConfig(queryOptions));

            Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
        }
示例#13
0
        public void BatchStatement_Should_Use_Routing_Key_Of_First_Statement_With_SimpleStatement_Instances()
        {
            var rawRoutingKey = new byte[] { 1, 2, 3, 4 };
            var s1            = new SimpleStatement("Q1").SetRoutingKey(new RoutingKey(rawRoutingKey));
            var s2            = new SimpleStatement("Q2").SetRoutingKey(new RoutingKey(new byte[] { 100, 101, 102 }));
            var batch         = new BatchStatement().Add(s1).Add(s2);

            Assert.AreEqual(BitConverter.ToString(rawRoutingKey),
                            BitConverter.ToString(batch.RoutingKey.RawRoutingKey));
        }
示例#14
0
        public BatchStatement GetBatchStatement(IEnumerable <Cql> cqlToBatch)
        {
            var batch = new BatchStatement();

            foreach (Cql cql in cqlToBatch)
            {
                batch.Add(GetStatement(cql));
            }
            return(batch);
        }
示例#15
0
        public void BatchStatement_Default_QueryOptions_Are_Used()
        {
            var stmt = new BatchStatement();

            Assert.Null(stmt.ConsistencyLevel);
            var session = GetInstance();
            var request = (BatchRequest)session.GetRequest(stmt);

            Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
        }
        public async Task UpdateRoleAsync(CassandraRole role, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (role == null)
            {
                throw new ArgumentNullException("role");
            }
            if (string.IsNullOrEmpty(role.Name))
            {
                throw new ArgumentNullException("role", "role.Name cannot be null or empty");
            }

            var modifiedDate = DateTimeOffset.UtcNow;

            role.Modified = modifiedDate;
            var    batch = new BatchStatement();
            string oldName;
            var    changed = role.HasNameChanged(out oldName);

            if (changed)
            {
                // This a Create/Delete move
                // can only change the name if that target name does not exist.
                var findResult = await FindRoleByNameAsync(role.Name);

                if (findResult.Any())
                {
                    // sorry, no go, this is record must either be deleted first or use another name.
                    throw new Exception(
                              string.Format(
                                  "Cannot change role name:[{0}] to an existing role, pick another name, or delete this one first",
                                  role.Name));
                }
                var boundStatements = await BuildCreateStatements(role);

                batch.AddRange(boundStatements);
                var oldRole = new CassandraRole(role.TenantId, oldName);
                boundStatements = await BuildDeleteStatements(oldRole);

                batch.AddRange(boundStatements);
                await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false);
                await RenameRoleNameInUsersAsync(oldName, role.Name, cancellationToken);
            }
            else
            {
                PreparedStatement[] prepared = await _updateRole;

                // UPDATE roles ...
                batch.Add(prepared[0].Bind(role.Name, role.DisplayName, role.IsSystemRole, modifiedDate, role.Id));
                // UPDATE roles_by_name ... (since username hasn't changed)
                batch.Add(prepared[1].Bind(role.DisplayName, role.IsSystemRole, modifiedDate, role.TenantId, role.Name));

                await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false);
            }
        }
示例#17
0
        public void BatchStatement_QueryOptions_Are_Used()
        {
            var stmt = new BatchStatement();

            Assert.Null(stmt.ConsistencyLevel);
            var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
            var session      = GetInstance(queryOptions);
            var request      = (BatchRequest)session.GetRequest(stmt);

            Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
        }
        public RowSet InvokeUpdateOrder(object[] parameters)
        {
            BatchStatement batch         = new BatchStatement();
            List <Order>   orderProducts = EntityMapper.ToOrders(session.Execute(preparedStatements[Statements.SELECT_ORDER_FROM_ORDER].Bind(parameters)));

            foreach (Order orderToUpdate in orderProducts)
            {
                batch.Add(preparedStatements[Statements.UPDATE_STATUS_ORDER].Bind(parameters[0], parameters[1], orderToUpdate.ProductName));
            }
            return(session.Execute(batch));
        }
示例#19
0
        /// <summary>
        /// Gets the timestamp of the request or null if not defined.
        /// </summary>
        private static long?GetRequestTimestamp(BatchStatement statement, ITimestampGenerator timestampGenerator)
        {
            if (statement.Timestamp != null)
            {
                return(TypeSerializer.SinceUnixEpoch(statement.Timestamp.Value).Ticks / 10);
            }

            var timestamp = timestampGenerator.Next();

            return(timestamp != long.MinValue ? (long?)timestamp : null);
        }
示例#20
0
        public void BatchStatement_Statement_Level_Settings_Are_Used()
        {
            var stmt = new BatchStatement();

            stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
            Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
            var session = GetInstance();
            var request = (BatchRequest)session.GetRequest(stmt);

            Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
        }
示例#21
0
        public void Execute(ICqlBatch batch)
        {
            if (batch == null)
            {
                throw new ArgumentNullException("batch");
            }

            BatchStatement batchStatement = _statementFactory.GetBatchStatement(batch.Statements);

            _session.Execute(batchStatement);
        }
示例#22
0
        public async Task ExecuteAsync(ICqlBatch batch)
        {
            if (batch == null)
            {
                throw new ArgumentNullException("batch");
            }

            BatchStatement batchStatement = await _statementFactory.GetBatchStatementAsync(batch.Statements);

            await _session.ExecuteAsync(batchStatement);
        }
示例#23
0
            public async Task DeleteAsync(CassandraRole role)
            {
                PreparedStatement[] prepared = await _deleteRole;
                var batch = new BatchStatement();

                // DELETE FROM roles ...
                batch.Add(prepared[0].Bind(role.Id));

                // DELETE FROM roles_by_rolename ...
                batch.Add(prepared[1].Bind(role.Name, role.TenantId));
                await _session.ExecuteAsync(batch).ConfigureAwait(false);
            }
        public void Add(Cliente p_cliente)
        {
            Guid      id            = Guid.NewGuid();
            LocalDate date          = new LocalDate(p_cliente.DataNascimento.Year, p_cliente.DataNascimento.Month, p_cliente.DataNascimento.Day);
            var       userTrackStmt = session.Prepare(@"INSERT INTO cliente (id, nome, email, cpf, datanascimento) 
                                                VALUES (?, ?, ?, ?, ?)");

            var batch = new BatchStatement()
                        .Add(userTrackStmt.Bind(id, p_cliente.Nome, p_cliente.Email, p_cliente.CPF, date));

            session.Execute(batch);
        }
示例#25
0
        public void BatchStatement_Max_Queries_Test()
        {
            var batch = new BatchStatement();
            var id    = Guid.NewGuid();

            for (int i = 0; i < ushort.MaxValue; i++)
            {
                batch.Add(new SimpleStatement("QUERY", id));
            }
            // It shouldn't allow more
            Assert.Throws <ArgumentOutOfRangeException>(() => batch.Add(new SimpleStatement("QUERY", id)));
        }
 public void Batch_Payload_Test()
 {
     var outgoing = new Dictionary<string, byte[]> { { "k1-batch", Encoding.UTF8.GetBytes("value1") }, { "k2-batch", Encoding.UTF8.GetBytes("value2") } };
     var stmt = new BatchStatement();
     stmt.Add(new SimpleStatement(String.Format("INSERT INTO {0} (k, i) VALUES ('one', 1)", Table)));
     stmt.SetOutgoingPayload(outgoing);
     var rs = Session.Execute(stmt);
     Assert.NotNull(rs.Info.IncomingPayload);
     Assert.AreEqual(outgoing.Count, rs.Info.IncomingPayload.Count);
     CollectionAssert.AreEqual(outgoing["k1-batch"], rs.Info.IncomingPayload["k1-batch"]);
     CollectionAssert.AreEqual(outgoing["k2-batch"], rs.Info.IncomingPayload["k2-batch"]);
 }
示例#27
0
        public void BatchPreparedStatementsFlagsNotSupportedInC2_0()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            CreateTable(tableName);

            var ps    = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            var batch = new BatchStatement();

            batch.Add(ps.Bind(new object[] { 1, "label1", 1 }));
            Assert.Throws <NotSupportedException>(() => Session.Execute(batch.SetTimestamp(DateTime.Now)));
        }
示例#28
0
        public void Batch_PreparedStatement_AsyncTest()
        {
            List<object[]> expectedValues = new List<object[]> { new object[] { 10, "label1", 1 }, new object[] { 11, "label2", 2 }, new object[] { 12, "label3", 3 } };

            PreparedStatement ps = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", _tableName));
            BatchStatement batch = new BatchStatement();
            foreach (object[] val in expectedValues)
            {
                batch.Add(ps.Bind(val));
            }
            Assert.DoesNotThrow(() => Session.ExecuteAsync(batch).Wait());
        }
示例#29
0
        public string RegisterNewUser([FromBody] User user)
        {
            ISession session = SessionManager.GetSession();

            if (session == null)
            {
                return("Session error");
            }

            HttpPostedFileBase user_image = Request.Files["user_image_blob"];

            byte[] user_image_blob = null;
            if (user_image != null)
            {
                if (user_image.ContentType != "image/jpeg")
                {
                    return("file format error");
                }
                user_image_blob = new byte[user_image.ContentLength];
                user_image.InputStream.Read(user_image_blob, 0, user_image.ContentLength);
            }

            if (user.profile_description == null)
            {
                user.profile_description = "";
            }
            var st = session.Prepare("insert into \"user\" (user_image_blob, user_name, full_name, profile_description, user_password)" +
                                     "values (?,?,?,?,?)");

            var statement = st.Bind(user_image_blob, user.user_name.ToLower(), user.full_name, user.profile_description, user.user_password);


            var st3 = session.Prepare("UPDATE user_stats SET number_of_followers = number_of_followers + 0, number_of_following = number_of_following + 0, number_of_posts = number_of_posts + 0 " +
                                      "WHERE user_name = ?");

            var statement3 = st3.Bind(user.user_name.ToLower());

            var batch = new BatchStatement()
                        .Add(statement);

            RowSet newUser      = session.Execute(batch);
            RowSet updateResult = session.Execute(statement3);

            if (newUser.IsFullyFetched && updateResult.IsFullyFetched)
            {
                return("success");
            }
            else
            {
                return("Writing error.");
            }
        }
示例#30
0
        public string FollowUser()
        {
            ISession session = SessionManager.GetSession();

            if (Session["user_name"] == null)
            {
                return("you muste be logged in");
            }

            if (session == null)
            {
                return("DB error");
            }

            byte[] following_image_blob = null;
            if (Request["following_image_blob"] != null)
            {
                following_image_blob = Convert.FromBase64String(Request["following_image_blob"]);
            }
            //insert into the people i follow
            var st = session.Prepare("INSERT INTO people_i_follow(user_name, following_user_name, following_full_name, following_image_blob)" +
                                     "VALUES(?, ?, ?, ?)");
            var statement = st.Bind(Session["user_name"], Request["following_user_name"], Request["following_full_name"], following_image_blob);
            //update number of people i follow
            var st2        = session.Prepare("UPDATE user_stats SET number_of_following = number_of_following + 1 WHERE user_name = ?");
            var statement2 = st2.Bind(Session["user_name"]);

            //insert me into that persons followers
            var st3 = session.Prepare("INSERT INTO my_followers(user_name, follower_user_name, follower_full_name, follower_image_blob)" +
                                      "VALUES(?, ?, ?, ?)");
            var statement3 = st3.Bind(Request["following_user_name"], Session["user_name"], Session["full_name"], Session["user_image_blob"]);
            //update that persons number of followers
            var st4        = session.Prepare("UPDATE user_stats SET number_of_followers = number_of_followers + 1 WHERE user_name = ?");
            var statement4 = st4.Bind(Request["following_user_name"]);

            var batch = new BatchStatement()
                        .Add(statement)
                        .Add(statement3);

            RowSet result      = session.Execute(batch);
            RowSet updateStas  = session.Execute(statement2);
            RowSet updateStas2 = session.Execute(statement4);

            if (result.IsFullyFetched && updateStas.IsFullyFetched && updateStas2.IsFullyFetched)
            {
                return("success");
            }
            else
            {
                return("error");
            }
        }
        public void CreateFolder(InventoryFolder folder)
        {
            var skelInsert    = SKEL_INSERT_STMT.Bind(folder.OwnerId, folder.FolderId, folder.Name, folder.ParentId, folder.Type, (int)folder.Level);
            var contentInsert = FOLDER_ATTRIB_INSERT_STMT.Bind(folder.FolderId, FOLDER_MAGIC_ENTRY, folder.Name, folder.Type, UnixTimeNow(), folder.OwnerId);

            var batch = new BatchStatement()
                        .Add(skelInsert)
                        .Add(contentInsert);

            _session.Execute(batch);

            VersionInc(folder.OwnerId, folder.FolderId);
        }
        public void SaveFolder(InventoryFolder folder)
        {
            var skelUpdate    = SKEL_UPDATE_STMT.Bind(folder.Name, folder.Type, folder.OwnerId, folder.FolderId);
            var contentUpdate = FOLDER_UPDATE_STMT.Bind(folder.Name, folder.Type, folder.FolderId);

            var batch = new BatchStatement()
                        .Add(skelUpdate)
                        .Add(contentUpdate);

            _session.Execute(batch);

            VersionInc(folder.OwnerId, folder.FolderId);
        }
        private void DeleteFolder(Guid ownerId, Guid folderId)
        {
            var folderRemove  = FOLDER_REMOVE_STMT.Bind(folderId);
            var skelRemove    = SKEL_REMOVE_STMT.Bind(ownerId, folderId);
            var versionRemove = FOLDER_VERSION_REMOVE_STMT.Bind(ownerId, folderId);

            var batch = new BatchStatement()
                        .Add(folderRemove)
                        .Add(skelRemove);

            _session.Execute(batch);
            _session.Execute(versionRemove);
        }
        public void PurgeItem(InventoryItem item)
        {
            var removeItem      = FOLDER_ITEM_REMOVE_STMT.Bind(item.FolderId, item.ItemId);
            var removeOwnership = ITEM_OWNERSHIP_REMOVE.Bind(item.ItemId);

            var batch = new BatchStatement()
                        .Add(removeItem)
                        .Add(removeOwnership);

            _session.Execute(batch);

            VersionInc(item.OwnerId, item.FolderId);
        }
示例#35
0
        public void Batch_SimpleStatementSingle()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            CreateTable(tableName);

            var batch = new BatchStatement();
            var simpleStatement = new SimpleStatement(String.Format("INSERT INTO {0} (id, label, number) VALUES ({1}, '{2}', {3})", _tableName, 20, "label 20", 20));
            batch.Add(simpleStatement);
            Session.Execute(batch);

            //Verify Results
            var rs = Session.Execute(String.Format("SELECT * FROM {0} WHERE id IN ({1})", _tableName, 20));
            var row = rs.First();
            CollectionAssert.AreEqual(row, new object[] { 20, "label 20", 20});
        }
示例#36
0
        public void Batch_PreparedStatement()
        {
            List<object[]> expectedValues = new List<object[]> { new object[] { 1, "label1", 1 }, new object[] { 2, "label2", 2 }, new object[] { 3, "label3", 3 } };

            PreparedStatement ps = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", _tableName));
            BatchStatement batch = new BatchStatement();
            foreach (object[] val in expectedValues)
            {
                batch.Add(ps.Bind(val));
            }
            Session.Execute(batch);

            // Verify results
            var rs = Session.Execute(String.Format("SELECT * FROM {0} WHERE id IN ({1}, {2}, {3})", _tableName, 1, 2, 3));

            VerifyData(rs, expectedValues);
        }
示例#37
0
 public Task<BatchStatement> GetBatchStatementAsync(ISession session, IEnumerable<Cql> cqlToBatch)
 {
     // Get all the statements async in parallel, then add to batch
     return Task.Factory.ContinueWhenAll(cqlToBatch.Select(cql => GetStatementAsync(session, cql)).ToArray(), (tasks) =>
     {
         var batch = new BatchStatement();
         foreach (var t in tasks)
         {
             if (t.Exception != null)
             {
                 throw t.Exception;
             }
             batch.Add(t.Result);
         }
         return batch;
     }, TaskContinuationOptions.ExecuteSynchronously);
 }
示例#38
0
        public void BatchPreparedStatementBasicAsyncTest()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            List<object[]> expectedValues = new List<object[]> { new object[] { 1, "label1", 1 }, new object[] { 2, "label2", 2 }, new object[] { 3, "label3", 3 } };

            CreateTable(tableName);

            PreparedStatement ps = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            BatchStatement batch = new BatchStatement();
            foreach (object[] val in expectedValues)
            {
                batch.Add(ps.Bind(val));
            }
            var task = Session.ExecuteAsync(batch);
            var rs = task.Result;

            // Verify results
            VerifyData(rs, expectedValues);
        }
示例#39
0
        public BatchRequest(int protocolVersion, BatchStatement statement, ConsistencyLevel consistency)
        {
            ProtocolVersion = protocolVersion;
            if (ProtocolVersion < 2)
            {
                throw new NotSupportedException("Batch request is supported in C* >= 2.0.x");
            }

            _type = statement.BatchType;
            _requests = statement.Queries
                .Select(q => q.CreateBatchRequest(ProtocolVersion))
                .ToArray();
            Consistency = consistency;
            _timestamp = statement.Timestamp;
            if (statement.IsTracing)
            {
                _headerFlags = FrameHeader.HeaderFlag.Tracing;
            }
            if (statement.SerialConsistencyLevel != ConsistencyLevel.Any)
            {
                if (protocolVersion < 3)
                {
                    throw new NotSupportedException("Serial consistency level for BATCH request is supported in Cassandra 2.1 or above.");
                }
                if (statement.SerialConsistencyLevel < ConsistencyLevel.Serial)
                {
                    throw new RequestInvalidException("Non-serial consistency specified as a serial one.");
                }
                _batchFlags |= QueryProtocolOptions.QueryFlags.WithSerialConsistency;
                _serialConsistency = statement.SerialConsistencyLevel;
            }
            if (_timestamp != null)
            {
                if (protocolVersion < 3)
                {
                    throw new NotSupportedException("Timestamp for BATCH request is supported in Cassandra 2.1 or above.");
                }
                _batchFlags |= QueryProtocolOptions.QueryFlags.WithDefaultTimestamp;
            }
        }
示例#40
0
        public void LinqUpdate_Batch()
        {
            // Setup
            Table<Movie> table = new Table<Movie>(_session, new MappingConfiguration());
            table.CreateIfNotExists();
            Movie movieToUpdate1 = _movieList[1];
            Movie movieToUpdate2 = _movieList[2];

            BatchStatement batch = new BatchStatement();

            var expectedMovie1 = new Movie(movieToUpdate1.Title, movieToUpdate1.Director, "something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate1.MovieMaker, 1212);
            var update1 = table.Where(m => m.Title == movieToUpdate1.Title && m.MovieMaker == movieToUpdate1.MovieMaker && m.Director == movieToUpdate1.Director)
                 .Select(m => new Movie { Year = expectedMovie1.Year, MainActor = expectedMovie1.MainActor })
                 .Update();
            batch.Add(update1);

            var expectedMovie2 = new Movie(movieToUpdate2.Title, movieToUpdate2.Director, "also_something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate2.MovieMaker, 1212);
            var update2 = table.Where(m => m.Title == movieToUpdate2.Title && m.MovieMaker == movieToUpdate2.MovieMaker && m.Director == movieToUpdate2.Director)
                 .Select(m => new Movie { Year = expectedMovie2.Year, MainActor = expectedMovie2.MainActor })
                 .Update();
            batch.Add(update2);

            table.GetSession().Execute(batch);

            List<Movie> actualMovieList = table.Execute().ToList();
            Assert.AreEqual(_movieList.Count, actualMovieList.Count());
            Assert.AreNotEqual(expectedMovie1.MainActor, expectedMovie2.MainActor);
            Assert.IsFalse(Movie.ListContains(_movieList, expectedMovie1));
            Assert.IsFalse(Movie.ListContains(_movieList, expectedMovie2));
            Movie.AssertListContains(actualMovieList, expectedMovie1);
            Movie.AssertListContains(actualMovieList, expectedMovie2);
        }
        public void NestedCollections_BatchStatements()
        {
            using (var session = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint).Build().Connect())
            {
                string keyspaceName = TestUtils.GetUniqueKeyspaceName().ToLower();
                string fqTableName = keyspaceName + "." + TestUtils.GetUniqueKeyspaceName().ToLower();
                SetupForFrozenNestedCollectionTest(session, keyspaceName, fqTableName);
                var cqlInsertStr = String.Format("INSERT INTO {0} (id, map1, map2, list1) VALUES (?, ?, ?, ?)", fqTableName);
                PreparedStatement preparedStatement = session.Prepare(cqlInsertStr);
                BatchStatement batchStatement = new BatchStatement();
                var map1Value = GetMap1Val();
                var map2Value = GetMap2Val();
                var list1Value = GetList1Val();

                // Insert
                batchStatement.Add(preparedStatement.Bind(1, map1Value, map2Value, list1Value));
                session.Execute(batchStatement);

                // Validate the end state of data in C*
                string cqlSelectStr = String.Format("SELECT id, map1, map2, list1 FROM {0} WHERE id = 1", fqTableName);
                PreparedStatement preparedSelect = session.Prepare(cqlSelectStr);
                var row = session.Execute(preparedSelect.Bind(new object[] { })).First();

                ValidateSelectedNestedFrozenRow(row);
            }
        }
 public void RequestHandler_GetRequest_BatchStatement_Statement_Level_Settings_Are_Used()
 {
     var stmt = new BatchStatement();
     stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
     Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
     var request = (BatchRequest)RequestHandler<RowSet>.GetRequest(stmt, 2, GetConfig());
     Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
 }
示例#43
0
        public void BatchSerialConsistencyTest()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            CreateTable(tableName);

            var query = new SimpleStatement(String.Format("INSERT INTO {0} (id) values (-99999)", tableName));

            Assert.Throws<ArgumentException>(() =>
            {
                //You can not specify local serial consistency as a valid read one.
                var batch = new BatchStatement()
                    .Add(query)
                    .SetBatchType(BatchType.Logged)
                    .SetSerialConsistencyLevel(ConsistencyLevel.Quorum);
                Session.Execute(batch);
            });

            //It should work
            var statement = new BatchStatement()
                .Add(query)
                .SetConsistencyLevel(ConsistencyLevel.Quorum)
                .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);

            //Read consistency specified and write consistency specified
            Session.Execute(statement);
        }
示例#44
0
        public void BatchSimpleStatementMultiple()
        {
            SimpleStatement simpleStatement = null;
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            var expectedValues = new List<object[]>();

            CreateTable(tableName);

            BatchStatement batch = new BatchStatement();

            for(var x = 1; x <= 5; x++)
            {
                simpleStatement = new SimpleStatement(String.Format("INSERT INTO {0} (id, label, number) VALUES ({1}, '{2}', {3})", tableName, x, "label" + x, x * x));
                expectedValues.Add(new object[] { x, "label" + x, x * x });
                batch.Add(simpleStatement);
            }
            Session.Execute(batch);

            var rs = Session.Execute("SELECT * FROM " + tableName);

            VerifyData(rs.OrderBy(r => r.GetValue<int>("id")), expectedValues);
        }
示例#45
0
 public void BatchStatement_Statement_Level_Settings_Are_Used()
 {
     var stmt = new BatchStatement();
     stmt.SetConsistencyLevel(ConsistencyLevel.EachQuorum);
     Assert.AreEqual(ConsistencyLevel.EachQuorum, stmt.ConsistencyLevel);
     var session = GetInstance();
     var request = (BatchRequest)session.GetRequest(stmt);
     Assert.AreEqual(ConsistencyLevel.EachQuorum, request.Consistency);
 }
示例#46
0
 public void BatchStatement_Default_QueryOptions_Are_Used()
 {
     var stmt = new BatchStatement();
     Assert.Null(stmt.ConsistencyLevel);
     var session = GetInstance();
     var request = (BatchRequest)session.GetRequest(stmt);
     Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
 }
示例#47
0
 public void BatchStatement_QueryOptions_Are_Used()
 {
     var stmt = new BatchStatement();
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
     var session = GetInstance(queryOptions);
     var request = (BatchRequest)session.GetRequest(stmt);
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
 }
示例#48
0
        public void BatchSimpleStatementSingleBinded()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            CreateTable(tableName);

            var batch = new BatchStatement();

            var simpleStatement = new SimpleStatement(String.Format("INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            batch.Add(simpleStatement.Bind(100, "label 100", 10000));
            Session.Execute(batch);

            //Verify Results
            var rs = Session.Execute("SELECT * FROM " + tableName);
            var row = rs.First();
            Assert.True(row != null, "There should be a row stored.");
            Assert.True(row.SequenceEqual(new object[] { 100, "label 100", 10000}), "Stored values dont match");
        }
示例#49
0
 public void BatchStatement_Bind_SetsRoutingValues_Single()
 {
     const int protocolVersion = 2;
     var batch = new BatchStatement();
     Assert.Null(batch.RoutingKey);
     batch.SetRoutingValues("id1-value");
     batch.Serializer = new Serializer(protocolVersion);
     CollectionAssert.AreEqual(batch.Serializer.Serialize("id1-value"), batch.RoutingKey.RawRoutingKey);
 }
示例#50
0
        public void BatchStatementOnTwoTablesWithOneInvalidTableTest()
        {
            var batch = new BatchStatement();
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();

            CreateTable(tableName);

            batch.Add(new SimpleStatement(String.Format(@"INSERT INTO {0} (id, label, number) VALUES ({1}, '{2}', {3})", tableName, 1, "label1", 1)));
            batch.Add(new SimpleStatement(String.Format(@"INSERT INTO table2 (id, label, number) VALUES ({0}, '{1}', {2})", 2, "label2", 2)));

            Assert.Throws<InvalidQueryException>(
                delegate { Session.Execute(batch); }, "expected InvalidQueryException, but did not get one");
        }
示例#51
0
        public void BatchStatementTwoTablesTest()
        {
            var expectedValues = new List<object[]>();
            var batch = new BatchStatement();

            CreateTwoTableTestEnv("table1", "table2");

            batch.Add(new SimpleStatement(String.Format(@"INSERT INTO table1 (id, label, number) VALUES ({0}, '{1}', {2})", 1, "label1", 1)));
            batch.Add(new SimpleStatement(String.Format(@"INSERT INTO table2 (id, label, number) VALUES ({0}, '{1}', {2})", 2, "label2", 2)));

            Session.Execute(batch);

            //Verify Results
            RowSet rsTable1 = Session.Execute("SELECT * FROM table1");
            VerifyData(rsTable1, new List<object[]> {new object[] { 1, "label1", 1 } });

            RowSet rsTable2 = Session.Execute("SELECT * FROM table2");
            VerifyData(rsTable2, new List<object[]> { new object[] { 2, "label2", 2 } });
        }
 public void RequestHandler_GetRequest_BatchStatement_QueryOptions_Are_Used()
 {
     var stmt = new BatchStatement();
     Assert.Null(stmt.ConsistencyLevel);
     var queryOptions = new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
     var request = (BatchRequest)RequestHandler<RowSet>.GetRequest(stmt, 2, GetConfig(queryOptions));
     Assert.AreEqual(queryOptions.GetConsistencyLevel(), request.Consistency);
 }
示例#53
0
        public void LargeBatchPreparedStatement()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N");

            CreateTable(tableName);

            PreparedStatement ps = Session.Prepare(String.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            BatchStatement batch = new BatchStatement();
            List<object[]> expectedValues = new List<object[]>();

            int numberOfPreparedStatements = 100;
            for (var x = 1; x <= numberOfPreparedStatements; x++)
            {
                expectedValues.Add(new object[] { x, "value" + x, x });
                batch.Add(ps.Bind(new object[] { x, "value" + x , x }));
            }

            Session.Execute(batch);

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

            VerifyData(rs.OrderBy(r => r.GetValue<int>("id")), expectedValues);
        }
示例#54
0
        public void BatchTimestampTest()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            CreateTable(tableName);

            var query = new SimpleStatement(String.Format("INSERT INTO {0} (id) values (-99999)", tableName));

            Assert.DoesNotThrow(() =>
            {
                //It should work
                var statement = new BatchStatement()
                    .Add(query)
                    .SetConsistencyLevel(ConsistencyLevel.Quorum)
                    .SetTimestamp(DateTime.Now);

                //Read consistency specified and write consistency specified
                Session.Execute(statement);
            });
        }
示例#55
0
        public void BatchPreparedStatementsFlagsNotSupportedInC2_0()
        {
            var tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            CreateTable(tableName);

            var ps = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            var batch = new BatchStatement();
            batch.Add(ps.Bind(new object[] { 1, "label1", 1 }));
            Assert.Throws<NotSupportedException>(() => Session.Execute(batch.SetTimestamp(DateTime.Now)));
        }
 public void RequestHandler_GetRequest_BatchStatement_Default_QueryOptions_Are_Used()
 {
     var stmt = new BatchStatement();
     Assert.Null(stmt.ConsistencyLevel);
     var request = (BatchRequest)RequestHandler<RowSet>.GetRequest(stmt, 2, GetConfig());
     Assert.AreEqual(DefaultQueryOptions.GetConsistencyLevel(), request.Consistency);
 }
示例#57
0
        public void BatchPreparedStatementsNotSupportedInC1_2()
        {
            string tableName = "table" + Guid.NewGuid().ToString("N").ToLower();
            CreateTable(tableName);

            var ps = Session.Prepare(string.Format(@"INSERT INTO {0} (id, label, number) VALUES (?, ?, ?)", tableName));
            BatchStatement batch = new BatchStatement();
            batch.Add(ps.Bind(new object[] { 1, "label1", 1 }));
            try
            {
                Session.Execute(batch);
                Assert.Fail("Cassandra version below 2.0, should not execute batches of prepared statements");
            }
            catch (NotSupportedException ex)
            {
                //This is OK
                Assert.True(ex.Message.ToLower().Contains("batch"));
            }
        }
示例#58
0
 public void BatchStatement_Bind_SetsRoutingValues_Single()
 {
     const int protocolVersion = 2;
     var batch = new BatchStatement();
     Assert.Null(batch.RoutingKey);
     batch.SetRoutingValues("id1-value");
     batch.ProtocolVersion = protocolVersion;
     CollectionAssert.AreEqual(TypeCodec.Encode(protocolVersion, "id1-value"), batch.RoutingKey.RawRoutingKey);
 }
示例#59
0
 public void BatchStatement_Bind_SetsRoutingValues_Multiple()
 {
     const int protocolVersion = 2;
     var batch = new BatchStatement();
     Assert.Null(batch.RoutingKey);
     batch.SetRoutingValues("id11", "id22");
     batch.ProtocolVersion = protocolVersion;
     var expectedRoutingKey = new byte[0]
         .Concat(new byte[] { 0, 4 })
         .Concat(TypeCodec.Encode(protocolVersion, "id11"))
         .Concat(new byte[] { 0 })
         .Concat(new byte[] { 0, 4 })
         .Concat(TypeCodec.Encode(protocolVersion, "id22"))
         .Concat(new byte[] { 0 });
     CollectionAssert.AreEqual(expectedRoutingKey, batch.RoutingKey.RawRoutingKey);
 }
示例#60
0
        ///////////////////////////////////////
        ///  Test Helper Methods
        ///////////////////////////////////////

        private void DoBatchInsertTest(ConsistencyLevel expectedConsistencyLevel)
        {
            // Add a few more records via batch statement
            BatchStatement batch = new BatchStatement();
            batch.SetConsistencyLevel(expectedConsistencyLevel);
            var addlPocoList = ManyDataTypesEntity.GetDefaultAllDataTypesList();
            foreach (var manyDataTypesPoco in addlPocoList)
            {
                string simpleStatementStr = GetSimpleStatementInsertString(manyDataTypesPoco);
                SimpleStatement simpleStatement = new SimpleStatement(simpleStatementStr);
                batch.Add(simpleStatement);
            }

            // Validate Results
            var result = _session.Execute(batch);
            Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
            int totalExpectedRecords = _defaultPocoList.Count + addlPocoList.Count;
            result = _session.Execute(_defaultSelectStatement);
            Assert.AreEqual(totalExpectedRecords, result.GetRows().ToList().Count);
        }