/// <summary> /// Add a track to the database /// </summary> public void Add(TrackDto track) { if (track == null) { throw new ArgumentNullException("track"); } // Compute the first letter of the artists name for the artists_by_first_letter table string artistFirstLetter = track.Artist.Substring(0, 1).ToUpper(); PreparedStatement preparedStatement = _session.Prepare("INSERT INTO artists_by_first_letter (first_letter, artist) VALUES (?, ?)"); BoundStatement boundStatement = preparedStatement.Bind(artistFirstLetter, track.Artist); _session.Execute(boundStatement); preparedStatement = _session.Prepare("INSERT INTO track_by_id (genre, track_id, artist, track, track_length_in_seconds) VALUES (?, ?, ?, ?, ?)"); boundStatement = preparedStatement.Bind(track.Genre, track.TrackId, track.Artist, track.Track, track.LengthInSeconds); _session.Execute(boundStatement); preparedStatement = _session.Prepare("INSERT INTO track_by_genre (genre, track_id, artist, track, track_length_in_seconds) VALUES (?, ?, ?, ?, ?)"); boundStatement = preparedStatement.Bind(track.Genre, track.TrackId, track.Artist, track.Track, track.LengthInSeconds); _session.Execute(boundStatement); preparedStatement = _session.Prepare("INSERT INTO track_by_artist (genre, track_id, artist, track, track_length_in_seconds) VALUES (?, ?, ?, ?, ?)"); boundStatement = preparedStatement.Bind(track.Genre, track.TrackId, track.Artist, track.Track, track.LengthInSeconds); _session.Execute(boundStatement); }
public async Task <List <BoundStatement> > BuildBoundStatements_ForUpsert( IEnumerable <IDocumentRecord> items) { var result = new List <BoundStatement>(); foreach (var item in items) { PreparedStatement prepared = await _UpsertFlattenedDocumentById; BoundStatement bound = prepared.Bind( item.Id, item.DocumentType, item.DocumentVersion, item.DocumentJson ); result.Add(bound); prepared = await _UpsertFlattenedDocumentByTypeAndVersion; bound = prepared.Bind( item.Id, item.DocumentType, item.DocumentVersion, item.DocumentJson ); result.Add(bound); } return(result); }
public async Task <List <BoundStatement> > BuildBoundStatements_ForScopeClaimRecord_Create( IEnumerable <ScopeClaimRecord> scopeClaimRecords) { var result = new List <BoundStatement>(); foreach (var scopeClaimRecord in scopeClaimRecords) { /* * @"scopeclaims_by_name_and_scopeid(Name,ScopeId,ScopeName,AlwaysIncludeInIdToken,Description) " + */ PreparedStatement prepared = await _CreateScopeClaimByNameAndScopeId; BoundStatement bound = prepared.Bind( scopeClaimRecord.Name, scopeClaimRecord.ScopeId, scopeClaimRecord.ScopeName ); result.Add(bound); prepared = await _CreateScopeClaimByNameAndScopeName; bound = prepared.Bind( scopeClaimRecord.Name, scopeClaimRecord.ScopeId, scopeClaimRecord.ScopeName ); result.Add(bound); } return(result); }
protected override Task DeleteAsync(SnapshotMetadata metadata) { IStatement bound = _deleteSnapshot.Bind(metadata.PersistenceId, metadata.SequenceNr) .SetConsistencyLevel(_cassandraExtension.SnapshotStoreSettings.WriteConsistency); return(_session.ExecuteAsync(bound)); }
public void DeserializationTests() { var rowIdArray = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var ticksArray = new[] { 35465410426481591, 63546500026481590, 70011723893288L, 1723893288L }; const string format = "yyyy-MM-dd HH:mm:ss.SSS"; for (var i = 0; i < rowIdArray.Length; i++) { var rowId = rowIdArray[i]; var ticks = ticksArray[i]; var timeUuid = TimeUuid.NewId(new DateTimeOffset(ticks, TimeSpan.Zero)); Session.Execute(_insertPrepared.Bind(rowId, timeUuid)); var row = Session.Execute(_selectPrepared.Bind(rowId)).FirstOrDefault(); Assert.NotNull(row); var resultTimeUuidValue = row.GetValue <TimeUuid>("timeuuid_sample"); Assert.AreEqual(timeUuid, resultTimeUuidValue); Assert.AreEqual(timeUuid.GetDate(), resultTimeUuidValue.GetDate()); if (row.GetColumn("timeuuid_date_value") != null) { // the timestamp retrieved by the cql function has lower precision than timeuuid const long precision = 10000L; Assert.AreEqual( timeUuid.GetDate().Ticks / precision, row.GetValue <DateTimeOffset>("timeuuid_date_value").Ticks / precision); } //Still defaults to Guid var boxedValue = row.GetValue <object>("timeuuid_sample"); Assert.IsInstanceOf <Guid>(boxedValue); Assert.AreEqual(resultTimeUuidValue, (TimeUuid)(Guid)boxedValue); //The precision is lost, up to milliseconds is fine Assert.AreEqual(timeUuid.GetDate().ToString(format), row.GetValue <DateTimeOffset>(2).ToString(format)); } }
public async Task <List <BoundStatement> > BuildBoundStatements_ForCreate( IEnumerable <FlattenedRefreshTokenHandle> flattenedTokenHandles) { var result = new List <BoundStatement>(); foreach (var flattenedTokenHandle in flattenedTokenHandles) { PreparedStatement prepared = await _CreateRefreshTokenByClientId; BoundStatement bound = prepared.Bind( flattenedTokenHandle.AccessToken, flattenedTokenHandle.ClientId, flattenedTokenHandle.CreationTime, flattenedTokenHandle.Expires, flattenedTokenHandle.Key, flattenedTokenHandle.LifeTime, flattenedTokenHandle.SubjectId, flattenedTokenHandle.Version ); result.Add(bound); prepared = await _CreateRefreshTokenByKey; bound = prepared.Bind( flattenedTokenHandle.AccessToken, flattenedTokenHandle.ClientId, flattenedTokenHandle.CreationTime, flattenedTokenHandle.Expires, flattenedTokenHandle.Key, flattenedTokenHandle.LifeTime, flattenedTokenHandle.SubjectId, flattenedTokenHandle.Version ); result.Add(bound); } return(result); }
/// <summary> /// Returns the user associated with this login /// </summary> public async Task <User> FindAsync(UserLoginInfo login) { if (login == null) { throw new ArgumentNullException("login"); } PreparedStatement prepared = await _getLoginsByProvider; BoundStatement bound = prepared.Bind(login.LoginProvider, login.ProviderKey); RowSet loginRows = await _session.ExecuteAsync(bound).ConfigureAwait(false); Row loginResult = loginRows.FirstOrDefault(); if (loginResult == null) { return(null); } prepared = await _findById; bound = prepared.Bind(loginResult.GetValue <Guid>("id")); RowSet rows = await _session.ExecuteAsync(bound).ConfigureAwait(false); return(User.FromRow(rows.SingleOrDefault())); }
private async Task <List <BoundStatement> > BuildBoundStatements_ForCreate( IList <FlattenedConsentRecord> flattenedConsentRecords) { try { var result = new List <BoundStatement>(); foreach (var record in flattenedConsentRecords) { var consent = record.Record; PreparedStatement prepared = await _CreateConsentById; BoundStatement bound = prepared.Bind( record.Id, consent.ClientId, consent.Scopes, consent.Subject); result.Add(bound); prepared = await _CreateConsentByClientId; bound = prepared.Bind( record.Id, consent.ClientId, consent.Scopes, consent.Subject); result.Add(bound); } return(result); } catch (Exception e) { throw; } }
public InventoryFolder GetFolder(Guid folderId) { var statement = FOLDER_SELECT_STMT.Bind(folderId); var rowset = _session.Execute(statement); var itemList = new List <InventoryItem>(); InventoryFolder retFolder = null; foreach (var row in rowset) { if (row.GetValue <Guid>("item_id") == FOLDER_MAGIC_ENTRY) { retFolder = new InventoryFolder { FolderId = folderId }; //this is the data row that holds the information for the folder itself MapRowToFolder(retFolder, row); } else { itemList.Add(MapRowToItem(row)); } } if (retFolder != null) { retFolder.Items = itemList; } return(retFolder); }
private void reprepareOnNewlyUpNodeTest(bool useKeyspace) { string keyspace = "tester"; var clusterInfo = TestUtils.CcmSetup(2, null, keyspace); var cluster = clusterInfo.Cluster; var session = clusterInfo.Session; try { string modifiedKs = ""; if (useKeyspace) { session.ChangeKeyspace(keyspace); } else { modifiedKs = keyspace + "."; } try { session.WaitForSchemaAgreement( session.Execute("CREATE TABLE " + modifiedKs + "test(k text PRIMARY KEY, i int)") ); } catch (AlreadyExistsException) { } session.Execute("INSERT INTO " + modifiedKs + "test (k, i) VALUES ('123', 17)"); session.Execute("INSERT INTO " + modifiedKs + "test (k, i) VALUES ('124', 18)"); PreparedStatement ps = session.Prepare("SELECT * FROM " + modifiedKs + "test WHERE k = ?"); var rs = session.Execute(ps.Bind("123")); Assert.AreEqual(rs.First().GetValue <int>("i"), 17); TestUtils.CcmStopNode(clusterInfo, 1); Thread.Sleep(3000); TestUtils.CcmStart(clusterInfo, 1); Thread.Sleep(40000); TestUtils.CcmStopNode(clusterInfo, 2); Assert.True(session.Cluster.AllHosts().Select(h => h.IsUp).Count() > 0, "There should be one node up"); for (var i = 0; i < 10; i++) { var rowset = session.Execute(ps.Bind("124")); Assert.AreEqual(rowset.First().GetValue <int>("i"), 18); } } finally { cluster.Shutdown(); TestUtils.CcmRemove(clusterInfo); } }
private void reprepareOnNewlyUpNodeTest(bool useKeyspace) { string keyspace = "tester"; Session.CreateKeyspaceIfNotExists(keyspace); string modifiedKs = ""; if (useKeyspace) { Session.ChangeKeyspace(keyspace); } else { modifiedKs = keyspace + "."; } try { Session.WaitForSchemaAgreement( Session.Execute("CREATE TABLE " + modifiedKs + "test(k text PRIMARY KEY, i int)") ); } catch (AlreadyExistsException) { } Session.Execute("INSERT INTO " + modifiedKs + "test (k, i) VALUES ('123', 17)"); Session.Execute("INSERT INTO " + modifiedKs + "test (k, i) VALUES ('124', 18)"); PreparedStatement ps = Session.Prepare("SELECT * FROM " + modifiedKs + "test WHERE k = ?"); using (var rs = Session.Execute(ps.Bind("123"))) { Assert.Equal(rs.GetRows().First().GetValue <int>("i"), 17); // ERROR } CCMBridge.ReusableCCMCluster.CCMBridge.Stop(); TestUtils.waitForDown(Options.Default.IP_PREFIX + "1", Session.Cluster, 30); CCMBridge.ReusableCCMCluster.CCMBridge.Start(); TestUtils.waitFor(Options.Default.IP_PREFIX + "1", Session.Cluster, 30); try { using (var rowset = Session.Execute(ps.Bind("124"))) { Assert.Equal(rowset.GetRows().First().GetValue <int>("i"), 18); } } catch (NoHostAvailableException e) { Debug.WriteLine(">> " + e.Errors); throw e; } }
protected override async Task <SelectedSnapshot> LoadAsync(string persistenceId, SnapshotSelectionCriteria criteria) { bool hasNextPage = true; byte[] nextPageState = null; while (hasNextPage) { // Get a page of metadata that match the criteria IStatement getMetadata = _selectSnapshotMetadata.Bind(persistenceId, criteria.MaxSequenceNr) .SetConsistencyLevel(_cassandraExtension.SnapshotStoreSettings.ReadConsistency) .SetPageSize(_cassandraExtension.SnapshotStoreSettings.MaxMetadataResultSize) .SetPagingState(nextPageState) .SetAutoPage(false); RowSet metadataRows = await _session.ExecuteAsync(getMetadata).ConfigureAwait(false); nextPageState = metadataRows.PagingState; hasNextPage = nextPageState != null; IEnumerable <SnapshotMetadata> page = metadataRows.Select(MapRowToSnapshotMetadata) .Where(md => md.Timestamp <= criteria.MaxTimeStamp); // Try to get the first available snapshot from the page foreach (SnapshotMetadata md in page) { try { IStatement getSnapshot = _selectSnapshot.Bind(md.PersistenceId, md.SequenceNr) .SetConsistencyLevel(_cassandraExtension.SnapshotStoreSettings.ReadConsistency); RowSet snapshotRows = await _session.ExecuteAsync(getSnapshot).ConfigureAwait(false); // If we didn't get a snapshot for some reason, just try the next one Row snapshotRow = snapshotRows.SingleOrDefault(); if (snapshotRow == null) { continue; } // We found a snapshot so create the necessary class and return the result return(new SelectedSnapshot(md, Deserialize(snapshotRow.GetValue <byte[]>("snapshot")))); } catch (Exception e) { // If there is a problem, just try the next snapshot _log.Warning("Unexpected exception while retrieveing snapshot {0} for id {1}: {2}", md.SequenceNr, md.PersistenceId, e); } } // Just try the next page if available } // Out of snapshots that match or none found return(null); }
private void ReprepareTest(bool useKeyspace) { string keyspace = DefaultKeyspaceName; ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(1); testCluster.InitClient(); // make sure client session was just created var nonShareableSession = testCluster.Session; string fqKeyspaceName = ""; if (useKeyspace) { nonShareableSession.ChangeKeyspace(keyspace); } else { fqKeyspaceName = keyspace + "."; } try { nonShareableSession.Execute("CREATE TABLE " + fqKeyspaceName + "test(k text PRIMARY KEY, i int)"); } catch (AlreadyExistsException) { } nonShareableSession.Execute("INSERT INTO " + fqKeyspaceName + "test (k, i) VALUES ('123', 17)"); nonShareableSession.Execute("INSERT INTO " + fqKeyspaceName + "test (k, i) VALUES ('124', 18)"); PreparedStatement ps = nonShareableSession.Prepare("SELECT * FROM " + fqKeyspaceName + "test WHERE k = ?"); var rs = nonShareableSession.Execute(ps.Bind("123")); Assert.AreEqual(rs.First().GetValue <int>("i"), 17); testCluster.Stop(1); TestUtils.WaitForDown(testCluster.ClusterIpPrefix + "1", testCluster.Cluster, 40); testCluster.Start(1); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 60); Assert.True(nonShareableSession.Cluster.AllHosts().Select(h => h.IsUp).Any(), "There should be one node up"); for (var i = 0; i < 10; i++) { var rowset = nonShareableSession.Execute(ps.Bind("124")); Assert.AreEqual(rowset.First().GetValue <int>("i"), 18); } }
public void addHotel(int hotelId, string name, int rooms) { BoundStatement bs = INSERT_INTO_HOTELS.Bind(hotelId, name); try { session.Execute(bs); } catch (Exception) { throw; } for (int i = 0; i < rooms; i++) { bs = INSERT_INTO_FREEROOMS.Bind(hotelId, i); try { session.Execute(bs); } catch (Exception) { throw; } } }
public IEnumerable <AggregateCommit> LoadAggregateCommits(int batchSize) { var queryStatement = loadAggregateEventsPreparedStatement.Bind().SetPageSize(batchSize); var result = session.Execute(queryStatement); foreach (var row in result.GetRows()) { var data = row.GetValue <byte[]>("data"); using (var stream = new MemoryStream(data)) { AggregateCommit commit; try { commit = (AggregateCommit)serializer.Deserialize(stream); } catch (Exception ex) { string error = "Failed to deserialize an AggregateCommit. EventBase64bytes: " + Convert.ToBase64String(data); log.ErrorException(error, ex); continue; } yield return(commit); } } }
/// <summary> /// Records that playback has been started for a video. /// </summary> public async Task RecordPlaybackStarted(RecordPlaybackStarted playback) { PreparedStatement prepared = await _statementCache.NoContext.GetOrAddAsync("UPDATE video_playback_stats SET views = views + 1 WHERE videoid = ?"); BoundStatement bound = prepared.Bind(playback.VideoId); await _session.ExecuteAsync(bound).ConfigureAwait(false); }
public void insertRange(PreparedStatement prepStatement, int startIndex, int endIndex) { System.Threading.Thread.Sleep(500); // Console.WriteLine("Inserting values from " + startIndex + " to " + endIndex); Stopwatch t = Stopwatch.StartNew(); for (int idx = startIndex; idx < endIndex; idx++) { try { Session.Execute( prepStatement .Bind(new object[] { idx, "author"+idx, idx % 2 == 0 ? false : true, "body"+idx }).SetConsistencyLevel(ConsistencyLevel.Quorum)); } catch (Exception ex) { Console.WriteLine("Error while inserting " + ex.StackTrace); } } var elapsedMs = t.ElapsedMilliseconds; Interlocked.Add(ref totalElapsedTime, elapsedMs); var avg = elapsedMs / (endIndex - startIndex); // Console.WriteLine("... Inserted values from " + startIndex + " to " + endIndex + " avg:" + avg + "ms"); }
private void SerializeDeserializeCollectionsTest(bool prepared, string table, object value) { PreparedStatement insertPs = null; PreparedStatement selectPs = null; var insertQuery = string.Format("INSERT INTO {0} (id, value) VALUES (?, ?)", table); var selectQuery = string.Format("SELECT * FROM {0} where id = ?", table); if (prepared) { insertPs = Session.Prepare(insertQuery); selectPs = Session.Prepare(selectQuery); } var id = Guid.NewGuid(); var statement = prepared ? (IStatement)insertPs.Bind(id, value) : new SimpleStatement(insertQuery, id, value); Session.Execute(statement); statement = prepared ? (IStatement)selectPs.Bind(id) : new SimpleStatement(selectQuery, id); var row = Session.Execute(statement).FirstOrDefault(); Assert.NotNull(row, "Row for value {0} not found", value); if (value is IEnumerable) { CollectionAssert.AreEqual((IEnumerable)value, row.GetValue <IEnumerable>("value")); } else { Assert.AreEqual(value, row.GetValue <object>("value")); } }
public async Task Handle(AddSampleUsers busCommand) { // Create some fake user data var users = Enumerable.Range(0, busCommand.NumberOfUsers).Select(idx => { var user = new CreateUser { UserId = Guid.NewGuid(), FirstName = Name.GetFirstName(), LastName = Name.GetLastName(), Password = PasswordPattern.Bothify() }; user.EmailAddress = string.Format("{0}[email protected]", Internet.GetUserName(user.FirstName, user.LastName)); return(user); }).ToArray(); // Get statement for recording sample users PreparedStatement prepared = await _statementCache.NoContext.GetOrAddAsync("INSERT INTO sample_data_users (userid) VALUES (?)"); // Add the user and record their Id in C* (not a big deal if we fail halfway through since this is sample data) foreach (CreateUser user in users) { await _userManagement.CreateUser(user).ConfigureAwait(false); BoundStatement bound = prepared.Bind(user.UserId); await _session.ExecuteAsync(bound).ConfigureAwait(false); } }
private static void ProcessRecords(IEnumerable <dynamic> records) { _logger.LogInformation("Processing records..."); IList <CColumn> columns = GetColumnsInfo(Settings.Values.Connections.Target.Keyspace, Settings.Values.Connections.Target.Table); PreparedStatement pStatement = PrepareStatementForInsertion(columns); var insertStatements = new List <BoundStatement>(); foreach (IDictionary <string, object> record in records) { var row = new List <string>(record.Values.Count); row.AddRange(record.Values.Cast <string>()); dynamic[] preparedRow = PrepareRowForInsertion(columns, row); BoundStatement bStatement = pStatement.Bind(preparedRow); insertStatements.Add(bStatement); if (insertStatements.Count >= Settings.Values.InsertionBatch) { ExecuteInsertAsync(insertStatements).Wait(); insertStatements.Clear(); } } if (insertStatements.Count > 0) { ExecuteInsertAsync(insertStatements).Wait(); } }
public InventoryItem GetItem(Guid itemId, Guid parentFolderHint) { if (parentFolderHint == Guid.Empty) { var findParent = ITEM_OWNERSHIP_SELECT.Bind(itemId); var rowset = _session.Execute(findParent); foreach (var row in rowset) { //there should only be one parentFolderHint = row.GetValue <Guid>("parent_folder_id"); break; } } if (parentFolderHint == Guid.Empty) { //we couldnt find the parent folder return(null); } var findItem = FOLDER_ITEM_SELECT_STMT.Bind(parentFolderHint, itemId); var itemRowset = _session.Execute(findItem); foreach (var row in itemRowset) { //there should only be one return(MapRowToItem(row)); } return(null); }
private void SerializeDeserializeTest(bool prepared) { PreparedStatement insertPs = null; PreparedStatement selectPs = null; var prefix = "simple-"; if (prepared) { insertPs = Session.Prepare(InsertGeoQuery); selectPs = Session.Prepare(SelectGeoQuery); prefix = "prepared-"; } foreach (var value in Values) { var id = prefix + value; var statement = prepared ? (IStatement)insertPs.Bind(id, value) : new SimpleStatement(InsertGeoQuery, id, value); Session.Execute(statement); statement = prepared ? (IStatement)selectPs.Bind(id) : new SimpleStatement(SelectGeoQuery, id); var row = Session.Execute(statement).FirstOrDefault(); Assert.NotNull(row, "Row with id '{0}' not found", id); Assert.AreEqual(value, row.GetValue <object>("value")); } }
public InventorySkeletonEntry GetInventorySkeletonEntry(Guid userId, Guid folderId) { var statement = SKEL_SINGLE_SELECT_STMT.Bind(userId, folderId); var rowset = _session.Execute(statement); InventorySkeletonEntry entry = null; foreach (var row in rowset) { //should only be one entry = MapRowToSkeletonItem(row); break; } if (entry != null) { //look up the version statement = FOLDER_VERSION_SINGLE_SELECT_STMT.Bind(userId, folderId); rowset = _session.Execute(statement); foreach (var row in rowset) { //should only be one entry.Version = row.GetValue <long>("version"); } } return(entry); }
protected void query(CCMBridge.CCMCluster c, int n, bool usePrepared, ConsistencyLevel cl) { if (usePrepared) { BoundStatement bs = prepared.Bind(0); for (int i = 0; i < n; ++i) { IPAddress ccord; ConsistencyLevel cac; using (var rs = c.Session.Execute(bs)) { ccord = rs.Info.QueriedHost; cac = rs.Info.AchievedConsistency; } addCoordinator(ccord, cac); } } else { RoutingKey routingKey = new RoutingKey(); routingKey.RawRoutingKey = Enumerable.Repeat((byte)0x00, 4).ToArray(); for (int i = 0; i < n; ++i) { IPAddress ccord; ConsistencyLevel cac; using (var rs = c.Session.Execute(new SimpleStatement(String.Format("SELECT * FROM {0} WHERE k = 0", TABLE)).SetRoutingKey(routingKey).SetConsistencyLevel(cl))) { ccord = rs.Info.QueriedHost; cac = rs.Info.AchievedConsistency; Console.WriteLine(string.Format("Query {0} executed by {1} with consistency {2}", i.ToString(), ccord.ToString(), cac.ToString())); } addCoordinator(ccord, cac); } } }
public void AddTopic(Guid topicId, string title, string body) { //We will be inserting 2 rows in 2 column families. //One for the topic and other for the first message (the topic body). //We will do it in a batch, this way we can ensure that the 2 rows are inserted in the same atomic operation. var batch = new BatchStatement(); //bind the parameters on each statement and add them to the batch batch.Add(_insertTopicStatement.Bind(topicId, title, DateTime.Now)); batch.Add(_insertMessageStatement.Bind(topicId, DateTime.Now, body)); //You can set other options of the batch execution, for example the consistency level. batch.SetConsistencyLevel(ConsistencyLevel.Quorum); //Execute the insert of the 2 rows Session.Execute(batch); }
/// <summary> /// Uses a batch statement to delete the node from the Apache Cassandra /// autocomplete database. /// </summary> /// <param name="id">The id of the node to delete</param> public void DeleteNode(string id) { using (ISession session = connection.Connect(autocompleteKeySpace)) { // Get the data from the metadata table RowSet metadataResult = session.Execute(session.Prepare($"SELECT * FROM {autocompleteMetadataTable} WHERE id = ?").Bind(id)); // Get the first record from the result Row resultRow = metadataResult.First(); // Get the prefix and remaining value information List <string> prefixValues = resultRow.GetValue <List <string> >("prefixValues"); List <string> remainingValues = resultRow.GetValue <List <string> >("remainingValues"); // Prepare the delete statement PreparedStatement deleteStatement = session.Prepare( $"DELETE FROM {autocompleteTable} WHERE prefix = ? AND remaining = ? AND id = ?"); // Create the batch statement BatchStatement batch = new BatchStatement(); // For each of the prefix and remaining values for (int i = 0; i < prefixValues.Count; i++) { // Add a delete statement to the batch batch.Add(deleteStatement.Bind(prefixValues[i], remainingValues[i], id)); } // Execute the statement session.Execute(batch); } }
public void PagingOnBoundStatementTest_Async_UsingConfigBasedPagingSetting() { var pageSize = 10; var queryOptions = new QueryOptions().SetPageSize(pageSize); Builder builder = new Builder().WithQueryOptions(queryOptions).WithDefaultKeyspace(KeyspaceName); builder.AddContactPoint(TestCluster.InitialContactPoint); using (ISession session = builder.Build().Connect()) { var totalRowLength = 1003; Tuple <string, string> tableNameAndStaticKeyVal = CreateTableWithCompositeIndexAndInsert(session, totalRowLength); string statementToBeBound = "SELECT * from " + tableNameAndStaticKeyVal.Item1 + " where label=?"; PreparedStatement preparedStatementWithoutPaging = session.Prepare(statementToBeBound); PreparedStatement preparedStatementWithPaging = session.Prepare(statementToBeBound); BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(tableNameAndStaticKeyVal.Item2); BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(tableNameAndStaticKeyVal.Item2); var rsWithSessionPagingInherited = session.ExecuteAsync(boundStatemetWithPaging).Result; var rsWithoutPagingInherited = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(pageSize, rsWithSessionPagingInherited.InnerQueueCount); Assert.AreEqual(totalRowLength, rsWithoutPagingInherited.InnerQueueCount); var allTheRowsPaged = rsWithSessionPagingInherited.ToList(); Assert.AreEqual(totalRowLength, allTheRowsPaged.Count); } }
public void PagingOnBoundStatementTest_PageOverZeroRows() { var pageSize = 10; var totalRowLength = 11; string tableName = CreateSimpleTableAndInsert(totalRowLength); // insert a guid that we'll keep track of Guid guid = Guid.NewGuid(); string statementToBeBound = "SELECT * from " + tableName + " where id=?"; PreparedStatement preparedStatementWithoutPaging = Session.Prepare(statementToBeBound); PreparedStatement preparedStatementWithPaging = Session.Prepare(statementToBeBound); BoundStatement boundStatemetWithoutPaging = preparedStatementWithoutPaging.Bind(guid); BoundStatement boundStatemetWithPaging = preparedStatementWithPaging.Bind(guid); boundStatemetWithPaging.SetPageSize(pageSize); var rsWithPaging = Session.Execute(boundStatemetWithPaging); var rsWithoutPaging = Session.Execute(boundStatemetWithoutPaging); //Check that the internal list of items count is pageSize Assert.AreEqual(0, rsWithPaging.InnerQueueCount); Assert.AreEqual(0, rsWithoutPaging.InnerQueueCount); var allTheRowsPaged = rsWithPaging.ToList(); Assert.AreEqual(0, allTheRowsPaged.Count); }
public void NestedCollections_BatchStatements() { using (var cluster = ClusterBuilder().AddContactPoint(TestCluster.InitialContactPoint).Build()) { var session = cluster.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 insertRange(PreparedStatement prepStatement, int startIndex, int endIndex) { System.Threading.Thread.Sleep(500); // Console.WriteLine("Inserting values from " + startIndex + " to " + endIndex); Stopwatch t = Stopwatch.StartNew(); for (int idx = startIndex; idx < endIndex; idx++) { try { Session.Execute( prepStatement .Bind(new object[] { idx, "author" + idx, idx % 2 == 0 ? false : true, "body" + idx }).SetConsistencyLevel(ConsistencyLevel.Quorum)); } catch (Exception ex) { Console.WriteLine("Error while inserting " + ex.StackTrace); } } var elapsedMs = t.ElapsedMilliseconds; Interlocked.Add(ref totalElapsedTime, elapsedMs); var avg = elapsedMs / (endIndex - startIndex); // Console.WriteLine("... Inserted values from " + startIndex + " to " + endIndex + " avg:" + avg + "ms"); }
public List <InventorySkeletonEntry> GetInventorySkeleton(Guid userId) { var statement = SKEL_SELECT_STMT.Bind(userId); var rowset = _session.Execute(statement); var retList = new Dictionary <Guid, InventorySkeletonEntry>(); foreach (var row in rowset) { retList.Add(row.GetValue <Guid>("folder_id"), MapRowToSkeletonItem(row)); } //look up the versions statement = FOLDER_VERSION_SELECT_STMT.Bind(userId); rowset = _session.Execute(statement); foreach (var row in rowset) { var folderId = row.GetValue <Guid>("folder_id"); if (retList.ContainsKey(folderId)) { retList[folderId].Version = row.GetValue <long>("version"); } } return(new List <InventorySkeletonEntry>(retList.Values)); }
public void insertRange(PreparedStatement prepStatement, int startIndex, int endIndex) { // Console.WriteLine("Inserting values from " + startIndex + " to " + endIndex); Stopwatch t = Stopwatch.StartNew(); int pendingJobs = 0; for (int idx = startIndex; idx < endIndex; idx++) { Interlocked.Increment(ref pendingJobs); Session.BeginExecute( prepStatement .Bind(new object[] { idx, "author"+idx, idx % 2 == 0 ? false : true, "body"+idx }).SetConsistencyLevel(ConsistencyLevel.One), (ar) => { try { Session.EndExecute(ar); } catch (NoHostAvailableException ex) { foreach( var node in ex.Errors) { Console.WriteLine("Error on " + node.Key.ToString()); var expts = node.Value; foreach(var excpt in expts) Console.WriteLine(" Error while inserting " + excpt.StackTrace + "\n!!!MESSAGE!!!\n" + excpt.Message); } } catch (Exception ex) { Console.WriteLine("Error while inserting " + ex.StackTrace + "\n!!!MESSAGE!!!\n" + ex.Message ); } finally { Interlocked.Decrement(ref pendingJobs); } }, null); } while (true) { Thread.MemoryBarrier(); if (pendingJobs == 0) break; Thread.Sleep(10); } var elapsedMs = t.ElapsedMilliseconds; // _writeHistogram.Update(elapsedMs); Interlocked.Add(ref totalElapsedTime, elapsedMs); var avg = elapsedMs / (endIndex - startIndex); // Console.WriteLine("... Inserted values from " + startIndex + " to " + endIndex + " avg:" + avg +"ms"); }
internal static void ExecutePreparedQuery(Session session, PreparedStatement prepared, object[] values, ConsistencyLevel consistency = ConsistencyLevel.Default, string messageInstead = null) { if (messageInstead != null) Console.WriteLine("CQL<\t" + messageInstead); else Console.WriteLine("CQL< Executing Prepared Query:\t"); session.Execute(prepared.Bind(values).SetConsistencyLevel(consistency)); Console.WriteLine("CQL> (OK)."); }
////////////////////////////// // Test Helpers ////////////////////////////// private void AssertValid(ISession session, PreparedStatement ps, object value) { try { session.Execute(ps.Bind(Guid.NewGuid(), value)); } catch (Exception e) { string assertFailMsg = string.Format("Exception was thrown, but shouldn't have been! \nException message: {0}, Exception StackTrace: {1}", e.Message, e.StackTrace); Assert.Fail(assertFailMsg); } }
private void Check_Expected(PreparedStatement select, object[] expected) { var row = Session.Execute(select.Bind(0)).First(); Assert.IsNotNull(row); Assert.AreEqual(expected[1], row.GetValue<int?>("v0")); Assert.AreEqual(expected[2], row.GetValue<int?>("v1")); }
internal static RowSet ExecutePreparedSelectQuery(ISession session, PreparedStatement prepared, object[] values, string messageInstead = null) { RowSet ret = session.Execute(prepared.Bind(values).SetConsistencyLevel(session.Cluster.Configuration.QueryOptions.GetConsistencyLevel())); return ret; }